mirror of
https://github.com/Laxilef/OTGateway.git
synced 2026-12-02 11:13:03 +05:00
docs: add English translations of agent and code style guides
This commit is contained in:
1 parent
a1b133e4d2
commit
5fb4231201
4 files changed
+979
-377
No files matched your search
+222
-208
@@ -1,35 +1,37 @@
|
||||
# Стиль кода OTGateway
|
||||
# OTGateway code style
|
||||
|
||||
Документ задаёт правила оформления и читаемости для всего проекта OTGateway:
|
||||
прошивки, веб-интерфейса, инструментов, примеров и документации. Основной образец
|
||||
C++ — `src/opentherm.cpp`. Существующий код не требуется массово
|
||||
переформатировать: применяй правила к изменяемому участку, если нет явного требования переформатировать весь код в файле.
|
||||
**English** · [Русский](CODESTYLE.RU.md)
|
||||
|
||||
Последнее явное указание пользователя важнее этого документа. В остальных
|
||||
случаях сохраняй стиль окружающего кода и учитывай приведённые ниже исключения.
|
||||
Рабочие процедуры описаны в `AGENTS.md`, особенности алгоритмов и совместимости
|
||||
OpenTherm — в коде, спецификации и `agent-notes/`. Изменение оформления само по
|
||||
себе не является основанием менять поведение.
|
||||
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.
|
||||
|
||||
- Используй два пробела на уровень вложенности, без табуляции.
|
||||
- Сохраняй UTF-8 и существующие окончания строк. В `src/opentherm.cpp` — CRLF.
|
||||
Проверяй, что кириллица в документации и строках не повредилась при записи.
|
||||
- Открывающая `{` находится на строке объявления или управляющей конструкции.
|
||||
- У `if`, `else`, `while`, `for` и других блоков обязательны фигурные скобки,
|
||||
даже если внутри одно действие. Это относится и к JavaScript.
|
||||
- После `if`, `while`, `for`, `switch` ставь пробел перед `(`; между именем
|
||||
функции и `(` пробела нет.
|
||||
- Оформляй `*` и `&` по окружающему коду. В новых фрагментах `opentherm.cpp`
|
||||
используются, например, `const uint8_t* buffer` и `const auto& config`.
|
||||
Не вводи ради этого массовую правку существующих объявлений.
|
||||
- Не оставляй пробелы в конце строк; файл заканчивается переводом строки.
|
||||
- Не вводи произвольный жёсткий лимит длины строки. Переноси выражения по смыслу,
|
||||
когда строка становится трудной для чтения.
|
||||
## Basic formatting
|
||||
|
||||
В проекте принято отделять следующую ветку условного блока пустой строкой,
|
||||
сохраняя `} else` на одной строке:
|
||||
- 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()) {
|
||||
@@ -43,18 +45,18 @@ if (response.isSuccess()) {
|
||||
}
|
||||
```
|
||||
|
||||
## Пустые строки и комментарии
|
||||
## Blank lines and comments
|
||||
|
||||
- Разделяй самостоятельные смысловые блоки пустой строкой, в том числе два
|
||||
соседних блока настройки задач.
|
||||
- Перед комментарием, начинающим новый смысловой блок, нужна пустая строка.
|
||||
Исключение: комментарий стоит первым сразу после открывающей `{`.
|
||||
- Между комментарием и относящимся к нему кодом пустая строка не нужна.
|
||||
- Новые комментарии к коду пиши на английском. Объясняй причину, ограничение
|
||||
или неочевидное действие; не пересказывай очевидное присваивание.
|
||||
- Не удаляй комментарии о совместимости с устройствами при упрощении кода.
|
||||
- В примерах для начинающих поясняй назначение существенных вызовов API,
|
||||
даже если опытному разработчику они понятны.
|
||||
- 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()) {
|
||||
@@ -66,11 +68,11 @@ if (response.isSuccess()) {
|
||||
}
|
||||
```
|
||||
|
||||
## Переносы строк и цепочки методов
|
||||
## 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(
|
||||
@@ -79,9 +81,9 @@ ESP_LOGI(
|
||||
);
|
||||
```
|
||||
|
||||
В обычной цепочке настройки задачи первый метод начинается на строке переменной.
|
||||
Следующие методы — с новой строки и дополнительным отступом. Используй
|
||||
возвращаемую ссылку `Task&`, чтобы не повторять имя задачи:
|
||||
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.
|
||||
@@ -94,7 +96,7 @@ readDhwBurnerHoursTask.setInterval(60000)
|
||||
openthermTaskManager.addTask(readDhwBurnerHoursTask);
|
||||
```
|
||||
|
||||
Одиночный вызов не оформляй как цепочку с отдельно стоящим именем переменной:
|
||||
Keep the variable and method together for a single call.
|
||||
|
||||
```cpp
|
||||
initializeSlaveTask.setEnabledWhen([] {
|
||||
@@ -102,8 +104,8 @@ initializeSlaveTask.setEnabledWhen([] {
|
||||
});
|
||||
```
|
||||
|
||||
Для сложных построителей отдельно согласовано оформление с именем
|
||||
объекта на собственной строке. Сохраняй его при работе с такой цепочкой:
|
||||
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
|
||||
@@ -118,27 +120,26 @@ request
|
||||
.setDhwBlocking(dhwBlocking);
|
||||
```
|
||||
|
||||
Не считай это общим требованием переносить имя объекта перед любой цепочкой.
|
||||
В многострочных логических условиях ставь `&&` и `||` в начале строки
|
||||
продолжения. Для `if`/`else if` отступ продолжения — четыре пробела
|
||||
от начала исходной строки. Если первый операнд уже вынесен на отдельную строку
|
||||
внутри аргумента вызова или группы в скобках, следующие строки с `&&`/`||`
|
||||
выравнивай по нему без дополнительных
|
||||
двух пробелов. Группируй связанные условия скобками и не меняй их порядок
|
||||
или приоритет ради выравнивания.
|
||||
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.
|
||||
|
||||
В многострочных `return` ставь `&&` и `||` в конце предыдущей строки,
|
||||
а продолжение выравнивай под началом выражения после `return`.
|
||||
Во вложенных группах также выравнивай операнды по первому выражению группы.
|
||||
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) {
|
||||
@@ -162,40 +163,41 @@ if (prevSettings && Sensors::hasEnabledAndValid(*prevSettings)
|
||||
}
|
||||
```
|
||||
|
||||
## Имена и структура файлов
|
||||
## Names and file structure
|
||||
|
||||
| Элемент | Принятый вид |
|
||||
| Element | Convention |
|
||||
| --- | --- |
|
||||
| Функции, методы, переменные, поля | `camelCase`: `readPressure`, `targetTemp` |
|
||||
| Классы и структуры | `PascalCase`: `Message`, `Config`, `Float` |
|
||||
| Задачи | Действие + предмет + `Task`: `writeRoomSetpointTask` |
|
||||
| Менеджеры | Назначение + `TaskManager`: `openthermTaskManager` |
|
||||
| Логические предикаты | По смыслу: `isSlaveReady`, `canUseBus`, `needWriteRoomSetpoint` |
|
||||
| Макросы и значения обычных перечислений | `UPPER_SNAKE_CASE` по принятому API |
|
||||
| Идентификаторы OpenTherm | Согласованное имя из API/спецификации: `TSet`, `Tr`, `TsetCH2` |
|
||||
| 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` |
|
||||
|
||||
- Чтение ID обозначай префиксом `read`, запись — `write`. Если выделена функция,
|
||||
её имя должно соответствовать задаче: `writeRoomSetpointTask` вызывает
|
||||
`writeRoomSetpoint`, а не `setRoomSetpoint`.
|
||||
- `get` уместен для получения уже имеющихся данных, например `Float::get()`.
|
||||
Имя должно давать понять, выполняется ли обмен с устройством.
|
||||
- Давай имена по смыслу данных. Различай комнатную температуру, температуру
|
||||
теплоносителя, уставку, фактическое состояние и передаваемый флаг.
|
||||
- Для GPIO используй `gpio`, направления — `rx` и `tx`: `rxGpio`, `txGpio`.
|
||||
Тип номера GPIO ESP32 — `gpio_num_t`.
|
||||
- Не добавляй избыточный контекст к имени внутри уже понятного namespace:
|
||||
`Config`, а не `WorkerConfig`, если это общая конфигурация объекта.
|
||||
- Для общей отправки сообщения используй согласованный термин `sendMessage`.
|
||||
Не возвращай неясные `exchange` и `submit` в этот API.
|
||||
- Не вводи служебные `Kind`, лишние псевдонимы и сокращения без понятной задачи.
|
||||
- Имена модулей проекта сохраняй в существующем виде: `opentherm.cpp`,
|
||||
`network.cpp`, `logging.cpp`; заголовки классов — по стилю соответствующего модуля.
|
||||
- Группируй связанные типы осмысленными namespace и каталогами с заглавной буквы:
|
||||
`ESP32OT::Messages`, `Messages/Float.h`.
|
||||
Часто используемые общие типы не прячь без необходимости глубже:
|
||||
`ESP32OT::MessageID::TSet`.
|
||||
- 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`.
|
||||
|
||||
Внутри namespace тоже нужен отступ:
|
||||
Indent declarations inside namespaces too.
|
||||
|
||||
```cpp
|
||||
namespace ESP32OT {
|
||||
@@ -205,13 +207,12 @@ namespace ESP32OT {
|
||||
}
|
||||
```
|
||||
|
||||
Выравнивай колонки длинных перечислений и таблиц констант по окружающему коду.
|
||||
Не добавляй дублирующие значения перечислений ради короткого синонима.
|
||||
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()) {
|
||||
@@ -232,13 +233,12 @@ if (response.getData() != request.getData()) {
|
||||
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.
|
||||
|
||||
Вложенность уместна, когда она показывает настоящую зависимость операций.
|
||||
Например, ошибка необязательной записи `MaxTSet` не должна отменять следующую
|
||||
обязательную запись `TSet`:
|
||||
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) {
|
||||
@@ -256,105 +256,115 @@ if (settings.opentherm.options.maxTempSyncWithTargetTemp) {
|
||||
const auto response = slave.sendRequest(heatingSetpointRequest);
|
||||
```
|
||||
|
||||
Общее присваивание перед проверкой echo можно сохранить и в линейном коде
|
||||
с ранними выходами; само по себе оно не требует дополнительной вложенности.
|
||||
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.
|
||||
|
||||
- Не заменяй все условия одним шаблоном автоматически. Выбирай структуру,
|
||||
которая ясно показывает зависимости и сохраняет побочные эффекты.
|
||||
- Предпочитай обычный `while` конструкции `for (; condition; ...)`.
|
||||
- Не строй большие `switch` для ручной диспетчеризации ID или шагов, если
|
||||
операции естественно выражаются отдельными задачами.
|
||||
- В небольших учебных примерах, например Slave, `switch` по ID уместен.
|
||||
Ветви одного уровня оформляй одинаково: `if / else if / else`, с `break`
|
||||
для завершения `case`. Не смешивай без причины выход из `case` и всей функции.
|
||||
- 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
|
||||
|
||||
- Для локальных функций и данных `.cpp` используй `static`, а не анонимный namespace.
|
||||
- Не добавляй `inline` только потому, что функция короткая. В `.cpp` это не нужно
|
||||
для выбора оптимизации компилятором; в заголовках учитывай ODR и способ определения.
|
||||
- `this->` необязателен. Не добавляй без необходимости (конфликтов).
|
||||
- Небольшую функцию, вызываемую только одной задачей, можно встроить в callback.
|
||||
Содержательный повторно используемый алгоритм оставляй отдельной функцией.
|
||||
- Callback, используемый один раз, обычно записывай лямбдой на месте регистрации.
|
||||
Общий `onDone` нескольких задач может быть отдельной `static` функцией.
|
||||
- Никогда не объявляй лямбды и callbacks в заголовках `if`, `for`, `while`.
|
||||
Вызов с callback записывай отдельным выражением; в условии проверяй результат.
|
||||
- Не создавай обёртку, класс, файл, диспетчер или таблицу только ради структуры.
|
||||
`constexpr`, шаблоны, наследование и контейнеры должны давать конкретную пользу.
|
||||
- Используй `const` для неизменяемых данных. `auto` подходит, когда тип очевиден
|
||||
из вызова; явный тип нужен там, где он поясняет формат или единицы данных.
|
||||
- Выбирай тип по данным: фиксированную разрядность для бинарных полей протокола,
|
||||
`gpio_num_t` для GPIO. Не вводи динамическое выделение там, где хватает значения.
|
||||
- Не применяй `std::move` к обычному `float` и не усложняй владение без причины.
|
||||
- Не дублируй состояние, проверки и парсинг, уже представленные в библиотеке,
|
||||
`settings` или `vars`. Отдельный флаг нужен только для отдельного состояния.
|
||||
- Сохраняй экономное использование flash и heap: общие строки в `strings.h`,
|
||||
минимум лишних копий и частых выделений памяти. Рост динамических буферов
|
||||
должен быть обоснован и ограничен по потребностям задачи.
|
||||
- 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
|
||||
|
||||
- Перед каждым самостоятельным блоком добавления задач в менеджер пиши короткий
|
||||
английский комментарий о назначении блока.
|
||||
- Простые условия включения — поддержка функции, наличие датчика, готовность
|
||||
устройства — размещай в `setEnabledWhen`, если нет отдельной причины проверять
|
||||
их внутри тела. Не дублируй одно и то же условие механически в двух местах.
|
||||
- Повторная проверка состояния оправдана, если оно могло измениться во время
|
||||
блокирующей операции или определяет завершение последовательности.
|
||||
- Настраивай период через `setInterval`. Не добавляй второй ручной таймер для
|
||||
того же ограничения частоты. Время успешного ответа или потери связи может
|
||||
иметь самостоятельный смысл и не является таким дублем.
|
||||
- Не добавляй `resume(delay)` по шаблону: период задачи и отложенное возобновление
|
||||
имеют разное назначение. Проверяй семантику используемой версии библиотеки.
|
||||
- Не рассчитывай, что `forceRun()` проверяет `setEnabledWhen`: в используемой
|
||||
Mycila он обходит условия. Для условного запуска ONCE нужен корректный вызов
|
||||
с учётом её pause/resume, например `resume().tryRun()` или явная проверка:
|
||||
- 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();
|
||||
}
|
||||
```
|
||||
- Не вводи ручной арбитраж, массивы шагов или систему приоритетов, когда достаточно
|
||||
последовательного менеджера, интервалов и предикатов.
|
||||
- Для обычных запросов внутри OpenTherm-задач используй понятный синхронный код.
|
||||
Не превращай его в цепочки callback с большим `switch` только ради асинхронности, если это не влияет на производительность.
|
||||
- Изменяй задачу через её изменяемый объект. Параметр `const Mycila::Task&`
|
||||
в `onDone` нельзя использовать для вызова неконстантного `setInterval`.
|
||||
- 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
|
||||
|
||||
- Используй готовые типизированные Message-обёртки для сборки и разбора данных.
|
||||
Не собирай raw вручную, чтобы затем сразу завернуть его в подходящий тип.
|
||||
- Обёртка содержит функциональность своего формата/ID. Избыточное уточнение типа
|
||||
в методе не нужно: `Float::get()`, а не `Float::getFloat()`.
|
||||
- Доступ к raw сохраняй для низкоуровневой работы и логирования. Не создавай
|
||||
автоматическую фабрику подклассов, `variant` или полиморфную диспетчеризацию,
|
||||
если вызывающий код всё равно вручную выбирает формат и это не даёт другой пользы.
|
||||
- Различай ошибку обмена и несовпадение подтверждённых данных. Для mismatch
|
||||
используй понятный текст с ожидаемым и полученным значениями.
|
||||
- Общий формат повторяющегося сообщения выноси в общую строку/константу.
|
||||
Форматные спецификаторы должны соответствовать фактическим типам аргументов.
|
||||
- Значения, нужные остальному проекту, сохраняй в соответствующих полях `vars`.
|
||||
Не меняй порядок сохранения и проверки ответа только ради красивой ветки.
|
||||
- При сравнении `float` выбирай допуск по физическому смыслу величины. Если
|
||||
требуется точное совпадение переданных данных, используй их кодированное
|
||||
представление, когда это предусмотрено логикой.
|
||||
- Не помещай пароли, токены, секреты и приватные конфигурации в диагностические сообщения.
|
||||
- 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
|
||||
|
||||
- Примеры показывают простой основной путь использования API. Избегай служебной
|
||||
«магии», ручных счётчиков, флагов ожидания и скрытых требований к порядку вызовов,
|
||||
если библиотека уже предоставляет нужный механизм.
|
||||
- Поясняй неочевидные проверки результата, например зачем нужен `hasFrame()`
|
||||
в обработчике статусов, допускающем завершение без принятого кадра.
|
||||
- В примерах с GPIO-настройками через build flags, как TransparentProxy,
|
||||
используй защищённые `#ifndef` значения по умолчанию. Вложенные директивы
|
||||
оформляй с отступом:
|
||||
- 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
|
||||
@@ -362,22 +372,26 @@ const auto response = slave.sendRequest(heatingSetpointRequest);
|
||||
#endif
|
||||
```
|
||||
|
||||
- Не переноси в основной код предположения, допустимые только в демонстрации,
|
||||
например безусловный `Serial.printf` из callback.
|
||||
- HTML, CSS и JavaScript оформляй читаемо с отступами окружающего файла;
|
||||
минификация выполняется при сборке. Для JS действуют те же требования к скобкам
|
||||
и смысловому разделению блоков.
|
||||
- Для недоверенного текста используй `textContent`/`setTextValue`. Вставка HTML
|
||||
должна быть необходима по смыслу и учитывать происхождение данных.
|
||||
- Сохраняй порядок полей структур в сериализации и обратном преобразовании.
|
||||
- Основной README и комментарии — на английском, русская версия README —
|
||||
отдельный документ. Этот CODESTYLE и рабочие заметки проекта могут быть
|
||||
на русском.
|
||||
- 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.
|
||||
Reference in new issue
Block a user