Files
OTGateway/CODESTYLE.md
T

398 lines
18 KiB
Markdown

# OTGateway code style
**English** · [Русский](CODESTYLE.RU.md)
These formatting and readability guidelines apply to the firmware, web interface,
tools, examples and documentation. Use `src/opentherm.cpp` as the primary C++
reference. Apply the guidelines to the code you change. Reformat a whole file
only when explicitly asked to do so.
The user's latest explicit instruction takes precedence over this guide. Otherwise,
follow the surrounding code and the exceptions below. See [AGENTS.md](AGENTS.md)
for project procedures, and the code, the OpenTherm specification and `agent-notes/`
for algorithm and compatibility details. Formatting alone does not justify a
change in behavior.
## Basic formatting
- Indent each level with two spaces. Avoid tabs.
- Preserve UTF-8 and the existing line endings. `src/opentherm.cpp` uses CRLF.
Check that Cyrillic characters in documentation and strings survive edits.
- Put the opening `{` on the same line as the declaration or control statement.
- Use braces for `if`, `else`, `while`, `for` and other blocks, even when they contain
a single statement. This also applies to JavaScript.
- Put a space before `(` after `if`, `while`, `for` and `switch`. A function name is
immediately followed by `(`.
- Follow the surrounding code when placing `*` and `&`. New code in `opentherm.cpp`
uses forms such as `const uint8_t* buffer` and `const auto& config`. Leave
unrelated declarations in their existing style.
- Remove trailing whitespace and end each file with a newline.
- Avoid an arbitrary hard line length limit. When a line becomes difficult to
read, break the expression at a logical boundary.
Separate successive conditional branches with a blank line and keep `} else` on
one line.
```cpp
if (response.isSuccess()) {
handleResponse(response);
} else if (shouldRetry()) {
scheduleRetry();
} else {
reportFailure();
}
```
## Blank lines and comments
- Use a blank line between logically independent blocks, including adjacent task
configuration blocks.
- Leave a blank line before a comment that starts a new logical block, except
when the comment comes immediately after the opening `{`.
- Keep a comment directly above the code it describes.
- Write new code comments in English. Explain the reason, constraint or
non-obvious action. Avoid restating an obvious assignment.
- Preserve comments about device compatibility when simplifying code.
- In examples for beginners, explain what the important API calls do, even if an
experienced developer would recognize them.
```cpp
if (response.isSuccess()) {
// Store the acknowledged value for the rest of the application.
vars.slave.heating.indoorTemp = response.get();
// Publish the acknowledged temperature.
ESP_LOGI(L_OT_HEATING, "Received indoor temp: %.2f", vars.slave.heating.indoorTemp);
}
```
## Line breaks and method chains
Keep short calls on one line. For a long call, indent the arguments by two
additional spaces and place the closing parenthesis on its own line. Short,
related arguments can share a line.
```cpp
ESP_LOGI(
L_OT_HEATING, "Set current indoor temp: %.2f (converted: %.2f, response: %.2f)",
indoorTemp, convertedTemp, vars.slave.heating.indoorTemp
);
```
In a typical task configuration chain, write the first method on the same line
as the task variable. Start each subsequent method on a new, indented line.
Use the returned `Task&` reference to avoid repeating the task name.
```cpp
// Read the DHW burner operating hours.
readDhwBurnerHoursTask.setInterval(60000)
.setEnabledWhen([] {
return isSlaveReady()
&& Sensors::getAmountByType(Sensors::Type::OT_DHW_BURNER_HOURS, true);
})
.onDone(onOperationDone);
openthermTaskManager.addTask(readDhwBurnerHoursTask);
```
Keep the variable and method together for a single call.
```cpp
initializeSlaveTask.setEnabledWhen([] {
return canUseBus() && vars.slave.connected;
});
```
For complex builders, the project uses a separate convention that places the
object name on its own line. Preserve this format when editing such a chain.
```cpp
request
.setCentralHeatingEnabled(getSlaveChannelEnabled(
vars.master.heating.enabled, settings.opentherm.heatingDisablingAction
))
.setHotWaterEnabled(
settings.opentherm.options.dhwSupport
&& getSlaveChannelEnabled(vars.master.dhw.enabled, settings.opentherm.dhwDisablingAction)
)
.setCoolingEnabled(settings.opentherm.options.coolingSupport)
.setDhwBlocking(dhwBlocking);
```
Other method chains do not require a separate line for the object name.
In multiline conditions, place `&&` and `||` at the beginning of each continuation
line. For `if`/`else if`, indent continuation lines four spaces from the start
of the original line. If the first operand already has its own line inside a
function argument or parenthesized group, align subsequent `&&`/`||` lines with
it without adding another two spaces. Use parentheses to group related
conditions. Preserve evaluation order and operator precedence when aligning them.
In multiline `return` statements, place `&&` and `||` at the end of the preceding
line. Align the continuation with the start of the expression after `return`.
Within a nested group, align the operands with the group's first expression.
In multiline Boolean assignments, also place `&&` and `||` at the end of the
preceding line. Align the continuation with the start of the right-hand side.
For a long type or variable name, move the entire right-hand side to the next
line after `=` and indent it four spaces from the start of the declaration.
Keep simple conditions made up of several short checks on one line. Multiple
`&&`/`||` operators alone do not require a line break. Split long or complex
conditions where a break helps the reader.
```cpp
if (!response.isSuccess() || response.getRequestCode() != 10 || response.getResponseCode() < 128) {
ESP_LOGE(L_OT, "Boiler diagnostic reset failed");
return;
}
return settings.mqtt.enabled && isNetworkConnected() && !isMqttBlocked() &&
!mqttConfigureTask.scheduled() && isMqttConnected();
const bool hasOutput = activeSerial.load(std::memory_order_relaxed) ||
activeWebSerial.load(std::memory_order_relaxed);
const bool hasOutput =
activeSerial.load(std::memory_order_relaxed) ||
activeWebSerial.load(std::memory_order_relaxed);
if (prevSettings && Sensors::hasEnabledAndValid(*prevSettings)
&& (metadataChanged || !settings.mqtt.homeAssistantDiscovery)) {
deleteConnectionDynamicSensor(*prevSettings);
}
```
## Names and file structure
| Element | Convention |
| --- | --- |
| Functions, methods, variables and fields | `camelCase`, e.g. `readPressure`, `targetTemp` |
| Classes and structs | `PascalCase`, e.g. `Message`, `Config`, `Float` |
| Tasks | Action + object + `Task`, e.g. `writeRoomSetpointTask` |
| Managers | Purpose + `TaskManager`, e.g. `openthermTaskManager` |
| Boolean predicates | Name the condition, e.g. `isSlaveReady`, `canUseBus`, `needWriteRoomSetpoint` |
| Macros and unscoped enum values | `UPPER_SNAKE_CASE` according to the API convention |
| OpenTherm IDs | Use the established API or specification name, e.g. `TSet`, `Tr`, `TsetCH2` |
- Prefix ID reads with `read` and writes with `write`. If you extract a function,
match its name to the task. `writeRoomSetpointTask` calls `writeRoomSetpoint`.
The name `setRoomSetpoint` omits the write.
- Use `get` for data that is already available, as in `Float::get()`. The name
should make clear whether the call communicates with the device.
- Name variables for the data they hold. Distinguish room temperature, heating
water temperature, a setpoint, an actual state and a transmitted flag.
- Use `gpio` for GPIO and `rx` and `tx` for direction, as in `rxGpio` and `txGpio`.
Use `gpio_num_t` for ESP32 GPIO numbers.
- Avoid repeating context already supplied by a namespace. Use `Config` for an
object's general configuration. In that context, `WorkerConfig` adds
unnecessary detail.
- Use the agreed name `sendMessage` for the general message-sending operation.
Avoid reintroducing the ambiguous names `exchange` and `submit` in this API.
- Introduce helper `Kind` types, aliases and abbreviations only when they serve a
clear purpose.
- Keep existing module names such as `opentherm.cpp`, `network.cpp` and
`logging.cpp`. Name class headers according to the module's style.
- Group related types in meaningful namespaces and directories with an initial
capital, as in `ESP32OT::Messages` and `Messages/Float.h`. Keep frequently used
shared types accessible without unnecessary nesting, as in `ESP32OT::MessageID::TSet`.
Indent declarations inside namespaces too.
```cpp
namespace ESP32OT {
namespace Messages {
// Message declarations belong here.
}
}
```
Align columns in long enums and constant tables with the surrounding code.
Avoid adding duplicate enum values solely to provide shorter names.
## Conditions and control flow
Prefer an early return on failure so that the main path stays linear.
```cpp
if (!response.isSuccess()) {
ESP_LOGW(L_OT_HEATING, "Failed set current indoor temp");
return;
}
vars.slave.heating.indoorTemp = response.get();
if (response.getData() != request.getData()) {
ESP_LOGW(
L_OT_HEATING, responseMismatchMessage,
request.getData(), response.getData()
);
return;
}
ESP_LOGI(L_OT_HEATING, "Set current indoor temp: %.2f", vars.slave.heating.indoorTemp);
```
An early return must still allow all required work to run, including connection
checks, limit corrections, the next independent operation and state updates.
Preserve the order of the original algorithm.
Use nesting to show genuine dependencies between operations. For example, a
failed optional `MaxTSet` write must still allow the required `TSet` write to run.
```cpp
if (settings.opentherm.options.maxTempSyncWithTargetTemp) {
const auto response = slave.sendRequest(maxTemperatureRequest);
if (response.isSuccess() && response.getData() == maxTemperatureRequest.getData()) {
ESP_LOGI(L_OT_HEATING, "Set max heating temp");
} else {
ESP_LOGW(L_OT_HEATING, "Failed set max heating temp");
}
}
// Send TSet even if the optional MaxTSet write failed.
const auto response = slave.sendRequest(heatingSetpointRequest);
```
A common assignment before the echo check can stay in linear code that uses
early returns. The assignment alone does not require another level of nesting.
- Choose each conditional structure to show the dependencies and preserve side
effects. Avoid applying one pattern to all conditions.
- Prefer a plain `while` loop to `for (; condition; ...)`.
- Avoid a large `switch` that manually dispatches IDs or steps when separate
tasks naturally express the operations.
- A `switch` on an ID is appropriate in small teaching examples such as Slave.
Give branches at the same level a consistent `if / else if / else` structure.
Use `break` to end a `case`. Mix exits from a `case` and returns from the
function only when there is a reason for both.
## Functions, types and abstractions
- Use `static` for file-local functions and data in `.cpp` files. Avoid anonymous
namespaces for these declarations.
- A short function alone does not warrant `inline`. The compiler can choose to
inline functions in a `.cpp` file without it. In headers, consider the One
Definition Rule (ODR) and how the function is defined.
- `this->` is optional. Add it only when needed, for example to resolve a name
conflict.
- A small function called by a single task can be inlined into its callback.
Keep a substantial reusable algorithm in its own function.
- Usually write a callback used only once as a lambda where it is registered.
An `onDone` handler shared by several tasks can be a separate `static` function.
- Never declare lambdas or callbacks in the header of an `if`, `for` or `while`
statement. Make the call that takes the callback in a separate statement,
then test its result in the condition.
- Avoid adding a wrapper, class, file, dispatcher or table solely for
structure. Use `constexpr`, templates, inheritance and containers when they
provide a concrete benefit.
- Use `const` for data that stays unchanged. Use `auto` when the call makes the
type clear. Spell out the type when it clarifies the data format or units.
- Choose types to match the data. Use fixed-width types for binary protocol
fields and `gpio_num_t` for GPIO. Avoid dynamic allocation where a value suffices.
- Avoid `std::move` on a plain `float` and unnecessary ownership complexity.
- Reuse state, validation and parsing already provided by the library,
`settings` or `vars`. Use a separate flag only for a distinct state.
- Conserve flash and heap. Reuse shared strings from `strings.h`, minimize
unnecessary copies and avoid frequent allocations. Justify any growth in
dynamic buffers and bound it to what the task requires.
## Writing tasks
- Introduce each independent block that adds tasks to a manager with a short
English comment explaining its purpose.
- Put simple enabling conditions such as feature support, sensor availability
and device readiness in `setEnabledWhen`, unless there is a specific reason
to check them inside the body. Avoid duplicating a check in both places by
default.
- Recheck a state if it could have changed during a blocking operation or if it
determines when a sequence ends.
- Configure the period with `setInterval`. Avoid a second manual timer for the
same rate limit. The time of a successful response or a lost connection may
have a separate purpose and can be tracked independently.
- Use `resume(delay)` deliberately. A task interval and a delayed resume serve
different purposes. Check the behavior of the library version in use.
- In the Mycila version used here, `forceRun()` bypasses `setEnabledWhen`. When
running a task conditionally in ONCE mode, account for its pause/resume behavior.
Use a suitable call such as `resume().tryRun()` or check the conditions
explicitly.
```cpp
if (readModulationTask.idle() && readModulationTask.enabled()) {
readModulationTask.forceRun();
}
```
- Use manual arbitration, step arrays or a priority system only when a
sequential manager, intervals and predicates are insufficient.
- For ordinary requests within OpenTherm tasks, use straightforward synchronous
code. Avoid replacing it with callback chains and a large `switch` solely for
asynchrony when this has no effect on performance.
- Modify a task through its mutable object. The `const Mycila::Task&` parameter
of `onDone` cannot be used to call the non-const `setInterval` method.
Changes to task periods, operation order or device control conditions require
justification beyond readability.
## Messages and logging
- Use the existing typed Message wrappers to construct and parse data. Avoid
assembling raw data by hand only to wrap it immediately in the matching type.
- A wrapper implements the behavior of its format or ID. Use `Float::get()`.
Repeating its type in `Float::getFloat()` adds no information.
- Keep raw data accessible for low-level operations and logging. Avoid adding
an automatic subclass factory, a `variant` or polymorphic dispatch if callers
still select the format manually and the change offers no other benefit.
- Distinguish a communication error from a mismatch in acknowledged data. For
a mismatch, report both the expected and the received value.
- Extract a repeated message format into a shared string or constant. Match the
format specifiers to the actual argument types.
- Store values needed by the rest of the project in the corresponding `vars`
fields. Preserve the order of storing and checking the response when
restructuring a branch for readability.
- Choose `float` comparison tolerances based on the physical quantity. When the
logic requires an exact match of transmitted data, compare the encoded
representations where appropriate.
- Keep passwords, tokens, secrets and private configuration data out of
diagnostic messages.
## Examples, web code and documentation
- Show the simplest normal way to use the API in examples. Avoid hidden
mechanisms, manual counters, waiting flags and implicit call-order
requirements if the library already provides what is needed.
- Explain non-obvious result checks such as the need for `hasFrame()` in a
status handler that can complete without receiving a frame.
- In examples such as TransparentProxy that configure GPIOs through build
flags, guard default values with `#ifndef`. Indent nested directives.
```cpp
#ifndef BOILER_RX_GPIO
#define BOILER_RX_GPIO GPIO_NUM_35
#endif
```
- Keep assumptions specific to a demonstration out of production code, such
as an unconditional `Serial.printf` inside a callback.
- Format HTML, CSS and JavaScript for readability and follow the indentation
of the surrounding file. The build handles minification. The same rules for
braces and separation of logical blocks apply to JavaScript.
- Use `textContent`/`setTextValue` for untrusted text. Insert HTML only when
the content requires it and you have accounted for the origin of the data.
- Preserve struct field order during serialization and deserialization.
- Write the main README and code comments in English. Keep the Russian README
in a separate document. When editing either language version of `AGENTS.md`
or `CODESTYLE.md`, update its translation in the same change. Project working
notes may be in Russian.
## Before finishing an edit
- Check the changed section against the surrounding code and the user's latest
instructions.
- Check indentation, blank lines, line breaks in method chains, comments and
line endings.
- Remove accidental formatting changes outside the area you edited.
- Verify that shortening the code preserved the order of operations and all
required branches.
- Add rules, abstractions and exceptions only when the task calls for them.