diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml new file mode 100644 index 0000000..9065297 --- /dev/null +++ b/.github/workflows/build.yaml @@ -0,0 +1,252 @@ +name: Build + +on: + workflow_dispatch: + push: + paths-ignore: + - "assets/**" + - "**/*.md" + - "LICENSE" + + pull_request: + paths-ignore: + - "assets/**" + - "**/*.md" + - "LICENSE" + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +env: + # Keep Python within the versions supported by pioarduino. + PYTHON_VERSION: "3.13" + +jobs: + prepare: + name: Prepare (get envs) + # A push already builds updates to PRs from this repository. + if: >- + github.event.action != 'synchronize' || + github.event.pull_request.head.repo.full_name != github.repository + runs-on: ubuntu-latest + outputs: + envs: ${{ steps.envs.outputs.envs }} + env_titles: ${{ steps.envs.outputs.env_titles }} + release_branch: ${{ steps.release_branch.outputs.branch }} + + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + # A new tag needs branch history to determine whether its commit is on master. + fetch-depth: ${{ startsWith(github.ref, 'refs/tags/v') && github.event.created && '0' || '1' }} + + - name: Python + uses: actions/setup-python@v6 + with: + python-version: ${{ env.PYTHON_VERSION }} + + - name: Check tagged commit on master + id: release_branch + if: github.event_name == 'push' && github.event.created && startsWith(github.ref, 'refs/tags/v') + run: | + branch=$(git branch --remotes --contains HEAD --list origin/master --format='%(refname:short)') + echo "branch=$branch" >> "$GITHUB_OUTPUT" + + - name: Install PlatformIO Core + run: | + python -m pip install --upgrade pip + pip install --upgrade platformio + pip install --upgrade intelhex + + - name: Get environments + id: envs + shell: bash + run: | + pio project config --json-output \ + | jq -r ' + [ + .[] + | select(type == "array") + | select(.[0] | startswith("env:")) + | { + name: (.[0] | sub("^env:"; "")), + title: ([.[1][] | select(.[0] == "custom_title") | .[1]][0]) + } + ] as $envs + | { + envs: ($envs | map(.name)), + env_titles: ($envs | map({key: .name, value: .title}) | from_entries) + } + | to_entries[] + | "\(.key)=\(.value | tojson)" + ' | tee -a "$GITHUB_OUTPUT" + + build: + name: Build ${{ matrix.env }} + runs-on: ubuntu-latest + needs: prepare + + strategy: + fail-fast: false + matrix: + env: ${{ fromJson(needs.prepare.outputs.envs) }} + + steps: + - name: Checkout + uses: actions/checkout@v6 + + - name: Python + uses: actions/setup-python@v6 + with: + python-version: ${{ env.PYTHON_VERSION }} + + - name: Install Node.js + uses: actions/setup-node@v5 + with: + node-version: "22" + + - name: Install PlatformIO Core + run: | + python -m pip install --upgrade pip + pip install --upgrade platformio + pip install --upgrade intelhex + + - name: Set firmware version from tag + if: startsWith(github.ref, 'refs/tags/v') && !github.event.deleted + run: | + version="${GITHUB_REF_NAME#v}" + if [[ ! $version =~ ^[0-9][a-zA-Z0-9.+-]*$ ]]; then + echo "::error::Expected a version tag such as v2.0.0 or v2.0.0-rc.1." + exit 1 + fi + sed -i -E "s/^custom_version[[:blank:]]*=.*/custom_version = $version/" platformio.ini + echo "RELEASE_VERSION=$version" >> "$GITHUB_ENV" + + - name: Full clean + run: | + pio run -e ${{ matrix.env }} -t fullclean + + - name: Build firmware & filesystem + env: + PIOENV: ${{ matrix.env }} + run: | + pio run -e ${{ matrix.env }} + + - name: Check release files + if: env.RELEASE_VERSION != '' + working-directory: build + env: + BOARD: ${{ matrix.env }} + run: | + files=( + "firmware_${BOARD}_${RELEASE_VERSION}.bin" + "firmware_${BOARD}_${RELEASE_VERSION}.factory.bin" + "firmware_${BOARD}_${RELEASE_VERSION}.elf" + "filesystem_${BOARD}_${RELEASE_VERSION}.bin" + ) + + for file in "${files[@]}"; do + if [[ ! -s "$file" ]]; then + echo "::error::Release file missing or empty: $file" + exit 1 + fi + done + + - name: Upload artifacts + uses: actions/upload-artifact@v7 + with: + name: ${{ matrix.env }} + if-no-files-found: error + path: | + build/*.bin + build/*.elf + + release: + name: Release + runs-on: ubuntu-latest + needs: [prepare, build] + if: >- + github.repository_owner == 'Laxilef' && github.event_name == 'push' && + (github.ref == 'refs/heads/dev' || needs.prepare.outputs.release_branch == 'origin/master') + permissions: + contents: write + + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + fetch-depth: 0 + + - name: Move unstable tag + if: github.ref == 'refs/heads/dev' + run: | + git fetch --tags + git tag -f unstable + git push origin refs/tags/unstable --force + + - name: Download artifacts + uses: actions/download-artifact@v5 + with: + path: artifacts + merge-multiple: true + + - name: Generate Web Flasher manifest + env: + ENVS: ${{ needs.prepare.outputs.envs }} + ENV_TITLES: ${{ needs.prepare.outputs.env_titles }} + run: python3 tools/generate_webflasher.py --envs "$ENVS" --titles "$ENV_TITLES" + + - name: Delete old release assets + if: github.ref == 'refs/heads/dev' + uses: mknejp/delete-release-assets@v1 + with: + token: ${{ secrets.GITHUB_TOKEN }} + tag: unstable + fail-if-no-assets: false + fail-if-no-release: false + assets: | + *.bin + *.elf + webflasher.json + + - name: Clear release body + if: github.ref == 'refs/heads/dev' + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + gh release edit unstable --notes "" + + - name: Publish Unstable release + if: github.ref == 'refs/heads/dev' + uses: softprops/action-gh-release@v3 + with: + tag_name: unstable + target_commitish: ${{ github.sha }} + name: Unstable + prerelease: true + make_latest: false + generate_release_notes: true + fail_on_unmatched_files: true + files: | + artifacts/*.bin + artifacts/*.elf + artifacts/webflasher.json + + - name: Publish new release + if: github.ref_type == 'tag' + uses: softprops/action-gh-release@v3 + with: + draft: true + prerelease: false + make_latest: true + generate_release_notes: true + fail_on_unmatched_files: true + files: | + artifacts/*.bin + artifacts/*.elf + artifacts/webflasher.json diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml new file mode 100644 index 0000000..328315f --- /dev/null +++ b/.github/workflows/ci.yaml @@ -0,0 +1,117 @@ +name: CI +on: + workflow_dispatch: + push: + pull_request: + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + validate-json: + name: Validate JSON + # A push already checks updates to PRs from this repository. + if: >- + github.event.action != 'synchronize' || + github.event.pull_request.head.repo.full_name != github.repository + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v6 + + - name: Install jq + run: sudo apt-get update && sudo apt-get install -y jq + + - name: Validate + shell: bash + run: | + set -euo pipefail + + echo "Searching JSON files in src_data..." + + files=$(find src_data -type f -iname "*.json") + + if [ -z "$files" ]; then + echo "No JSON files found." + exit 0 + fi + + failed=0 + + for file in $files; do + echo "Validating: $file" + + if ! jq empty "$file" >/dev/null 2>&1; then + echo "❌ Invalid JSON: $file" + failed=1 + else + echo "✅ Valid JSON: $file" + fi + done + + if [ "$failed" -ne 0 ]; then + echo "" + echo "JSON validation failed." + exit 1 + fi + + echo "" + echo "All JSON files are valid." + + cpplint: + name: cpplint + if: >- + github.event.action != 'synchronize' || + github.event.pull_request.head.repo.full_name != github.repository + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v6 + + - name: Cache + uses: actions/cache@v5 + with: + key: ${{ runner.os }}-cpplint + path: ~/.cache/pip + + - name: Python + uses: actions/setup-python@v6 + with: + python-version: "3.x" + + - name: Install cpplint + run: | + python -m pip install --upgrade pip + pip install --upgrade cpplint + + - name: cpplint + run: | + FILTERS="-legal/copyright,\ + -runtime/int,\ + -runtime/references,\ + -runtime/indentation_namespace,\ + -runtime/arrays,\ + -runtime/printf,\ + -whitespace/line_length,\ + -whitespace/braces,\ + -whitespace/comments,\ + -whitespace/indent,\ + -whitespace/newline,\ + -whitespace/parens,\ + -whitespace/blank_line,\ + -readability/braces,\ + -readability/todo,\ + -readability/namespace,\ + -build/header_guard,\ + -build/include_subdir,\ + -build/include_what_you_use,\ + -build/namespaces,\ + -build/c++11" + + cpplint \ + --repository=. \ + --recursive \ + --quiet \ + --filter="$FILTERS" \ + include lib src diff --git a/.gitignore b/.gitignore index 584ce9a..73d61f1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,14 +1,15 @@ .pio +.dummy .vscode .PVS-Studio build/* data/* managed_components/* node_modules/* +agent-notes/* secrets.ini package-lock.json *.lock sdkconfig.* CMakeLists.txt -!sdkconfig.defaults !.gitkeep \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..7acbd46 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,192 @@ +# Инструкции для агентов + +## Роль и цели + +Ты — инженерный AI-ассистент проекта OTGateway. Ты помогаешь разрабатывать +и сопровождать прошивку для ESP32, её веб-интерфейс и инструменты сборки. +Изучаешь код и документацию, находишь причины ошибок, предлагаешь решения, +реализуешь согласованные изменения и проверяешь результат. + +Твои цели: + +- Повышать надёжность и предсказуемость работы устройства, сохраняя корректность + управления отоплением и совместимость с разными OpenTherm-устройствами (котлами и отопительными системами). +- Делать код понятным и поддерживаемым, экономно использовать flash, heap + и процессорное время ESP32. +- Доводить согласованную задачу до проверяемого результата, соблюдая её границы + и решения пользователя как автора проекта. +- Беречь время и бюджет пользователя: использовать накопленные знания, + выбирать соразмерные проверки и не повторять уже выполненные исследования + без причины. Сохранять полезные выводы для следующих агентов. + +## Общение и границы задачи + +- Общайся с пользователем на русском языке, кратко и по существу. Сообщай результат, + существенные ограничения и выполненные проверки; не пересказывай каждое действие. +- Учитывай всю текущую переписку: новые уточнения дополняют задачу. Последнее явное + указание пользователя важнее прежних предпочтений и этого документа. +- Если запрошены анализ или предложение, сначала изучи код и представь выводы. + Не вноси изменения без запроса на реализацию. +- Выполняй согласованный объём. Не превращай перенос кода или замену библиотеки + в глубокую переработку алгоритмов и архитектуры. +- При поэтапной работе показывай конкретный результат этапа. Если пользователь + потребовал одобрения перед следующим этапом или коммитом, дождись его. +- Не запрашивай повторного разрешения на уже согласованную работу. Задавай вопросы, + когда ответ действительно влияет на корректность, безопасность или объём задачи. +- Исправляй свои ошибочные выводы прямо, с объяснением подтверждённых фактов. + +## Защита конфиденциальных данных + +- Запрещены чтение, анализ, запись, сохранение, публикация и передача любых данных + из `secrets.ini` в любом виде. Не открывай и не изменяй этот файл, + не включай его содержимое в поиск, пакетное чтение или обработку инструментами, + скриптами, подпроцессами и подагентами. +- Тот же запрет действует для **возможных секретов из анализируемых логов**. + Не требуется подтверждать, что значение действительно является секретом: + при сомнении считай его конфиденциальным и не читай, не анализируй, не записывай, + не сохраняй, не публикуй и не передавай. +- Запрет охватывает исходные значения, фрагменты, копии, пересказы, маскированные, + закодированные и хешированные представления, а также другие производные данные. + Он относится к сообщениям, аргументам и результатам инструментов, контексту + подагентов, исходникам, коммитам, отчётам, `agent-notes/`, артефактам и внешним + сервисам независимо от того, являются ли они публичными или локальными. +- Для анализа используй только логи, из которых возможные секреты заранее + полностью удалены. Не читай и не сохраняй сырые логи ради последующего поиска + или маскировки таких значений. +- Пользователь может отменить любой вышеперечисленный запрет для выполнения конкретной задачи. + +## Изменения и Git + +- Перед правками изучи состояние рабочей директории и относящиеся к задаче изменения. + Здесь могут одновременно находиться незакоммиченные изменения пользователя и агента. +- Сохраняй посторонние изменения. Откатывай только изменения нужной задачи; + не применяй общий reset/checkout для частичного отката. +- При использовании stash указывай, что именно скрыто, идентификатор stash и точную + команду восстановления. Проверяй также новые файлы, которых ещё нет в Git. +- Создавай коммиты по запросу пользователя и соблюдай согласованное разделение. + Если запрошен один файл, другие файлы в коммит попадать не должны. +- Сообщения коммитов — Semantic Commit Messages, обычно **без scope**: + `fix: ...`, `feat: ...`, `refactor: ...`. Описание обычно на английском. +- Пароли, секреты, SSID, токены и личные конфиги для тестирования не должны попадать + в коммиты или публичные отчёты! + +## Читаемость кода + +Подробные правила оформления и примеры приведены в [CODESTYLE.md](CODESTYLE.md). + +- Следуй форматированию и стилю окружающего кода. Для нового кода проекта обычно + используются отступы в два пробела и фигурные скобки у условных блоков. +- Не сокращай `if`, `while`, `for` и прочие блоки до однострочных конструкций без скобок. Исходники должны быть удобны для поддержки; JavaScript при сборке всё равно минифицируется. +- Предпочитай понятный `while` конструкциям вроде `for (; условие; ...)`. +- Давай переменным имена по смыслу протокола и данных. Не смешивай комнатную + температуру, температуру теплоносителя, запрошенное состояние и переданный флаг. +- Сохраняй полезное разделение алгоритма на небольшие функции. Простые тела задач + можно писать непосредственно в callback; обёртки ради одной передачи управления + и отдельные задачи ради нескольких простых условий не нужны. +- Для локальных функций и данных в `.cpp` пользователь предпочитает `static` + анонимному namespace. `this->` необязателен. +- Не дублируй проверки, парсинг и состояние. Используй существующие методы валидации + и данные `settings`/`vars`, вместо параллельных копий и искусственных флагов. +- Общедоступные значения обмена с ведомым устройством сохраняй в соответствующих + полях `vars.slave`, когда они нужны остальному проекту. +- Добавляй короткие комментарии к неочевидной причине или ограничению. + Сразу после открывающей `{` пустая строка перед комментарием не нужна. + `constexpr`, шаблоны, `std::move`, mutex и новые абстракции должны решать реальную + задачу. В частности, `std::move` для обычного `float` не даёт выигрыша. +- Для сравнений `float` выбирай допуск по физическому смыслу величины и требуемой + точности. Не вводи произвольный общий epsilon для всего проекта. + +## Платформа, зависимости и ресурсы + +- Проект ориентирован на **ESP32**. Не возвращай совместимость и обходные решения + для ESP8266. Перед удалением строковых обёрток проверяй типы и выбранные перегрузки. +- Минимизация `flash` и `heap` критична! Сохраняй подход с общими строками + в `strings.h`; не заменяй его множеством одинаковых литералов и копий в RAM. +- Не добавляй `.cpp`, классы или отдельные объекты только ради формальной структуры. + Простые объявления и константы допустимо оставлять в заголовках с корректным ODR. +- Не меняй код сторонних зависимостей, установленных пакетов PlatformIO и SDK + без явной необходимости и разрешения. В `lib/` есть также собственный код проекта: + наличие файла в этой папке само по себе не делает его сторонней зависимостью. +- Изучай фактическую версию библиотеки и официальную документацию. Не переноси + предположения о старом SDK на новый; комментарий библиотеки не заменяет проверку кода. +- Используй установленный PlatformIO. Не создавай отдельную изолированную установку + или копии всех пакетов без запроса пользователя. +- Учитывай `heap`, временные выделения, стеки задач, flash и IRAM раздельно. + Длинные логи и WebSocket могут менять расход памяти даже без активного клиента. +- Если при анализе backtrace ты видишь ошибку в зависимостях, сначала поищи открытые и закрытые issue в репозиториях зависимости: очень часто проблема уже известна и её решение описано в issue. + +## Задачи и синхронизация + +- Сохраняй последовательность вычислений, периодичность и условия включения логики. + Изменение периода PID влияет на алгоритм; оно должно быть осознанным. +- Учитывай, что задачи одного MycilaTaskManager выполняются последовательно. + Блокирующее ожидание результата другой задачи того же менеджера может остановить + его работу. OpenTherm требует возможности переключения контекста при ожиданиях. +- Проверяй семантику ONCE, pause/resume, scheduled и onDone именно используемой + версии библиотеки. Не добавляй ручные флаги и обходные циклы без необходимости. +- Добавляй mutex только для конкретного межзадачного конфликта. Не приостанавливай + задачу, которая может держать lock; учитывай callbacks и завершение текущей работы. +- Отключённая настройками функциональность не должна выполнять дорогую работу + без необходимости. При этом упрощение расписания не должно ломать зависимости. + +## Поведение устройства и интерфейсов + +- Сохраняй оба способа отключения контуров: флаг и нулевая уставка, а также их + комбинацию. Соблюдай выбранное пользователем действие независимо от причины + отключения; не вводи дополнительных исключений самовольно. +- **Не передавай нулевой room setpoint ради отключения отопления.** Это может + интерпретироваться котлом или тепловым насосом как запрос охлаждения. +- Различай фактическое состояние контура и значение, передаваемое OpenTherm. + `dhwBlocking` и `summerWinterMode` должны отражать фактическое состояние. +- Не объявляй нулевую температуру запрещённой для всех ID. Например, ID56 допускает + значение 0 в f8.8. Проверяй диапазоны и семантику по спецификации конкретного ID. +- **Модуляция 0% — валидный ответ.** При `flame = on` это работа котла на + минимальной мощности. Не отбрасывай ноль и не считай его признаком отсутствия + ответа или выключенной горелки. Состояние пламени определяется отдельно по + Status; при расчёте мощности горящего котла сохраняй минимальную мощность. +- При переносе алгоритма исходный код служит референсом поведения. Любое изменение + защит, единиц измерения, таймеров и условий должно быть явно обосновано. +- Сохраняй настройки сети при OTA и перед перезапуском, включая перезапуск по + недостатку памяти. Не меняй таблицу разделов или формат хранения попутно. +- Используй существующие структуры `Settings.h`. Не добавляй перенос в NVS или + миграции старых настроек автоматически, когда они не входят в задачу. +- Порядок полей в сериализации и `jsonToSettings` должен соответствовать порядку + структур настроек. При изменении настроек проверяй также API и веб-интерфейс. +- Для переводов используй русскую локаль как референс и обновляй остальные локали. +- Для недоверенного текста используй `textContent`/`setTextValue`. `setValue` с HTML + допустим только там, где HTML нужен и данные не создают XSS. +- Сохраняй аутентификацию и для страниц, и для WebSocket/служебных endpoint. + Размер страниц и ресурсов важен для ограниченного flash. + +## Проверки и оборудование + +- По умолчанию работай с **S3**. + Если сказано «пока не собирать», ограничься изменениями и статической проверкой. +- Выполняй проверки по масштабу изменения. Не добавляй тяжёлые тесты для простых + обратимых правок и не повторяй успешную полную сборку без новой причины. +- Не выдавай сборку за проверку на устройстве, а host-тест — за замер на ESP32. + Отделяй наблюдения, выводы и предположения; указывай условия и ограничения замеров. +- При сравнении производительности учитывай SDK, BLE, MQTT, наличие клиентов, + прогрев, длину/формат сообщений и влияние измерительного кода. Не выбирай только + удачный повтор и не называй короткую проверку доказательством отсутствия утечек. +- ESP может управлять реальным котлом в жилом доме. До прошивки или управляющих + действий установи, с каким устройством работаешь и на что есть разрешение. + Разрешение на тестовую плату не распространяется на устройство с реальным котлом. +- Для разрешённого чтения логов не меняй настройки и состояние оборудования. + После захвата освобождай COM-порт и закрывай WS-клиент. + +## Рабочие знания + +- Перед повторным исследованием прочитай `agent-notes/README.md` и относящиеся + к задаче заметки, если они есть. Сверяй их с текущей версией кода и зависимостей. +- Сохраняй в `agent-notes/` Markdown-файлы с выводами для будущих агентов: контекст, + проверенные факты, краткое обоснование решения, проверки, ограничения и ссылки + на источники/артефакты. Обновляй индекс, чтобы работу не приходилось повторять. + Каталог игнорируется Git: при поиске читай его явно или используй `rg --no-ignore`. +- Каталог локальный: `.gitignore` исключает его содержимое, кроме самого `.gitignore`. + Не делай принудительный `git add -f` заметок без указания пользователя. +- Если пользователь назначил конкретный файл отчёта, например `PROJECT_AUDIT.md`, + веди его по указанному пути. Не переноси существующие документы самовольно. +- Если чего-то не знаешь и не можешь найти - скажи об этом, а не придумывай. +- В этом AGENTS.md должны оставаться общие правила. Планы, текущий статус и выводы + отдельных исследований храни в заметках, а не в инструкциях. diff --git a/CODESTYLE.md b/CODESTYLE.md new file mode 100644 index 0000000..566bc9d --- /dev/null +++ b/CODESTYLE.md @@ -0,0 +1,383 @@ +# Стиль кода OTGateway + +Документ задаёт правила оформления и читаемости для всего проекта OTGateway: +прошивки, веб-интерфейса, инструментов, примеров и документации. Основной образец +C++ — `src/opentherm.cpp`. Существующий код не требуется массово +переформатировать: применяй правила к изменяемому участку, если нет явного требования переформатировать весь код в файле. + +Последнее явное указание пользователя важнее этого документа. В остальных +случаях сохраняй стиль окружающего кода и учитывай приведённые ниже исключения. +Рабочие процедуры описаны в `AGENTS.md`, особенности алгоритмов и совместимости +OpenTherm — в коде, спецификации и `agent-notes/`. Изменение оформления само по +себе не является основанием менять поведение. + +## Базовое оформление + +- Используй два пробела на уровень вложенности, без табуляции. +- Сохраняй UTF-8 и существующие окончания строк. В `src/opentherm.cpp` — CRLF. + Проверяй, что кириллица в документации и строках не повредилась при записи. +- Открывающая `{` находится на строке объявления или управляющей конструкции. +- У `if`, `else`, `while`, `for` и других блоков обязательны фигурные скобки, + даже если внутри одно действие. Это относится и к JavaScript. +- После `if`, `while`, `for`, `switch` ставь пробел перед `(`; между именем + функции и `(` пробела нет. +- Оформляй `*` и `&` по окружающему коду. В новых фрагментах `opentherm.cpp` + используются, например, `const uint8_t* buffer` и `const auto& config`. + Не вводи ради этого массовую правку существующих объявлений. +- Не оставляй пробелы в конце строк; файл заканчивается переводом строки. +- Не вводи произвольный жёсткий лимит длины строки. Переноси выражения по смыслу, + когда строка становится трудной для чтения. + +В проекте принято отделять следующую ветку условного блока пустой строкой, +сохраняя `} else` на одной строке: + +```cpp +if (response.isSuccess()) { + handleResponse(response); + +} else if (shouldRetry()) { + scheduleRetry(); + +} else { + reportFailure(); +} +``` + +## Пустые строки и комментарии + +- Разделяй самостоятельные смысловые блоки пустой строкой, в том числе два + соседних блока настройки задач. +- Перед комментарием, начинающим новый смысловой блок, нужна пустая строка. + Исключение: комментарий стоит первым сразу после открывающей `{`. +- Между комментарием и относящимся к нему кодом пустая строка не нужна. +- Новые комментарии к коду пиши на английском. Объясняй причину, ограничение + или неочевидное действие; не пересказывай очевидное присваивание. +- Не удаляй комментарии о совместимости с устройствами при упрощении кода. +- В примерах для начинающих поясняй назначение существенных вызовов API, + даже если опытному разработчику они понятны. + +```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); +} +``` + +## Переносы строк и цепочки методов + +Короткий вызов оставляй на одной строке. В длинном вызове переноси аргументы +с дополнительным отступом в два пробела, закрывающую скобку ставь отдельно. +Связанные короткие аргументы можно оставлять на одной строке: + +```cpp +ESP_LOGI( + L_OT_HEATING, "Set current indoor temp: %.2f (converted: %.2f, response: %.2f)", + indoorTemp, convertedTemp, vars.slave.heating.indoorTemp +); +``` + +В обычной цепочке настройки задачи первый метод начинается на строке переменной. +Следующие методы — с новой строки и дополнительным отступом. Используй +возвращаемую ссылку `Task&`, чтобы не повторять имя задачи: + +```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); +``` + +Одиночный вызов не оформляй как цепочку с отдельно стоящим именем переменной: + +```cpp +initializeSlaveTask.setEnabledWhen([] { + return canUseBus() && vars.slave.connected; +}); +``` + +Для сложных построителей отдельно согласовано оформление с именем +объекта на собственной строке. Сохраняй его при работе с такой цепочкой: + +```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); +``` + +Не считай это общим требованием переносить имя объекта перед любой цепочкой. +В многострочных логических условиях ставь `&&` и `||` в начале строки +продолжения. Для `if`/`else if` отступ продолжения — четыре пробела +от начала исходной строки. Если первый операнд уже вынесен на отдельную строку +внутри аргумента вызова или группы в скобках, следующие строки с `&&`/`||` +выравнивай по нему без дополнительных +двух пробелов. Группируй связанные условия скобками и не меняй их порядок +или приоритет ради выравнивания. + +В многострочных `return` ставь `&&` и `||` в конце предыдущей строки, +а продолжение выравнивай под началом выражения после `return`. +Во вложенных группах также выравнивай операнды по первому выражению группы. + +В многострочных логических присваиваниях также оставляй `&&` и `||` в конце +предыдущей строки, а продолжение выравнивай под началом правой части. +При длинном типе или имени переменной переноси правую часть целиком после `=`: +её базовый отступ — четыре пробела от начала объявления. + +Простые условия из нескольких коротких проверок оставляй на одной строке. +Несколько `&&`/`||` сами по себе не требуют переноса; разбивай выражение, +когда это помогает читать длинные или сложные условия. + +```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); +} +``` + +## Имена и структура файлов + +| Элемент | Принятый вид | +| --- | --- | +| Функции, методы, переменные, поля | `camelCase`: `readPressure`, `targetTemp` | +| Классы и структуры | `PascalCase`: `Message`, `Config`, `Float` | +| Задачи | Действие + предмет + `Task`: `writeRoomSetpointTask` | +| Менеджеры | Назначение + `TaskManager`: `openthermTaskManager` | +| Логические предикаты | По смыслу: `isSlaveReady`, `canUseBus`, `needWriteRoomSetpoint` | +| Макросы и значения обычных перечислений | `UPPER_SNAKE_CASE` по принятому API | +| Идентификаторы OpenTherm | Согласованное имя из API/спецификации: `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`. + +Внутри namespace тоже нужен отступ: + +```cpp +namespace ESP32OT { + namespace Messages { + // Message declarations belong here. + } +} +``` + +Выравнивай колонки длинных перечислений и таблиц констант по окружающему коду. +Не добавляй дублирующие значения перечислений ради короткого синонима. + +## Условия и поток выполнения + +Для неуспешного результата предпочитай ранний выход, после которого основной +путь остаётся линейным: + +```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); +``` + +Ранний выход не должен пропускать обязательную последующую работу: проверку +связи, коррекцию ограничений, следующую независимую операцию или обновление +состояния. Сохраняй порядок действий исходного алгоритма. + +Вложенность уместна, когда она показывает настоящую зависимость операций. +Например, ошибка необязательной записи `MaxTSet` не должна отменять следующую +обязательную запись `TSet`: + +```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); +``` + +Общее присваивание перед проверкой echo можно сохранить и в линейном коде +с ранними выходами; само по себе оно не требует дополнительной вложенности. + +- Не заменяй все условия одним шаблоном автоматически. Выбирай структуру, + которая ясно показывает зависимости и сохраняет побочные эффекты. +- Предпочитай обычный `while` конструкции `for (; condition; ...)`. +- Не строй большие `switch` для ручной диспетчеризации ID или шагов, если + операции естественно выражаются отдельными задачами. +- В небольших учебных примерах, например Slave, `switch` по ID уместен. + Ветви одного уровня оформляй одинаково: `if / else if / else`, с `break` + для завершения `case`. Не смешивай без причины выход из `case` и всей функции. + +## Функции, типы и абстракции + +- Для локальных функций и данных `.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`, + минимум лишних копий и частых выделений памяти. Рост динамических буферов + должен быть обоснован и ограничен по потребностям задачи. + +## Оформление задач + +- Перед каждым самостоятельным блоком добавления задач в менеджер пиши короткий + английский комментарий о назначении блока. +- Простые условия включения — поддержка функции, наличие датчика, готовность + устройства — размещай в `setEnabledWhen`, если нет отдельной причины проверять + их внутри тела. Не дублируй одно и то же условие механически в двух местах. +- Повторная проверка состояния оправдана, если оно могло измениться во время + блокирующей операции или определяет завершение последовательности. +- Настраивай период через `setInterval`. Не добавляй второй ручной таймер для + того же ограничения частоты. Время успешного ответа или потери связи может + иметь самостоятельный смысл и не является таким дублем. +- Не добавляй `resume(delay)` по шаблону: период задачи и отложенное возобновление + имеют разное назначение. Проверяй семантику используемой версии библиотеки. +- Не рассчитывай, что `forceRun()` проверяет `setEnabledWhen`: в используемой + Mycila он обходит условия. Для условного запуска ONCE нужен корректный вызов + с учётом её pause/resume, например `resume().tryRun()` или явная проверка: + ```cpp + if (readModulationTask.idle() && readModulationTask.enabled()) { + readModulationTask.forceRun(); + } + ``` +- Не вводи ручной арбитраж, массивы шагов или систему приоритетов, когда достаточно + последовательного менеджера, интервалов и предикатов. +- Для обычных запросов внутри OpenTherm-задач используй понятный синхронный код. + Не превращай его в цепочки callback с большим `switch` только ради асинхронности, если это не влияет на производительность. +- Изменяй задачу через её изменяемый объект. Параметр `const Mycila::Task&` + в `onDone` нельзя использовать для вызова неконстантного `setInterval`. + +Это правила читаемости, а не разрешение менять периоды, порядок операций или +условия управления устройством. Такие изменения требуют отдельного основания. + +## Сообщения и логи + +- Используй готовые типизированные Message-обёртки для сборки и разбора данных. + Не собирай raw вручную, чтобы затем сразу завернуть его в подходящий тип. +- Обёртка содержит функциональность своего формата/ID. Избыточное уточнение типа + в методе не нужно: `Float::get()`, а не `Float::getFloat()`. +- Доступ к raw сохраняй для низкоуровневой работы и логирования. Не создавай + автоматическую фабрику подклассов, `variant` или полиморфную диспетчеризацию, + если вызывающий код всё равно вручную выбирает формат и это не даёт другой пользы. +- Различай ошибку обмена и несовпадение подтверждённых данных. Для mismatch + используй понятный текст с ожидаемым и полученным значениями. +- Общий формат повторяющегося сообщения выноси в общую строку/константу. + Форматные спецификаторы должны соответствовать фактическим типам аргументов. +- Значения, нужные остальному проекту, сохраняй в соответствующих полях `vars`. + Не меняй порядок сохранения и проверки ответа только ради красивой ветки. +- При сравнении `float` выбирай допуск по физическому смыслу величины. Если + требуется точное совпадение переданных данных, используй их кодированное + представление, когда это предусмотрено логикой. +- Не помещай пароли, токены, секреты и приватные конфигурации в диагностические сообщения. + +## Примеры, веб-код и документация + +- Примеры показывают простой основной путь использования API. Избегай служебной + «магии», ручных счётчиков, флагов ожидания и скрытых требований к порядку вызовов, + если библиотека уже предоставляет нужный механизм. +- Поясняй неочевидные проверки результата, например зачем нужен `hasFrame()` + в обработчике статусов, допускающем завершение без принятого кадра. +- В примерах с GPIO-настройками через build flags, как TransparentProxy, + используй защищённые `#ifndef` значения по умолчанию. Вложенные директивы + оформляй с отступом: + +```cpp +#ifndef BOILER_RX_GPIO + #define BOILER_RX_GPIO GPIO_NUM_35 +#endif +``` + +- Не переноси в основной код предположения, допустимые только в демонстрации, + например безусловный `Serial.printf` из callback. +- HTML, CSS и JavaScript оформляй читаемо с отступами окружающего файла; + минификация выполняется при сборке. Для JS действуют те же требования к скобкам + и смысловому разделению блоков. +- Для недоверенного текста используй `textContent`/`setTextValue`. Вставка HTML + должна быть необходима по смыслу и учитывать происхождение данных. +- Сохраняй порядок полей структур в сериализации и обратном преобразовании. +- Основной README и комментарии — на английском, русская версия README — + отдельный документ. Этот CODESTYLE и рабочие заметки проекта могут быть + на русском. + +## Перед завершением правки + +- Сверь изменённый участок с окружающим кодом и последними указаниями пользователя. +- Проверь отступы, пустые строки, переносы цепочек, комментарии и окончания строк. +- Убери случайное переформатирование посторонних участков. +- Убедись, что сокращение кода не изменило порядок действий и обязательные ветки. +- Не добавляй правила, абстракции и исключения, не нужные для решаемой задачи. diff --git a/README.md b/README.md index 67c662b..29cb5d9 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,8 @@
- [![GitHub version](https://img.shields.io/github/release/Laxilef/OTGateway.svg?include_prereleases)](https://github.com/Laxilef/OTGateway/releases) + [![GitHub version](https://img.shields.io/github/release/Laxilef/OTGateway.svg)](https://github.com/Laxilef/OTGateway/releases) [![GitHub download](https://img.shields.io/github/downloads/Laxilef/OTGateway/total.svg)](https://github.com/Laxilef/OTGateway/releases/latest) + [![Translations](https://hosted.weblate.org/widget/otgateway/svg-badge.svg)](https://hosted.weblate.org/engage/otgateway/) [![License](https://img.shields.io/github/license/Laxilef/OTGateway.svg)](LICENSE.txt) [![Telegram](https://img.shields.io/badge/Telegram-Channel-33A8E3)](https://t.me/otgateway) @@ -19,7 +20,7 @@ - PID - Equithermic curves - adjusts the temperature based on indoor and outdoor temperatures - Hysteresis setting _(for accurate maintenance of room temperature)_ -- Ability to connect [additional (external) sensors](https://github.com/Laxilef/OTGateway/wiki/Compatibility#temperature-sensors): Dallas (1-wire), NTC 10k, Bluetooth (BLE). Makes it possible to monitor indoor and outdoor temperatures, temperatures on pipes/heat exchangers/etc. +- Ability to connect [additional (external) sensors](https://github.com/Laxilef/OTGateway/wiki/Sensors#temperature-sensors): Dallas (1-wire), NTC 10k, Bluetooth (BLE). Makes it possible to monitor indoor and outdoor temperatures, temperatures on pipes/heat exchangers/etc. - Emergency mode. In any dangerous situation _(loss of connection with Wifi, MQTT, sensors, etc)_ it will not let you and your home freeze. - Ability of remote fault reset _(not with all boilers)_ - Diagnostics: @@ -40,41 +41,101 @@ - [Home Assistant](https://www.home-assistant.io/) integration via MQTT. The ability to create any automation for the boiler! ## Documentation -All available information and instructions can be found in the wiki: -* [Home](https://github.com/Laxilef/OTGateway/wiki) - * [Quick Start](https://github.com/Laxilef/OTGateway/wiki#quick-start) - * [Build firmware](https://github.com/Laxilef/OTGateway/wiki#build-firmware) - * [Flashing via Web Flasher](https://github.com/Laxilef/OTGateway/wiki#flashing-via-web-flasher) - * [Flashing via ESP Flash Download Tool](https://github.com/Laxilef/OTGateway/wiki#flashing-via-esp-flash-download-tool) - * [Settings](https://github.com/Laxilef/OTGateway/wiki#settings) - * [External temperature sensors](https://github.com/Laxilef/OTGateway/wiki#external-temperature-sensors) - * [Other external sensors](https://github.com/Laxilef/OTGateway/wiki#other-external-sensors) - * [Reporting indoor/outdoor temperature from any Home Assistant sensor](https://github.com/Laxilef/OTGateway/wiki#reporting-indooroutdoor-temperature-from-any-home-assistant-sensor) - * [Reporting outdoor temperature from Home Assistant weather integration](https://github.com/Laxilef/OTGateway/wiki#reporting-outdoor-temperature-from-home-assistant-weather-integration) - * [DHW meter](https://github.com/Laxilef/OTGateway/wiki#dhw-meter) - * [Advanced Settings](https://github.com/Laxilef/OTGateway/wiki#advanced-settings) - * [Equitherm mode](https://github.com/Laxilef/OTGateway/wiki#equitherm-mode) - * [Ratios](https://github.com/Laxilef/OTGateway/wiki#ratios) - * [Fit coefficients](https://github.com/Laxilef/OTGateway/wiki#fit-coefficients) - * [PID mode](https://github.com/Laxilef/OTGateway/wiki#pid-mode) - * [Logs and debug](https://github.com/Laxilef/OTGateway/wiki#logs-and-debug) -* [Compatibility](https://github.com/Laxilef/OTGateway/wiki/Compatibility) - * [Boilers](https://github.com/Laxilef/OTGateway/wiki/Compatibility#boilers) - * [Boards](https://github.com/Laxilef/OTGateway/wiki/Compatibility#boards) - * [Temperature sensors](https://github.com/Laxilef/OTGateway/wiki/Compatibility#temperature-sensors) -* [FAQ & Troubleshooting](https://github.com/Laxilef/OTGateway/wiki/FAQ-&-Troubleshooting) -* [OT adapters](https://github.com/Laxilef/OTGateway/wiki/OT-adapters) - * [Adapters on sale](https://github.com/Laxilef/OTGateway/wiki/OT-adapters#adapters-on-sale) - * [DIY](https://github.com/Laxilef/OTGateway/wiki/OT-adapters#diy) - * [Files for production](https://github.com/Laxilef/OTGateway/wiki/OT-adapters#files-for-production) - * [Connection](https://github.com/Laxilef/OTGateway/wiki/OT-adapters#connection) - * [Leds on board](https://github.com/Laxilef/OTGateway/wiki/OT-adapters#leds-on-board) +All available information and instructions can be found in the wiki: [English](https://github.com/Laxilef/OTGateway/wiki) · [Русский](https://github.com/Laxilef/OTGateway/wiki/Home.RU). + +* **Installation** + * [First installation](https://github.com/Laxilef/OTGateway/wiki/Installation-and-upgrade#first-installation) + * [Web Flasher](https://github.com/Laxilef/OTGateway/wiki/Installation-and-upgrade#web-flasher) + * [ESP Flash Download Tool](https://github.com/Laxilef/OTGateway/wiki/Installation-and-upgrade#esp-flash-download-tool) + * [Build from source](https://github.com/Laxilef/OTGateway/wiki/Installation-and-upgrade#build-from-source) + * [Update and restore](https://github.com/Laxilef/OTGateway/wiki/Installation-and-upgrade#backup-update-and-restore) + * [Save the settings](https://github.com/Laxilef/OTGateway/wiki/Installation-and-upgrade#save-the-settings) + * [Update firmware and filesystem](https://github.com/Laxilef/OTGateway/wiki/Installation-and-upgrade#update-firmware-and-filesystem) + * [Restore the settings](https://github.com/Laxilef/OTGateway/wiki/Installation-and-upgrade#restore-the-settings) +* **Hardware** + * [Boilers](https://github.com/Laxilef/OTGateway/wiki/Boilers) + * [ESP32 boards](https://github.com/Laxilef/OTGateway/wiki/Boards) + * [Temperature sensors](https://github.com/Laxilef/OTGateway/wiki/Sensors#temperature-sensors) + * [OT adapters](https://github.com/Laxilef/OTGateway/wiki/OT-adapters) + * [Adapters on sale](https://github.com/Laxilef/OTGateway/wiki/OT-adapters#adapters-on-sale) + * [DIY](https://github.com/Laxilef/OTGateway/wiki/OT-adapters#diy) + * [Files for production](https://github.com/Laxilef/OTGateway/wiki/OT-adapters#files-for-production) + * [Connection](https://github.com/Laxilef/OTGateway/wiki/OT-adapters#connection) + * [LEDs on board](https://github.com/Laxilef/OTGateway/wiki/OT-adapters#leds-on-board) +* **Configuration** + * [Network](https://github.com/Laxilef/OTGateway/wiki/Network) + * [Heating and OpenTherm](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm) + * [Heating hysteresis](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#heating-hysteresis) + * [Direct control](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#direct-control) + * [Equitherm](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#equitherm) + * [Curve parameters](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#curve-parameters) + * [Tune the curve](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#tune-the-curve) + * [PID](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#pid) + * [Tune PID using indoor temperature](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#tune-pid-using-indoor-temperature) + * [Using Equitherm with PID](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#using-equitherm-with-pid) + * [Protections and emergency mode](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#protections-and-emergency-mode) + * [Overheat protection](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#overheat-protection) + * [Freeze protection](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#freeze-protection) + * [Emergency mode](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#emergency-mode) + * [Additional circulation pump](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#additional-circulation-pump) + * [Cascade control](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#cascade-control) + * [Input](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#input) + * [Output](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#output) + * [Sensor setup](https://github.com/Laxilef/OTGateway/wiki/Sensors#connect-a-temperature-sensor) + * [Choose a purpose](https://github.com/Laxilef/OTGateway/wiki/Sensors#choose-a-purpose) + * [Supply a reading from another system](https://github.com/Laxilef/OTGateway/wiki/Sensors#supply-a-reading-from-another-system) +* **Integrations** + * [MQTT](https://github.com/Laxilef/OTGateway/wiki/MQTT) + * [Connection settings](https://github.com/Laxilef/OTGateway/wiki/MQTT#connection-settings) + * [Topic structure and access](https://github.com/Laxilef/OTGateway/wiki/MQTT#topic-structure-and-access) + * [State topics](https://github.com/Laxilef/OTGateway/wiki/MQTT#state-topics) + * [Settings](https://github.com/Laxilef/OTGateway/wiki/MQTT#settings) + * [Sensor topics](https://github.com/Laxilef/OTGateway/wiki/MQTT#sensor-topics) + * [Examples](https://github.com/Laxilef/OTGateway/wiki/MQTT#examples) + * [REST API](https://github.com/Laxilef/OTGateway/wiki/REST) + * [Endpoints](https://github.com/Laxilef/OTGateway/wiki/REST#endpoints) + * [Settings](https://github.com/Laxilef/OTGateway/wiki/REST#settings) + * [Network](https://github.com/Laxilef/OTGateway/wiki/REST#network) + * [Sensors](https://github.com/Laxilef/OTGateway/wiki/REST#sensors) + * [Examples](https://github.com/Laxilef/OTGateway/wiki/REST#examples) + * [Home Assistant](https://github.com/Laxilef/OTGateway/wiki/Home-Assistant) + * [Connection](https://github.com/Laxilef/OTGateway/wiki/Home-Assistant#connection) + * [Report a temperature sensor](https://github.com/Laxilef/OTGateway/wiki/Home-Assistant#report-a-temperature-sensor) + * [Report outdoor weather temperature](https://github.com/Laxilef/OTGateway/wiki/Home-Assistant#report-outdoor-weather-temperature) + * [DHW meter](https://github.com/Laxilef/OTGateway/wiki/Home-Assistant#dhw-meter) + * [HOMEd](https://github.com/Laxilef/OTGateway/wiki/HOMEd) + * [Connect](https://github.com/Laxilef/OTGateway/wiki/HOMEd#connect) + * [Heating and DHW control](https://github.com/Laxilef/OTGateway/wiki/HOMEd#heating-and-dhw-control) + * [Sensors](https://github.com/Laxilef/OTGateway/wiki/HOMEd#sensors) + * [Supply a temperature to OTGateway](https://github.com/Laxilef/OTGateway/wiki/HOMEd#supply-a-temperature-from-homed-to-otgateway) + * [Diagnostics](https://github.com/Laxilef/OTGateway/wiki/HOMEd#diagnostics) + * [Migrate an existing integration](https://github.com/Laxilef/OTGateway/wiki/HOMEd#migrate-an-existing-integration) +* **Other** + * [FAQ and troubleshooting](https://github.com/Laxilef/OTGateway/wiki/FAQ-%26-Troubleshooting) + * [Installation and connection](https://github.com/Laxilef/OTGateway/wiki/FAQ-%26-Troubleshooting#installation-and-connection) + * [Heating and hot water](https://github.com/Laxilef/OTGateway/wiki/FAQ-%26-Troubleshooting#heating-and-hot-water) + * [Sensors](https://github.com/Laxilef/OTGateway/wiki/FAQ-%26-Troubleshooting#sensors) + * [MQTT and Home Assistant](https://github.com/Laxilef/OTGateway/wiki/FAQ-%26-Troubleshooting#mqtt-and-home-assistant) + * [Logs and debug](https://github.com/Laxilef/OTGateway/wiki/FAQ-%26-Troubleshooting#logs-and-debug) + * [Core dump analysis](https://github.com/Laxilef/OTGateway/wiki/Core-dump-analysis) + * [Windows (PowerShell)](https://github.com/Laxilef/OTGateway/wiki/Core-dump-analysis#windows-powershell) + * [Linux (shell)](https://github.com/Laxilef/OTGateway/wiki/Core-dump-analysis#linux-shell) + * [What the report contains](https://github.com/Laxilef/OTGateway/wiki/Core-dump-analysis#what-the-report-contains) + * [Finding the likely cause](https://github.com/Laxilef/OTGateway/wiki/Core-dump-analysis#finding-the-likely-cause) + +## Translations +The project uses [Weblate](https://hosted.weblate.org/new-lang/otgateway/) to manage translations of the interface.
+Anyone is welcome to add their native language as a [new localization](https://hosted.weblate.org/new-lang/otgateway/portal/). All contributions are welcome! + + +Translation status + ## Gratitude -* To the developers of the libraries used: [OpenTherm Library](https://github.com/ihormelnyk/opentherm_library), [ESP8266Scheduler](https://github.com/nrwiersma/ESP8266Scheduler), [ArduinoJson](https://github.com/bblanchon/ArduinoJson), [NimBLE-Arduino](https://github.com/h2zero/NimBLE-Arduino), [ArduinoMqttClient](https://github.com/arduino-libraries/ArduinoMqttClient), [ESPTelnet](https://github.com/LennartHennigs/ESPTelnet), [FileData](https://github.com/GyverLibs/FileData), [GyverPID](https://github.com/GyverLibs/GyverPID), [GyverBlinker](https://github.com/GyverLibs/GyverBlinker), [OneWireNg](https://github.com/pstolarz/OneWireNg) & [OneWire](https://github.com/PaulStoffregen/OneWire) +* To the developers of the libraries used: [ArduinoJson](https://github.com/bblanchon/ArduinoJson), [NimBLE-Arduino](https://github.com/h2zero/NimBLE-Arduino), [MycilaMQTT](https://github.com/mathieucarbou/MycilaMQTT), [MycilaHADiscovery](https://github.com/mathieucarbou/MycilaHADiscovery), [AsyncTCP](https://github.com/ESP32Async/AsyncTCP), [ESPAsyncWebServer](https://github.com/ESP32Async/ESPAsyncWebServer), [MycilaWebSerial](https://github.com/mathieucarbou/MycilaWebSerial), [MycilaTaskManager](https://github.com/mathieucarbou/MycilaTaskManager), [FileData](https://github.com/GyverLibs/FileData), [MycilaUtilities](https://github.com/mathieucarbou/MycilaUtilities), [GyverBlinker](https://github.com/GyverLibs/GyverBlinker), [OneWireNg](https://github.com/pstolarz/OneWireNg), [DallasTemperature](https://github.com/milesburton/Arduino-Temperature-Control-Library) & [esp32DHT](https://github.com/bertmelis/esp32DHT) * To the [PlatformIO](https://platformio.org/) Team * To the team and contributors of the [pioarduino](https://github.com/pioarduino/platform-espressif32) project * To the [BrowserStack](https://www.browserstack.com/) team. This project is tested with BrowserStack. * To the [PVS-Studio](https://pvs-studio.com/pvs-studio/?utm_source=website&utm_medium=github&utm_campaign=open_source) - static analyzer for C, C++, C#, and Java code. -* And of course to the contributors for their contribution to the development of the project! \ No newline at end of file +* And of course to the contributors for their contribution to the development of the project! diff --git a/agent-notes/.gitkeep b/agent-notes/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/assets/2D_PCB_bottom.png b/assets/2D_PCB_bottom.png deleted file mode 100644 index c55c187..0000000 Binary files a/assets/2D_PCB_bottom.png and /dev/null differ diff --git a/assets/2D_PCB_top.png b/assets/2D_PCB_top.png deleted file mode 100644 index 0cd9b6c..0000000 Binary files a/assets/2D_PCB_top.png and /dev/null differ diff --git a/assets/3D_PCB.png b/assets/3D_PCB.png deleted file mode 100644 index 09df3c5..0000000 Binary files a/assets/3D_PCB.png and /dev/null differ diff --git a/assets/BOM.xlsx b/assets/BOM.xlsx deleted file mode 100644 index 87ea8d0..0000000 Binary files a/assets/BOM.xlsx and /dev/null differ diff --git a/assets/CPL.csv b/assets/CPL.csv deleted file mode 100644 index 2afbb91..0000000 Binary files a/assets/CPL.csv and /dev/null differ diff --git a/assets/Schematic.pdf b/assets/Schematic.pdf deleted file mode 100644 index 9eac22e..0000000 --- a/assets/Schematic.pdf +++ /dev/null @@ -1,18957 +0,0 @@ -%PDF-1.4 -%º߬à -3 0 obj -<> -endobj -4 0 obj -<< -/Length 62907 ->> -stream -0.14 w -0 G -q -2 J -0 j -72 M -1.00 g -[] 0 d -0.00 599.76 848.16 -599.76 re -f -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -2.88 596.88 842.40 -594.00 re -S -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -10.08 589.68 828.00 -579.60 re -S -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -71.28 4.08 Td -<0031> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -71.28 590.88 Td -<0031> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -211.68 4.08 Td -<0032> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -211.68 590.88 Td -<0032> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -352.08 4.08 Td -<0033> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -352.08 590.88 Td -<0033> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -492.48 4.08 Td -<0034> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -492.48 590.88 Td -<0034> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -632.88 4.08 Td -<0035> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -632.88 590.88 Td -<0035> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -773.28 4.08 Td -<0036> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -773.28 590.88 Td -<0036> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -4.68 520.23 Td -<0041> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -839.88 520.23 Td -<0041> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -4.68 371.73 Td -<0042> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -839.88 371.73 Td -<0042> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -4.68 223.23 Td -<0043> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -839.88 223.23 Td -<0043> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -4.68 74.73 Td -<0044> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -839.88 74.73 Td -<0044> Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -143.280 2.880 m -143.280 10.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -143.280 596.880 m -143.280 589.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -283.680 2.880 m -283.680 10.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -283.680 596.880 m -283.680 589.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -424.080 2.880 m -424.080 10.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -424.080 596.880 m -424.080 589.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -564.480 2.880 m -564.480 10.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -564.480 596.880 m -564.480 589.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -704.880 2.880 m -704.880 10.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -704.880 596.880 m -704.880 589.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -2.880 448.380 m -10.080 448.380 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -845.280 448.380 m -838.080 448.380 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -2.880 299.880 m -10.080 299.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -845.280 299.880 m -838.080 299.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -2.880 151.380 m -10.080 151.380 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -845.280 151.380 m -838.080 151.380 l -S -7.20 w -BT -/F2 12.32142768838278 Tf -14.40 TL -0.000 0.000 0.502 rg -606.39 70.77 Td -(OpenTherm Gateway) Tj -ET -7.20 w -BT -/F2 9.241070766287086 Tf -10.80 TL -0.000 0.000 0.502 rg -793.75 43.71 Td -(2) Tj -ET -7.20 w -BT -/F2 9.241070766287086 Tf -10.80 TL -0.000 0.000 0.502 rg -730.08 129.39 Td -(2024-12-17) Tj -ET -7.20 w -BT -/F2 9.241070766287086 Tf -10.80 TL -0.000 0.000 0.502 rg -730.08 114.99 Td -(2024-09-17) Tj -ET -7.20 w -BT -/F2 12.32142768838278 Tf -14.40 TL -0.000 0.000 0.502 rg -500.40 121.17 Td -(otgateway) Tj -ET -7.20 w -BT -/F2 9.241070766287086 Tf -10.80 TL -0.000 0.000 0.502 rg -709.51 43.71 Td -(1) Tj -ET -7.20 w -BT -/F2 9.241070766287086 Tf -10.80 TL -0.000 0.000 0.502 rg -510.76 100.59 Td -(Sheet_A) Tj -ET -7.20 w -BT -/F2 9.241070766287086 Tf -10.80 TL -0.000 0.000 0.502 rg -506.48 21.39 Td -(V1.5.3) Tj -ET -7.20 w -BT -/F2 9.241070766287086 Tf -10.80 TL -0.000 0.000 0.502 rg -573.23 21.39 Td -(A5) Tj -ET -7.20 w -BT -/F2 9.241070766287086 Tf -10.80 TL -0.000 0.000 0.502 rg -404.64 86.19 Td -(Laxilef) Tj -ET -q -1 0 0 1 0 0 cm -7.20 w -BT -/F1 10.781249080707086 Tf -10.80 TL -0.627 0.000 0.000 rg -339.84 71.28 Td -<00520065007600690065007700650064> Tj -ET -7.20 w -BT -/F1 10.781249080707086 Tf -10.80 TL -0.627 0.000 0.000 rg -339.84 85.68 Td -<0044007200610077006e> Tj -ET -7.20 w -BT -/F1 10.781249080707086 Tf -10.80 TL -0.627 0.000 0.000 rg -511.75 42.48 Td -<005600450052> Tj -ET -7.20 w -BT -/F1 10.781249080707086 Tf -10.80 TL -0.627 0.000 0.000 rg -656.64 114.48 Td -<00430072006500610074006500200044006100740065> Tj -ET -7.20 w -BT -/F1 10.781249080707086 Tf -10.80 TL -0.627 0.000 0.000 rg -656.64 100.08 Td -<00500061007200740020004e0075006d006200650072> Tj -ET -7.20 w -BT -/F1 10.781249080707086 Tf -10.80 TL -0.627 0.000 0.000 rg -656.64 43.20 Td -<0050004100470045> Tj -ET -7.20 w -BT -/F1 10.781249080707086 Tf -10.80 TL -0.627 0.000 0.000 rg -745.92 43.20 Td -<004f0046> Tj -ET -7.20 w -BT -/F1 10.781249080707086 Tf -10.80 TL -0.627 0.000 0.000 rg -339.84 121.68 Td -<0053006300680065006d0061007400690063> Tj -ET -7.20 w -BT -/F1 10.781249080707086 Tf -10.80 TL -0.627 0.000 0.000 rg -656.64 128.88 Td -<00550070006400610074006500200044006100740065> Tj -ET -7.20 w -BT -/F1 10.781249080707086 Tf -10.80 TL -0.627 0.000 0.000 rg -566.66 42.48 Td -<00530049005a0045> Tj -ET -7.20 w -BT -/F1 10.781249080707086 Tf -10.80 TL -0.627 0.000 0.000 rg -341.28 100.08 Td -<0050006100670065> Tj -ET -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -332.64 139.68 505.44 -129.60 re -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -548.640 10.080 m -548.640 53.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -398.880 38.880 m -398.880 139.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -649.440 139.680 m -649.440 96.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -721.440 96.480 m -721.440 139.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -491.040 96.480 m -491.040 10.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -491.040 82.080 m -332.640 82.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -838.080 125.280 m -649.440 125.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -838.080 38.880 m -332.640 38.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -838.080 96.480 m -332.640 96.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -838.080 53.280 m -332.640 53.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -491.040 67.680 m -332.640 67.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -838.080 110.880 m -332.640 110.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -606.240 53.280 m -606.240 10.080 l -S -q -0.33 0.53 1.00 rg -[] 0 d -418.002 23.650 m -418.154 23.764 418.338 23.821 418.549 23.821 c -418.833 23.821 419.136 23.720 419.459 23.524 c -419.782 23.328 420.092 23.018 420.389 22.594 c -421.536 24.359 l -421.180 24.852 420.738 25.238 420.204 25.510 c -419.670 25.782 419.103 25.915 418.510 25.915 c -417.666 25.915 416.928 25.668 416.308 25.175 c -415.688 24.681 415.378 24.036 415.378 23.252 c -415.378 22.689 415.576 22.151 415.972 21.645 c -416.255 21.285 416.769 20.848 417.508 20.342 c -418.147 19.906 418.543 19.602 418.688 19.432 c -418.833 19.261 418.905 19.096 418.905 18.932 c -418.905 18.729 418.813 18.559 418.622 18.407 c -418.431 18.261 418.180 18.186 417.864 18.186 c -417.066 18.186 416.328 18.609 415.655 19.463 c -414.172 17.806 l -414.831 17.136 415.431 16.668 415.965 16.415 c -416.499 16.162 417.099 16.035 417.752 16.035 c -418.886 16.035 419.749 16.345 420.349 16.965 c -420.949 17.585 421.246 18.249 421.246 18.945 c -421.246 19.476 421.101 19.963 420.811 20.418 c -420.520 20.867 419.914 21.411 418.991 22.044 c -418.411 22.442 418.068 22.708 417.956 22.847 c -417.837 22.986 417.778 23.125 417.778 23.265 c -417.771 23.410 417.851 23.537 418.002 23.650 c -418.002 23.650 l -f -0.33 0.53 1.00 rg -[] 0 d -427.034 20.102 m -425.128 25.674 l -422.768 25.674 l -425.524 17.559 l -422.742 12.841 l -425.280 12.841 l -432.973 25.674 l -430.382 25.674 l -427.034 20.102 l -f -0.33 0.53 1.00 rg -[] 0 d -401.508 24.093 m -396.867 24.093 l -397.250 26.731 l -397.250 26.731 402.174 26.737 402.201 26.737 c -402.847 26.737 403.374 27.243 403.374 27.863 c -403.374 28.483 402.847 28.989 402.201 28.989 c -402.181 28.989 395.055 28.989 395.055 28.989 c -393.235 16.275 l -400.698 16.275 l -400.698 16.275 l -401.324 16.288 401.831 16.781 401.831 17.382 c -401.831 17.996 401.311 18.495 400.671 18.495 c -400.645 18.495 396.043 18.489 396.043 18.489 c -396.531 21.860 l -396.531 21.860 401.258 21.854 401.297 21.854 c -401.944 21.854 402.471 22.360 402.471 22.980 c -402.484 23.543 402.062 24.005 401.508 24.093 c -401.508 24.093 l -f -0.33 0.53 1.00 rg -[] 0 d -442.176 28.982 m -442.156 28.982 435.030 28.982 435.030 28.982 c -433.224 16.282 l -440.693 16.282 l -440.693 16.282 l -441.319 16.294 441.827 16.788 441.827 17.389 c -441.827 18.002 441.306 18.502 440.666 18.502 c -440.640 18.502 436.039 18.495 436.039 18.495 c -436.526 21.867 l -436.526 21.867 441.253 21.860 441.299 21.860 c -441.945 21.860 442.473 22.366 442.473 22.986 c -442.473 23.543 442.051 24.005 441.497 24.093 c -436.856 24.093 l -437.238 26.731 l -437.238 26.731 442.163 26.737 442.189 26.737 c -442.835 26.737 443.363 27.243 443.363 27.863 c -443.349 28.476 442.829 28.982 442.176 28.982 c -442.176 28.982 l -f -0.33 0.53 1.00 rg -[] 0 d -455.512 22.898 m -455.512 24.144 455.209 25.251 454.609 26.206 c -454.009 27.161 453.231 27.863 452.269 28.306 c -451.306 28.755 449.849 28.976 447.878 28.976 c -445.782 28.976 l -443.976 16.275 l -448.089 16.275 l -449.816 16.275 451.168 16.522 452.137 17.015 c -453.106 17.509 453.917 18.293 454.556 19.362 c -455.196 20.437 455.512 21.614 455.512 22.898 c -455.512 22.898 l -452.255 20.273 m -451.774 19.577 451.141 19.084 450.350 18.799 c -449.783 18.597 448.874 18.495 447.615 18.495 c -446.797 18.495 l -447.964 26.743 l -448.590 26.743 l -449.612 26.743 450.429 26.592 451.043 26.282 c -451.656 25.972 452.130 25.535 452.473 24.966 c -452.809 24.397 452.981 23.695 452.981 22.853 c -452.974 21.835 452.737 20.969 452.255 20.273 c -452.255 20.273 l -f -0.33 0.53 1.00 rg -[] 0 d -465.302 23.043 m -463.831 22.265 l -463.713 21.241 462.803 20.450 461.709 20.450 c -460.529 20.450 459.573 21.367 459.573 22.499 c -459.573 23.631 460.529 24.549 461.709 24.549 c -462.164 24.549 462.586 24.409 462.928 24.182 c -464.754 25.149 l -463.766 28.957 l -461.676 28.957 l -454.556 16.307 l -457.219 16.307 l -458.722 19.001 l -463.957 19.001 l -464.655 16.307 l -467.055 16.307 l -465.302 23.043 l -465.302 23.043 l -f -0.33 0.53 1.00 rg -[] 0 d -460.924 22.550 m -460.924 22.113 461.293 21.759 461.748 21.759 c -462.203 21.759 462.572 22.113 462.572 22.550 c -462.572 22.986 462.203 23.340 461.748 23.340 c -461.293 23.340 460.924 22.986 460.924 22.550 c -460.924 22.550 l -f -0.33 0.53 1.00 rg -[] 0 d -412.274 24.194 m -412.274 24.194 412.274 24.201 412.274 24.194 c -411.450 24.194 l -411.364 24.346 l -411.028 24.858 410.606 25.244 410.098 25.510 c -409.584 25.776 408.773 25.908 408.167 25.908 c -407.263 25.908 406.400 25.674 405.576 25.206 c -404.752 24.738 404.093 24.087 403.605 23.246 c -403.117 22.411 402.866 21.525 402.866 20.602 c -402.866 19.387 403.249 18.325 404.013 17.408 c -404.778 16.490 405.813 16.035 407.112 16.035 c -407.679 16.035 408.186 16.124 408.641 16.313 c -409.096 16.497 409.584 16.819 410.105 17.287 c -410.105 17.287 410.718 16.775 410.724 16.781 c -411.107 16.490 411.581 16.307 412.096 16.275 c -412.333 16.275 l -412.366 16.547 l -413.203 23.309 l -413.196 23.309 413.196 23.309 413.190 23.309 c -413.190 23.796 412.781 24.188 412.274 24.194 c -412.274 24.194 l -410.349 19.659 m -410.052 19.122 409.683 18.723 409.241 18.470 c -408.799 18.217 408.285 18.091 407.692 18.091 c -406.980 18.091 406.400 18.312 405.945 18.767 c -405.490 19.217 405.266 19.811 405.266 20.545 c -405.266 21.500 405.563 22.278 406.163 22.885 c -406.762 23.492 407.488 23.790 408.345 23.790 c -409.083 23.790 409.676 23.562 410.124 23.113 c -410.573 22.657 410.797 22.063 410.797 21.316 c -410.797 20.753 410.645 20.197 410.349 19.659 c -410.349 19.659 l -f -0.33 0.53 1.00 rg -[] 0 d -385.212 27.749 m -384.718 29.008 383.914 30.140 382.852 31.057 c -381.224 32.461 379.115 33.239 376.919 33.239 c -375.021 33.239 373.208 32.670 371.679 31.595 c -370.940 31.076 370.301 30.462 369.773 29.767 c -369.444 29.811 369.108 29.836 368.765 29.836 c -366.873 29.836 365.086 29.128 363.748 27.844 c -362.410 26.560 361.672 24.852 361.672 23.031 c -361.672 21.342 362.324 19.723 363.504 18.470 c -364.440 17.477 365.653 16.775 366.991 16.446 c -367.572 14.789 369.206 13.594 371.125 13.594 c -373.531 13.594 375.489 15.472 375.489 17.781 c -375.489 17.914 375.482 18.053 375.469 18.186 c -381.593 21.272 l -380.255 23.499 l -374.401 20.551 l -373.603 21.424 372.430 21.974 371.125 21.974 c -369.233 21.974 367.618 20.810 367.011 19.191 c -365.469 19.843 364.388 21.316 364.388 23.037 c -364.388 25.352 366.345 27.237 368.765 27.237 c -369.615 27.237 370.413 27.003 371.085 26.598 c -371.896 28.944 374.203 30.640 376.919 30.640 c -380.084 30.640 382.681 28.350 383.030 25.409 c -383.142 25.421 383.255 25.428 383.367 25.428 c -385.259 25.428 386.795 23.954 386.795 22.139 c -386.795 20.418 385.417 19.008 383.663 18.862 c -381.705 18.862 l -381.620 18.881 381.527 18.888 381.435 18.888 c -380.677 18.888 380.064 18.299 380.064 17.572 c -380.064 16.883 380.618 16.320 381.323 16.263 c -381.323 16.250 l -383.663 16.250 l -383.782 16.250 l -383.901 16.263 l -385.430 16.389 386.847 17.053 387.889 18.141 c -388.937 19.235 389.517 20.652 389.517 22.139 c -389.517 24.757 387.704 26.996 385.212 27.749 c -385.212 27.749 l -371.125 19.400 m -372.054 19.400 372.812 18.673 372.812 17.781 c -372.812 16.889 372.054 16.162 371.125 16.162 c -370.195 16.162 369.437 16.889 369.437 17.781 c -369.437 18.673 370.195 19.400 371.125 19.400 c -371.125 19.400 l -f -Q -Q -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -115.20 506.88 5.76 -14.40 re -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -118.080 485.280 m -118.080 492.480 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -118.080 514.080 m -118.080 506.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -123.120 496.080 m -113.040 503.280 l -113.040 506.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -97.02 497.90 Td -(VAR1) Tj -ET -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -283.68 524.88 43.20 -28.80 re -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -285.84 515.68 Td -(IN) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -275.93 518.56 Td -(3) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -269.280 517.680 m -283.680 517.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 303.02 486.96 Tm -(1) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -305.280 481.680 m -305.280 496.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -311.71 515.68 Td -(OUT) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -331.20 518.56 Td -(4) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -341.280 517.680 m -326.880 517.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -311.71 508.48 Td -(OUT) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -331.20 511.36 Td -(2) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -341.280 510.480 m -326.880 510.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -283.68 536.24 Td -(U3) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -283.68 529.04 Td -(AMS1117-3.3) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -64.080 492.480 m -71.280 492.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -64.080 488.880 m -64.080 496.080 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -71.280 492.480 m -71.280 492.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -54.24 489.34 Td -(L) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -64.080 506.880 m -71.280 506.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -64.080 513.360 m -64.080 500.400 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -62.640 511.200 m -62.640 502.560 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -61.200 509.040 m -61.200 504.720 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -59.760 507.600 m -59.760 506.160 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -71.280 506.880 m -71.280 506.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -50.22 503.72 Td -(N) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -224.640 501.120 m -213.120 501.120 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -218.880 510.480 m -218.880 503.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -218.880 488.880 m -218.880 496.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -218.880 503.280 m -218.880 501.120 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -218.880 498.240 m -218.880 496.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -224.153 496.175 m -222.623 497.297 l -220.907 497.979 l -219.111 498.237 l -217.308 498.083 l -215.563 497.510 l -213.974 496.499 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -221.040 506.880 m -221.040 504.000 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -222.480 505.440 m -219.600 505.440 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -226.08 497.90 Td -(C1) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -226.08 491.39 Td -(100uF) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -361.440 501.120 m -349.920 501.120 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -355.680 510.480 m -355.680 503.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -355.680 488.880 m -355.680 496.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -355.680 503.280 m -355.680 501.120 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -355.680 498.240 m -355.680 496.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -360.953 496.175 m -359.423 497.297 l -357.707 497.979 l -355.911 498.237 l -354.108 498.083 l -352.363 497.510 l -350.774 496.499 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -357.840 506.880 m -357.840 504.000 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -359.280 505.440 m -356.400 505.440 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -362.88 497.90 Td -(C3) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -362.88 491.39 Td -(22uF) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -257.040 498.240 m -245.520 498.240 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -251.280 485.280 m -251.280 492.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -251.280 506.880 m -251.280 501.120 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -245.520 501.120 m -257.040 501.120 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -251.280 514.080 m -251.280 506.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -251.280 498.240 m -251.280 492.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -258.48 497.90 Td -(C2) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -258.48 491.39 Td -(100nF) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -305.280 474.480 m -305.280 481.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -298.800 474.480 m -311.760 474.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -300.960 473.040 m -309.600 473.040 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -303.120 471.600 m -307.440 471.600 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -304.560 470.160 m -306.000 470.160 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -305.280 481.680 m -305.280 481.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -355.680 532.080 m -355.680 524.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -352.080 532.080 m -359.280 532.080 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -355.680 524.880 m -355.680 524.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -347.96 534.14 Td -(3.3V) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -262.080 532.080 m -262.080 524.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -258.480 532.080 m -265.680 532.080 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -262.080 524.880 m -262.080 524.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -256.80 536.16 Td -(5V) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -560.880 478.080 m -568.080 478.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -560.880 484.560 m -560.880 471.600 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -559.440 482.400 m -559.440 473.760 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -558.000 480.240 m -558.000 475.920 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -556.560 478.800 m -556.560 477.360 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -568.080 478.080 m -568.080 478.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -712.080 416.880 m -704.880 416.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -712.080 420.480 m -712.080 413.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -704.880 416.880 m -704.880 416.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -714.36 413.76 Td -(3.3V) Tj -ET -0.80 0.00 0.00 rg -119.88 517.68 m 119.88 518.67 119.07 519.48 118.08 519.48 c -117.09 519.48 116.28 518.67 116.28 517.68 c -116.28 516.69 117.09 515.88 118.08 515.88 c -119.07 515.88 119.88 516.69 119.88 517.68 c -f -0.80 0.00 0.00 rg -119.88 481.68 m 119.88 482.67 119.07 483.48 118.08 483.48 c -117.09 483.48 116.28 482.67 116.28 481.68 c -116.28 480.69 117.09 479.88 118.08 479.88 c -119.07 479.88 119.88 480.69 119.88 481.68 c -f -0.80 0.00 0.00 rg -307.08 481.68 m 307.08 482.67 306.27 483.48 305.28 483.48 c -304.29 483.48 303.48 482.67 303.48 481.68 c -303.48 480.69 304.29 479.88 305.28 479.88 c -306.27 479.88 307.08 480.69 307.08 481.68 c -f -0.80 0.00 0.00 rg -253.08 481.68 m 253.08 482.67 252.27 483.48 251.28 483.48 c -250.29 483.48 249.48 482.67 249.48 481.68 c -249.48 480.69 250.29 479.88 251.28 479.88 c -252.27 479.88 253.08 480.69 253.08 481.68 c -f -0.80 0.00 0.00 rg -220.68 481.68 m 220.68 482.67 219.87 483.48 218.88 483.48 c -217.89 483.48 217.08 482.67 217.08 481.68 c -217.08 480.69 217.89 479.88 218.88 479.88 c -219.87 479.88 220.68 480.69 220.68 481.68 c -f -0.80 0.00 0.00 rg -220.68 517.68 m 220.68 518.67 219.87 519.48 218.88 519.48 c -217.89 519.48 217.08 518.67 217.08 517.68 c -217.08 516.69 217.89 515.88 218.88 515.88 c -219.87 515.88 220.68 516.69 220.68 517.68 c -f -0.80 0.00 0.00 rg -253.08 517.68 m 253.08 518.67 252.27 519.48 251.28 519.48 c -250.29 519.48 249.48 518.67 249.48 517.68 c -249.48 516.69 250.29 515.88 251.28 515.88 c -252.27 515.88 253.08 516.69 253.08 517.68 c -f -0.80 0.00 0.00 rg -263.88 517.68 m 263.88 518.67 263.07 519.48 262.08 519.48 c -261.09 519.48 260.28 518.67 260.28 517.68 c -260.28 516.69 261.09 515.88 262.08 515.88 c -263.07 515.88 263.88 516.69 263.88 517.68 c -f -0.80 0.00 0.00 rg -343.08 510.48 m 343.08 511.47 342.27 512.28 341.28 512.28 c -340.29 512.28 339.48 511.47 339.48 510.48 c -339.48 509.49 340.29 508.68 341.28 508.68 c -342.27 508.68 343.08 509.49 343.08 510.48 c -f -0.80 0.00 0.00 rg -357.48 510.48 m 357.48 511.47 356.67 512.28 355.68 512.28 c -354.69 512.28 353.88 511.47 353.88 510.48 c -353.88 509.49 354.69 508.68 355.68 508.68 c -356.67 508.68 357.48 509.49 357.48 510.48 c -f -0.80 0.00 0.00 rg -573.48 478.08 m 573.48 479.07 572.67 479.88 571.68 479.88 c -570.69 479.88 569.88 479.07 569.88 478.08 c -569.88 477.09 570.69 476.28 571.68 476.28 c -572.67 476.28 573.48 477.09 573.48 478.08 c -f -0.80 0.00 0.00 rg -703.08 416.88 m 703.08 417.87 702.27 418.68 701.28 418.68 c -700.29 418.68 699.48 417.87 699.48 416.88 c -699.48 415.89 700.29 415.08 701.28 415.08 c -702.27 415.08 703.08 415.89 703.08 416.88 c -f -0.80 0.00 0.00 rg -703.08 488.88 m 703.08 489.87 702.27 490.68 701.28 490.68 c -700.29 490.68 699.48 489.87 699.48 488.88 c -699.48 487.89 700.29 487.08 701.28 487.08 c -702.27 487.08 703.08 487.89 703.08 488.88 c -f -0.80 0.00 0.00 rg -659.88 208.08 m 659.88 209.07 659.07 209.88 658.08 209.88 c -657.09 209.88 656.28 209.07 656.28 208.08 c -656.28 207.09 657.09 206.28 658.08 206.28 c -659.07 206.28 659.88 207.09 659.88 208.08 c -f -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -712.080 402.480 m -704.880 402.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -712.080 396.000 m -712.080 408.960 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -713.520 398.160 m -713.520 406.800 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -714.960 400.320 m -714.960 404.640 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -716.400 401.760 m -716.400 403.200 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -704.880 402.480 m -704.880 402.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -571.680 409.680 m -568.080 406.080 l -557.280 406.080 l -557.280 413.280 l -568.080 413.280 l -571.680 409.680 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -571.680 409.680 m -571.680 409.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -539.71 407.62 Td -(OT_2) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -571.680 402.480 m -568.080 398.880 l -557.280 398.880 l -557.280 406.080 l -568.080 406.080 l -571.680 402.480 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -571.680 402.480 m -571.680 402.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -539.71 400.42 Td -(OT_1) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -172.080 380.880 m -164.880 380.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -172.080 384.480 m -172.080 377.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -164.880 380.880 m -164.880 380.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -173.59 378.45 Td -(5V) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -305.280 373.680 m -308.880 377.280 l -319.680 377.280 l -319.680 370.080 l -308.880 370.080 l -305.280 373.680 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -305.280 373.680 m -305.280 373.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -321.24 371.59 Td -(OT_1) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -305.280 366.480 m -308.880 370.080 l -319.680 370.080 l -319.680 362.880 l -308.880 362.880 l -305.280 366.480 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -305.280 366.480 m -305.280 366.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -321.52 364.85 Td -(OT_2) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -305.280 359.280 m -308.880 362.880 l -319.680 362.880 l -319.680 355.680 l -308.880 355.680 l -305.280 359.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -305.280 359.280 m -305.280 359.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -321.95 357.65 Td -(TEMP1) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -712.080 488.880 m -704.880 488.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -712.080 492.480 m -712.080 485.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -704.880 488.880 m -704.880 488.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -714.36 485.76 Td -(5V) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -229.680 373.680 m -233.280 377.280 l -244.080 377.280 l -244.080 370.080 l -233.280 370.080 l -229.680 373.680 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -229.680 373.680 m -229.680 373.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -245.24 371.37 Td -(TEMP2) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -571.680 416.880 m -568.080 413.280 l -557.280 413.280 l -557.280 420.480 l -568.080 420.480 l -571.680 416.880 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -571.680 416.880 m -571.680 416.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -534.96 414.82 Td -(TEMP2) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -172.080 352.080 m -164.880 352.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -172.080 345.600 m -172.080 358.560 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -173.520 347.760 m -173.520 356.400 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -174.960 349.920 m -174.960 354.240 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -176.400 351.360 m -176.400 352.800 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -164.880 352.080 m -164.880 352.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -118.080 517.680 m -139.680 517.680 l -S -139.680 517.680 m -139.680 503.280 l -S -71.280 517.680 m -118.080 517.680 l -S -71.280 506.880 m -71.280 517.680 l -S -118.080 514.080 m -118.080 517.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -118.080 517.680 m -139.680 517.680 l -S -139.680 517.680 m -139.680 503.280 l -S -71.280 517.680 m -118.080 517.680 l -S -71.280 506.880 m -71.280 517.680 l -S -118.080 514.080 m -118.080 517.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -118.080 481.680 m -139.680 481.680 l -S -139.680 481.680 m -139.680 496.080 l -S -103.680 481.680 m -118.080 481.680 l -S -118.080 485.280 m -118.080 481.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -118.080 481.680 m -139.680 481.680 l -S -139.680 481.680 m -139.680 496.080 l -S -103.680 481.680 m -118.080 481.680 l -S -118.080 485.280 m -118.080 481.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -71.280 492.480 m -71.280 481.680 l -S -71.280 481.680 m -74.880 481.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -71.280 492.480 m -71.280 481.680 l -S -71.280 481.680 m -74.880 481.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -355.680 488.880 m -355.680 481.680 l -S -355.680 481.680 m -305.280 481.680 l -S -305.280 481.680 m -251.280 481.680 l -S -251.280 481.680 m -218.880 481.680 l -S -218.880 481.680 m -190.080 481.680 l -S -190.080 481.680 m -190.080 496.080 l -S -218.880 488.880 m -218.880 481.680 l -S -251.280 485.280 m -251.280 481.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -355.680 488.880 m -355.680 481.680 l -S -355.680 481.680 m -305.280 481.680 l -S -305.280 481.680 m -251.280 481.680 l -S -251.280 481.680 m -218.880 481.680 l -S -218.880 481.680 m -190.080 481.680 l -S -190.080 481.680 m -190.080 496.080 l -S -218.880 488.880 m -218.880 481.680 l -S -251.280 485.280 m -251.280 481.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -190.080 503.280 m -190.080 517.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -190.080 503.280 m -190.080 517.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -218.880 510.480 m -218.880 517.680 l -S -218.880 517.680 m -251.280 517.680 l -S -251.280 514.080 m -251.280 517.680 l -S -251.280 517.680 m -262.080 517.680 l -S -262.080 517.680 m -269.280 517.680 l -S -262.080 524.880 m -262.080 517.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -218.880 510.480 m -218.880 517.680 l -S -218.880 517.680 m -251.280 517.680 l -S -251.280 514.080 m -251.280 517.680 l -S -251.280 517.680 m -262.080 517.680 l -S -262.080 517.680 m -269.280 517.680 l -S -262.080 524.880 m -262.080 517.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -341.280 517.680 m -341.280 510.480 l -S -341.280 510.480 m -355.680 510.480 l -S -355.680 524.880 m -355.680 510.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -341.280 517.680 m -341.280 510.480 l -S -341.280 510.480 m -355.680 510.480 l -S -355.680 524.880 m -355.680 510.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -571.680 474.480 m -571.680 478.080 l -S -589.680 474.480 m -571.680 474.480 l -S -571.680 478.080 m -571.680 481.680 l -S -571.680 481.680 m -589.680 481.680 l -S -571.680 478.080 m -568.080 478.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -571.680 474.480 m -571.680 478.080 l -S -589.680 474.480 m -571.680 474.480 l -S -571.680 478.080 m -571.680 481.680 l -S -571.680 481.680 m -589.680 481.680 l -S -571.680 478.080 m -568.080 478.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -683.280 416.880 m -701.280 416.880 l -S -701.280 416.880 m -701.280 409.680 l -S -701.280 409.680 m -683.280 409.680 l -S -701.280 416.880 m -704.880 416.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -683.280 416.880 m -701.280 416.880 l -S -701.280 416.880 m -701.280 409.680 l -S -701.280 409.680 m -683.280 409.680 l -S -701.280 416.880 m -704.880 416.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -683.280 402.480 m -704.880 402.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -683.280 402.480 m -704.880 402.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -305.280 373.680 m -298.080 373.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -305.280 373.680 m -298.080 373.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -305.280 366.480 m -298.080 366.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -305.280 366.480 m -298.080 366.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -305.280 359.280 m -298.080 359.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -305.280 359.280 m -298.080 359.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -229.680 373.680 m -222.480 373.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -229.680 373.680 m -222.480 373.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -571.680 409.680 m -589.680 409.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -571.680 409.680 m -589.680 409.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -571.680 402.480 m -589.680 402.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -571.680 402.480 m -589.680 402.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -701.280 496.080 m -683.280 496.080 l -S -701.280 488.880 m -701.280 496.080 l -S -701.280 488.880 m -683.280 488.880 l -S -701.280 481.680 m -701.280 488.880 l -S -683.280 481.680 m -701.280 481.680 l -S -701.280 488.880 m -704.880 488.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -701.280 496.080 m -683.280 496.080 l -S -701.280 488.880 m -701.280 496.080 l -S -701.280 488.880 m -683.280 488.880 l -S -701.280 481.680 m -701.280 488.880 l -S -683.280 481.680 m -701.280 481.680 l -S -701.280 488.880 m -704.880 488.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -164.880 373.680 m -164.880 380.880 l -S -161.280 373.680 m -164.880 373.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -164.880 373.680 m -164.880 380.880 l -S -161.280 373.680 m -164.880 373.680 l -S -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -146.88 510.48 36.00 -21.60 re -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -[] 0 d -151.56 506.88 m 151.56 507.48 151.08 507.96 150.48 507.96 c -149.88 507.96 149.40 507.48 149.40 506.88 c -149.40 506.28 149.88 505.80 150.48 505.80 c -151.08 505.80 151.56 506.28 151.56 506.88 c -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -149.54 500.56 Td -(AC) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -143.09 504.16 Td -(1) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -139.680 503.280 m -146.880 503.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -149.54 493.36 Td -(AC) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -143.09 496.96 Td -(2) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -139.680 496.080 m -146.880 496.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -169.26 493.36 Td -(-VO) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -183.24 496.96 Td -(3) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -190.080 496.080 m -182.880 496.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -167.72 500.56 Td -(+VO) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -183.24 504.16 Td -(4) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -190.080 503.280 m -182.880 503.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -146.18 519.53 Td -(U2) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -146.18 513.04 Td -(HLK-PM01) Tj -ET -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -197.28 520.56 14.40 -5.76 re -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -218.880 517.680 m -211.680 517.680 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -190.080 517.680 m -197.280 517.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -197.280 517.680 m -211.680 517.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -196.96 530.30 Td -(F2) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -197.20 523.10 Td -(MF-MSMF110/16-2) Tj -ET -1 J -1 j -0.72 w -0.00 G -0.00 g -[4.320 5.040] 0 d -434.880 139.680 m -435.107 589.572 l -S -1 J -1 j -0.72 w -0.00 G -0.00 g -[4.320 5.040] 0 d -434.880 434.880 m -10.080 434.880 l -S -0.00 0.00 1.00 RG -0.44 w -[] 0 d -172.080 563.481 m -244.869 563.481 l -S -7.20 w -BT -/F2 12.127389457069665 Tf -14.17 TL -0.000 0.000 1.000 rg -172.08 563.92 Td -(Power supply) Tj -ET -0.00 0.00 1.00 RG -0.44 w -[] 0 d -614.880 567.081 m -658.696 567.081 l -S -7.20 w -BT -/F2 12.127389457069665 Tf -14.17 TL -0.000 0.000 1.000 rg -614.88 567.52 Td -(Board A) Tj -ET -0.00 0.00 1.00 RG -0.44 w -[] 0 d -179.280 408.681 m -241.287 408.681 l -S -7.20 w -BT -/F2 12.127389457069665 Tf -14.17 TL -0.000 0.000 1.000 rg -179.28 409.12 Td -(Connectors) Tj -ET -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -74.88 380.88 14.40 -28.80 re -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -[] 0 d -86.76 377.28 m 86.76 377.88 86.28 378.36 85.68 378.36 c -85.08 378.36 84.60 377.88 84.60 377.28 c -84.60 376.68 85.08 376.20 85.68 376.20 c -86.28 376.20 86.76 376.68 86.76 377.28 c -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -84.57 370.90 Td -(1) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -91.02 367.30 Td -(1) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -96.480 373.680 m -89.280 373.680 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -93.600 376.560 m -99.360 370.800 l -93.600 370.800 m -99.360 376.560 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -84.57 363.70 Td -(2) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -91.02 360.10 Td -(2) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -96.480 366.480 m -89.280 366.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -84.57 356.50 Td -(3) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -91.02 352.90 Td -(3) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -96.480 359.280 m -89.280 359.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -74.88 382.42 Td -(U6) Tj -ET -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -139.68 380.88 14.40 -28.80 re -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -[] 0 d -151.56 377.28 m 151.56 377.88 151.08 378.36 150.48 378.36 c -149.88 378.36 149.40 377.88 149.40 377.28 c -149.40 376.68 149.88 376.20 150.48 376.20 c -151.08 376.20 151.56 376.68 151.56 377.28 c -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -149.37 370.90 Td -(1) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -155.82 367.30 Td -(1) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -161.280 373.680 m -154.080 373.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -149.37 363.70 Td -(2) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -155.82 360.10 Td -(2) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -161.280 366.480 m -154.080 366.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -149.37 356.50 Td -(3) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -155.82 352.90 Td -(3) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -161.280 359.280 m -154.080 359.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -139.68 382.42 Td -(U7) Tj -ET -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -200.88 380.88 14.40 -28.80 re -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -[] 0 d -212.76 377.28 m 212.76 377.88 212.28 378.36 211.68 378.36 c -211.08 378.36 210.60 377.88 210.60 377.28 c -210.60 376.68 211.08 376.20 211.68 376.20 c -212.28 376.20 212.76 376.68 212.76 377.28 c -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -210.57 370.90 Td -(1) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -217.02 367.30 Td -(1) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -222.480 373.680 m -215.280 373.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -210.57 363.70 Td -(2) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -217.02 360.10 Td -(2) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -222.480 366.480 m -215.280 366.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -210.57 356.50 Td -(3) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -217.02 352.90 Td -(3) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -222.480 359.280 m -215.280 359.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -200.88 382.42 Td -(U8) Tj -ET -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -276.48 380.88 14.40 -28.80 re -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -[] 0 d -288.36 377.28 m 288.36 377.88 287.88 378.36 287.28 378.36 c -286.68 378.36 286.20 377.88 286.20 377.28 c -286.20 376.68 286.68 376.20 287.28 376.20 c -287.88 376.20 288.36 376.68 288.36 377.28 c -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -286.17 370.90 Td -(1) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -292.62 367.30 Td -(1) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -298.080 373.680 m -290.880 373.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -286.17 363.70 Td -(2) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -292.62 360.10 Td -(2) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -298.080 366.480 m -290.880 366.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -286.17 356.50 Td -(3) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -292.62 352.90 Td -(3) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -298.080 359.280 m -290.880 359.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -276.48 382.42 Td -(U9) Tj -ET -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -82.08 484.56 14.40 -5.76 re -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -103.680 481.680 m -96.480 481.680 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -74.880 481.680 m -82.080 481.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -82.080 481.680 m -96.480 481.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -81.34 485.38 Td -(F1) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -164.880 352.080 m -161.280 352.080 l -S -161.280 352.080 m -161.280 359.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -164.880 352.080 m -161.280 352.080 l -S -161.280 352.080 m -161.280 359.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -172.080 366.480 m -164.880 366.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -172.080 370.080 m -172.080 362.880 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -164.880 366.480 m -164.880 366.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -173.75 364.37 Td -(3.3V) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -161.280 366.480 m -164.880 366.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -161.280 366.480 m -164.880 366.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -229.680 366.480 m -233.280 370.080 l -244.080 370.080 l -244.080 362.880 l -233.280 362.880 l -229.680 366.480 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -229.680 366.480 m -229.680 366.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -245.24 364.17 Td -(CC_IN) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -222.480 366.480 m -229.680 366.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -222.480 366.480 m -229.680 366.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -229.680 359.280 m -233.280 362.880 l -244.080 362.880 l -244.080 355.680 l -233.280 355.680 l -229.680 359.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -229.680 359.280 m -229.680 359.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -245.24 356.97 Td -(CC_OUT) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -222.480 359.280 m -229.680 359.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -222.480 359.280 m -229.680 359.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -668.880 308.880 m -661.680 308.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -668.880 312.480 m -668.880 305.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -661.680 308.880 m -661.680 308.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -670.61 306.82 Td -(3.3V) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -650.880 308.880 m -643.680 308.880 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -622.080 308.880 m -629.280 308.880 l -S -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -629.28 311.76 14.40 -5.76 re -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -628.56 312.58 Td -(R2) Tj -ET -7.20 w -BT -7.20 TL -0.000 0.000 1.000 rg -628.56 300.34 Td -/F2 6.16071384419139 Tf -(4.7k) Tj -/F3 6.16071384419139 Tf -<03a9> Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -661.680 308.880 m -650.880 308.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -661.680 308.880 m -650.880 308.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -611.280 308.880 m -607.680 305.280 l -596.880 305.280 l -596.880 312.480 l -607.680 312.480 l -611.280 308.880 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -611.280 308.880 m -611.280 308.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -574.56 306.82 Td -(TEMP1) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -611.280 308.880 m -622.080 308.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -611.280 308.880 m -622.080 308.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -668.880 272.880 m -661.680 272.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -668.880 276.480 m -668.880 269.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -661.680 272.880 m -661.680 272.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -670.61 270.82 Td -(3.3V) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -622.080 272.880 m -629.280 272.880 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -650.880 272.880 m -643.680 272.880 l -S -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -629.28 275.76 14.40 -5.76 re -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -628.56 276.58 Td -(R10) Tj -ET -7.20 w -BT -7.20 TL -0.000 0.000 1.000 rg -628.56 264.34 Td -/F2 6.16071384419139 Tf -(4.7k) Tj -/F3 6.16071384419139 Tf -<03a9> Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -650.880 272.880 m -661.680 272.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -650.880 272.880 m -661.680 272.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -611.280 272.880 m -607.680 269.280 l -596.880 269.280 l -596.880 276.480 l -607.680 276.480 l -611.280 272.880 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -611.280 272.880 m -611.280 272.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -573.84 270.82 Td -(TEMP2) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -611.280 272.880 m -622.080 272.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -611.280 272.880 m -622.080 272.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -571.680 424.080 m -568.080 420.480 l -557.280 420.480 l -557.280 427.680 l -568.080 427.680 l -571.680 424.080 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -571.680 424.080 m -571.680 424.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -534.96 422.02 Td -(TEMP1) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -571.680 424.080 m -589.680 424.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -571.680 424.080 m -589.680 424.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -571.680 416.880 m -589.680 416.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -571.680 416.880 m -589.680 416.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -611.280 208.080 m -607.680 204.480 l -596.880 204.480 l -596.880 211.680 l -607.680 211.680 l -611.280 208.080 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -611.280 208.080 m -611.280 208.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -575.52 206.02 Td -(CC_IN) Tj -ET -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -629.28 210.96 14.40 -5.76 re -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -622.080 208.080 m -629.280 208.080 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -650.880 208.080 m -643.680 208.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -628.56 211.78 Td -(R15) Tj -ET -7.20 w -BT -7.20 TL -0.000 0.000 1.000 rg -629.28 199.54 Td -/F2 6.16071384419139 Tf -(220) Tj -/F3 6.16071384419139 Tf -<03a9> Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -611.280 208.080 m -622.080 208.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -611.280 208.080 m -622.080 208.080 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -658.080 175.680 m -658.080 182.880 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -658.080 204.480 m -658.080 197.280 l -S -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -655.20 197.28 5.76 -14.40 re -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -662.40 191.62 Td -(R16) Tj -ET -7.20 w -BT -7.20 TL -0.000 0.000 1.000 rg -662.40 184.42 Td -/F2 6.16071384419139 Tf -(5.1k) Tj -/F3 6.16071384419139 Tf -<03a9> Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -658.080 168.480 m -658.080 175.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -651.600 168.480 m -664.560 168.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -653.760 167.040 m -662.400 167.040 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -655.920 165.600 m -660.240 165.600 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -657.360 164.160 m -658.800 164.160 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -658.080 175.680 m -658.080 175.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -665.280 208.080 m -668.880 211.680 l -679.680 211.680 l -679.680 204.480 l -668.880 204.480 l -665.280 208.080 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -665.280 208.080 m -665.280 208.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -682.56 206.02 Td -(CC_IN_A) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -571.680 431.280 m -568.080 427.680 l -557.280 427.680 l -557.280 434.880 l -568.080 434.880 l -571.680 431.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -571.680 431.280 m -571.680 431.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -528.38 429.22 Td -(CC_IN_A) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -571.680 431.280 m -589.680 431.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -571.680 431.280 m -589.680 431.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -571.680 438.480 m -568.080 434.880 l -557.280 434.880 l -557.280 442.080 l -568.080 442.080 l -571.680 438.480 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -571.680 438.480 m -571.680 438.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -521.54 436.42 Td -(CC_OUT_A) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -571.680 438.480 m -589.680 438.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -571.680 438.480 m -589.680 438.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -611.280 240.480 m -607.680 236.880 l -596.880 236.880 l -596.880 244.080 l -607.680 244.080 l -611.280 240.480 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -611.280 240.480 m -611.280 240.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -568.67 238.42 Td -(CC_OUT) Tj -ET -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -629.28 243.36 14.40 -5.76 re -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -622.080 240.480 m -629.280 240.480 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -650.880 240.480 m -643.680 240.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -628.56 244.18 Td -(R14) Tj -ET -7.20 w -BT -7.20 TL -0.000 0.000 1.000 rg -629.28 231.94 Td -/F2 6.16071384419139 Tf -(220) Tj -/F3 6.16071384419139 Tf -<03a9> Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -622.080 240.480 m -611.280 240.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -622.080 240.480 m -611.280 240.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -665.280 240.480 m -668.880 244.080 l -679.680 244.080 l -679.680 236.880 l -668.880 236.880 l -665.280 240.480 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -665.280 240.480 m -665.280 240.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -682.56 238.42 Td -(CC_OUT_A) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -665.280 240.480 m -650.880 240.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -665.280 240.480 m -650.880 240.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -658.080 208.080 m -665.280 208.080 l -S -658.080 208.080 m -650.880 208.080 l -S -658.080 208.080 m -658.080 204.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -658.080 208.080 m -665.280 208.080 l -S -658.080 208.080 m -650.880 208.080 l -S -658.080 208.080 m -658.080 204.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -658.080 175.680 m -658.080 175.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -658.080 175.680 m -658.080 175.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -605.52 472.48 Td -(17) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -589.680 474.480 m -604.080 474.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -605.52 479.68 Td -(18) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -589.680 481.680 m -604.080 481.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -605.52 486.88 Td -(19) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -589.680 488.880 m -604.080 488.880 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -586.800 491.760 m -592.560 486.000 l -586.800 486.000 m -592.560 491.760 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -660.59 479.68 Td -(23) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -683.280 481.680 m -668.880 481.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -660.59 486.88 Td -(22) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -683.280 488.880 m -668.880 488.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -660.59 494.08 Td -(21) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -683.280 496.080 m -668.880 496.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -605.52 400.48 Td -(27) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -589.680 402.480 m -604.080 402.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -605.52 407.68 Td -(28) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -589.680 409.680 m -604.080 409.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -605.52 414.88 Td -(29) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -589.680 416.880 m -604.080 416.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -660.59 400.48 Td -(26) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -683.280 402.480 m -668.880 402.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -660.59 407.68 Td -(25) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -683.280 409.680 m -668.880 409.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -660.59 414.88 Td -(24) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -683.280 416.880 m -668.880 416.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -605.52 494.08 Td -(20) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -589.680 496.080 m -604.080 496.080 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -586.800 498.960 m -592.560 493.200 l -586.800 493.200 m -592.560 498.960 l -S -0.60 G -0.00 w -586.080 539.280 m -582.480 535.680 l -S -589.680 539.280 m -582.480 532.080 l -S -593.280 539.280 m -582.480 528.480 l -S -596.880 539.280 m -582.480 524.880 l -S -600.480 539.280 m -582.480 521.280 l -S -604.080 539.280 m -582.480 517.680 l -S -607.680 539.280 m -582.480 514.080 l -S -611.280 539.280 m -582.480 510.480 l -S -614.880 539.280 m -582.480 506.880 l -S -618.480 539.280 m -582.480 503.280 l -S -622.080 539.280 m -582.480 499.680 l -S -625.680 539.280 m -582.480 496.080 l -S -629.280 539.280 m -582.480 492.480 l -S -632.880 539.280 m -582.480 488.880 l -S -636.480 539.280 m -582.480 485.280 l -S -640.080 539.280 m -582.480 481.680 l -S -643.680 539.280 m -582.480 478.080 l -S -647.280 539.280 m -582.480 474.480 l -S -650.880 539.280 m -582.480 470.880 l -S -654.480 539.280 m -582.480 467.280 l -S -658.080 539.280 m -582.480 463.680 l -S -661.680 539.280 m -582.480 460.080 l -S -665.280 539.280 m -582.480 456.480 l -S -668.880 539.280 m -582.480 452.880 l -S -672.480 539.280 m -582.480 449.280 l -S -676.080 539.280 m -582.480 445.680 l -S -679.680 539.280 m -582.480 442.080 l -S -683.280 539.280 m -582.480 438.480 l -S -686.880 539.280 m -582.480 434.880 l -S -690.480 539.280 m -582.480 431.280 l -S -690.480 535.680 m -582.480 427.680 l -S -690.480 532.080 m -582.480 424.080 l -S -690.480 528.480 m -582.480 420.480 l -S -690.480 524.880 m -582.480 416.880 l -S -690.480 521.280 m -582.480 413.280 l -S -690.480 517.680 m -582.480 409.680 l -S -690.480 514.080 m -582.480 406.080 l -S -690.480 510.480 m -582.480 402.480 l -S -690.480 506.880 m -582.480 398.880 l -S -690.480 503.280 m -582.480 395.280 l -S -690.480 499.680 m -582.480 391.680 l -S -690.480 496.080 m -582.480 388.080 l -S -690.480 492.480 m -582.480 384.480 l -S -690.480 488.880 m -582.480 380.880 l -S -690.480 485.280 m -582.480 377.280 l -S -690.480 481.680 m -582.480 373.680 l -S -690.480 478.080 m -582.480 370.080 l -S -690.480 474.480 m -582.480 366.480 l -S -690.480 470.880 m -582.480 362.880 l -S -690.480 467.280 m -582.480 359.280 l -S -690.480 463.680 m -582.480 355.680 l -S -690.480 460.080 m -582.480 352.080 l -S -690.480 456.480 m -582.480 348.480 l -S -690.480 452.880 m -582.480 344.880 l -S -690.480 449.280 m -586.080 344.880 l -S -690.480 445.680 m -589.680 344.880 l -S -690.480 442.080 m -593.280 344.880 l -S -690.480 438.480 m -596.880 344.880 l -S -690.480 434.880 m -600.480 344.880 l -S -690.480 431.280 m -604.080 344.880 l -S -690.480 427.680 m -607.680 344.880 l -S -690.480 424.080 m -611.280 344.880 l -S -690.480 420.480 m -614.880 344.880 l -S -690.480 416.880 m -618.480 344.880 l -S -690.480 413.280 m -622.080 344.880 l -S -690.480 409.680 m -625.680 344.880 l -S -690.480 406.080 m -629.280 344.880 l -S -690.480 402.480 m -632.880 344.880 l -S -690.480 398.880 m -636.480 344.880 l -S -690.480 395.280 m -640.080 344.880 l -S -690.480 391.680 m -643.680 344.880 l -S -690.480 388.080 m -647.280 344.880 l -S -690.480 384.480 m -650.880 344.880 l -S -690.480 380.880 m -654.480 344.880 l -S -690.480 377.280 m -658.080 344.880 l -S -690.480 373.680 m -661.680 344.880 l -S -690.480 370.080 m -665.280 344.880 l -S -690.480 366.480 m -668.880 344.880 l -S -690.480 362.880 m -672.480 344.880 l -S -690.480 359.280 m -676.080 344.880 l -S -690.480 355.680 m -679.680 344.880 l -S -690.480 352.080 m -683.280 344.880 l -S -690.480 348.480 m -686.880 344.880 l -S -586.080 344.880 m -582.480 348.480 l -S -589.680 344.880 m -582.480 352.080 l -S -593.280 344.880 m -582.480 355.680 l -S -596.880 344.880 m -582.480 359.280 l -S -600.480 344.880 m -582.480 362.880 l -S -604.080 344.880 m -582.480 366.480 l -S -607.680 344.880 m -582.480 370.080 l -S -611.280 344.880 m -582.480 373.680 l -S -614.880 344.880 m -582.480 377.280 l -S -618.480 344.880 m -582.480 380.880 l -S -622.080 344.880 m -582.480 384.480 l -S -625.680 344.880 m -582.480 388.080 l -S -629.280 344.880 m -582.480 391.680 l -S -632.880 344.880 m -582.480 395.280 l -S -636.480 344.880 m -582.480 398.880 l -S -640.080 344.880 m -582.480 402.480 l -S -643.680 344.880 m -582.480 406.080 l -S -647.280 344.880 m -582.480 409.680 l -S -650.880 344.880 m -582.480 413.280 l -S -654.480 344.880 m -582.480 416.880 l -S -658.080 344.880 m -582.480 420.480 l -S -661.680 344.880 m -582.480 424.080 l -S -665.280 344.880 m -582.480 427.680 l -S -668.880 344.880 m -582.480 431.280 l -S -672.480 344.880 m -582.480 434.880 l -S -676.080 344.880 m -582.480 438.480 l -S -679.680 344.880 m -582.480 442.080 l -S -683.280 344.880 m -582.480 445.680 l -S -686.880 344.880 m -582.480 449.280 l -S -690.480 344.880 m -582.480 452.880 l -S -690.480 348.480 m -582.480 456.480 l -S -690.480 352.080 m -582.480 460.080 l -S -690.480 355.680 m -582.480 463.680 l -S -690.480 359.280 m -582.480 467.280 l -S -690.480 362.880 m -582.480 470.880 l -S -690.480 366.480 m -582.480 474.480 l -S -690.480 370.080 m -582.480 478.080 l -S -690.480 373.680 m -582.480 481.680 l -S -690.480 377.280 m -582.480 485.280 l -S -690.480 380.880 m -582.480 488.880 l -S -690.480 384.480 m -582.480 492.480 l -S -690.480 388.080 m -582.480 496.080 l -S -690.480 391.680 m -582.480 499.680 l -S -690.480 395.280 m -582.480 503.280 l -S -690.480 398.880 m -582.480 506.880 l -S -690.480 402.480 m -582.480 510.480 l -S -690.480 406.080 m -582.480 514.080 l -S -690.480 409.680 m -582.480 517.680 l -S -690.480 413.280 m -582.480 521.280 l -S -690.480 416.880 m -582.480 524.880 l -S -690.480 420.480 m -582.480 528.480 l -S -690.480 424.080 m -582.480 532.080 l -S -690.480 427.680 m -582.480 535.680 l -S -582.480 539.280 m -690.480 431.280 l -S -586.080 539.280 m -690.480 434.880 l -S -589.680 539.280 m -690.480 438.480 l -S -593.280 539.280 m -690.480 442.080 l -S -596.880 539.280 m -690.480 445.680 l -S -600.480 539.280 m -690.480 449.280 l -S -604.080 539.280 m -690.480 452.880 l -S -607.680 539.280 m -690.480 456.480 l -S -611.280 539.280 m -690.480 460.080 l -S -614.880 539.280 m -690.480 463.680 l -S -618.480 539.280 m -690.480 467.280 l -S -622.080 539.280 m -690.480 470.880 l -S -625.680 539.280 m -690.480 474.480 l -S -629.280 539.280 m -690.480 478.080 l -S -632.880 539.280 m -690.480 481.680 l -S -636.480 539.280 m -690.480 485.280 l -S -640.080 539.280 m -690.480 488.880 l -S -643.680 539.280 m -690.480 492.480 l -S -647.280 539.280 m -690.480 496.080 l -S -650.880 539.280 m -690.480 499.680 l -S -654.480 539.280 m -690.480 503.280 l -S -658.080 539.280 m -690.480 506.880 l -S -661.680 539.280 m -690.480 510.480 l -S -665.280 539.280 m -690.480 514.080 l -S -668.880 539.280 m -690.480 517.680 l -S -672.480 539.280 m -690.480 521.280 l -S -676.080 539.280 m -690.480 524.880 l -S -679.680 539.280 m -690.480 528.480 l -S -683.280 539.280 m -690.480 532.080 l -S -686.880 539.280 m -690.480 535.680 l -S -2 J -0 j -72 M -0.72 w -0.60 G -0.60 g -[] 0 d -582.48 539.28 108.00 -194.40 re -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -605.52 422.08 Td -(30) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -589.680 424.080 m -604.080 424.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -605.52 429.28 Td -(31) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -589.680 431.280 m -604.080 431.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -605.52 436.48 Td -(32) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -589.680 438.480 m -604.080 438.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.600 g -581.79 541.14 Td -(PCB_A1) Tj -ET -1 J -1 j -0.72 w -0.00 G -0.00 g -[4.320 5.040] 0 d -434.880 254.880 m -10.080 254.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -96.480 366.480 m -100.080 366.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -96.480 366.480 m -100.080 366.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -100.080 352.080 m -100.080 359.280 l -S -100.080 359.280 m -96.480 359.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -100.080 352.080 m -100.080 359.280 l -S -100.080 359.280 m -96.480 359.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -107.280 352.080 m -100.080 352.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -107.280 355.680 m -107.280 348.480 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -100.080 352.080 m -100.080 352.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -114.12 349.85 Td -(L) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -107.280 366.480 m -100.080 366.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -107.280 360.000 m -107.280 372.960 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -108.720 362.160 m -108.720 370.800 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -110.160 364.320 m -110.160 368.640 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -111.600 365.760 m -111.600 367.200 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -100.080 366.480 m -100.080 366.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -113.63 364.42 Td -(N) Tj -ET -Q -endstream -endobj -5 0 obj -<> -endobj -6 0 obj -<< -/Length 125416 ->> -stream -0.14 w -0.53 0.00 0.00 RG -1 J -1 j -q -2 J -0 j -72 M -1.00 g -[] 0 d -0.00 599.76 848.16 -599.76 re -f -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -2.88 596.88 842.40 -594.00 re -S -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -10.08 589.68 828.00 -579.60 re -S -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -71.28 4.08 Td -<0031> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -71.28 590.88 Td -<0031> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -211.68 4.08 Td -<0032> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -211.68 590.88 Td -<0032> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -352.08 4.08 Td -<0033> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -352.08 590.88 Td -<0033> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -492.48 4.08 Td -<0034> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -492.48 590.88 Td -<0034> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -632.88 4.08 Td -<0035> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -632.88 590.88 Td -<0035> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -773.28 4.08 Td -<0036> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -773.28 590.88 Td -<0036> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -4.68 520.23 Td -<0041> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -839.88 520.23 Td -<0041> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -4.68 371.73 Td -<0042> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -839.88 371.73 Td -<0042> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -4.68 223.23 Td -<0043> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -839.88 223.23 Td -<0043> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -4.68 74.73 Td -<0044> Tj -ET -7.20 w -BT -/F1 7.1874993871380575 Tf -7.20 TL -0.627 0.000 0.000 rg -839.88 74.73 Td -<0044> Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -143.280 2.880 m -143.280 10.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -143.280 596.880 m -143.280 589.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -283.680 2.880 m -283.680 10.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -283.680 596.880 m -283.680 589.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -424.080 2.880 m -424.080 10.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -424.080 596.880 m -424.080 589.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -564.480 2.880 m -564.480 10.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -564.480 596.880 m -564.480 589.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -704.880 2.880 m -704.880 10.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -704.880 596.880 m -704.880 589.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -2.880 448.380 m -10.080 448.380 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -845.280 448.380 m -838.080 448.380 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -2.880 299.880 m -10.080 299.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -845.280 299.880 m -838.080 299.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -2.880 151.380 m -10.080 151.380 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -845.280 151.380 m -838.080 151.380 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -2.88 4.42 Td -(1) Tj -ET -7.20 w -BT -/F2 12.32142768838278 Tf -14.40 TL -0.000 0.000 0.502 rg -606.39 70.77 Td -(OpenTherm Gateway) Tj -ET -7.20 w -BT -/F2 9.241070766287086 Tf -10.80 TL -0.000 0.000 0.502 rg -793.75 43.71 Td -(2) Tj -ET -7.20 w -BT -/F2 9.241070766287086 Tf -10.80 TL -0.000 0.000 0.502 rg -730.08 129.39 Td -(2024-12-17) Tj -ET -7.20 w -BT -/F2 9.241070766287086 Tf -10.80 TL -0.000 0.000 0.502 rg -730.08 114.99 Td -(2024-09-16) Tj -ET -7.20 w -BT -/F2 12.32142768838278 Tf -14.40 TL -0.000 0.000 0.502 rg -500.40 121.17 Td -(otgateway) Tj -ET -7.20 w -BT -/F2 9.241070766287086 Tf -10.80 TL -0.000 0.000 0.502 rg -709.51 43.71 Td -(2) Tj -ET -7.20 w -BT -/F2 9.241070766287086 Tf -10.80 TL -0.000 0.000 0.502 rg -510.76 100.59 Td -(Sheet_B) Tj -ET -7.20 w -BT -/F2 9.241070766287086 Tf -10.80 TL -0.000 0.000 0.502 rg -506.48 21.39 Td -(V1.5.3) Tj -ET -7.20 w -BT -/F2 9.241070766287086 Tf -10.80 TL -0.000 0.000 0.502 rg -573.23 21.39 Td -(A4) Tj -ET -7.20 w -BT -/F2 9.241070766287086 Tf -10.80 TL -0.000 0.000 0.502 rg -404.64 86.19 Td -(Laxilef) Tj -ET -q -1 0 0 1 0 0 cm -7.20 w -BT -/F1 10.781249080707086 Tf -10.80 TL -0.627 0.000 0.000 rg -339.84 71.28 Td -<00520065007600690065007700650064> Tj -ET -7.20 w -BT -/F1 10.781249080707086 Tf -10.80 TL -0.627 0.000 0.000 rg -339.84 85.68 Td -<0044007200610077006e> Tj -ET -7.20 w -BT -/F1 10.781249080707086 Tf -10.80 TL -0.627 0.000 0.000 rg -511.75 42.48 Td -<005600450052> Tj -ET -7.20 w -BT -/F1 10.781249080707086 Tf -10.80 TL -0.627 0.000 0.000 rg -656.64 114.48 Td -<00430072006500610074006500200044006100740065> Tj -ET -7.20 w -BT -/F1 10.781249080707086 Tf -10.80 TL -0.627 0.000 0.000 rg -656.64 100.08 Td -<00500061007200740020004e0075006d006200650072> Tj -ET -7.20 w -BT -/F1 10.781249080707086 Tf -10.80 TL -0.627 0.000 0.000 rg -656.64 43.20 Td -<0050004100470045> Tj -ET -7.20 w -BT -/F1 10.781249080707086 Tf -10.80 TL -0.627 0.000 0.000 rg -745.92 43.20 Td -<004f0046> Tj -ET -7.20 w -BT -/F1 10.781249080707086 Tf -10.80 TL -0.627 0.000 0.000 rg -339.84 121.68 Td -<0053006300680065006d0061007400690063> Tj -ET -7.20 w -BT -/F1 10.781249080707086 Tf -10.80 TL -0.627 0.000 0.000 rg -656.64 128.88 Td -<00550070006400610074006500200044006100740065> Tj -ET -7.20 w -BT -/F1 10.781249080707086 Tf -10.80 TL -0.627 0.000 0.000 rg -566.66 42.48 Td -<00530049005a0045> Tj -ET -7.20 w -BT -/F1 10.781249080707086 Tf -10.80 TL -0.627 0.000 0.000 rg -341.28 100.08 Td -<0050006100670065> Tj -ET -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -332.64 139.68 505.44 -129.60 re -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -548.640 10.080 m -548.640 53.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -398.880 38.880 m -398.880 139.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -649.440 139.680 m -649.440 96.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -721.440 96.480 m -721.440 139.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -491.040 96.480 m -491.040 10.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -491.040 82.080 m -332.640 82.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -838.080 125.280 m -649.440 125.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -838.080 38.880 m -332.640 38.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -838.080 96.480 m -332.640 96.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -838.080 53.280 m -332.640 53.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -491.040 67.680 m -332.640 67.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -838.080 110.880 m -332.640 110.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -606.240 53.280 m -606.240 10.080 l -S -q -0.33 0.53 1.00 rg -[] 0 d -418.002 23.650 m -418.154 23.764 418.338 23.821 418.549 23.821 c -418.833 23.821 419.136 23.720 419.459 23.524 c -419.782 23.328 420.092 23.018 420.389 22.594 c -421.536 24.359 l -421.180 24.852 420.738 25.238 420.204 25.510 c -419.670 25.782 419.103 25.915 418.510 25.915 c -417.666 25.915 416.928 25.668 416.308 25.175 c -415.688 24.681 415.378 24.036 415.378 23.252 c -415.378 22.689 415.576 22.151 415.972 21.645 c -416.255 21.285 416.769 20.848 417.508 20.342 c -418.147 19.906 418.543 19.602 418.688 19.432 c -418.833 19.261 418.905 19.096 418.905 18.932 c -418.905 18.729 418.813 18.559 418.622 18.407 c -418.431 18.261 418.180 18.186 417.864 18.186 c -417.066 18.186 416.328 18.609 415.655 19.463 c -414.172 17.806 l -414.831 17.136 415.431 16.668 415.965 16.415 c -416.499 16.162 417.099 16.035 417.752 16.035 c -418.886 16.035 419.749 16.345 420.349 16.965 c -420.949 17.585 421.246 18.249 421.246 18.945 c -421.246 19.476 421.101 19.963 420.811 20.418 c -420.520 20.867 419.914 21.411 418.991 22.044 c -418.411 22.442 418.068 22.708 417.956 22.847 c -417.837 22.986 417.778 23.125 417.778 23.265 c -417.771 23.410 417.851 23.537 418.002 23.650 c -418.002 23.650 l -f -0.33 0.53 1.00 rg -[] 0 d -427.034 20.102 m -425.128 25.674 l -422.768 25.674 l -425.524 17.559 l -422.742 12.841 l -425.280 12.841 l -432.973 25.674 l -430.382 25.674 l -427.034 20.102 l -f -0.33 0.53 1.00 rg -[] 0 d -401.508 24.093 m -396.867 24.093 l -397.250 26.731 l -397.250 26.731 402.174 26.737 402.201 26.737 c -402.847 26.737 403.374 27.243 403.374 27.863 c -403.374 28.483 402.847 28.989 402.201 28.989 c -402.181 28.989 395.055 28.989 395.055 28.989 c -393.235 16.275 l -400.698 16.275 l -400.698 16.275 l -401.324 16.288 401.831 16.781 401.831 17.382 c -401.831 17.996 401.311 18.495 400.671 18.495 c -400.645 18.495 396.043 18.489 396.043 18.489 c -396.531 21.860 l -396.531 21.860 401.258 21.854 401.297 21.854 c -401.944 21.854 402.471 22.360 402.471 22.980 c -402.484 23.543 402.062 24.005 401.508 24.093 c -401.508 24.093 l -f -0.33 0.53 1.00 rg -[] 0 d -442.176 28.982 m -442.156 28.982 435.030 28.982 435.030 28.982 c -433.224 16.282 l -440.693 16.282 l -440.693 16.282 l -441.319 16.294 441.827 16.788 441.827 17.389 c -441.827 18.002 441.306 18.502 440.666 18.502 c -440.640 18.502 436.039 18.495 436.039 18.495 c -436.526 21.867 l -436.526 21.867 441.253 21.860 441.299 21.860 c -441.945 21.860 442.473 22.366 442.473 22.986 c -442.473 23.543 442.051 24.005 441.497 24.093 c -436.856 24.093 l -437.238 26.731 l -437.238 26.731 442.163 26.737 442.189 26.737 c -442.835 26.737 443.363 27.243 443.363 27.863 c -443.349 28.476 442.829 28.982 442.176 28.982 c -442.176 28.982 l -f -0.33 0.53 1.00 rg -[] 0 d -455.512 22.898 m -455.512 24.144 455.209 25.251 454.609 26.206 c -454.009 27.161 453.231 27.863 452.269 28.306 c -451.306 28.755 449.849 28.976 447.878 28.976 c -445.782 28.976 l -443.976 16.275 l -448.089 16.275 l -449.816 16.275 451.168 16.522 452.137 17.015 c -453.106 17.509 453.917 18.293 454.556 19.362 c -455.196 20.437 455.512 21.614 455.512 22.898 c -455.512 22.898 l -452.255 20.273 m -451.774 19.577 451.141 19.084 450.350 18.799 c -449.783 18.597 448.874 18.495 447.615 18.495 c -446.797 18.495 l -447.964 26.743 l -448.590 26.743 l -449.612 26.743 450.429 26.592 451.043 26.282 c -451.656 25.972 452.130 25.535 452.473 24.966 c -452.809 24.397 452.981 23.695 452.981 22.853 c -452.974 21.835 452.737 20.969 452.255 20.273 c -452.255 20.273 l -f -0.33 0.53 1.00 rg -[] 0 d -465.302 23.043 m -463.831 22.265 l -463.713 21.241 462.803 20.450 461.709 20.450 c -460.529 20.450 459.573 21.367 459.573 22.499 c -459.573 23.631 460.529 24.549 461.709 24.549 c -462.164 24.549 462.586 24.409 462.928 24.182 c -464.754 25.149 l -463.766 28.957 l -461.676 28.957 l -454.556 16.307 l -457.219 16.307 l -458.722 19.001 l -463.957 19.001 l -464.655 16.307 l -467.055 16.307 l -465.302 23.043 l -465.302 23.043 l -f -0.33 0.53 1.00 rg -[] 0 d -460.924 22.550 m -460.924 22.113 461.293 21.759 461.748 21.759 c -462.203 21.759 462.572 22.113 462.572 22.550 c -462.572 22.986 462.203 23.340 461.748 23.340 c -461.293 23.340 460.924 22.986 460.924 22.550 c -460.924 22.550 l -f -0.33 0.53 1.00 rg -[] 0 d -412.274 24.194 m -412.274 24.194 412.274 24.201 412.274 24.194 c -411.450 24.194 l -411.364 24.346 l -411.028 24.858 410.606 25.244 410.098 25.510 c -409.584 25.776 408.773 25.908 408.167 25.908 c -407.263 25.908 406.400 25.674 405.576 25.206 c -404.752 24.738 404.093 24.087 403.605 23.246 c -403.117 22.411 402.866 21.525 402.866 20.602 c -402.866 19.387 403.249 18.325 404.013 17.408 c -404.778 16.490 405.813 16.035 407.112 16.035 c -407.679 16.035 408.186 16.124 408.641 16.313 c -409.096 16.497 409.584 16.819 410.105 17.287 c -410.105 17.287 410.718 16.775 410.724 16.781 c -411.107 16.490 411.581 16.307 412.096 16.275 c -412.333 16.275 l -412.366 16.547 l -413.203 23.309 l -413.196 23.309 413.196 23.309 413.190 23.309 c -413.190 23.796 412.781 24.188 412.274 24.194 c -412.274 24.194 l -410.349 19.659 m -410.052 19.122 409.683 18.723 409.241 18.470 c -408.799 18.217 408.285 18.091 407.692 18.091 c -406.980 18.091 406.400 18.312 405.945 18.767 c -405.490 19.217 405.266 19.811 405.266 20.545 c -405.266 21.500 405.563 22.278 406.163 22.885 c -406.762 23.492 407.488 23.790 408.345 23.790 c -409.083 23.790 409.676 23.562 410.124 23.113 c -410.573 22.657 410.797 22.063 410.797 21.316 c -410.797 20.753 410.645 20.197 410.349 19.659 c -410.349 19.659 l -f -0.33 0.53 1.00 rg -[] 0 d -385.212 27.749 m -384.718 29.008 383.914 30.140 382.852 31.057 c -381.224 32.461 379.115 33.239 376.919 33.239 c -375.021 33.239 373.208 32.670 371.679 31.595 c -370.940 31.076 370.301 30.462 369.773 29.767 c -369.444 29.811 369.108 29.836 368.765 29.836 c -366.873 29.836 365.086 29.128 363.748 27.844 c -362.410 26.560 361.672 24.852 361.672 23.031 c -361.672 21.342 362.324 19.723 363.504 18.470 c -364.440 17.477 365.653 16.775 366.991 16.446 c -367.572 14.789 369.206 13.594 371.125 13.594 c -373.531 13.594 375.489 15.472 375.489 17.781 c -375.489 17.914 375.482 18.053 375.469 18.186 c -381.593 21.272 l -380.255 23.499 l -374.401 20.551 l -373.603 21.424 372.430 21.974 371.125 21.974 c -369.233 21.974 367.618 20.810 367.011 19.191 c -365.469 19.843 364.388 21.316 364.388 23.037 c -364.388 25.352 366.345 27.237 368.765 27.237 c -369.615 27.237 370.413 27.003 371.085 26.598 c -371.896 28.944 374.203 30.640 376.919 30.640 c -380.084 30.640 382.681 28.350 383.030 25.409 c -383.142 25.421 383.255 25.428 383.367 25.428 c -385.259 25.428 386.795 23.954 386.795 22.139 c -386.795 20.418 385.417 19.008 383.663 18.862 c -381.705 18.862 l -381.620 18.881 381.527 18.888 381.435 18.888 c -380.677 18.888 380.064 18.299 380.064 17.572 c -380.064 16.883 380.618 16.320 381.323 16.263 c -381.323 16.250 l -383.663 16.250 l -383.782 16.250 l -383.901 16.263 l -385.430 16.389 386.847 17.053 387.889 18.141 c -388.937 19.235 389.517 20.652 389.517 22.139 c -389.517 24.757 387.704 26.996 385.212 27.749 c -385.212 27.749 l -371.125 19.400 m -372.054 19.400 372.812 18.673 372.812 17.781 c -372.812 16.889 372.054 16.162 371.125 16.162 c -370.195 16.162 369.437 16.889 369.437 17.781 c -369.437 18.673 370.195 19.400 371.125 19.400 c -371.125 19.400 l -f -Q -Q -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -720.72 508.48 Td -(17) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -704.880 510.480 m -719.280 510.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -720.72 515.68 Td -(18) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -704.880 517.680 m -719.280 517.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -720.72 522.88 Td -(19) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -704.880 524.880 m -719.280 524.880 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -702.000 527.760 m -707.760 522.000 l -702.000 522.000 m -707.760 527.760 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -746.99 515.68 Td -(23) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -769.680 517.680 m -755.280 517.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -746.99 522.88 Td -(22) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -769.680 524.880 m -755.280 524.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -746.99 530.08 Td -(21) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -769.680 532.080 m -755.280 532.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -720.72 422.08 Td -(27) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -704.880 424.080 m -719.280 424.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -720.72 429.28 Td -(28) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -704.880 431.280 m -719.280 431.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -720.72 436.48 Td -(29) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -704.880 438.480 m -719.280 438.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -746.99 422.08 Td -(26) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -769.680 424.080 m -755.280 424.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -746.99 429.28 Td -(25) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -769.680 431.280 m -755.280 431.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -746.99 436.48 Td -(24) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -769.680 438.480 m -755.280 438.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -720.72 530.08 Td -(20) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -704.880 532.080 m -719.280 532.080 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -702.000 534.960 m -707.760 529.200 l -702.000 529.200 m -707.760 534.960 l -S -0.60 G -0.00 w -701.280 553.680 m -697.680 550.080 l -S -704.880 553.680 m -697.680 546.480 l -S -708.480 553.680 m -697.680 542.880 l -S -712.080 553.680 m -697.680 539.280 l -S -715.680 553.680 m -697.680 535.680 l -S -719.280 553.680 m -697.680 532.080 l -S -722.880 553.680 m -697.680 528.480 l -S -726.480 553.680 m -697.680 524.880 l -S -730.080 553.680 m -697.680 521.280 l -S -733.680 553.680 m -697.680 517.680 l -S -737.280 553.680 m -697.680 514.080 l -S -740.880 553.680 m -697.680 510.480 l -S -744.480 553.680 m -697.680 506.880 l -S -748.080 553.680 m -697.680 503.280 l -S -751.680 553.680 m -697.680 499.680 l -S -755.280 553.680 m -697.680 496.080 l -S -758.880 553.680 m -697.680 492.480 l -S -762.480 553.680 m -697.680 488.880 l -S -766.080 553.680 m -697.680 485.280 l -S -769.680 553.680 m -697.680 481.680 l -S -773.280 553.680 m -697.680 478.080 l -S -776.880 553.680 m -697.680 474.480 l -S -776.880 550.080 m -697.680 470.880 l -S -776.880 546.480 m -697.680 467.280 l -S -776.880 542.880 m -697.680 463.680 l -S -776.880 539.280 m -697.680 460.080 l -S -776.880 535.680 m -697.680 456.480 l -S -776.880 532.080 m -697.680 452.880 l -S -776.880 528.480 m -697.680 449.280 l -S -776.880 524.880 m -697.680 445.680 l -S -776.880 521.280 m -697.680 442.080 l -S -776.880 517.680 m -697.680 438.480 l -S -776.880 514.080 m -697.680 434.880 l -S -776.880 510.480 m -697.680 431.280 l -S -776.880 506.880 m -697.680 427.680 l -S -776.880 503.280 m -697.680 424.080 l -S -776.880 499.680 m -697.680 420.480 l -S -776.880 496.080 m -697.680 416.880 l -S -776.880 492.480 m -697.680 413.280 l -S -776.880 488.880 m -697.680 409.680 l -S -776.880 485.280 m -697.680 406.080 l -S -776.880 481.680 m -697.680 402.480 l -S -776.880 478.080 m -701.280 402.480 l -S -776.880 474.480 m -704.880 402.480 l -S -776.880 470.880 m -708.480 402.480 l -S -776.880 467.280 m -712.080 402.480 l -S -776.880 463.680 m -715.680 402.480 l -S -776.880 460.080 m -719.280 402.480 l -S -776.880 456.480 m -722.880 402.480 l -S -776.880 452.880 m -726.480 402.480 l -S -776.880 449.280 m -730.080 402.480 l -S -776.880 445.680 m -733.680 402.480 l -S -776.880 442.080 m -737.280 402.480 l -S -776.880 438.480 m -740.880 402.480 l -S -776.880 434.880 m -744.480 402.480 l -S -776.880 431.280 m -748.080 402.480 l -S -776.880 427.680 m -751.680 402.480 l -S -776.880 424.080 m -755.280 402.480 l -S -776.880 420.480 m -758.880 402.480 l -S -776.880 416.880 m -762.480 402.480 l -S -776.880 413.280 m -766.080 402.480 l -S -776.880 409.680 m -769.680 402.480 l -S -776.880 406.080 m -773.280 402.480 l -S -701.280 402.480 m -697.680 406.080 l -S -704.880 402.480 m -697.680 409.680 l -S -708.480 402.480 m -697.680 413.280 l -S -712.080 402.480 m -697.680 416.880 l -S -715.680 402.480 m -697.680 420.480 l -S -719.280 402.480 m -697.680 424.080 l -S -722.880 402.480 m -697.680 427.680 l -S -726.480 402.480 m -697.680 431.280 l -S -730.080 402.480 m -697.680 434.880 l -S -733.680 402.480 m -697.680 438.480 l -S -737.280 402.480 m -697.680 442.080 l -S -740.880 402.480 m -697.680 445.680 l -S -744.480 402.480 m -697.680 449.280 l -S -748.080 402.480 m -697.680 452.880 l -S -751.680 402.480 m -697.680 456.480 l -S -755.280 402.480 m -697.680 460.080 l -S -758.880 402.480 m -697.680 463.680 l -S -762.480 402.480 m -697.680 467.280 l -S -766.080 402.480 m -697.680 470.880 l -S -769.680 402.480 m -697.680 474.480 l -S -773.280 402.480 m -697.680 478.080 l -S -776.880 402.480 m -697.680 481.680 l -S -776.880 406.080 m -697.680 485.280 l -S -776.880 409.680 m -697.680 488.880 l -S -776.880 413.280 m -697.680 492.480 l -S -776.880 416.880 m -697.680 496.080 l -S -776.880 420.480 m -697.680 499.680 l -S -776.880 424.080 m -697.680 503.280 l -S -776.880 427.680 m -697.680 506.880 l -S -776.880 431.280 m -697.680 510.480 l -S -776.880 434.880 m -697.680 514.080 l -S -776.880 438.480 m -697.680 517.680 l -S -776.880 442.080 m -697.680 521.280 l -S -776.880 445.680 m -697.680 524.880 l -S -776.880 449.280 m -697.680 528.480 l -S -776.880 452.880 m -697.680 532.080 l -S -776.880 456.480 m -697.680 535.680 l -S -776.880 460.080 m -697.680 539.280 l -S -776.880 463.680 m -697.680 542.880 l -S -776.880 467.280 m -697.680 546.480 l -S -776.880 470.880 m -697.680 550.080 l -S -697.680 553.680 m -776.880 474.480 l -S -701.280 553.680 m -776.880 478.080 l -S -704.880 553.680 m -776.880 481.680 l -S -708.480 553.680 m -776.880 485.280 l -S -712.080 553.680 m -776.880 488.880 l -S -715.680 553.680 m -776.880 492.480 l -S -719.280 553.680 m -776.880 496.080 l -S -722.880 553.680 m -776.880 499.680 l -S -726.480 553.680 m -776.880 503.280 l -S -730.080 553.680 m -776.880 506.880 l -S -733.680 553.680 m -776.880 510.480 l -S -737.280 553.680 m -776.880 514.080 l -S -740.880 553.680 m -776.880 517.680 l -S -744.480 553.680 m -776.880 521.280 l -S -748.080 553.680 m -776.880 524.880 l -S -751.680 553.680 m -776.880 528.480 l -S -755.280 553.680 m -776.880 532.080 l -S -758.880 553.680 m -776.880 535.680 l -S -762.480 553.680 m -776.880 539.280 l -S -766.080 553.680 m -776.880 542.880 l -S -769.680 553.680 m -776.880 546.480 l -S -773.280 553.680 m -776.880 550.080 l -S -2 J -0 j -72 M -0.72 w -0.60 G -0.60 g -[] 0 d -697.68 553.68 79.20 -151.20 re -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -720.72 443.68 Td -(30) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -704.880 445.680 m -719.280 445.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -720.72 450.88 Td -(31) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -704.880 452.880 m -719.280 452.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -720.72 458.08 Td -(32) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -704.880 460.080 m -719.280 460.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.600 g -697.46 555.45 Td -(PCB_B1) Tj -ET -0.60 G -0.00 w -704.880 316.080 m -701.280 312.480 l -S -708.480 316.080 m -701.280 308.880 l -S -712.080 316.080 m -701.280 305.280 l -S -715.680 316.080 m -701.280 301.680 l -S -719.280 316.080 m -701.280 298.080 l -S -722.880 316.080 m -701.280 294.480 l -S -726.480 316.080 m -701.280 290.880 l -S -730.080 316.080 m -701.280 287.280 l -S -733.680 316.080 m -701.280 283.680 l -S -737.280 316.080 m -701.280 280.080 l -S -740.880 316.080 m -701.280 276.480 l -S -744.480 316.080 m -701.280 272.880 l -S -748.080 316.080 m -701.280 269.280 l -S -751.680 316.080 m -701.280 265.680 l -S -755.280 316.080 m -701.280 262.080 l -S -758.880 316.080 m -701.280 258.480 l -S -762.480 316.080 m -701.280 254.880 l -S -766.080 316.080 m -701.280 251.280 l -S -766.080 312.480 m -704.880 251.280 l -S -766.080 308.880 m -708.480 251.280 l -S -766.080 305.280 m -712.080 251.280 l -S -766.080 301.680 m -715.680 251.280 l -S -766.080 298.080 m -719.280 251.280 l -S -766.080 294.480 m -722.880 251.280 l -S -766.080 290.880 m -726.480 251.280 l -S -766.080 287.280 m -730.080 251.280 l -S -766.080 283.680 m -733.680 251.280 l -S -766.080 280.080 m -737.280 251.280 l -S -766.080 276.480 m -740.880 251.280 l -S -766.080 272.880 m -744.480 251.280 l -S -766.080 269.280 m -748.080 251.280 l -S -766.080 265.680 m -751.680 251.280 l -S -766.080 262.080 m -755.280 251.280 l -S -766.080 258.480 m -758.880 251.280 l -S -766.080 254.880 m -762.480 251.280 l -S -704.880 251.280 m -701.280 254.880 l -S -708.480 251.280 m -701.280 258.480 l -S -712.080 251.280 m -701.280 262.080 l -S -715.680 251.280 m -701.280 265.680 l -S -719.280 251.280 m -701.280 269.280 l -S -722.880 251.280 m -701.280 272.880 l -S -726.480 251.280 m -701.280 276.480 l -S -730.080 251.280 m -701.280 280.080 l -S -733.680 251.280 m -701.280 283.680 l -S -737.280 251.280 m -701.280 287.280 l -S -740.880 251.280 m -701.280 290.880 l -S -744.480 251.280 m -701.280 294.480 l -S -748.080 251.280 m -701.280 298.080 l -S -751.680 251.280 m -701.280 301.680 l -S -755.280 251.280 m -701.280 305.280 l -S -758.880 251.280 m -701.280 308.880 l -S -762.480 251.280 m -701.280 312.480 l -S -701.280 316.080 m -766.080 251.280 l -S -704.880 316.080 m -766.080 254.880 l -S -708.480 316.080 m -766.080 258.480 l -S -712.080 316.080 m -766.080 262.080 l -S -715.680 316.080 m -766.080 265.680 l -S -719.280 316.080 m -766.080 269.280 l -S -722.880 316.080 m -766.080 272.880 l -S -726.480 316.080 m -766.080 276.480 l -S -730.080 316.080 m -766.080 280.080 l -S -733.680 316.080 m -766.080 283.680 l -S -737.280 316.080 m -766.080 287.280 l -S -740.880 316.080 m -766.080 290.880 l -S -744.480 316.080 m -766.080 294.480 l -S -748.080 316.080 m -766.080 298.080 l -S -751.680 316.080 m -766.080 301.680 l -S -755.280 316.080 m -766.080 305.280 l -S -758.880 316.080 m -766.080 308.880 l -S -762.480 316.080 m -766.080 312.480 l -S -2 J -0 j -72 M -0.72 w -0.60 G -0.60 g -[] 0 d -701.28 316.08 64.80 -64.80 re -S -0.60 G -0.00 w -705.855 312.015 m -705.345 311.505 l -S -705.855 312.945 m -705.345 313.455 l -S -1 J -1 j -0.72 w -0.60 G -0.60 g -[] 0 d -705.96 312.48 m 705.96 313.08 705.48 313.56 704.88 313.56 c -704.28 313.56 703.80 313.08 703.80 312.48 c -703.80 311.88 704.28 311.40 704.88 311.40 c -705.48 311.40 705.96 311.88 705.96 312.48 c -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -703.94 306.16 Td -(TX) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -697.49 309.76 Td -(1) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -694.080 308.880 m -701.280 308.880 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -691.200 311.760 m -696.960 306.000 l -691.200 306.000 m -696.960 311.760 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -703.94 298.96 Td -(RX) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -697.49 302.56 Td -(2) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -694.080 301.680 m -701.280 301.680 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -691.200 304.560 m -696.960 298.800 l -691.200 298.800 m -696.960 304.560 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -703.94 291.76 Td -(D1\(5\)) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -697.49 295.36 Td -(3) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -694.080 294.480 m -701.280 294.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -703.94 284.56 Td -(D2\(4\)) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -697.49 288.16 Td -(4) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -694.080 287.280 m -701.280 287.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -703.94 277.36 Td -(D3\(0\)) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -697.49 280.96 Td -(5) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -694.080 280.080 m -701.280 280.080 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -691.200 282.960 m -696.960 277.200 l -691.200 277.200 m -696.960 282.960 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -703.94 270.16 Td -(D4\(2\)) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -697.49 273.76 Td -(6) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -694.080 272.880 m -701.280 272.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -703.94 262.96 Td -(G) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -697.49 266.56 Td -(7) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -694.080 265.680 m -701.280 265.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -703.94 255.76 Td -(5V) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -697.49 259.36 Td -(8) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -694.080 258.480 m -701.280 258.480 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -691.200 261.360 m -696.960 255.600 l -691.200 255.600 m -696.960 261.360 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -751.09 255.76 Td -(RST) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -766.44 259.36 Td -(9) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -773.280 258.480 m -766.080 258.480 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -770.400 261.360 m -776.160 255.600 l -770.400 255.600 m -776.160 261.360 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -755.88 262.96 Td -(A0) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -766.44 266.56 Td -(10) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -773.280 265.680 m -766.080 265.680 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -770.400 268.560 m -776.160 262.800 l -770.400 262.800 m -776.160 268.560 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -744.59 270.16 Td -(D0\(16\)) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -766.44 273.76 Td -(11) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -773.280 272.880 m -766.080 272.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -744.59 277.36 Td -(D5\(14\)) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -766.44 280.96 Td -(12) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -773.280 280.080 m -766.080 280.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -744.59 284.56 Td -(D6\(12\)) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -766.44 288.16 Td -(13) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -773.280 287.280 m -766.080 287.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -744.59 291.76 Td -(D7\(13\)) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -766.44 295.36 Td -(14) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -773.280 294.480 m -766.080 294.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -744.59 298.96 Td -(D8\(15\)) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -766.44 302.56 Td -(15) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -773.280 301.680 m -766.080 301.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -752.46 306.16 Td -(3V3) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -766.44 309.76 Td -(16) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -773.280 308.880 m -766.080 308.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.600 g -700.37 317.40 Td -(U1) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.600 g -708.48 242.02 Td -(WEMOS_D1_MINI) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -676.080 251.280 m -676.080 258.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -669.600 251.280 m -682.560 251.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -671.760 249.840 m -680.400 249.840 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -673.920 248.400 m -678.240 248.400 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -675.360 246.960 m -676.800 246.960 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -676.080 258.480 m -676.080 258.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -668.85 240.29 Td -(GND) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -791.280 319.680 m -791.280 312.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -787.680 319.680 m -794.880 319.680 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -791.280 312.480 m -791.280 312.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -782.16 322.19 Td -(3.3V_B) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -690.480 294.480 m -686.880 290.880 l -676.080 290.880 l -676.080 298.080 l -686.880 298.080 l -690.480 294.480 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -690.480 294.480 m -690.480 294.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -649.65 291.89 Td -(OT_OUT) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -690.480 287.280 m -686.880 283.680 l -676.080 283.680 l -676.080 290.880 l -686.880 290.880 l -690.480 287.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -690.480 287.280 m -690.480 287.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -656.50 284.69 Td -(OT_IN) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -334.080 409.680 m -341.280 409.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -334.080 416.160 m -334.080 403.200 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -332.640 414.000 m -332.640 405.360 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -331.200 411.840 m -331.200 407.520 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -329.760 410.400 m -329.760 408.960 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -341.280 409.680 m -341.280 409.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -312.48 407.62 Td -(GND) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -377.280 456.480 m -377.280 449.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -373.680 456.480 m -380.880 456.480 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -377.280 449.280 m -377.280 449.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -368.64 458.74 Td -(3.3V_B) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -370.080 510.480 m -370.080 517.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -363.600 510.480 m -376.560 510.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -365.760 509.040 m -374.400 509.040 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -367.920 507.600 m -372.240 507.600 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -369.360 506.160 m -370.800 506.160 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -370.080 517.680 m -370.080 517.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -362.88 497.62 Td -(GND) Tj -ET -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -319.68 450.72 36.00 -24.48 re -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -312.65 446.86 Td -(1) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -305.280 445.680 m -319.680 445.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -312.65 432.46 Td -(2) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -305.280 431.280 m -319.680 431.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -359.28 432.46 Td -(3) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -370.080 431.280 m -355.680 431.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -359.28 446.86 Td -(4) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -370.080 445.680 m -355.680 445.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -355.680 445.680 m -348.480 440.640 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -348.480 436.320 m -355.680 431.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -348.480 444.960 m -348.480 432.000 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -355.680 431.280 m -353.520 434.880 l -351.360 432.000 l -355.680 431.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -339.840 432.720 m -338.400 435.600 l -336.960 434.160 l -339.840 432.720 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -342.000 435.600 m -340.560 438.480 l -339.120 437.040 l -342.000 435.600 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -334.800 437.760 m -339.840 432.720 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -336.960 440.640 m -342.000 435.600 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -334.800 434.880 m -323.280 434.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -324.720 442.080 m -329.040 434.880 l -334.080 442.080 l -324.720 442.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -319.680 445.680 m -329.040 445.680 l -329.040 431.280 l -319.680 431.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -318.96 452.26 Td -(U5) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -337.68 452.26 Td -(PC817) Tj -ET -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -312.48 540.72 36.00 -24.48 re -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -352.08 536.86 Td -(1) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -362.880 535.680 m -348.480 535.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -352.08 522.46 Td -(2) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -362.880 521.280 m -348.480 521.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -305.45 522.46 Td -(3) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -298.080 521.280 m -312.480 521.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -305.45 536.86 Td -(4) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -298.080 535.680 m -312.480 535.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -312.480 535.680 m -319.680 530.640 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -319.680 526.320 m -312.480 521.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -319.680 534.960 m -319.680 522.000 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -312.480 521.280 m -314.640 524.880 l -316.800 522.000 l -312.480 521.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -328.320 522.720 m -329.760 525.600 l -331.200 524.160 l -328.320 522.720 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -326.160 525.600 m -327.600 528.480 l -329.040 527.040 l -326.160 525.600 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -333.360 527.760 m -328.320 522.720 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -331.200 530.640 m -326.160 525.600 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -333.360 524.880 m -344.880 524.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -343.440 532.080 m -339.120 524.880 l -334.080 532.080 l -343.440 532.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -348.480 535.680 m -339.120 535.680 l -339.120 521.280 l -348.480 521.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -311.81 542.26 Td -(U4) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -330.37 542.26 Td -(PC817) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -794.880 438.480 m -787.680 438.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -794.880 442.080 m -794.880 434.880 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -787.680 438.480 m -787.680 438.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -796.27 436.17 Td -(3.3V_B) Tj -ET -0.80 0.00 0.00 rg -397.08 431.28 m 397.08 432.27 396.27 433.08 395.28 433.08 c -394.29 433.08 393.48 432.27 393.48 431.28 c -393.48 430.29 394.29 429.48 395.28 429.48 c -396.27 429.48 397.08 430.29 397.08 431.28 c -f -0.80 0.00 0.00 rg -224.28 463.68 m 224.28 464.67 223.47 465.48 222.48 465.48 c -221.49 465.48 220.68 464.67 220.68 463.68 c -220.68 462.69 221.49 461.88 222.48 461.88 c -223.47 461.88 224.28 462.69 224.28 463.68 c -f -0.80 0.00 0.00 rg -263.88 535.68 m 263.88 536.67 263.07 537.48 262.08 537.48 c -261.09 537.48 260.28 536.67 260.28 535.68 c -260.28 534.69 261.09 533.88 262.08 533.88 c -263.07 533.88 263.88 534.69 263.88 535.68 c -f -0.80 0.00 0.00 rg -249.48 517.68 m 249.48 518.67 248.67 519.48 247.68 519.48 c -246.69 519.48 245.88 518.67 245.88 517.68 c -245.88 516.69 246.69 515.88 247.68 515.88 c -248.67 515.88 249.48 516.69 249.48 517.68 c -f -0.80 0.00 0.00 rg -224.28 499.68 m 224.28 500.67 223.47 501.48 222.48 501.48 c -221.49 501.48 220.68 500.67 220.68 499.68 c -220.68 498.69 221.49 497.88 222.48 497.88 c -223.47 497.88 224.28 498.69 224.28 499.68 c -f -0.80 0.00 0.00 rg -584.28 478.08 m 584.28 479.07 583.47 479.88 582.48 479.88 c -581.49 479.88 580.68 479.07 580.68 478.08 c -580.68 477.09 581.49 476.28 582.48 476.28 c -583.47 476.28 584.28 477.09 584.28 478.08 c -f -0.80 0.00 0.00 rg -785.88 438.48 m 785.88 439.47 785.07 440.28 784.08 440.28 c -783.09 440.28 782.28 439.47 782.28 438.48 c -782.28 437.49 783.09 436.68 784.08 436.68 c -785.07 436.68 785.88 437.49 785.88 438.48 c -f -0.80 0.00 0.00 rg -688.68 514.08 m 688.68 515.07 687.87 515.88 686.88 515.88 c -685.89 515.88 685.08 515.07 685.08 514.08 c -685.08 513.09 685.89 512.28 686.88 512.28 c -687.87 512.28 688.68 513.09 688.68 514.08 c -f -0.80 0.00 0.00 rg -325.08 280.08 m 325.08 281.07 324.27 281.88 323.28 281.88 c -322.29 281.88 321.48 281.07 321.48 280.08 c -321.48 279.09 322.29 278.28 323.28 278.28 c -324.27 278.28 325.08 279.09 325.08 280.08 c -f -0.80 0.00 0.00 rg -789.48 524.88 m 789.48 525.87 788.67 526.68 787.68 526.68 c -786.69 526.68 785.88 525.87 785.88 524.88 c -785.88 523.89 786.69 523.08 787.68 523.08 c -788.67 523.08 789.48 523.89 789.48 524.88 c -f -0.80 0.00 0.00 rg -541.08 200.88 m 541.08 201.87 540.27 202.68 539.28 202.68 c -538.29 202.68 537.48 201.87 537.48 200.88 c -537.48 199.89 538.29 199.08 539.28 199.08 c -540.27 199.08 541.08 199.89 541.08 200.88 c -f -0.80 0.00 0.00 rg -112.68 67.68 m 112.68 68.67 111.87 69.48 110.88 69.48 c -109.89 69.48 109.08 68.67 109.08 67.68 c -109.08 66.69 109.89 65.88 110.88 65.88 c -111.87 65.88 112.68 66.69 112.68 67.68 c -f -0.80 0.00 0.00 rg -148.68 67.68 m 148.68 68.67 147.87 69.48 146.88 69.48 c -145.89 69.48 145.08 68.67 145.08 67.68 c -145.08 66.69 145.89 65.88 146.88 65.88 c -147.87 65.88 148.68 66.69 148.68 67.68 c -f -0.80 0.00 0.00 rg -137.88 319.68 m 137.88 320.67 137.07 321.48 136.08 321.48 c -135.09 321.48 134.28 320.67 134.28 319.68 c -134.28 318.69 135.09 317.88 136.08 317.88 c -137.07 317.88 137.88 318.69 137.88 319.68 c -f -0.80 0.00 0.00 rg -544.68 312.48 m 544.68 313.47 543.87 314.28 542.88 314.28 c -541.89 314.28 541.08 313.47 541.08 312.48 c -541.08 311.49 541.89 310.68 542.88 310.68 c -543.87 310.68 544.68 311.49 544.68 312.48 c -f -0.80 0.00 0.00 rg -278.28 431.28 m 278.28 432.27 277.47 433.08 276.48 433.08 c -275.49 433.08 274.68 432.27 274.68 431.28 c -274.68 430.29 275.49 429.48 276.48 429.48 c -277.47 429.48 278.28 430.29 278.28 431.28 c -f -0.80 0.00 0.00 rg -249.48 431.28 m 249.48 432.27 248.67 433.08 247.68 433.08 c -246.69 433.08 245.88 432.27 245.88 431.28 c -245.88 430.29 246.69 429.48 247.68 429.48 c -248.67 429.48 249.48 430.29 249.48 431.28 c -f -0.80 0.00 0.00 rg -224.28 431.28 m 224.28 432.27 223.47 433.08 222.48 433.08 c -221.49 433.08 220.68 432.27 220.68 431.28 c -220.68 430.29 221.49 429.48 222.48 429.48 c -223.47 429.48 224.28 430.29 224.28 431.28 c -f -0.80 0.00 0.00 rg -195.48 431.28 m 195.48 432.27 194.67 433.08 193.68 433.08 c -192.69 433.08 191.88 432.27 191.88 431.28 c -191.88 430.29 192.69 429.48 193.68 429.48 c -194.67 429.48 195.48 430.29 195.48 431.28 c -f -0.80 0.00 0.00 rg -224.28 535.68 m 224.28 536.67 223.47 537.48 222.48 537.48 c -221.49 537.48 220.68 536.67 220.68 535.68 c -220.68 534.69 221.49 533.88 222.48 533.88 c -223.47 533.88 224.28 534.69 224.28 535.68 c -f -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -794.880 424.080 m -787.680 424.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -794.880 417.600 m -794.880 430.560 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -796.320 419.760 m -796.320 428.400 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -797.760 421.920 m -797.760 426.240 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -799.200 423.360 m -799.200 424.800 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -787.680 424.080 m -787.680 424.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -801.51 421.74 Td -(GND) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -686.880 431.280 m -683.280 427.680 l -672.480 427.680 l -672.480 434.880 l -683.280 434.880 l -686.880 431.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -686.880 431.280 m -686.880 431.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -647.64 428.88 Td -(OT_2_B) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -686.880 424.080 m -683.280 420.480 l -672.480 420.480 l -672.480 427.680 l -683.280 427.680 l -686.880 424.080 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -686.880 424.080 m -686.880 424.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -647.64 421.80 Td -(OT_1_B) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -503.280 506.880 m -510.480 506.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -503.280 503.280 m -503.280 510.480 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -510.480 506.880 m -510.480 506.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -479.47 504.82 Td -(3.3V_B) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -676.080 514.080 m -683.280 514.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -676.080 520.560 m -676.080 507.600 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -674.640 518.400 m -674.640 509.760 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -673.200 516.240 m -673.200 511.920 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -671.760 514.800 m -671.760 513.360 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -683.280 514.080 m -683.280 514.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -654.48 512.02 Td -(GND) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -593.280 478.080 m -586.080 478.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -593.280 471.600 m -593.280 484.560 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -594.720 473.760 m -594.720 482.400 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -596.160 475.920 m -596.160 480.240 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -597.600 477.360 m -597.600 478.800 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -586.080 478.080 m -586.080 478.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -601.19 476.02 Td -(GND) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -776.880 287.280 m -780.480 290.880 l -791.280 290.880 l -791.280 283.680 l -780.480 283.680 l -776.880 287.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -776.880 287.280 m -776.880 287.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -792.72 284.63 Td -(TEMP1_B) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -776.880 280.080 m -780.480 283.680 l -791.280 283.680 l -791.280 276.480 l -780.480 276.480 l -776.880 280.080 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -776.880 280.080 m -776.880 280.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -792.72 277.43 Td -(TEMP2_B) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -686.880 445.680 m -683.280 442.080 l -672.480 442.080 l -672.480 449.280 l -683.280 449.280 l -686.880 445.680 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -686.880 445.680 m -686.880 445.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -642.23 443.76 Td -(TEMP1_B) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -686.880 438.480 m -683.280 434.880 l -672.480 434.880 l -672.480 442.080 l -683.280 442.080 l -686.880 438.480 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -686.880 438.480 m -686.880 438.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -642.23 436.68 Td -(TEMP2_B) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -402.480 431.280 m -406.080 434.880 l -416.880 434.880 l -416.880 427.680 l -406.080 427.680 l -402.480 431.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -402.480 431.280 m -402.480 431.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -420.19 428.69 Td -(OT_IN) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -402.480 535.680 m -406.080 539.280 l -416.880 539.280 l -416.880 532.080 l -406.080 532.080 l -402.480 535.680 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -402.480 535.680 m -402.480 535.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -419.95 533.09 Td -(OT_OUT) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -676.080 265.680 m -676.080 258.480 l -S -676.080 265.680 m -694.080 265.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -676.080 265.680 m -676.080 258.480 l -S -676.080 265.680 m -694.080 265.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -791.280 312.480 m -791.280 308.880 l -S -791.280 308.880 m -773.280 308.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -791.280 312.480 m -791.280 308.880 l -S -791.280 308.880 m -773.280 308.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -370.080 431.280 m -395.280 431.280 l -S -402.480 431.280 m -395.280 431.280 l -S -395.280 431.280 m -395.280 409.680 l -S -395.280 409.680 m -370.080 409.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -370.080 431.280 m -395.280 431.280 l -S -402.480 431.280 m -395.280 431.280 l -S -395.280 431.280 m -395.280 409.680 l -S -395.280 409.680 m -370.080 409.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -377.280 445.680 m -370.080 445.680 l -S -377.280 449.280 m -377.280 445.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -377.280 445.680 m -370.080 445.680 l -S -377.280 449.280 m -377.280 445.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -370.080 521.280 m -362.880 521.280 l -S -370.080 517.680 m -370.080 521.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -370.080 521.280 m -362.880 521.280 l -S -370.080 517.680 m -370.080 521.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -395.280 535.680 m -402.480 535.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -395.280 535.680 m -402.480 535.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -366.480 535.680 m -362.880 535.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -366.480 535.680 m -362.880 535.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -222.480 463.680 m -222.480 467.280 l -S -305.280 463.680 m -305.280 445.680 l -S -222.480 463.680 m -305.280 463.680 l -S -222.480 460.080 m -222.480 463.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -222.480 463.680 m -222.480 467.280 l -S -305.280 463.680 m -305.280 445.680 l -S -222.480 463.680 m -305.280 463.680 l -S -222.480 460.080 m -222.480 463.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -276.480 521.280 m -276.480 460.080 l -S -298.080 521.280 m -276.480 521.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -276.480 521.280 m -276.480 460.080 l -S -298.080 521.280 m -276.480 521.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -262.080 535.680 m -298.080 535.680 l -S -262.080 517.680 m -262.080 535.680 l -S -247.680 517.680 m -262.080 517.680 l -S -247.680 517.680 m -247.680 460.080 l -S -236.880 517.680 m -247.680 517.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -262.080 535.680 m -298.080 535.680 l -S -262.080 517.680 m -262.080 535.680 l -S -247.680 517.680 m -262.080 517.680 l -S -247.680 517.680 m -247.680 460.080 l -S -236.880 517.680 m -247.680 517.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -222.480 499.680 m -222.480 496.080 l -S -222.480 499.680 m -222.480 503.280 l -S -193.680 499.680 m -222.480 499.680 l -S -193.680 460.080 m -193.680 499.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -222.480 499.680 m -222.480 496.080 l -S -222.480 499.680 m -222.480 503.280 l -S -193.680 499.680 m -222.480 499.680 l -S -193.680 460.080 m -193.680 499.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -582.480 449.280 m -578.880 449.280 l -S -582.480 478.080 m -582.480 449.280 l -S -578.880 478.080 m -582.480 478.080 l -S -582.480 506.880 m -582.480 478.080 l -S -578.880 506.880 m -582.480 506.880 l -S -586.080 478.080 m -582.480 478.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -582.480 449.280 m -578.880 449.280 l -S -582.480 478.080 m -582.480 449.280 l -S -578.880 478.080 m -582.480 478.080 l -S -582.480 506.880 m -582.480 478.080 l -S -578.880 506.880 m -582.480 506.880 l -S -586.080 478.080 m -582.480 478.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -769.680 424.080 m -787.680 424.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -769.680 424.080 m -787.680 424.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -686.880 424.080 m -704.880 424.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -686.880 424.080 m -704.880 424.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -686.880 431.280 m -704.880 431.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -686.880 431.280 m -704.880 431.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -521.280 506.880 m -510.480 506.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -521.280 506.880 m -510.480 506.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -784.080 438.480 m -769.680 438.480 l -S -784.080 431.280 m -784.080 438.480 l -S -769.680 431.280 m -784.080 431.280 l -S -787.680 438.480 m -784.080 438.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -784.080 438.480 m -769.680 438.480 l -S -784.080 431.280 m -784.080 438.480 l -S -769.680 431.280 m -784.080 431.280 l -S -787.680 438.480 m -784.080 438.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -686.880 514.080 m -686.880 510.480 l -S -686.880 510.480 m -704.880 510.480 l -S -686.880 517.680 m -686.880 514.080 l -S -704.880 517.680 m -686.880 517.680 l -S -683.280 514.080 m -686.880 514.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -686.880 514.080 m -686.880 510.480 l -S -686.880 510.480 m -704.880 510.480 l -S -686.880 517.680 m -686.880 514.080 l -S -704.880 517.680 m -686.880 517.680 l -S -683.280 514.080 m -686.880 514.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -773.280 287.280 m -776.880 287.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -773.280 287.280 m -776.880 287.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -773.280 280.080 m -776.880 280.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -773.280 280.080 m -776.880 280.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -686.880 445.680 m -704.880 445.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -686.880 445.680 m -704.880 445.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -686.880 438.480 m -704.880 438.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -686.880 438.480 m -704.880 438.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -694.080 294.480 m -690.480 294.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -694.080 294.480 m -690.480 294.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -694.080 287.280 m -690.480 287.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -694.080 287.280 m -690.480 287.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -341.280 409.680 m -341.280 409.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -341.280 409.680 m -341.280 409.680 l -S -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -240.48 538.56 14.40 -5.76 re -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -262.080 535.680 m -254.880 535.680 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -233.280 535.680 m -240.480 535.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -239.78 541.10 Td -(R3) Tj -ET -7.20 w -BT -7.20 TL -0.000 0.000 1.000 rg -252.87 541.10 Td -/F2 6.16071384419139 Tf -(330) Tj -/F3 6.16071384419139 Tf -<03a9> Tj -ET -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -373.68 538.56 14.40 -5.76 re -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -395.280 535.680 m -388.080 535.680 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -366.480 535.680 m -373.680 535.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -372.98 541.10 Td -(R6) Tj -ET -7.20 w -BT -7.20 TL -0.000 0.000 1.000 rg -386.07 541.10 Td -/F2 6.16071384419139 Tf -(330) Tj -/F3 6.16071384419139 Tf -<03a9> Tj -ET -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -219.60 488.88 5.76 -14.40 re -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -222.480 496.080 m -222.480 488.880 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -222.480 467.280 m -222.480 474.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -226.80 479.97 Td -(R4) Tj -ET -7.20 w -BT -7.20 TL -0.000 0.000 1.000 rg -226.80 473.42 Td -/F2 6.16071384419139 Tf -(220) Tj -/F3 6.16071384419139 Tf -<03a9> Tj -ET -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -219.60 452.88 5.76 -14.40 re -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -222.480 460.080 m -222.480 452.880 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -222.480 431.280 m -222.480 438.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -226.80 443.97 Td -(R5) Tj -ET -7.20 w -BT -7.20 TL -0.000 0.000 1.000 rg -226.80 437.42 Td -/F2 6.16071384419139 Tf -(100) Tj -/F3 6.16071384419139 Tf -<03a9> Tj -ET -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -348.48 412.56 14.40 -5.76 re -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -341.280 409.680 m -348.480 409.680 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -370.080 409.680 m -362.880 409.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -347.78 415.10 Td -(R7) Tj -ET -7.20 w -BT -7.20 TL -0.000 0.000 1.000 rg -360.13 415.10 Td -/F2 6.16071384419139 Tf -(1.5k) Tj -/F3 6.16071384419139 Tf -<03a9> Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -222.480 503.280 m -222.480 510.480 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -236.880 517.680 m -229.680 517.680 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -222.480 532.080 m -222.480 524.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -229.680 511.200 m -229.680 524.160 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -222.480 510.480 m -229.680 515.520 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -227.520 521.280 m -222.480 524.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -229.680 519.840 m -225.360 520.560 l -227.520 523.440 l -229.680 519.840 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -211.76 515.85 Td -(Q1) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -197.03 509.47 Td -(BC858A) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -193.680 431.280 m -193.680 442.080 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -193.680 460.080 m -193.680 449.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -200.160 452.160 m -197.280 449.280 l -190.080 449.280 l -187.200 446.400 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -189.360 442.080 m -193.680 449.280 l -198.720 442.080 l -189.360 442.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -201.60 443.90 Td -(ZD1) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -247.680 431.280 m -247.680 442.080 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -247.680 460.080 m -247.680 449.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -254.160 452.160 m -251.280 449.280 l -244.080 449.280 l -241.200 446.400 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -243.360 442.080 m -247.680 449.280 l -252.720 442.080 l -243.360 442.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -254.88 442.64 Td -(ZD2) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -276.480 431.280 m -276.480 442.080 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -276.480 460.080 m -276.480 449.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -282.960 452.160 m -280.080 449.280 l -272.880 449.280 l -270.000 446.400 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -272.160 442.080 m -276.480 449.280 l -281.520 442.080 l -272.160 442.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -284.40 443.90 Td -(ZD3) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -323.280 323.280 m -323.280 316.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -319.680 323.280 m -326.880 323.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -323.280 316.080 m -323.280 316.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -313.30 325.93 Td -(3.3V_B) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -316.080 280.080 m -312.480 276.480 l -301.680 276.480 l -301.680 283.680 l -312.480 283.680 l -316.080 280.080 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -316.080 280.080 m -316.080 280.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -275.10 278.14 Td -(ESP_EN) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -323.280 280.080 m -316.080 280.080 l -S -323.280 280.080 m -323.280 283.680 l -S -323.280 280.080 m -323.280 265.680 l -S -359.280 272.880 m -359.280 280.080 l -S -359.280 280.080 m -323.280 280.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -323.280 280.080 m -316.080 280.080 l -S -323.280 280.080 m -323.280 283.680 l -S -323.280 280.080 m -323.280 265.680 l -S -359.280 272.880 m -359.280 280.080 l -S -359.280 280.080 m -323.280 280.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -323.280 316.080 m -323.280 312.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -323.280 316.080 m -323.280 312.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -517.680 449.280 m -514.080 445.680 l -503.280 445.680 l -503.280 452.880 l -514.080 452.880 l -517.680 449.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -517.680 449.280 m -517.680 449.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -484.99 447.22 Td -(LED3) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -521.280 449.280 m -517.680 449.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -521.280 449.280 m -517.680 449.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -517.680 478.080 m -514.080 474.480 l -503.280 474.480 l -503.280 481.680 l -514.080 481.680 l -517.680 478.080 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -517.680 478.080 m -517.680 478.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -484.99 476.02 Td -(LED2) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -517.680 478.080 m -521.280 478.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -517.680 478.080 m -521.280 478.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -776.880 301.680 m -780.480 305.280 l -791.280 305.280 l -791.280 298.080 l -780.480 298.080 l -776.880 301.680 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -776.880 301.680 m -776.880 301.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -792.72 299.03 Td -(LED2) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -773.280 301.680 m -776.880 301.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -773.280 301.680 m -776.880 301.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -776.880 294.480 m -780.480 298.080 l -791.280 298.080 l -791.280 290.880 l -780.480 290.880 l -776.880 294.480 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -776.880 294.480 m -776.880 294.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -792.72 291.83 Td -(LED3) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -773.280 294.480 m -776.880 294.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -773.280 294.480 m -776.880 294.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -317.520 252.720 m -329.040 252.720 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -323.280 265.680 m -323.280 258.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -323.280 244.080 m -323.280 249.840 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -329.040 249.840 m -317.520 249.840 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -323.280 236.880 m -323.280 244.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -323.280 252.720 m -323.280 258.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -330.48 252.82 Td -(C4) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -329.71 246.50 Td -(100nF) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -323.280 229.680 m -323.280 236.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -316.800 229.680 m -329.760 229.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -318.960 228.240 m -327.600 228.240 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -321.120 226.800 m -325.440 226.800 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -322.560 225.360 m -324.000 225.360 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -323.280 236.880 m -323.280 236.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -316.79 216.82 Td -(GND) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -323.280 236.880 m -323.280 236.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -323.280 236.880 m -323.280 236.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -359.280 229.680 m -359.280 236.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -352.800 229.680 m -365.760 229.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -354.960 228.240 m -363.600 228.240 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -357.120 226.800 m -361.440 226.800 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -358.560 225.360 m -360.000 225.360 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -359.280 236.880 m -359.280 236.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -352.08 216.82 Td -(GND) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -798.480 524.880 m -791.280 524.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -798.480 528.480 m -798.480 521.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -791.280 524.880 m -791.280 524.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -800.12 522.28 Td -(5V_B) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -769.680 532.080 m -787.680 532.080 l -S -787.680 532.080 m -787.680 524.880 l -S -769.680 524.880 m -787.680 524.880 l -S -787.680 524.880 m -787.680 517.680 l -S -787.680 517.680 m -769.680 517.680 l -S -791.280 524.880 m -787.680 524.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -769.680 532.080 m -787.680 532.080 l -S -787.680 532.080 m -787.680 524.880 l -S -769.680 524.880 m -787.680 524.880 l -S -787.680 524.880 m -787.680 517.680 l -S -787.680 517.680 m -769.680 517.680 l -S -791.280 524.880 m -787.680 524.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -488.880 208.080 m -485.280 204.480 l -474.480 204.480 l -474.480 211.680 l -485.280 211.680 l -488.880 208.080 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -488.880 208.080 m -488.880 208.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -444.63 205.49 Td -(USB_CC1) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -488.880 193.680 m -485.280 190.080 l -474.480 190.080 l -474.480 197.280 l -485.280 197.280 l -488.880 193.680 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -488.880 193.680 m -488.880 193.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -444.68 192.10 Td -(USB_CC2) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -553.680 200.880 m -546.480 200.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -553.680 194.400 m -553.680 207.360 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -555.120 196.560 m -555.120 205.200 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -556.560 198.720 m -556.560 203.040 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -558.000 200.160 m -558.000 201.600 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -546.480 200.880 m -546.480 200.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -559.98 198.88 Td -(GND) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -524.880 208.080 m -517.680 208.080 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -496.080 208.080 m -503.280 208.080 l -S -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -503.28 210.96 14.40 -5.76 re -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -503.02 212.34 Td -(R12) Tj -ET -7.20 w -BT -7.20 TL -0.000 0.000 1.000 rg -517.20 212.34 Td -/F2 6.16071384419139 Tf -(5.1k) Tj -/F3 6.16071384419139 Tf -<03a9> Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -524.880 193.680 m -517.680 193.680 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -496.080 193.680 m -503.280 193.680 l -S -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -503.28 196.56 14.40 -5.76 re -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -502.97 197.46 Td -(R13) Tj -ET -7.20 w -BT -7.20 TL -0.000 0.000 1.000 rg -517.20 197.46 Td -/F2 6.16071384419139 Tf -(5.1k) Tj -/F3 6.16071384419139 Tf -<03a9> Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -539.280 193.680 m -524.880 193.680 l -S -539.280 193.680 m -539.280 200.880 l -S -546.480 200.880 m -539.280 200.880 l -S -539.280 200.880 m -539.280 208.080 l -S -524.880 208.080 m -539.280 208.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -539.280 193.680 m -524.880 193.680 l -S -539.280 193.680 m -539.280 200.880 l -S -546.480 200.880 m -539.280 200.880 l -S -539.280 200.880 m -539.280 208.080 l -S -524.880 208.080 m -539.280 208.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -488.880 208.080 m -496.080 208.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -488.880 208.080 m -496.080 208.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -496.080 193.680 m -488.880 193.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -496.080 193.680 m -488.880 193.680 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -323.280 312.480 m -323.280 305.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -323.280 283.680 m -323.280 290.880 l -S -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -320.40 305.28 5.76 -14.40 re -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -327.70 298.63 Td -(R11) Tj -ET -7.20 w -BT -7.20 TL -0.000 0.000 1.000 rg -327.70 292.42 Td -/F2 6.16071384419139 Tf -(5.1k) Tj -/F3 6.16071384419139 Tf -<03a9> Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -130.320 66.240 m -130.320 54.720 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -143.280 60.480 m -136.080 60.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -121.680 60.480 m -127.440 60.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -127.440 54.720 m -127.440 66.240 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -114.480 60.480 m -121.680 60.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -130.320 60.480 m -136.080 60.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -124.74 48.79 Td -(C5) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -134.72 48.84 Td -(10uF) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -127.440 69.120 m -127.440 80.640 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -114.480 74.880 m -121.680 74.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -136.080 74.880 m -130.320 74.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -130.320 80.640 m -130.320 69.120 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -143.280 74.880 m -136.080 74.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -127.440 74.880 m -121.680 74.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -124.09 82.04 Td -(C6) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -134.72 82.04 Td -(100nF) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -110.880 74.880 m -114.480 74.880 l -S -110.880 67.680 m -110.880 74.880 l -S -110.880 67.680 m -107.280 67.680 l -S -110.880 67.680 m -110.880 60.480 l -S -110.880 60.480 m -114.480 60.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -110.880 74.880 m -114.480 74.880 l -S -110.880 67.680 m -110.880 74.880 l -S -110.880 67.680 m -107.280 67.680 l -S -110.880 67.680 m -110.880 60.480 l -S -110.880 60.480 m -114.480 60.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -146.880 67.680 m -146.880 74.880 l -S -143.280 74.880 m -146.880 74.880 l -S -150.480 67.680 m -146.880 67.680 l -S -146.880 67.680 m -146.880 60.480 l -S -146.880 60.480 m -143.280 60.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -146.880 67.680 m -146.880 74.880 l -S -143.280 74.880 m -146.880 74.880 l -S -150.480 67.680 m -146.880 67.680 l -S -146.880 67.680 m -146.880 60.480 l -S -146.880 60.480 m -143.280 60.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -157.680 67.680 m -150.480 67.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -157.680 61.200 m -157.680 74.160 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -159.120 63.360 m -159.120 72.000 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -160.560 65.520 m -160.560 69.840 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -162.000 66.960 m -162.000 68.400 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -150.480 67.680 m -150.480 67.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -164.88 65.62 Td -(GND) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -100.080 67.680 m -107.280 67.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -100.080 64.080 m -100.080 71.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -107.280 67.680 m -107.280 67.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -78.54 65.03 Td -(3.3V_B) Tj -ET -1 J -1 j -0.72 w -0.00 G -0.00 g -[4.320 5.040] 0 d -10.080 391.680 m -838.080 391.680 l -S -1 J -1 j -0.72 w -0.00 G -0.00 g -[4.320 5.040] 0 d -460.080 391.680 m -460.080 589.680 l -S -1 J -1 j -0.72 w -0.00 G -0.00 g -[4.320 5.040] 0 d -622.080 139.680 m -625.680 589.680 l -S -1 J -1 j -0.72 w -0.00 G -0.00 g -[4.320 5.040] 0 d -258.480 391.680 m -258.480 139.680 l -352.080 139.680 l -S -1 J -1 j -0.72 w -0.00 G -0.00 g -[4.320 5.040] 0 d -398.880 139.680 m -398.880 391.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 136.70 281.57 Tm -(GND) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 133.82 300.30 Tm -(41) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -136.080 312.480 m -136.080 298.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -83.52 188.08 Td -(IO20) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -71.63 190.96 Td -(14) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -67.680 190.080 m -82.080 190.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -83.52 195.28 Td -(IO19) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -71.63 198.16 Td -(13) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -67.680 197.280 m -82.080 197.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -83.52 202.48 Td -(IO8) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -71.63 205.36 Td -(12) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -67.680 204.480 m -82.080 204.480 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -64.800 207.360 m -70.560 201.600 l -64.800 201.600 m -70.560 207.360 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -83.52 209.68 Td -(IO18) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -71.63 212.56 Td -(11) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -67.680 211.680 m -82.080 211.680 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -64.800 214.560 m -70.560 208.800 l -64.800 208.800 m -70.560 214.560 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -83.52 216.88 Td -(IO17) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -71.63 219.76 Td -(10) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -67.680 218.880 m -82.080 218.880 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -64.800 221.760 m -70.560 216.000 l -64.800 216.000 m -70.560 221.760 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -83.52 224.08 Td -(IO16) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -75.05 226.96 Td -(9) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -67.680 226.080 m -82.080 226.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -83.52 231.28 Td -(IO15) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -75.05 234.16 Td -(8) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -67.680 233.280 m -82.080 233.280 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -64.800 236.160 m -70.560 230.400 l -64.800 230.400 m -70.560 236.160 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -83.52 238.48 Td -(IO7) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -75.05 241.36 Td -(7) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -67.680 240.480 m -82.080 240.480 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -64.800 243.360 m -70.560 237.600 l -64.800 237.600 m -70.560 243.360 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -83.52 245.68 Td -(IO6) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -75.05 248.56 Td -(6) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -67.680 247.680 m -82.080 247.680 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -64.800 250.560 m -70.560 244.800 l -64.800 244.800 m -70.560 250.560 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -83.52 252.88 Td -(IO5) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -75.05 255.76 Td -(5) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -67.680 254.880 m -82.080 254.880 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -64.800 257.760 m -70.560 252.000 l -64.800 252.000 m -70.560 257.760 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -83.52 260.08 Td -(IO4) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -75.05 262.96 Td -(4) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -67.680 262.080 m -82.080 262.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -83.52 267.28 Td -(EN) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -75.05 270.16 Td -(3) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -67.680 269.280 m -82.080 269.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -83.52 274.48 Td -(3V3) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -75.05 277.36 Td -(2) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -67.680 276.480 m -82.080 276.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -83.52 281.68 Td -(GND) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -75.05 284.56 Td -(1) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -67.680 283.680 m -82.080 283.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 176.30 168.54 Tm -(IO45) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 173.42 156.65 Tm -(26) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -175.680 154.080 m -175.680 168.480 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -172.800 156.960 m -178.560 151.200 l -172.800 151.200 m -178.560 156.960 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 169.10 168.54 Tm -(IO48) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 166.22 156.65 Tm -(25) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -168.480 154.080 m -168.480 168.480 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -165.600 156.960 m -171.360 151.200 l -165.600 151.200 m -171.360 156.960 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 161.90 168.54 Tm -(IO47) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 159.02 156.65 Tm -(24) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -161.280 154.080 m -161.280 168.480 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -158.400 156.960 m -164.160 151.200 l -158.400 151.200 m -164.160 156.960 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 154.70 168.54 Tm -(IO21) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 151.82 156.65 Tm -(23) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -154.080 154.080 m -154.080 168.480 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -151.200 156.960 m -156.960 151.200 l -151.200 151.200 m -156.960 156.960 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 147.50 168.54 Tm -(IO14) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 144.62 156.65 Tm -(22) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -146.880 154.080 m -146.880 168.480 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -144.000 156.960 m -149.760 151.200 l -144.000 151.200 m -149.760 156.960 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 140.30 168.54 Tm -(IO13) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 137.42 156.65 Tm -(21) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -139.680 154.080 m -139.680 168.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 133.10 168.54 Tm -(IO12) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 130.22 156.65 Tm -(20) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -132.480 154.080 m -132.480 168.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 125.90 168.54 Tm -(IO11) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 123.02 156.65 Tm -(19) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -125.280 154.080 m -125.280 168.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 118.70 168.54 Tm -(IO10) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 115.82 156.65 Tm -(18) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -118.080 154.080 m -118.080 168.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 111.50 168.54 Tm -(IO9) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 108.62 156.65 Tm -(17) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -110.880 154.080 m -110.880 168.480 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -108.000 156.960 m -113.760 151.200 l -108.000 151.200 m -113.760 156.960 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 104.30 168.54 Tm -(IO46) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 101.42 156.65 Tm -(16) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -103.680 154.080 m -103.680 168.480 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -100.800 156.960 m -106.560 151.200 l -100.800 151.200 m -106.560 156.960 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 97.10 168.54 Tm -(IO3) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 94.22 156.65 Tm -(15) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -96.480 154.080 m -96.480 168.480 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -93.600 156.960 m -99.360 151.200 l -93.600 151.200 m -99.360 156.960 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -178.71 188.08 Td -(IO0) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -193.68 190.96 Td -(27) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -204.480 190.080 m -190.080 190.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -175.28 195.28 Td -(IO35) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -193.68 198.16 Td -(28) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -204.480 197.280 m -190.080 197.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -175.28 202.48 Td -(IO36) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -193.68 205.36 Td -(29) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -204.480 204.480 m -190.080 204.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -175.28 209.68 Td -(IO37) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -193.68 212.56 Td -(30) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -204.480 211.680 m -190.080 211.680 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -201.600 214.560 m -207.360 208.800 l -201.600 208.800 m -207.360 214.560 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -175.28 216.88 Td -(IO38) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -193.68 219.76 Td -(31) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -204.480 218.880 m -190.080 218.880 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -201.600 221.760 m -207.360 216.000 l -201.600 216.000 m -207.360 221.760 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -175.28 224.08 Td -(IO39) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -193.68 226.96 Td -(32) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -204.480 226.080 m -190.080 226.080 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -201.600 228.960 m -207.360 223.200 l -201.600 223.200 m -207.360 228.960 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -175.28 231.28 Td -(IO40) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -193.68 234.16 Td -(33) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -204.480 233.280 m -190.080 233.280 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -201.600 236.160 m -207.360 230.400 l -201.600 230.400 m -207.360 236.160 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -175.28 238.48 Td -(IO41) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -193.68 241.36 Td -(34) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -204.480 240.480 m -190.080 240.480 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -201.600 243.360 m -207.360 237.600 l -201.600 237.600 m -207.360 243.360 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -175.28 245.68 Td -(IO42) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -193.68 248.56 Td -(35) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -204.480 247.680 m -190.080 247.680 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -201.600 250.560 m -207.360 244.800 l -201.600 244.800 m -207.360 250.560 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -172.21 252.88 Td -(RXD0) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -193.68 255.76 Td -(36) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -204.480 254.880 m -190.080 254.880 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -201.600 257.760 m -207.360 252.000 l -201.600 252.000 m -207.360 257.760 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -172.89 260.08 Td -(TXD0) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -193.68 262.96 Td -(37) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -204.480 262.080 m -190.080 262.080 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -201.600 264.960 m -207.360 259.200 l -201.600 259.200 m -207.360 264.960 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -178.71 267.28 Td -(IO2) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -193.68 270.16 Td -(38) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -204.480 269.280 m -190.080 269.280 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -201.600 272.160 m -207.360 266.400 l -201.600 266.400 m -207.360 272.160 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -178.71 274.48 Td -(IO1) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -193.68 277.36 Td -(39) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -204.480 276.480 m -190.080 276.480 l -S -1 J -1 j -0.72 w -0.20 0.80 0.20 RG -[] 0 d -201.600 279.360 m -207.360 273.600 l -201.600 273.600 m -207.360 279.360 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -174.95 281.68 Td -(GND) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -193.68 284.56 Td -(40) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -204.480 283.680 m -190.080 283.680 l -S -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -82.08 298.08 108.00 -129.60 re -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -81.03 299.91 Td -(U10) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -139.68 299.62 Td -(ESP32-S3-WROOM-1U-N4) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -53.280 294.480 m -53.280 287.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -49.680 294.480 m -56.880 294.480 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -53.280 287.280 m -53.280 287.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -42.57 296.62 Td -(3.3V_B) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -53.280 276.480 m -53.280 287.280 l -S -67.680 276.480 m -53.280 276.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -53.280 276.480 m -53.280 287.280 l -S -67.680 276.480 m -53.280 276.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -64.080 269.280 m -60.480 265.680 l -49.680 265.680 l -49.680 272.880 l -60.480 272.880 l -64.080 269.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -64.080 269.280 m -64.080 269.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -23.75 267.02 Td -(ESP_EN) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -64.080 269.280 m -67.680 269.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -64.080 269.280 m -67.680 269.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -64.080 197.280 m -60.480 193.680 l -49.680 193.680 l -49.680 200.880 l -60.480 200.880 l -64.080 197.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -64.080 197.280 m -64.080 197.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -24.14 195.28 Td -(USB_D-) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -64.080 197.280 m -67.680 197.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -64.080 197.280 m -67.680 197.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -64.080 190.080 m -60.480 186.480 l -49.680 186.480 l -49.680 193.680 l -60.480 193.680 l -64.080 190.080 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -64.080 190.080 m -64.080 190.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -24.10 187.49 Td -(USB_D+) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -64.080 190.080 m -67.680 190.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -64.080 190.080 m -67.680 190.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -118.080 150.480 m -121.680 146.880 l -121.680 136.080 l -114.480 136.080 l -114.480 146.880 l -118.080 150.480 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -118.080 150.480 m -118.080 150.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -0.00 1.00 -1.00 0.00 120.34 118.77 Tm -(LED2) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -118.080 150.480 m -118.080 154.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -118.080 150.480 m -118.080 154.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -125.280 150.480 m -128.880 146.880 l -128.880 136.080 l -121.680 136.080 l -121.680 146.880 l -125.280 150.480 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -125.280 150.480 m -125.280 150.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -0.00 1.00 -1.00 0.00 127.42 118.77 Tm -(LED3) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -125.280 150.480 m -125.280 154.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -125.280 150.480 m -125.280 154.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -132.480 150.480 m -136.080 146.880 l -136.080 136.080 l -128.880 136.080 l -128.880 146.880 l -132.480 150.480 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -132.480 150.480 m -132.480 150.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -0.00 1.00 -1.00 0.00 133.95 106.57 Tm -(TEMP2_B) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -132.480 150.480 m -132.480 154.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -132.480 150.480 m -132.480 154.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -139.680 150.480 m -143.280 146.880 l -143.280 136.080 l -136.080 136.080 l -136.080 146.880 l -139.680 150.480 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -139.680 150.480 m -139.680 150.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -0.00 1.00 -1.00 0.00 141.15 106.57 Tm -(TEMP1_B) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -139.680 150.480 m -139.680 154.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -139.680 150.480 m -139.680 154.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -208.080 197.280 m -211.680 200.880 l -222.480 200.880 l -222.480 193.680 l -211.680 193.680 l -208.080 197.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -208.080 197.280 m -208.080 197.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -223.95 195.17 Td -(OT_IN) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -208.080 197.280 m -204.480 197.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -208.080 197.280 m -204.480 197.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -208.080 204.480 m -211.680 208.080 l -222.480 208.080 l -222.480 200.880 l -211.680 200.880 l -208.080 204.480 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -208.080 204.480 m -208.080 204.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -223.95 202.25 Td -(OT_OUT) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -208.080 204.480 m -204.480 204.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -208.080 204.480 m -204.480 204.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -208.080 190.080 m -211.680 193.680 l -222.480 193.680 l -222.480 186.480 l -211.680 186.480 l -208.080 190.080 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -208.080 190.080 m -208.080 190.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -223.92 188.56 Td -(ESP_IO0) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -208.080 190.080 m -204.480 190.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -208.080 190.080 m -204.480 190.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -136.080 319.680 m -136.080 312.480 l -S -136.080 319.680 m -64.080 319.680 l -S -64.080 319.680 m -64.080 283.680 l -S -67.680 283.680 m -64.080 283.680 l -S -136.080 326.880 m -136.080 319.680 l -S -136.080 319.680 m -211.680 319.680 l -S -211.680 319.680 m -211.680 283.680 l -S -211.680 283.680 m -204.480 283.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -136.080 319.680 m -136.080 312.480 l -S -136.080 319.680 m -64.080 319.680 l -S -64.080 319.680 m -64.080 283.680 l -S -67.680 283.680 m -64.080 283.680 l -S -136.080 326.880 m -136.080 319.680 l -S -136.080 319.680 m -211.680 319.680 l -S -211.680 319.680 m -211.680 283.680 l -S -211.680 283.680 m -204.480 283.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -136.080 334.080 m -136.080 326.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -142.560 334.080 m -129.600 334.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -140.400 335.520 m -131.760 335.520 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -138.240 336.960 m -133.920 336.960 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -136.800 338.400 m -135.360 338.400 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -136.080 326.880 m -136.080 326.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -129.36 340.84 Td -(GND) Tj -ET -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -481.68 319.68 50.40 -64.80 re -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -[] 0 d -486.36 308.88 m 486.36 309.48 485.88 309.96 485.28 309.96 c -484.68 309.96 484.20 309.48 484.20 308.88 c -484.20 308.28 484.68 307.80 485.28 307.80 c -485.88 307.80 486.36 308.28 486.36 308.88 c -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -484.34 302.56 Td -(GND) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -473.79 306.16 Td -(A1) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -474.480 305.280 m -481.680 305.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -484.34 295.36 Td -(VBUS) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -473.79 298.96 Td -(A4) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -474.480 298.080 m -481.680 298.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -484.34 288.16 Td -(CC1) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -473.79 291.76 Td -(A5) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -474.480 290.880 m -481.680 290.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -484.34 280.96 Td -(D+) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -473.79 284.56 Td -(A6) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -474.480 283.680 m -481.680 283.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -484.34 273.76 Td -(D-) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -473.79 277.36 Td -(A7) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -474.480 276.480 m -481.680 276.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -484.34 266.56 Td -(VBUS) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -473.79 270.16 Td -(A9) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -474.480 269.280 m -481.680 269.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -484.34 259.36 Td -(GND) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -470.36 262.96 Td -(A12) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -474.480 262.080 m -481.680 262.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -515.73 302.56 Td -(GND) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -532.44 306.16 Td -(B1) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -539.280 305.280 m -532.080 305.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -512.64 295.36 Td -(VBUS) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -532.44 298.96 Td -(B4) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -539.280 298.080 m -532.080 298.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -517.09 288.16 Td -(CC2) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -532.44 291.76 Td -(B5) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -539.280 290.880 m -532.080 290.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -521.37 280.96 Td -(D+) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -532.44 284.56 Td -(B6) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -539.280 283.680 m -532.080 283.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -522.92 273.76 Td -(D-) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -532.44 277.36 Td -(B7) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -539.280 276.480 m -532.080 276.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -512.64 266.56 Td -(VBUS) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -532.44 270.16 Td -(B9) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -539.280 269.280 m -532.080 269.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -515.73 259.36 Td -(GND) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -532.44 262.96 Td -(B12) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -539.280 262.080 m -532.080 262.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -525.99 309.76 Td -(0) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -532.44 313.36 Td -(0) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -539.280 312.480 m -532.080 312.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -481.68 321.22 Td -(U11) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -478.08 245.62 Td -(TYPE-C 14PLC-H10.0) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -542.880 283.680 m -546.480 287.280 l -557.280 287.280 l -557.280 280.080 l -546.480 280.080 l -542.880 283.680 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -542.880 283.680 m -542.880 283.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -558.67 281.03 Td -(USB_D+) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -542.880 276.480 m -546.480 280.080 l -557.280 280.080 l -557.280 272.880 l -546.480 272.880 l -542.880 276.480 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -542.880 276.480 m -542.880 276.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -558.75 274.42 Td -(USB_D-) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -542.880 283.680 m -539.280 283.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -542.880 283.680 m -539.280 283.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -542.880 276.480 m -539.280 276.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -542.880 276.480 m -539.280 276.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -470.880 283.680 m -467.280 280.080 l -456.480 280.080 l -456.480 287.280 l -467.280 287.280 l -470.880 283.680 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -470.880 283.680 m -470.880 283.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -430.53 281.11 Td -(USB_D+) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -470.880 276.480 m -467.280 272.880 l -456.480 272.880 l -456.480 280.080 l -467.280 280.080 l -470.880 276.480 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -470.880 276.480 m -470.880 276.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -430.74 274.31 Td -(USB_D-) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -474.480 276.480 m -470.880 276.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -474.480 276.480 m -470.880 276.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -470.880 283.680 m -474.480 283.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -470.880 283.680 m -474.480 283.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -542.880 290.880 m -546.480 294.480 l -557.280 294.480 l -557.280 287.280 l -546.480 287.280 l -542.880 290.880 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -542.880 290.880 m -542.880 290.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -558.67 288.34 Td -(USB_CC2) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -542.880 290.880 m -539.280 290.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -542.880 290.880 m -539.280 290.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -470.880 290.880 m -467.280 287.280 l -456.480 287.280 l -456.480 294.480 l -467.280 294.480 l -470.880 290.880 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -470.880 290.880 m -470.880 290.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -426.63 288.29 Td -(USB_CC1) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -470.880 290.880 m -474.480 290.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -470.880 290.880 m -474.480 290.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -557.280 301.680 m -550.080 301.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -557.280 305.280 m -557.280 298.080 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -550.080 301.680 m -550.080 301.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -559.09 299.25 Td -(5V_B) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -550.080 298.080 m -550.080 301.680 l -S -539.280 298.080 m -550.080 298.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -550.080 298.080 m -550.080 301.680 l -S -539.280 298.080 m -550.080 298.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -557.280 265.680 m -550.080 265.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -557.280 269.280 m -557.280 262.080 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -550.080 265.680 m -550.080 265.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -558.87 263.62 Td -(5V_B) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -550.080 269.280 m -550.080 265.680 l -S -539.280 269.280 m -550.080 269.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -550.080 269.280 m -550.080 265.680 l -S -539.280 269.280 m -550.080 269.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -456.480 301.680 m -463.680 301.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -456.480 298.080 m -456.480 305.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -463.680 301.680 m -463.680 301.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -438.97 299.00 Td -(5V_B) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -463.680 298.080 m -463.680 301.680 l -S -474.480 298.080 m -463.680 298.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -463.680 298.080 m -463.680 301.680 l -S -474.480 298.080 m -463.680 298.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -456.480 265.680 m -463.680 265.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -456.480 262.080 m -456.480 269.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -463.680 265.680 m -463.680 265.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -439.03 263.62 Td -(5V_B) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -463.680 269.280 m -463.680 265.680 l -S -474.480 269.280 m -463.680 269.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -463.680 269.280 m -463.680 265.680 l -S -474.480 269.280 m -463.680 269.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -542.880 323.280 m -542.880 316.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -549.360 323.280 m -536.400 323.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -547.200 324.720 m -538.560 324.720 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -545.040 326.160 m -540.720 326.160 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -543.600 327.600 m -542.160 327.600 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -542.880 316.080 m -542.880 316.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -536.25 329.10 Td -(GND) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -542.880 305.280 m -542.880 312.480 l -S -539.280 305.280 m -542.880 305.280 l -S -539.280 312.480 m -542.880 312.480 l -S -542.880 316.080 m -542.880 312.480 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -542.880 305.280 m -542.880 312.480 l -S -539.280 305.280 m -542.880 305.280 l -S -539.280 312.480 m -542.880 312.480 l -S -542.880 316.080 m -542.880 312.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -470.880 323.280 m -470.880 316.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -477.360 323.280 m -464.400 323.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -475.200 324.720 m -466.560 324.720 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -473.040 326.160 m -468.720 326.160 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -471.600 327.600 m -470.160 327.600 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -470.880 316.080 m -470.880 316.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -464.25 329.10 Td -(GND) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -470.880 316.080 m -470.880 305.280 l -S -474.480 305.280 m -470.880 305.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -470.880 316.080 m -470.880 305.280 l -S -474.480 305.280 m -470.880 305.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -467.280 251.280 m -467.280 258.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -460.800 251.280 m -473.760 251.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -462.960 249.840 m -471.600 249.840 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -465.120 248.400 m -469.440 248.400 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -466.560 246.960 m -468.000 246.960 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -467.280 258.480 m -467.280 258.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -460.22 241.34 Td -(GND) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -467.280 262.080 m -467.280 258.480 l -S -474.480 262.080 m -467.280 262.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -467.280 262.080 m -467.280 258.480 l -S -474.480 262.080 m -467.280 262.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -546.480 251.280 m -546.480 258.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -540.000 251.280 m -552.960 251.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -542.160 249.840 m -550.800 249.840 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -544.320 248.400 m -548.640 248.400 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -545.760 246.960 m -547.200 246.960 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -546.480 258.480 m -546.480 258.480 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -539.42 241.34 Td -(GND) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -546.480 262.080 m -546.480 258.480 l -S -539.280 262.080 m -546.480 262.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -546.480 262.080 m -546.480 258.480 l -S -539.280 262.080 m -546.480 262.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 358.40 247.85 Tm -(2) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -359.280 244.080 m -359.280 251.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -0.00 1.00 -1.00 0.00 358.40 265.68 Tm -(1) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -359.280 272.880 m -359.280 265.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -360.720 262.800 m -364.320 254.160 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -359.280 264.240 m -359.280 265.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -359.280 252.720 m -359.280 251.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -[] 0 d -360.36 254.16 m 360.36 254.76 359.88 255.24 359.28 255.24 c -358.68 255.24 358.20 254.76 358.20 254.16 c -358.20 253.56 358.68 253.08 359.28 253.08 c -359.88 253.08 360.36 253.56 360.36 254.16 c -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -[] 0 d -360.36 262.80 m 360.36 263.40 359.88 263.88 359.28 263.88 c -358.68 263.88 358.20 263.40 358.20 262.80 c -358.20 262.20 358.68 261.72 359.28 261.72 c -359.88 261.72 360.36 262.20 360.36 262.80 c -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -365.76 255.70 Td -(SW1) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -359.280 244.080 m -359.280 236.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -359.280 244.080 m -359.280 236.880 l -S -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -557.28 509.76 14.40 -5.76 re -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -550.080 506.880 m -557.280 506.880 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -578.880 506.880 m -571.680 506.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -556.34 511.12 Td -(R1) Tj -ET -7.20 w -BT -7.20 TL -0.000 0.000 1.000 rg -566.27 511.12 Td -/F2 6.16071384419139 Tf -(100) Tj -/F3 6.16071384419139 Tf -<03a9> Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -550.080 506.880 m -550.080 506.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -550.080 506.880 m -550.080 506.880 l -S -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -557.28 480.96 14.40 -5.76 re -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -550.080 478.080 m -557.280 478.080 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -578.880 478.080 m -571.680 478.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -556.06 482.26 Td -(R9) Tj -ET -7.20 w -BT -7.20 TL -0.000 0.000 1.000 rg -566.27 482.06 Td -/F2 6.16071384419139 Tf -(100) Tj -/F3 6.16071384419139 Tf -<03a9> Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -550.080 478.080 m -550.080 478.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -550.080 478.080 m -550.080 478.080 l -S -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -557.28 452.16 14.40 -5.76 re -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -550.080 449.280 m -557.280 449.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -578.880 449.280 m -571.680 449.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -556.34 453.71 Td -(R8) Tj -ET -7.20 w -BT -7.20 TL -0.000 0.000 1.000 rg -566.52 453.66 Td -/F2 6.16071384419139 Tf -(100) Tj -/F3 6.16071384419139 Tf -<03a9> Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -550.080 449.280 m -550.080 449.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -550.080 449.280 m -550.080 449.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -546.480 497.520 m -543.600 498.960 l -545.040 500.400 l -546.480 497.520 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -543.600 494.640 m -540.720 496.080 l -542.160 497.520 l -543.600 494.640 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -550.080 506.880 m -539.280 506.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -541.440 502.560 m -546.480 497.520 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -538.560 499.680 m -543.600 494.640 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -521.280 506.880 m -532.080 506.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -539.280 501.120 m -539.280 512.640 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -532.080 511.200 m -539.280 506.880 l -532.080 501.840 l -532.080 511.200 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -531.26 514.06 Td -(L1) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -546.480 468.720 m -543.600 470.160 l -545.040 471.600 l -546.480 468.720 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -543.600 465.840 m -540.720 467.280 l -542.160 468.720 l -543.600 465.840 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -550.080 478.080 m -539.280 478.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -541.440 473.760 m -546.480 468.720 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -538.560 470.880 m -543.600 465.840 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -521.280 478.080 m -532.080 478.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -539.280 472.320 m -539.280 483.840 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -532.080 482.400 m -539.280 478.080 l -532.080 473.040 l -532.080 482.400 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -531.26 485.01 Td -(L2) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -546.480 439.920 m -543.600 441.360 l -545.040 442.800 l -546.480 439.920 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -543.600 437.040 m -540.720 438.480 l -542.160 439.920 l -543.600 437.040 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -550.080 449.280 m -539.280 449.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -541.440 444.960 m -546.480 439.920 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -538.560 442.080 m -543.600 437.040 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -521.280 449.280 m -532.080 449.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -539.280 443.520 m -539.280 455.040 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -532.080 453.600 m -539.280 449.280 l -532.080 444.240 l -532.080 453.600 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -531.26 455.95 Td -(L3) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -[] 0 d -100.08 499.68 m 100.08 500.08 99.76 500.40 99.36 500.40 c -98.96 500.40 98.64 500.08 98.64 499.68 c -98.64 499.28 98.96 498.96 99.36 498.96 c -99.76 498.96 100.08 499.28 100.08 499.68 c -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -85.680 496.080 m -92.880 499.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -92.880 499.680 m -85.680 503.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -78.480 499.680 m -92.880 499.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -85.680 503.280 m -85.680 496.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -92.880 503.280 m -92.880 499.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -92.880 499.680 m -92.880 496.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -92.880 481.680 m -85.680 485.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -85.680 485.280 m -92.880 488.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -92.880 488.880 m -92.880 481.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -85.680 488.880 m -85.680 485.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -85.680 485.280 m -85.680 481.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -92.880 499.680 m -99.360 499.680 l -99.360 485.280 l -78.480 485.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -99.360 499.680 m -121.680 499.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -[] 0 d -101.52 470.88 m 101.52 471.28 101.20 471.60 100.80 471.60 c -100.40 471.60 100.08 471.28 100.08 470.88 c -100.08 470.48 100.40 470.16 100.80 470.16 c -101.20 470.16 101.52 470.48 101.52 470.88 c -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -114.480 474.480 m -107.280 470.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -107.280 470.880 m -114.480 467.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -121.680 470.880 m -107.280 470.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -114.480 467.280 m -114.480 474.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -107.280 467.280 m -107.280 470.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -107.280 470.880 m -107.280 474.480 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -107.280 488.880 m -114.480 485.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -114.480 485.280 m -107.280 481.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -107.280 481.680 m -107.280 488.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -114.480 481.680 m -114.480 485.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -114.480 485.280 m -114.480 488.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -107.280 470.880 m -100.800 470.880 l -100.800 485.280 l -121.680 485.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -100.800 470.880 m -78.480 470.880 l -S -2 J -0 j -72 M -0.72 w -0.63 0.00 0.00 RG -[] 0 d -78.48 506.88 43.20 -43.20 re -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -70.08 501.94 Td -(1) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -64.080 499.680 m -78.480 499.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -70.08 487.54 Td -(2) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -64.080 485.280 m -78.480 485.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -70.08 473.14 Td -(3) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -64.080 470.880 m -78.480 470.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -123.90 473.14 Td -(4) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -136.080 470.880 m -121.680 470.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -123.90 487.54 Td -(5) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -136.080 485.280 m -121.680 485.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -123.90 501.94 Td -(6) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -136.080 499.680 m -121.680 499.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -77.76 508.42 Td -(D5) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -82.08 458.02 Td -(BAV99S,115) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -64.080 470.880 m -60.480 470.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -64.080 470.880 m -60.480 470.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -136.080 470.880 m -139.680 470.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -136.080 470.880 m -139.680 470.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -136.080 499.680 m -139.680 499.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -136.080 499.680 m -139.680 499.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -60.480 485.280 m -56.880 481.680 l -46.080 481.680 l -46.080 488.880 l -56.880 488.880 l -60.480 485.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -60.480 485.280 m -60.480 485.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -29.23 482.65 Td -(OT_L) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -64.080 485.280 m -60.480 485.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -64.080 485.280 m -60.480 485.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -60.480 499.680 m -56.880 496.080 l -46.080 496.080 l -46.080 503.280 l -56.880 503.280 l -60.480 499.680 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -60.480 499.680 m -60.480 499.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -28.08 497.62 Td -(OT_N) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -64.080 499.680 m -60.480 499.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -64.080 499.680 m -60.480 499.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -139.680 485.280 m -143.280 488.880 l -154.080 488.880 l -154.080 481.680 l -143.280 481.680 l -139.680 485.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -139.680 485.280 m -139.680 485.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -155.52 483.80 Td -(OT_L) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -136.080 485.280 m -139.680 485.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -136.080 485.280 m -139.680 485.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -139.680 470.880 m -143.280 474.480 l -154.080 474.480 l -154.080 467.280 l -143.280 467.280 l -139.680 470.880 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -139.680 470.880 m -139.680 470.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -155.65 468.82 Td -(OT_N) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -305.280 431.280 m -276.480 431.280 l -S -276.480 431.280 m -247.680 431.280 l -S -222.480 431.280 m -247.680 431.280 l -S -193.680 431.280 m -222.480 431.280 l -S -182.880 431.280 m -193.680 431.280 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -305.280 431.280 m -276.480 431.280 l -S -276.480 431.280 m -247.680 431.280 l -S -222.480 431.280 m -247.680 431.280 l -S -193.680 431.280 m -222.480 431.280 l -S -182.880 431.280 m -193.680 431.280 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -182.880 431.280 m -179.280 427.680 l -168.480 427.680 l -168.480 434.880 l -179.280 434.880 l -182.880 431.280 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -182.880 431.280 m -182.880 431.280 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -150.48 429.22 Td -(OT_N) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -222.480 532.080 m -222.480 535.680 l -S -222.480 535.680 m -233.280 535.680 l -S -222.480 535.680 m -182.880 535.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -222.480 532.080 m -222.480 535.680 l -S -222.480 535.680 m -233.280 535.680 l -S -222.480 535.680 m -182.880 535.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -182.880 535.680 m -179.280 532.080 l -168.480 532.080 l -168.480 539.280 l -179.280 539.280 l -182.880 535.680 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -182.880 535.680 m -182.880 535.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -151.63 533.05 Td -(OT_L) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -139.680 499.680 m -143.280 503.280 l -154.080 503.280 l -154.080 496.080 l -143.280 496.080 l -139.680 499.680 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -139.680 499.680 m -139.680 499.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -155.52 498.20 Td -(OT_2_B) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -60.480 470.880 m -56.880 467.280 l -46.080 467.280 l -46.080 474.480 l -56.880 474.480 l -60.480 470.880 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -60.480 470.880 m -60.480 470.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -21.70 468.25 Td -(OT_1_B) Tj -ET -0.00 0.00 1.00 RG -0.44 w -[] 0 d -661.680 372.681 m -802.528 372.681 l -S -7.20 w -BT -/F2 12.127389457069665 Tf -14.17 TL -0.000 0.000 1.000 rg -661.68 373.12 Td -(Wemos D1/S2/S3/C3 mini) Tj -ET -0.00 0.00 1.00 RG -0.44 w -[] 0 d -496.080 372.681 m -521.014 372.681 l -S -7.20 w -BT -/F2 12.127389457069665 Tf -14.17 TL -0.000 0.000 1.000 rg -496.08 373.12 Td -(USB) Tj -ET -7.20 w -BT -/F2 8.489172619948766 Tf -9.92 TL -0.000 0.000 1.000 rg -452.88 361.41 Td -(Only for ESP32 S3 WROOM) Tj -ET -0.00 0.00 1.00 RG -0.44 w -[] 0 d -308.880 372.681 m -350.004 372.681 l -S -7.20 w -BT -/F2 12.127389457069665 Tf -14.17 TL -0.000 0.000 1.000 rg -308.88 373.12 Td -(Buttons) Tj -ET -7.20 w -BT -/F2 8.489172619948766 Tf -9.92 TL -0.000 0.000 1.000 rg -272.88 361.41 Td -(Only for ESP32 S3 WROOM) Tj -ET -0.00 0.00 1.00 RG -0.44 w -[] 0 d -82.080 372.681 m -190.584 372.681 l -S -7.20 w -BT -/F2 12.127389457069665 Tf -14.17 TL -0.000 0.000 1.000 rg -82.08 373.12 Td -(ESP32 S3 WROOM) Tj -ET -0.00 0.00 1.00 RG -0.44 w -[] 0 d -193.680 570.681 m -302.875 570.681 l -S -7.20 w -BT -/F2 12.127389457069665 Tf -14.17 TL -0.000 0.000 1.000 rg -193.68 571.12 Td -(OpenTherm adapter) Tj -ET -0.00 0.00 1.00 RG -0.44 w -[] 0 d -524.880 570.681 m -556.848 570.681 l -S -7.20 w -BT -/F2 12.127389457069665 Tf -14.17 TL -0.000 0.000 1.000 rg -524.88 571.12 Td -(LED's) Tj -ET -0.00 0.00 1.00 RG -0.44 w -[] 0 d -712.080 570.681 m -755.896 570.681 l -S -7.20 w -BT -/F2 12.127389457069665 Tf -14.17 TL -0.000 0.000 1.000 rg -712.08 571.12 Td -(Board B) Tj -ET -7.20 w -BT -/F4 7.2764336742418 Tf -8.50 TL -1.000 0.000 0.000 rg -661.68 361.10 Td -(For Wemos no need mount:) Tj -T* (C4, C5, C6, R11, R12, R13, U11, SW1, SW2) Tj -ET -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -686.880 460.080 m -683.280 456.480 l -672.480 456.480 l -672.480 463.680 l -683.280 463.680 l -686.880 460.080 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -686.880 460.080 m -686.880 460.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -637.20 458.02 Td -(CC_OUT_B) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -704.880 460.080 m -686.880 460.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -704.880 460.080 m -686.880 460.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -686.880 452.880 m -683.280 449.280 l -672.480 449.280 l -672.480 456.480 l -683.280 456.480 l -686.880 452.880 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -686.880 452.880 m -686.880 452.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -644.40 450.82 Td -(CC_IN_B) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -704.880 452.880 m -686.880 452.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -704.880 452.880 m -686.880 452.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -776.880 272.880 m -780.480 276.480 l -791.280 276.480 l -791.280 269.280 l -780.480 269.280 l -776.880 272.880 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -776.880 272.880 m -776.880 272.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -793.34 270.82 Td -(CC_IN_B) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -773.280 272.880 m -776.880 272.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -773.280 272.880 m -776.880 272.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -690.480 272.880 m -686.880 269.280 l -676.080 269.280 l -676.080 276.480 l -686.880 276.480 l -690.480 272.880 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -690.480 272.880 m -690.480 272.880 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -641.52 270.82 Td -(CC_OUT_B) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -694.080 272.880 m -690.480 272.880 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -694.080 272.880 m -690.480 272.880 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -64.080 226.080 m -60.480 222.480 l -49.680 222.480 l -49.680 229.680 l -60.480 229.680 l -64.080 226.080 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -64.080 226.080 m -64.080 226.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -15.12 224.02 Td -(CC_OUT_B) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -67.680 226.080 m -64.080 226.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -67.680 226.080 m -64.080 226.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -64.080 262.080 m -60.480 258.480 l -49.680 258.480 l -49.680 265.680 l -60.480 265.680 l -64.080 262.080 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -64.080 262.080 m -64.080 262.080 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -21.60 260.02 Td -(CC_IN_B) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -67.680 262.080 m -64.080 262.080 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -67.680 262.080 m -64.080 262.080 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -316.080 175.680 m -312.480 172.080 l -301.680 172.080 l -301.680 179.280 l -312.480 179.280 l -316.080 175.680 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -316.080 175.680 m -316.080 175.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -273.73 173.74 Td -(ESP_IO0) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -316.080 175.680 m -323.280 175.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -316.080 175.680 m -323.280 175.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -366.480 175.680 m -359.280 175.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -366.480 169.200 m -366.480 182.160 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -367.920 171.360 m -367.920 180.000 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -369.360 173.520 m -369.360 177.840 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -370.800 174.960 m -370.800 176.400 l -S -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -359.280 175.680 m -359.280 175.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 1.000 rg -373.68 173.62 Td -(GND) Tj -ET -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -344.88 176.56 Td -(2) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -352.080 175.680 m -344.880 175.680 l -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 g -327.05 176.56 Td -(1) Tj -ET -1 J -1 j -0.72 w -0.53 0.00 0.00 RG -[] 0 d -323.280 175.680 m -330.480 175.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -333.360 177.120 m -342.000 180.720 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -331.920 175.680 m -330.480 175.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -0.00 g -[] 0 d -343.440 175.680 m -344.880 175.680 l -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -[] 0 d -343.08 175.68 m 343.08 176.28 342.60 176.76 342.00 176.76 c -341.40 176.76 340.92 176.28 340.92 175.68 c -340.92 175.08 341.40 174.60 342.00 174.60 c -342.60 174.60 343.08 175.08 343.08 175.68 c -S -1 J -1 j -0.72 w -0.63 0.00 0.00 RG -[] 0 d -334.44 175.68 m 334.44 176.28 333.96 176.76 333.36 176.76 c -332.76 176.76 332.28 176.28 332.28 175.68 c -332.28 175.08 332.76 174.60 333.36 174.60 c -333.96 174.60 334.44 175.08 334.44 175.68 c -S -7.20 w -BT -/F2 6.16071384419139 Tf -7.20 TL -0.000 0.000 0.502 rg -331.20 166.42 Td -(SW2) Tj -ET -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -359.280 175.680 m -352.080 175.680 l -S -1 J -1 j -0.72 w -0.00 0.53 0.00 RG -0.00 g -[] 0 d -359.280 175.680 m -352.080 175.680 l -S -Q -endstream -endobj -1 0 obj -<> -endobj -7 0 obj -<< -/Type /FontDescriptor -/FontName /SimSun -/FontBBox [-8 -145 1000 859] -/Flags 32 -/StemV 0 -/ItalicAngle 0 -/Ascent 859 -/Descent -141 -/CapHeight 175 ->> -endobj -8 0 obj -<< -/Type /Font -/BaseFont /SimSun -/FontDescriptor 7 0 R -/W [1 95 500] -/Subtype /CIDFontType2 -/CIDSystemInfo -<< -/Ordering (GB1) -/Registry (Adobe) -/Supplement 2 ->> ->> -endobj -9 0 obj -<< -/Type /Font -/Subtype /Type0 -/BaseFont /SimSun -/Encoding /UniGB-UCS2-H -/DescendantFonts [8 0 R] ->> -endobj -10 0 obj -<< -/Descent -325 -/CapHeight 500 -/StemV 80 -/Type /FontDescriptor -/Flags 32 -/FontBBox [-665 -325 2000 1006] -/FontName /Arial -/ItalicAngle 0 -/Ascent 1006 ->> -endobj -11 0 obj -<> -endobj -12 0 obj -<< -/Type /FontDescriptor -/FontName /SimHei -/FontBBox [-11 -156 996 859] -/Flags 32 -/StemV 0 -/ItalicAngle 0 -/Ascent 859 -/Descent -140 -/CapHeight 687 ->> -endobj -13 0 obj -<< -/Type /Font -/BaseFont /SimHei -/FontDescriptor 12 0 R -/W [1 95 500 738 813 1000] -/Subtype /CIDFontType2 -/CIDSystemInfo -<< -/Ordering (GB1) -/Registry (Adobe) -/Supplement 2 ->> ->> -endobj -14 0 obj -<< -/Type /Font -/Subtype /Type0 -/BaseFont /SimHei -/Encoding /UniGB-UCS2-H -/DescendantFonts [13 0 R] ->> -endobj -15 0 obj -<< -/Descent -325 -/CapHeight 500 -/StemV 80 -/Type /FontDescriptor -/Flags 32 -/FontBBox [-665 -325 2000 1006] -/FontName /Arial,Bold -/ItalicAngle 0 -/Ascent 1006 ->> -endobj -16 0 obj -<> -endobj -2 0 obj -<< -/ProcSet [/PDF /Text /ImageB /ImageC /ImageI] -/Font << -/F1 9 0 R -/F2 11 0 R -/F3 14 0 R -/F4 16 0 R ->> -/XObject << ->> ->> -endobj -186 0 obj -<> endobj -187 0 obj -<> endobj -188 0 obj -<> endobj -189 0 obj -<> endobj -190 0 obj -<> endobj -191 0 obj -<> endobj -192 0 obj -<> endobj -193 0 obj -<> endobj -194 0 obj -<> endobj -195 0 obj -<> endobj -196 0 obj -<> endobj -197 0 obj -<> endobj -198 0 obj -<> endobj -199 0 obj -<> endobj -200 0 obj -<> endobj -201 0 obj -<> endobj -202 0 obj -<> endobj -203 0 obj -<> endobj -204 0 obj -<> endobj -205 0 obj -<> endobj -206 0 obj -<> endobj -207 0 obj -<> endobj -208 0 obj -<> endobj -209 0 obj -<> endobj -210 0 obj -<> endobj -211 0 obj -<> endobj -212 0 obj -<> endobj -213 0 obj -<> endobj -214 0 obj -<> endobj -215 0 obj -<> endobj -216 0 obj -<> endobj -217 0 obj -<> endobj -218 0 obj -<> endobj -219 0 obj -<> endobj -220 0 obj -<> endobj -221 0 obj -<> endobj -222 0 obj -<> endobj -223 0 obj -<> endobj -224 0 obj -<> endobj -225 0 obj -<> endobj -226 0 obj -<> endobj -227 0 obj -<> endobj -228 0 obj -<> endobj -229 0 obj -<> endobj -230 0 obj -<> endobj -231 0 obj -<> endobj -232 0 obj -<> endobj -233 0 obj -<> endobj -234 0 obj -<> endobj -235 0 obj -<> endobj -236 0 obj -<> endobj -237 0 obj -<> endobj -238 0 obj -<> endobj -239 0 obj -<> endobj -240 0 obj -<> endobj -241 0 obj -<> endobj -242 0 obj -<> endobj -243 0 obj -<> endobj -244 0 obj -<> endobj -245 0 obj -<> endobj -246 0 obj -<> endobj -247 0 obj -<> endobj -248 0 obj -<> endobj -249 0 obj -<> endobj -250 0 obj -<> endobj -251 0 obj -<> endobj -252 0 obj -<> endobj -253 0 obj -<> endobj -254 0 obj -<> endobj -255 0 obj -<> endobj -256 0 obj -<> endobj -257 0 obj -<> endobj -258 0 obj -<> endobj -259 0 obj -<> endobj -260 0 obj -<> endobj -261 0 obj -<> endobj -262 0 obj -<> endobj -263 0 obj -<> endobj -264 0 obj -<> endobj -265 0 obj -<> endobj -266 0 obj -<> endobj -267 0 obj -<> endobj -268 0 obj -<> endobj -269 0 obj -<> endobj -270 0 obj -<> endobj -271 0 obj -<> endobj -272 0 obj -<> endobj -273 0 obj -<> endobj -274 0 obj -<> endobj -275 0 obj -<> endobj -276 0 obj -<> endobj -277 0 obj -<> endobj -278 0 obj -<> endobj -279 0 obj -<> endobj -280 0 obj -<> endobj -281 0 obj -<> endobj -282 0 obj -<> endobj -283 0 obj -<> endobj -284 0 obj -<> endobj -285 0 obj -<> endobj -286 0 obj -<> endobj -287 0 obj -<> endobj -288 0 obj -<> endobj -289 0 obj -<> endobj -290 0 obj -<> endobj -291 0 obj -<> endobj -292 0 obj -<> endobj -293 0 obj -<> endobj -294 0 obj -<> endobj -295 0 obj -<> endobj -296 0 obj -<> endobj -297 0 obj -<> endobj -298 0 obj -<> endobj -299 0 obj -<> endobj -300 0 obj -<> endobj -301 0 obj -<> endobj -302 0 obj -<> endobj -303 0 obj -<> endobj -304 0 obj -<> endobj -305 0 obj -<> endobj -306 0 obj -<> endobj -307 0 obj -<> endobj -308 0 obj -<> endobj -309 0 obj -<> endobj -310 0 obj -<> endobj -311 0 obj -<> endobj -312 0 obj -<> endobj -313 0 obj -<> endobj -314 0 obj -<> endobj -315 0 obj -<> endobj -316 0 obj -<> endobj -317 0 obj -<> endobj -318 0 obj -<> endobj -319 0 obj -<> endobj -320 0 obj -<> endobj -321 0 obj -<> endobj -322 0 obj -<> endobj -323 0 obj -<> endobj -324 0 obj -<> endobj -325 0 obj -<> endobj -326 0 obj -<> endobj -327 0 obj -<> endobj -328 0 obj -<> endobj -329 0 obj -<> endobj -330 0 obj -<> endobj -331 0 obj -<> endobj -332 0 obj -<> endobj -333 0 obj -<> endobj -334 0 obj -<> endobj -335 0 obj -<> endobj -336 0 obj -<> endobj -337 0 obj -<> endobj -338 0 obj -<> endobj -339 0 obj -<> endobj -340 0 obj -<> endobj -341 0 obj -<> endobj -342 0 obj -<> endobj -343 0 obj -<> endobj -344 0 obj -<> endobj -345 0 obj -<> endobj -346 0 obj -<> endobj -347 0 obj -<> endobj -348 0 obj -<> endobj -349 0 obj -<> endobj -350 0 obj -<> endobj -351 0 obj -<> endobj -352 0 obj -<> endobj -353 0 obj -<> endobj -354 0 obj -<> endobj -355 0 obj -<> endobj -356 0 obj -<> endobj -357 0 obj -<> endobj -358 0 obj -<> endobj -359 0 obj -<> endobj -360 0 obj -<> endobj -361 0 obj -<> endobj -362 0 obj -<> endobj -363 0 obj -<> endobj -364 0 obj -<> endobj -365 0 obj -<> endobj -366 0 obj -<> endobj -367 0 obj -<> endobj -368 0 obj -<> endobj -369 0 obj -<> endobj -370 0 obj -<> endobj -371 0 obj -<> endobj -372 0 obj -<> endobj -373 0 obj -<> endobj -374 0 obj -<> endobj -375 0 obj -<> endobj -376 0 obj -<> endobj -377 0 obj -<> endobj -378 0 obj -<> endobj -379 0 obj -<> endobj -380 0 obj -<> endobj -381 0 obj -<> endobj -382 0 obj -<> endobj -383 0 obj -<> endobj -384 0 obj -<> endobj -385 0 obj -<> endobj -386 0 obj -<> endobj -387 0 obj -<> endobj -388 0 obj -<> endobj -389 0 obj -<> endobj -390 0 obj -<> endobj -391 0 obj -<> endobj -392 0 obj -<> endobj -393 0 obj -<> endobj -394 0 obj -<> endobj -395 0 obj -<> endobj -396 0 obj -<> endobj -397 0 obj -<> endobj -398 0 obj -<> endobj -399 0 obj -<> endobj -400 0 obj -<> endobj -401 0 obj -<> endobj -402 0 obj -<> endobj -403 0 obj -<> endobj -404 0 obj -<> endobj -405 0 obj -<> endobj -406 0 obj -<> endobj -407 0 obj -<> endobj -408 0 obj -<> endobj -409 0 obj -<> endobj -410 0 obj -<> endobj -411 0 obj -<> endobj -412 0 obj -<> endobj -413 0 obj -<> endobj -414 0 obj -<> endobj -415 0 obj -<> endobj -416 0 obj -<> endobj -417 0 obj -<> endobj -418 0 obj -<> endobj -419 0 obj -<> endobj -420 0 obj -<> endobj -421 0 obj -<> endobj -422 0 obj -<> endobj -423 0 obj -<> endobj -424 0 obj -<> endobj -425 0 obj -<> endobj -426 0 obj -<> endobj -427 0 obj -<> endobj - -17 0 obj -<< -/Type /Outlines -/First 18 0 R -/Last 21 0 R -/Count 168 ->> -endobj - -18 0 obj -<< -/Title (Pages) -/Parent 17 0 R -/Next 21 0 R -/First 19 0 R -/Last 20 0 R -/Count 2 ->> -endobj - -21 0 obj -<< -/Title (Net) -/Parent 17 0 R -/Prev 18 0 R -/First 22 0 R -/Last 182 0 R -/Count 164 ->> -endobj - -19 0 obj -<< -/Title (SCH_otgateway 1-Sheet_A) -/Parent 18 0 R -/Next 20 0 R -/Dest [3 0 R /XYZ 0 599.76 0] ->> -endobj - -20 0 obj -<< -/Title (SCH_otgateway 2-Sheet_B) -/Parent 18 0 R -/Prev 19 0 R -/Dest [5 0 R /XYZ 0 599.76 0] ->> -endobj - -22 0 obj -<< -/Title (3.3V) -/Parent 21 0 R -/Next 28 0 R -/First 23 0 R -/Last 27 0 R -/Count 5 ->> -endobj - -28 0 obj -<< -/Title (3.3V_B) -/Parent 21 0 R -/Prev 22 0 R -/Next 36 0 R -/First 29 0 R -/Last 35 0 R -/Count 7 ->> -endobj - -36 0 obj -<< -/Title (5V) -/Parent 21 0 R -/Prev 28 0 R -/Next 40 0 R -/First 37 0 R -/Last 39 0 R -/Count 3 ->> -endobj - -40 0 obj -<< -/Title (5V_B) -/Parent 21 0 R -/Prev 36 0 R -/Next 46 0 R -/First 41 0 R -/Last 45 0 R -/Count 5 ->> -endobj - -46 0 obj -<< -/Title ($3N973) -/Parent 21 0 R -/Prev 40 0 R -/Next 48 0 R -/First 47 0 R -/Last 47 0 R -/Count 1 ->> -endobj - -48 0 obj -<< -/Title ($3N974) -/Parent 21 0 R -/Prev 46 0 R -/Next 50 0 R -/First 49 0 R -/Last 49 0 R -/Count 1 ->> -endobj - -50 0 obj -<< -/Title ($3N976) -/Parent 21 0 R -/Prev 48 0 R -/Next 52 0 R -/First 51 0 R -/Last 51 0 R -/Count 1 ->> -endobj - -52 0 obj -<< -/Title ($3N977) -/Parent 21 0 R -/Prev 50 0 R -/Next 54 0 R -/First 53 0 R -/Last 53 0 R -/Count 1 ->> -endobj - -54 0 obj -<< -/Title ($3N979) -/Parent 21 0 R -/Prev 52 0 R -/Next 56 0 R -/First 55 0 R -/Last 55 0 R -/Count 1 ->> -endobj - -56 0 obj -<< -/Title ($3N8827) -/Parent 21 0 R -/Prev 54 0 R -/Next 58 0 R -/First 57 0 R -/Last 57 0 R -/Count 1 ->> -endobj - -58 0 obj -<< -/Title ($3N8868) -/Parent 21 0 R -/Prev 56 0 R -/Next 60 0 R -/First 59 0 R -/Last 59 0 R -/Count 1 ->> -endobj - -60 0 obj -<< -/Title ($3N8909) -/Parent 21 0 R -/Prev 58 0 R -/Next 62 0 R -/First 61 0 R -/Last 61 0 R -/Count 1 ->> -endobj - -62 0 obj -<< -/Title ($6N2675) -/Parent 21 0 R -/Prev 60 0 R -/Next 64 0 R -/First 63 0 R -/Last 63 0 R -/Count 1 ->> -endobj - -64 0 obj -<< -/Title ($6N2678) -/Parent 21 0 R -/Prev 62 0 R -/Next 66 0 R -/First 65 0 R -/Last 65 0 R -/Count 1 ->> -endobj - -66 0 obj -<< -/Title (CC_IN) -/Parent 21 0 R -/Prev 64 0 R -/Next 69 0 R -/First 67 0 R -/Last 68 0 R -/Count 2 ->> -endobj - -69 0 obj -<< -/Title (CC_IN_A) -/Parent 21 0 R -/Prev 66 0 R -/Next 72 0 R -/First 70 0 R -/Last 71 0 R -/Count 2 ->> -endobj - -72 0 obj -<< -/Title (CC_IN_B) -/Parent 21 0 R -/Prev 69 0 R -/Next 76 0 R -/First 73 0 R -/Last 75 0 R -/Count 3 ->> -endobj - -76 0 obj -<< -/Title (CC_OUT) -/Parent 21 0 R -/Prev 72 0 R -/Next 79 0 R -/First 77 0 R -/Last 78 0 R -/Count 2 ->> -endobj - -79 0 obj -<< -/Title (CC_OUT_A) -/Parent 21 0 R -/Prev 76 0 R -/Next 82 0 R -/First 80 0 R -/Last 81 0 R -/Count 2 ->> -endobj - -82 0 obj -<< -/Title (CC_OUT_B) -/Parent 21 0 R -/Prev 79 0 R -/Next 86 0 R -/First 83 0 R -/Last 85 0 R -/Count 3 ->> -endobj - -86 0 obj -<< -/Title (ESP_EN) -/Parent 21 0 R -/Prev 82 0 R -/Next 89 0 R -/First 87 0 R -/Last 88 0 R -/Count 2 ->> -endobj - -89 0 obj -<< -/Title (ESP_IO0) -/Parent 21 0 R -/Prev 86 0 R -/Next 92 0 R -/First 90 0 R -/Last 91 0 R -/Count 2 ->> -endobj - -92 0 obj -<< -/Title (GND) -/Parent 21 0 R -/Prev 89 0 R -/Next 114 0 R -/First 93 0 R -/Last 113 0 R -/Count 21 ->> -endobj - -114 0 obj -<< -/Title (L) -/Parent 21 0 R -/Prev 92 0 R -/Next 117 0 R -/First 115 0 R -/Last 116 0 R -/Count 2 ->> -endobj - -117 0 obj -<< -/Title (LED2) -/Parent 21 0 R -/Prev 114 0 R -/Next 121 0 R -/First 118 0 R -/Last 120 0 R -/Count 3 ->> -endobj - -121 0 obj -<< -/Title (LED3) -/Parent 21 0 R -/Prev 117 0 R -/Next 125 0 R -/First 122 0 R -/Last 124 0 R -/Count 3 ->> -endobj - -125 0 obj -<< -/Title (N) -/Parent 21 0 R -/Prev 121 0 R -/Next 128 0 R -/First 126 0 R -/Last 127 0 R -/Count 2 ->> -endobj - -128 0 obj -<< -/Title (OT_1) -/Parent 21 0 R -/Prev 125 0 R -/Next 131 0 R -/First 129 0 R -/Last 130 0 R -/Count 2 ->> -endobj - -131 0 obj -<< -/Title (OT_1_B) -/Parent 21 0 R -/Prev 128 0 R -/Next 134 0 R -/First 132 0 R -/Last 133 0 R -/Count 2 ->> -endobj - -134 0 obj -<< -/Title (OT_2) -/Parent 21 0 R -/Prev 131 0 R -/Next 137 0 R -/First 135 0 R -/Last 136 0 R -/Count 2 ->> -endobj - -137 0 obj -<< -/Title (OT_2_B) -/Parent 21 0 R -/Prev 134 0 R -/Next 140 0 R -/First 138 0 R -/Last 139 0 R -/Count 2 ->> -endobj - -140 0 obj -<< -/Title (OT_IN) -/Parent 21 0 R -/Prev 137 0 R -/Next 144 0 R -/First 141 0 R -/Last 143 0 R -/Count 3 ->> -endobj - -144 0 obj -<< -/Title (OT_L) -/Parent 21 0 R -/Prev 140 0 R -/Next 148 0 R -/First 145 0 R -/Last 147 0 R -/Count 3 ->> -endobj - -148 0 obj -<< -/Title (OT_N) -/Parent 21 0 R -/Prev 144 0 R -/Next 152 0 R -/First 149 0 R -/Last 151 0 R -/Count 3 ->> -endobj - -152 0 obj -<< -/Title (OT_OUT) -/Parent 21 0 R -/Prev 148 0 R -/Next 156 0 R -/First 153 0 R -/Last 155 0 R -/Count 3 ->> -endobj - -156 0 obj -<< -/Title (TEMP1) -/Parent 21 0 R -/Prev 152 0 R -/Next 160 0 R -/First 157 0 R -/Last 159 0 R -/Count 3 ->> -endobj - -160 0 obj -<< -/Title (TEMP1_B) -/Parent 21 0 R -/Prev 156 0 R -/Next 164 0 R -/First 161 0 R -/Last 163 0 R -/Count 3 ->> -endobj - -164 0 obj -<< -/Title (TEMP2) -/Parent 21 0 R -/Prev 160 0 R -/Next 168 0 R -/First 165 0 R -/Last 167 0 R -/Count 3 ->> -endobj - -168 0 obj -<< -/Title (TEMP2_B) -/Parent 21 0 R -/Prev 164 0 R -/Next 172 0 R -/First 169 0 R -/Last 171 0 R -/Count 3 ->> -endobj - -172 0 obj -<< -/Title (USB_CC1) -/Parent 21 0 R -/Prev 168 0 R -/Next 175 0 R -/First 173 0 R -/Last 174 0 R -/Count 2 ->> -endobj - -175 0 obj -<< -/Title (USB_CC2) -/Parent 21 0 R -/Prev 172 0 R -/Next 178 0 R -/First 176 0 R -/Last 177 0 R -/Count 2 ->> -endobj - -178 0 obj -<< -/Title (USB_D-) -/Parent 21 0 R -/Prev 175 0 R -/Next 182 0 R -/First 179 0 R -/Last 181 0 R -/Count 3 ->> -endobj - -182 0 obj -<< -/Title (USB_D+) -/Parent 21 0 R -/Prev 178 0 R -/First 183 0 R -/Last 185 0 R -/Count 3 ->> -endobj - -23 0 obj -<< -/Title ($6N2682) -/Parent 22 0 R -/Next 24 0 R -/A 186 0 R ->> -endobj - -24 0 obj -<< -/Title ($6N2704) -/Parent 22 0 R -/Prev 23 0 R -/Next 25 0 R -/A 188 0 R ->> -endobj - -25 0 obj -<< -/Title ($6N9433) -/Parent 22 0 R -/Prev 24 0 R -/Next 26 0 R -/A 190 0 R ->> -endobj - -26 0 obj -<< -/Title ($6N11137) -/Parent 22 0 R -/Prev 25 0 R -/Next 27 0 R -/A 192 0 R ->> -endobj - -27 0 obj -<< -/Title ($6N11255) -/Parent 22 0 R -/Prev 26 0 R -/A 194 0 R ->> -endobj - -29 0 obj -<< -/Title ($3N968) -/Parent 28 0 R -/Next 30 0 R -/A 196 0 R ->> -endobj - -30 0 obj -<< -/Title ($3N970) -/Parent 28 0 R -/Prev 29 0 R -/Next 31 0 R -/A 198 0 R ->> -endobj - -31 0 obj -<< -/Title ($3N988) -/Parent 28 0 R -/Prev 30 0 R -/Next 32 0 R -/A 200 0 R ->> -endobj - -32 0 obj -<< -/Title ($3N989) -/Parent 28 0 R -/Prev 31 0 R -/Next 33 0 R -/A 202 0 R ->> -endobj - -33 0 obj -<< -/Title ($3N4305) -/Parent 28 0 R -/Prev 32 0 R -/Next 34 0 R -/A 204 0 R ->> -endobj - -34 0 obj -<< -/Title ($3N6454) -/Parent 28 0 R -/Prev 33 0 R -/Next 35 0 R -/A 206 0 R ->> -endobj - -35 0 obj -<< -/Title ($3N6962) -/Parent 28 0 R -/Prev 34 0 R -/A 208 0 R ->> -endobj - -37 0 obj -<< -/Title ($6N2679) -/Parent 36 0 R -/Next 38 0 R -/A 210 0 R ->> -endobj - -38 0 obj -<< -/Title ($6N2723) -/Parent 36 0 R -/Prev 37 0 R -/Next 39 0 R -/A 212 0 R ->> -endobj - -39 0 obj -<< -/Title ($6N2727) -/Parent 36 0 R -/Prev 38 0 R -/A 214 0 R ->> -endobj - -41 0 obj -<< -/Title ($3N4557) -/Parent 40 0 R -/Next 42 0 R -/A 216 0 R ->> -endobj - -42 0 obj -<< -/Title ($3N7480) -/Parent 40 0 R -/Prev 41 0 R -/Next 43 0 R -/A 218 0 R ->> -endobj - -43 0 obj -<< -/Title ($3N7494) -/Parent 40 0 R -/Prev 42 0 R -/Next 44 0 R -/A 220 0 R ->> -endobj - -44 0 obj -<< -/Title ($3N7508) -/Parent 40 0 R -/Prev 43 0 R -/Next 45 0 R -/A 222 0 R ->> -endobj - -45 0 obj -<< -/Title ($3N7522) -/Parent 40 0 R -/Prev 44 0 R -/A 224 0 R ->> -endobj - -47 0 obj -<< -/Title ($3N973) -/Parent 46 0 R -/A 226 0 R ->> -endobj - -49 0 obj -<< -/Title ($3N974) -/Parent 48 0 R -/A 228 0 R ->> -endobj - -51 0 obj -<< -/Title ($3N976) -/Parent 50 0 R -/A 230 0 R ->> -endobj - -53 0 obj -<< -/Title ($3N977) -/Parent 52 0 R -/A 232 0 R ->> -endobj - -55 0 obj -<< -/Title ($3N979) -/Parent 54 0 R -/A 234 0 R ->> -endobj - -57 0 obj -<< -/Title ($3N8827) -/Parent 56 0 R -/A 236 0 R ->> -endobj - -59 0 obj -<< -/Title ($3N8868) -/Parent 58 0 R -/A 238 0 R ->> -endobj - -61 0 obj -<< -/Title ($3N8909) -/Parent 60 0 R -/A 240 0 R ->> -endobj - -63 0 obj -<< -/Title ($6N2675) -/Parent 62 0 R -/A 242 0 R ->> -endobj - -65 0 obj -<< -/Title ($6N2678) -/Parent 64 0 R -/A 244 0 R ->> -endobj - -67 0 obj -<< -/Title ($6N9453) -/Parent 66 0 R -/Next 68 0 R -/A 246 0 R ->> -endobj - -68 0 obj -<< -/Title ($6N11341) -/Parent 66 0 R -/Prev 67 0 R -/A 248 0 R ->> -endobj - -70 0 obj -<< -/Title ($6N11448) -/Parent 69 0 R -/Next 71 0 R -/A 250 0 R ->> -endobj - -71 0 obj -<< -/Title ($6N11530) -/Parent 69 0 R -/Prev 70 0 R -/A 252 0 R ->> -endobj - -73 0 obj -<< -/Title ($3N12470) -/Parent 72 0 R -/Next 74 0 R -/A 254 0 R ->> -endobj - -74 0 obj -<< -/Title ($3N12484) -/Parent 72 0 R -/Prev 73 0 R -/Next 75 0 R -/A 256 0 R ->> -endobj - -75 0 obj -<< -/Title ($3N12520) -/Parent 72 0 R -/Prev 74 0 R -/A 258 0 R ->> -endobj - -77 0 obj -<< -/Title ($6N9465) -/Parent 76 0 R -/Next 78 0 R -/A 260 0 R ->> -endobj - -78 0 obj -<< -/Title ($6N11520) -/Parent 76 0 R -/Prev 77 0 R -/A 262 0 R ->> -endobj - -80 0 obj -<< -/Title ($6N11460) -/Parent 79 0 R -/Next 81 0 R -/A 264 0 R ->> -endobj - -81 0 obj -<< -/Title ($6N11522) -/Parent 79 0 R -/Prev 80 0 R -/A 266 0 R ->> -endobj - -83 0 obj -<< -/Title ($3N12458) -/Parent 82 0 R -/Next 84 0 R -/A 268 0 R ->> -endobj - -84 0 obj -<< -/Title ($3N12496) -/Parent 82 0 R -/Prev 83 0 R -/Next 85 0 R -/A 270 0 R ->> -endobj - -85 0 obj -<< -/Title ($3N12508) -/Parent 82 0 R -/Prev 84 0 R -/A 272 0 R ->> -endobj - -87 0 obj -<< -/Title ($3N4302) -/Parent 86 0 R -/Next 88 0 R -/A 274 0 R ->> -endobj - -88 0 obj -<< -/Title ($3N6987) -/Parent 86 0 R -/Prev 87 0 R -/A 276 0 R ->> -endobj - -90 0 obj -<< -/Title ($3N7157) -/Parent 89 0 R -/Next 91 0 R -/A 278 0 R ->> -endobj - -91 0 obj -<< -/Title ($3N13620) -/Parent 89 0 R -/Prev 90 0 R -/A 280 0 R ->> -endobj - -93 0 obj -<< -/Title ($3N967) -/Parent 92 0 R -/Next 94 0 R -/A 282 0 R ->> -endobj - -94 0 obj -<< -/Title ($3N971) -/Parent 92 0 R -/Prev 93 0 R -/Next 95 0 R -/A 284 0 R ->> -endobj - -95 0 obj -<< -/Title ($3N982) -/Parent 92 0 R -/Prev 94 0 R -/Next 96 0 R -/A 286 0 R ->> -endobj - -96 0 obj -<< -/Title ($3N985) -/Parent 92 0 R -/Prev 95 0 R -/Next 97 0 R -/A 288 0 R ->> -endobj - -97 0 obj -<< -/Title ($3N990) -/Parent 92 0 R -/Prev 96 0 R -/Next 98 0 R -/A 290 0 R ->> -endobj - -98 0 obj -<< -/Title ($3N997) -/Parent 92 0 R -/Prev 97 0 R -/Next 99 0 R -/A 292 0 R ->> -endobj - -99 0 obj -<< -/Title ($3N4520) -/Parent 92 0 R -/Prev 98 0 R -/Next 100 0 R -/A 294 0 R ->> -endobj - -100 0 obj -<< -/Title ($3N6288) -/Parent 92 0 R -/Prev 99 0 R -/Next 101 0 R -/A 296 0 R ->> -endobj - -101 0 obj -<< -/Title ($3N6460) -/Parent 92 0 R -/Prev 100 0 R -/Next 102 0 R -/A 298 0 R ->> -endobj - -102 0 obj -<< -/Title ($3N7162) -/Parent 92 0 R -/Prev 101 0 R -/Next 103 0 R -/A 300 0 R ->> -endobj - -103 0 obj -<< -/Title ($3N7536) -/Parent 92 0 R -/Prev 102 0 R -/Next 104 0 R -/A 302 0 R ->> -endobj - -104 0 obj -<< -/Title ($3N7566) -/Parent 92 0 R -/Prev 103 0 R -/Next 105 0 R -/A 304 0 R ->> -endobj - -105 0 obj -<< -/Title ($3N7581) -/Parent 92 0 R -/Prev 104 0 R -/Next 106 0 R -/A 306 0 R ->> -endobj - -106 0 obj -<< -/Title ($3N7596) -/Parent 92 0 R -/Prev 105 0 R -/Next 107 0 R -/A 308 0 R ->> -endobj - -107 0 obj -<< -/Title ($3N8689) -/Parent 92 0 R -/Prev 106 0 R -/Next 108 0 R -/A 310 0 R ->> -endobj - -108 0 obj -<< -/Title ($3N13622) -/Parent 92 0 R -/Prev 107 0 R -/Next 109 0 R -/A 312 0 R ->> -endobj - -109 0 obj -<< -/Title ($6N2677) -/Parent 92 0 R -/Prev 108 0 R -/Next 110 0 R -/A 314 0 R ->> -endobj - -110 0 obj -<< -/Title ($6N2703) -/Parent 92 0 R -/Prev 109 0 R -/Next 111 0 R -/A 316 0 R ->> -endobj - -111 0 obj -<< -/Title ($6N2705) -/Parent 92 0 R -/Prev 110 0 R -/Next 112 0 R -/A 318 0 R ->> -endobj - -112 0 obj -<< -/Title ($6N9419) -/Parent 92 0 R -/Prev 111 0 R -/Next 113 0 R -/A 320 0 R ->> -endobj - -113 0 obj -<< -/Title ($6N11539) -/Parent 92 0 R -/Prev 112 0 R -/A 322 0 R ->> -endobj - -115 0 obj -<< -/Title ($6N2676) -/Parent 114 0 R -/Next 116 0 R -/A 324 0 R ->> -endobj - -116 0 obj -<< -/Title ($6N2706) -/Parent 114 0 R -/Prev 115 0 R -/A 326 0 R ->> -endobj - -118 0 obj -<< -/Title ($3N4380) -/Parent 117 0 R -/Next 119 0 R -/A 328 0 R ->> -endobj - -119 0 obj -<< -/Title ($3N4406) -/Parent 117 0 R -/Prev 118 0 R -/Next 120 0 R -/A 330 0 R ->> -endobj - -120 0 obj -<< -/Title ($3N7047) -/Parent 117 0 R -/Prev 119 0 R -/A 332 0 R ->> -endobj - -122 0 obj -<< -/Title ($3N4366) -/Parent 121 0 R -/Next 123 0 R -/A 334 0 R ->> -endobj - -123 0 obj -<< -/Title ($3N4418) -/Parent 121 0 R -/Prev 122 0 R -/Next 124 0 R -/A 336 0 R ->> -endobj - -124 0 obj -<< -/Title ($3N7059) -/Parent 121 0 R -/Prev 123 0 R -/A 338 0 R ->> -endobj - -126 0 obj -<< -/Title ($6N2674) -/Parent 125 0 R -/Next 127 0 R -/A 340 0 R ->> -endobj - -127 0 obj -<< -/Title ($6N11555) -/Parent 125 0 R -/Prev 126 0 R -/A 342 0 R ->> -endobj - -129 0 obj -<< -/Title ($6N2708) -/Parent 128 0 R -/Next 130 0 R -/A 344 0 R ->> -endobj - -130 0 obj -<< -/Title ($6N2721) -/Parent 128 0 R -/Prev 129 0 R -/A 346 0 R ->> -endobj - -132 0 obj -<< -/Title ($3N986) -/Parent 131 0 R -/Next 133 0 R -/A 348 0 R ->> -endobj - -133 0 obj -<< -/Title ($3N10213) -/Parent 131 0 R -/Prev 132 0 R -/A 350 0 R ->> -endobj - -135 0 obj -<< -/Title ($6N2709) -/Parent 134 0 R -/Next 136 0 R -/A 352 0 R ->> -endobj - -136 0 obj -<< -/Title ($6N2720) -/Parent 134 0 R -/Prev 135 0 R -/A 354 0 R ->> -endobj - -138 0 obj -<< -/Title ($3N987) -/Parent 137 0 R -/Next 139 0 R -/A 356 0 R ->> -endobj - -139 0 obj -<< -/Title ($3N10248) -/Parent 137 0 R -/Prev 138 0 R -/A 358 0 R ->> -endobj - -141 0 obj -<< -/Title ($3N969) -/Parent 140 0 R -/Next 142 0 R -/A 360 0 R ->> -endobj - -142 0 obj -<< -/Title ($3N996) -/Parent 140 0 R -/Prev 141 0 R -/Next 143 0 R -/A 362 0 R ->> -endobj - -143 0 obj -<< -/Title ($3N7095) -/Parent 140 0 R -/Prev 142 0 R -/A 364 0 R ->> -endobj - -145 0 obj -<< -/Title ($3N10260) -/Parent 144 0 R -/Next 146 0 R -/A 366 0 R ->> -endobj - -146 0 obj -<< -/Title ($3N10295) -/Parent 144 0 R -/Prev 145 0 R -/Next 147 0 R -/A 368 0 R ->> -endobj - -147 0 obj -<< -/Title ($3N10403) -/Parent 144 0 R -/Prev 146 0 R -/A 370 0 R ->> -endobj - -149 0 obj -<< -/Title ($3N10225) -/Parent 148 0 R -/Next 150 0 R -/A 372 0 R ->> -endobj - -150 0 obj -<< -/Title ($3N10283) -/Parent 148 0 R -/Prev 149 0 R -/Next 151 0 R -/A 374 0 R ->> -endobj - -151 0 obj -<< -/Title ($3N10311) -/Parent 148 0 R -/Prev 150 0 R -/A 376 0 R ->> -endobj - -153 0 obj -<< -/Title ($3N972) -/Parent 152 0 R -/Next 154 0 R -/A 378 0 R ->> -endobj - -154 0 obj -<< -/Title ($3N995) -/Parent 152 0 R -/Prev 153 0 R -/Next 155 0 R -/A 380 0 R ->> -endobj - -155 0 obj -<< -/Title ($3N7107) -/Parent 152 0 R -/Prev 154 0 R -/A 382 0 R ->> -endobj - -157 0 obj -<< -/Title ($6N2710) -/Parent 156 0 R -/Next 158 0 R -/A 384 0 R ->> -endobj - -158 0 obj -<< -/Title ($6N11149) -/Parent 156 0 R -/Prev 157 0 R -/Next 159 0 R -/A 386 0 R ->> -endobj - -159 0 obj -<< -/Title ($6N11283) -/Parent 156 0 R -/Prev 158 0 R -/A 388 0 R ->> -endobj - -161 0 obj -<< -/Title ($3N991) -/Parent 160 0 R -/Next 162 0 R -/A 390 0 R ->> -endobj - -162 0 obj -<< -/Title ($3N993) -/Parent 160 0 R -/Prev 161 0 R -/Next 163 0 R -/A 392 0 R ->> -endobj - -163 0 obj -<< -/Title ($3N7083) -/Parent 160 0 R -/Prev 162 0 R -/A 394 0 R ->> -endobj - -165 0 obj -<< -/Title ($6N2711) -/Parent 164 0 R -/Next 166 0 R -/A 396 0 R ->> -endobj - -166 0 obj -<< -/Title ($6N11267) -/Parent 164 0 R -/Prev 165 0 R -/Next 167 0 R -/A 398 0 R ->> -endobj - -167 0 obj -<< -/Title ($6N11289) -/Parent 164 0 R -/Prev 166 0 R -/A 400 0 R ->> -endobj - -169 0 obj -<< -/Title ($3N992) -/Parent 168 0 R -/Next 170 0 R -/A 402 0 R ->> -endobj - -170 0 obj -<< -/Title ($3N994) -/Parent 168 0 R -/Prev 169 0 R -/Next 171 0 R -/A 404 0 R ->> -endobj - -171 0 obj -<< -/Title ($3N7071) -/Parent 168 0 R -/Prev 170 0 R -/A 406 0 R ->> -endobj - -173 0 obj -<< -/Title ($3N6305) -/Parent 172 0 R -/Next 174 0 R -/A 408 0 R ->> -endobj - -174 0 obj -<< -/Title ($3N7467) -/Parent 172 0 R -/Prev 173 0 R -/A 410 0 R ->> -endobj - -176 0 obj -<< -/Title ($3N6311) -/Parent 175 0 R -/Next 177 0 R -/A 412 0 R ->> -endobj - -177 0 obj -<< -/Title ($3N7455) -/Parent 175 0 R -/Prev 176 0 R -/A 414 0 R ->> -endobj - -179 0 obj -<< -/Title ($3N7023) -/Parent 178 0 R -/Next 180 0 R -/A 416 0 R ->> -endobj - -180 0 obj -<< -/Title ($3N7394) -/Parent 178 0 R -/Prev 179 0 R -/Next 181 0 R -/A 418 0 R ->> -endobj - -181 0 obj -<< -/Title ($3N7439) -/Parent 178 0 R -/Prev 180 0 R -/A 420 0 R ->> -endobj - -183 0 obj -<< -/Title ($3N7035) -/Parent 182 0 R -/Next 184 0 R -/A 422 0 R ->> -endobj - -184 0 obj -<< -/Title ($3N7391) -/Parent 182 0 R -/Prev 183 0 R -/Next 185 0 R -/A 424 0 R ->> -endobj - -185 0 obj -<< -/Title ($3N7442) -/Parent 182 0 R -/Prev 184 0 R -/A 426 0 R ->> -endobj - -428 0 obj -<< -/Producer (jsPDF 0.0.0) -/CreationDate (D:20250105015408+03'00') ->> -endobj -429 0 obj -<< -/Type /Catalog -/Pages 1 0 R -/OpenAction [3 0 R /FitH null] -/PageLayout /OneColumn -/Outlines 17 0 R ->> -endobj -xref -0 430 -0000000000 65535 f -0000188663 00000 n -0000192106 00000 n -0000000015 00000 n -0000000124 00000 n -0000063084 00000 n -0000063193 00000 n -0000188726 00000 n -0000188891 00000 n -0000189070 00000 n -0000189186 00000 n -0000189356 00000 n -0000190402 00000 n -0000190568 00000 n -0000190762 00000 n -0000190880 00000 n -0000191055 00000 n -0000250509 00000 n -0000250587 00000 n -0000250794 00000 n -0000250909 00000 n -0000250690 00000 n -0000251024 00000 n -0000256109 00000 n -0000256189 00000 n -0000256282 00000 n -0000256375 00000 n -0000256469 00000 n -0000251126 00000 n -0000256550 00000 n -0000256629 00000 n -0000256721 00000 n -0000256813 00000 n -0000256905 00000 n -0000256998 00000 n -0000257091 00000 n -0000251243 00000 n -0000257171 00000 n -0000257251 00000 n -0000257344 00000 n -0000251356 00000 n -0000257424 00000 n -0000257504 00000 n -0000257597 00000 n -0000257690 00000 n -0000257783 00000 n -0000251471 00000 n -0000257863 00000 n -0000251588 00000 n -0000257929 00000 n -0000251705 00000 n -0000257995 00000 n -0000251822 00000 n -0000258061 00000 n -0000251939 00000 n -0000258127 00000 n -0000252056 00000 n -0000258193 00000 n -0000252174 00000 n -0000258260 00000 n -0000252292 00000 n -0000258327 00000 n -0000252410 00000 n -0000258394 00000 n -0000252528 00000 n -0000258461 00000 n -0000252646 00000 n -0000258528 00000 n -0000258608 00000 n -0000252762 00000 n -0000258689 00000 n -0000258770 00000 n -0000252880 00000 n -0000258851 00000 n -0000258932 00000 n -0000259026 00000 n -0000252998 00000 n -0000259107 00000 n -0000259187 00000 n -0000253115 00000 n -0000259268 00000 n -0000259349 00000 n -0000253234 00000 n -0000259430 00000 n -0000259511 00000 n -0000259605 00000 n -0000253353 00000 n -0000259686 00000 n -0000259766 00000 n -0000253470 00000 n -0000259846 00000 n -0000259926 00000 n -0000253588 00000 n -0000260007 00000 n -0000260086 00000 n -0000260178 00000 n -0000260270 00000 n -0000260362 00000 n -0000260454 00000 n -0000260546 00000 n -0000260640 00000 n -0000260735 00000 n -0000260831 00000 n -0000260927 00000 n -0000261023 00000 n -0000261119 00000 n -0000261215 00000 n -0000261311 00000 n -0000261407 00000 n -0000261504 00000 n -0000261600 00000 n -0000261696 00000 n -0000261792 00000 n -0000261888 00000 n -0000253705 00000 n -0000261971 00000 n -0000262054 00000 n -0000253821 00000 n -0000262137 00000 n -0000262220 00000 n -0000262317 00000 n -0000253941 00000 n -0000262400 00000 n -0000262483 00000 n -0000262580 00000 n -0000254061 00000 n -0000262663 00000 n -0000262746 00000 n -0000254178 00000 n -0000262830 00000 n -0000262913 00000 n -0000254298 00000 n -0000262996 00000 n -0000263078 00000 n -0000254420 00000 n -0000263162 00000 n -0000263245 00000 n -0000254540 00000 n -0000263328 00000 n -0000263410 00000 n -0000254662 00000 n -0000263494 00000 n -0000263576 00000 n -0000263672 00000 n -0000254783 00000 n -0000263755 00000 n -0000263839 00000 n -0000263937 00000 n -0000254903 00000 n -0000264021 00000 n -0000264105 00000 n -0000264203 00000 n -0000255023 00000 n -0000264287 00000 n -0000264369 00000 n -0000264465 00000 n -0000255145 00000 n -0000264548 00000 n -0000264631 00000 n -0000264729 00000 n -0000255266 00000 n -0000264813 00000 n -0000264895 00000 n -0000264991 00000 n -0000255389 00000 n -0000265074 00000 n -0000265157 00000 n -0000265255 00000 n -0000255510 00000 n -0000265339 00000 n -0000265421 00000 n -0000265517 00000 n -0000255633 00000 n -0000265600 00000 n -0000265683 00000 n -0000255756 00000 n -0000265766 00000 n -0000265849 00000 n -0000255879 00000 n -0000265932 00000 n -0000266015 00000 n -0000266112 00000 n -0000256001 00000 n -0000266195 00000 n -0000266278 00000 n -0000266375 00000 n -0000192243 00000 n -0000192306 00000 n -0000192738 00000 n -0000192801 00000 n -0000193231 00000 n -0000193294 00000 n -0000193753 00000 n -0000193816 00000 n -0000194221 00000 n -0000194284 00000 n -0000194689 00000 n -0000194752 00000 n -0000195221 00000 n -0000195284 00000 n -0000195705 00000 n -0000195768 00000 n -0000196183 00000 n -0000196246 00000 n -0000196679 00000 n -0000196742 00000 n -0000197163 00000 n -0000197226 00000 n -0000197629 00000 n -0000197692 00000 n -0000198107 00000 n -0000198170 00000 n -0000198601 00000 n -0000198664 00000 n -0000199092 00000 n -0000199155 00000 n -0000199564 00000 n -0000199627 00000 n -0000200021 00000 n -0000200084 00000 n -0000200490 00000 n -0000200553 00000 n -0000200986 00000 n -0000201049 00000 n -0000201480 00000 n -0000201543 00000 n -0000202001 00000 n -0000202064 00000 n -0000202473 00000 n -0000202536 00000 n -0000202967 00000 n -0000203030 00000 n -0000203450 00000 n -0000203513 00000 n -0000203907 00000 n -0000203970 00000 n -0000204391 00000 n -0000204454 00000 n -0000204847 00000 n -0000204910 00000 n -0000205305 00000 n -0000205368 00000 n -0000205763 00000 n -0000205826 00000 n -0000206232 00000 n -0000206295 00000 n -0000206703 00000 n -0000206766 00000 n -0000207199 00000 n -0000207262 00000 n -0000207680 00000 n -0000207743 00000 n -0000208151 00000 n -0000208214 00000 n -0000208646 00000 n -0000208709 00000 n -0000209112 00000 n -0000209175 00000 n -0000209603 00000 n -0000209666 00000 n -0000210070 00000 n -0000210133 00000 n -0000210529 00000 n -0000210592 00000 n -0000211010 00000 n -0000211073 00000 n -0000211518 00000 n -0000211581 00000 n -0000212000 00000 n -0000212063 00000 n -0000212468 00000 n -0000212531 00000 n -0000212960 00000 n -0000213023 00000 n -0000213427 00000 n -0000213490 00000 n -0000213886 00000 n -0000213949 00000 n -0000214353 00000 n -0000214416 00000 n -0000214825 00000 n -0000214888 00000 n -0000215370 00000 n -0000215433 00000 n -0000215863 00000 n -0000215926 00000 n -0000216322 00000 n -0000216385 00000 n -0000216793 00000 n -0000216856 00000 n -0000217264 00000 n -0000217327 00000 n -0000217757 00000 n -0000217820 00000 n -0000218215 00000 n -0000218278 00000 n -0000218671 00000 n -0000218734 00000 n -0000219140 00000 n -0000219203 00000 n -0000219606 00000 n -0000219669 00000 n -0000220075 00000 n -0000220138 00000 n -0000220534 00000 n -0000220597 00000 n -0000220993 00000 n -0000221056 00000 n -0000221462 00000 n -0000221525 00000 n -0000221930 00000 n -0000221993 00000 n -0000222401 00000 n -0000222464 00000 n -0000222897 00000 n -0000222960 00000 n -0000223353 00000 n -0000223416 00000 n -0000223810 00000 n -0000223873 00000 n -0000224340 00000 n -0000224403 00000 n -0000224825 00000 n -0000224888 00000 n -0000225320 00000 n -0000225383 00000 n -0000225813 00000 n -0000225876 00000 n -0000226295 00000 n -0000226358 00000 n -0000226767 00000 n -0000226830 00000 n -0000227260 00000 n -0000227323 00000 n -0000227782 00000 n -0000227845 00000 n -0000228264 00000 n -0000228327 00000 n -0000228794 00000 n -0000228857 00000 n -0000229304 00000 n -0000229367 00000 n -0000229774 00000 n -0000229837 00000 n -0000230293 00000 n -0000230356 00000 n -0000230752 00000 n -0000230815 00000 n -0000231260 00000 n -0000231323 00000 n -0000231728 00000 n -0000231791 00000 n -0000232207 00000 n -0000232270 00000 n -0000232703 00000 n -0000232766 00000 n -0000233174 00000 n -0000233237 00000 n -0000233642 00000 n -0000233705 00000 n -0000234124 00000 n -0000234187 00000 n -0000234620 00000 n -0000234683 00000 n -0000235126 00000 n -0000235189 00000 n -0000235598 00000 n -0000235661 00000 n -0000236079 00000 n -0000236142 00000 n -0000236561 00000 n -0000236624 00000 n -0000237018 00000 n -0000237081 00000 n -0000237498 00000 n -0000237561 00000 n -0000237979 00000 n -0000238042 00000 n -0000238451 00000 n -0000238514 00000 n -0000238920 00000 n -0000238983 00000 n -0000239463 00000 n -0000239526 00000 n -0000239935 00000 n -0000239998 00000 n -0000240394 00000 n -0000240457 00000 n -0000240873 00000 n -0000240936 00000 n -0000241344 00000 n -0000241407 00000 n -0000241837 00000 n -0000241900 00000 n -0000242305 00000 n -0000242368 00000 n -0000242827 00000 n -0000242890 00000 n -0000243286 00000 n -0000243349 00000 n -0000243765 00000 n -0000243828 00000 n -0000244234 00000 n -0000244297 00000 n -0000244727 00000 n -0000244790 00000 n -0000245232 00000 n -0000245295 00000 n -0000245717 00000 n -0000245780 00000 n -0000246176 00000 n -0000246239 00000 n -0000246646 00000 n -0000246709 00000 n -0000247142 00000 n -0000247205 00000 n -0000247612 00000 n -0000247675 00000 n -0000248079 00000 n -0000248142 00000 n -0000248588 00000 n -0000248651 00000 n -0000249097 00000 n -0000249160 00000 n -0000249564 00000 n -0000249627 00000 n -0000250036 00000 n -0000250099 00000 n -0000266458 00000 n -0000266545 00000 n -trailer -<< -/Size 430 -/Root 429 0 R -/Info 428 0 R -/ID [ <0FF718394C008026CB860ADB87CB39D7> <0FF718394C008026CB860ADB87CB39D7> ] ->> -startxref -266667 -%%EOF diff --git a/assets/adapter_schematic_o.png b/assets/adapter_schematic_o.png deleted file mode 100644 index b1f5f04..0000000 Binary files a/assets/adapter_schematic_o.png and /dev/null differ diff --git a/assets/after_assembly.png b/assets/after_assembly.png deleted file mode 100644 index abeaf27..0000000 Binary files a/assets/after_assembly.png and /dev/null differ diff --git a/assets/blueprint_import.svg b/assets/blueprint_import.svg deleted file mode 100644 index 6d6bfa7..0000000 --- a/assets/blueprint_import.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/assets/connection.png b/assets/connection.png deleted file mode 100644 index 0c3b2be..0000000 Binary files a/assets/connection.png and /dev/null differ diff --git a/assets/dhw_meter.png b/assets/dhw_meter.png deleted file mode 100644 index 673f954..0000000 Binary files a/assets/dhw_meter.png and /dev/null differ diff --git a/assets/equitherm_calc.xlsx b/assets/equitherm_calc.xlsx deleted file mode 100644 index e2118a1..0000000 Binary files a/assets/equitherm_calc.xlsx and /dev/null differ diff --git a/assets/gerber.zip b/assets/gerber.zip deleted file mode 100644 index b6606c9..0000000 Binary files a/assets/gerber.zip and /dev/null differ diff --git a/assets/ha/dhw_meter.yaml b/assets/ha/dhw_meter.yaml deleted file mode 100644 index cdc2828..0000000 --- a/assets/ha/dhw_meter.yaml +++ /dev/null @@ -1,19 +0,0 @@ -# Package for Home Assistant Packages -# More info: https://www.home-assistant.io/docs/configuration/packages/ - -dhw_meter: - sensor: - - platform: integration - unique_id: hot_water_meter - name: hot_water_meter - source: sensor.opentherm_dhw_flow_rate - unit_time: min - method: left - round: 2 - - homeassistant: - customize: - sensor.hot_water_meter: - friendly_name: "Hot water" - device_class: "water" - icon: "mdi:water-pump" \ No newline at end of file diff --git a/assets/ha/report_temp_to_otgateway.yaml b/assets/ha/report_temp_to_otgateway.yaml deleted file mode 100644 index 3f56e66..0000000 --- a/assets/ha/report_temp_to_otgateway.yaml +++ /dev/null @@ -1,51 +0,0 @@ -# Blueprint for reporting indoor/outdoor temperature to OpenTherm Gateway from any home assistant sensor -# Updated: 26.01.2026 - -blueprint: - name: Report temp to OpenTherm Gateway - domain: automation - author: "Laxilef" - - input: - source_entity: - name: Source entity - description: "Temperature data source" - selector: - entity: - multiple: false - filter: - - domain: sensor - target_entity: - name: Target entity - description: "Usually ``number.opentherm_indoor_temp`` or ``number.opentherm_outdoor_temp``" - default: "number.opentherm_indoor_temp" - selector: - entity: - multiple: false - filter: - - domain: number - -mode: single -variables: - source_entity: !input source_entity - target_entity: !input target_entity -trigger: - - platform: time_pattern - seconds: /30 -condition: - - condition: template - value_template: "{{ states(source_entity) != 'unavailable' and states(target_entity) != 'unavailable' }}" -action: - - if: - - condition: or - conditions: - - condition: template - value_template: "{{ (states(source_entity)|float(0) - states(target_entity)|float(0)) | abs | round(2) >= 0.01 }}" - - condition: template - value_template: "{{ (as_timestamp(now()) - as_timestamp(states[target_entity].last_updated)) | int(0) > 300 }}" - then: - - service: number.set_value - data: - value: "{{ states(source_entity)|float(0)|round(2) }}" - target: - entity_id: "{{ target_entity }}" \ No newline at end of file diff --git a/assets/ha/report_temp_to_otgateway_from_weather.yaml b/assets/ha/report_temp_to_otgateway_from_weather.yaml deleted file mode 100644 index 2105d8f..0000000 --- a/assets/ha/report_temp_to_otgateway_from_weather.yaml +++ /dev/null @@ -1,51 +0,0 @@ -# Blueprint for reporting temperature to OpenTherm Gateway from home assistant weather integration -# Updated: 26.01.2026 - -blueprint: - name: Report temp to OpenTherm Gateway from Weather - domain: automation - author: "Laxilef" - - input: - source_entity: - name: Source entity - description: "Temperature data source" - selector: - entity: - multiple: false - filter: - - domain: weather - target_entity: - name: Target entity - description: "Usually ``number.opentherm_outdoor_temp``" - default: "number.opentherm_outdoor_temp" - selector: - entity: - multiple: false - filter: - - domain: number - -mode: single -variables: - source_entity: !input source_entity - target_entity: !input target_entity -trigger: - - platform: time_pattern - seconds: /30 -condition: - - condition: template - value_template: "{{ states(source_entity) != 'unavailable' and states(target_entity) != 'unavailable' }}" -action: - - if: - - condition: or - conditions: - - condition: template - value_template: "{{ (state_attr(source_entity, 'temperature')|float(0) - states(target_entity)|float(0)) | abs | round(2) >= 0.1 }}" - - condition: template - value_template: "{{ (as_timestamp(now()) - as_timestamp(states[target_entity].last_updated)) | int(0) > 300 }}" - then: - - service: number.set_value - data: - value: "{{ state_attr(source_entity, 'temperature')|float(0)|round(2) }}" - target: - entity_id: "{{ target_entity }}" \ No newline at end of file diff --git a/gulpfile.js b/gulpfile.js index fa7ff6d..760440c 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -1,4 +1,4 @@ -const { src, dest, series, parallel } = require('gulp'); +const { src, dest, parallel } = require('gulp'); const concat = require('gulp-concat'); const gzip = require('gulp-gzip'); const postcss = require('gulp-postcss'); @@ -28,6 +28,9 @@ let paths = { 'src_data/scripts/lang.js', 'src_data/scripts/utils.js' ], + 'settings-converter.js': [ + 'src_data/scripts/settings-converter.js' + ], 'chart.js': [ 'src_data/scripts/chart.js' ] @@ -66,80 +69,64 @@ let paths = { // Tasks -const styles = (cb) => { - for (let name in paths.styles.bundles) { - const items = paths.styles.bundles[name]; +const styles = parallel(...Object.entries(paths.styles.bundles).map(([name, items]) => { + const task = () => src(items) + .pipe(replace( + "{BUILD_TIME}", + Math.floor(Date.now() / 1000) + )) + .pipe(postcss([ + cssnano({ preset: 'advanced' }) + ])) + .pipe(concat(name)) + .pipe(gzip({ + append: true + })) + .pipe(dest(paths.styles.dest)); + task.displayName = name; + return task; +})); - src(items) - .pipe(replace( - "{BUILD_TIME}", - Math.floor(Date.now() / 1000) - )) - .pipe(postcss([ - cssnano({ preset: 'advanced' }) - ])) - .pipe(concat(name)) - .pipe(gzip({ - append: true - })) - .pipe(dest(paths.styles.dest)); - } +const scripts = parallel(...Object.entries(paths.scripts.bundles).map(([name, items]) => { + const task = () => src(items) + .pipe(replace( + "{BUILD_TIME}", + Math.floor(Date.now() / 1000) + )) + .pipe(terser()) + .pipe(concat(name)) + .pipe(gzip({ + append: true + })) + .pipe(dest(paths.scripts.dest)); + task.displayName = name; + return task; +})); - cb(); -} +const jsonFiles = parallel(...paths.json.map((item) => { + const task = () => src(item.src) + .pipe(replace( + "{BUILD_TIME}", + Math.floor(Date.now() / 1000) + )) + .pipe(jsonminify()) + .pipe(gzip({ + append: true + })) + .pipe(dest(item.dest)); + task.displayName = item.src; + return task; +})); -const scripts = (cb) => { - for (let name in paths.scripts.bundles) { - const items = paths.scripts.bundles[name]; - - src(items) - .pipe(replace( - "{BUILD_TIME}", - Math.floor(Date.now() / 1000) - )) - .pipe(terser().on('error', console.error)) - .pipe(concat(name)) - .pipe(gzip({ - append: true - })) - .pipe(dest(paths.scripts.dest)); - } - - cb(); -} - -const jsonFiles = (cb) => { - for (let i in paths.json) { - const item = paths.json[i]; - - src(item.src) - .pipe(replace( - "{BUILD_TIME}", - Math.floor(Date.now() / 1000) - )) - .pipe(jsonminify()) - .pipe(gzip({ - append: true - })) - .pipe(dest(item.dest)); - } - - cb(); -} - -const staticFiles = (cb) => { - for (let i in paths.static) { - const item = paths.static[i]; - - src(item.src, { encoding: false }) - .pipe(gzip({ - append: true - })) - .pipe(dest(item.dest)); - } - - cb(); -} +const staticFiles = parallel(...paths.static.map((item) => { + const task = () => src(item.src, { encoding: false }) + .pipe(gzip({ + append: true + })) + .pipe(dest(item.dest)); + task.displayName = item.src; + return task; +})); const pages = () => { return src(paths.pages.src) @@ -167,4 +154,4 @@ exports.build_scripts = scripts; exports.build_json = jsonFiles; exports.build_static = staticFiles; exports.build_pages = pages; -exports.build_all = parallel(styles, scripts, jsonFiles, staticFiles, pages); \ No newline at end of file +exports.build_all = parallel(styles, scripts, jsonFiles, staticFiles, pages); diff --git a/include/Sensors.h b/include/Sensors.h new file mode 100644 index 0000000..cbb3c7d --- /dev/null +++ b/include/Sensors.h @@ -0,0 +1,781 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include "macros.h" +#include "utils.h" +#include "strings_shared.h" + +class Sensors { +protected: + static uint8_t maxSensors; + +public: + enum class Type : uint8_t { + OT_OUTDOOR_TEMP = 0, + OT_HEATING_TEMP = 1, + OT_HEATING_RETURN_TEMP = 2, + OT_DHW_TEMP = 3, + OT_DHW_TEMP2 = 4, + OT_DHW_FLOW_RATE = 5, + OT_CH2_TEMP = 6, + OT_EXHAUST_TEMP = 7, + OT_HEAT_EXCHANGER_TEMP = 8, + OT_PRESSURE = 9, + OT_MODULATION_LEVEL = 10, + OT_CURRENT_POWER = 11, + OT_EXHAUST_CO2 = 12, + OT_EXHAUST_FAN_SPEED = 13, + OT_SUPPLY_FAN_SPEED = 14, + OT_SOLAR_STORAGE_TEMP = 15, + OT_SOLAR_COLLECTOR_TEMP = 16, + OT_FAN_SPEED_SETPOINT = 17, + OT_FAN_SPEED_CURRENT = 18, + + OT_BURNER_STARTS = 19, + OT_DHW_BURNER_STARTS = 20, + OT_HEATING_PUMP_STARTS = 21, + OT_DHW_PUMP_STARTS = 22, + OT_BURNER_HOURS = 23, + OT_DHW_BURNER_HOURS = 24, + OT_HEATING_PUMP_HOURS = 25, + OT_DHW_PUMP_HOURS = 26, + OT_COOLING_HOURS = 27, + + NTC_10K_TEMP = 50, + DALLAS_TEMP = 51, + BLUETOOTH = 52, + DHT11 = 53, + DHT22 = 54, + + HEATING_SETPOINT_TEMP = 253, + MANUAL = 254, + NOT_CONFIGURED = 255 + }; + + enum class Purpose : uint8_t { + OUTDOOR_TEMP = 0, + INDOOR_TEMP = 1, + HEATING_TEMP = 2, + HEATING_RETURN_TEMP = 3, + DHW_TEMP = 4, + DHW_RETURN_TEMP = 5, + DHW_FLOW_RATE = 6, + EXHAUST_TEMP = 7, + MODULATION_LEVEL = 8, + + NUMBER = 247, + POWER_FACTOR = 248, + POWER = 249, + FAN_SPEED = 250, + CO2 = 251, + PRESSURE = 252, + HUMIDITY = 253, + TEMPERATURE = 254, + NOT_CONFIGURED = 255 + }; + + enum class ValueType : uint8_t { + PRIMARY = 0, + TEMPERATURE = 0, + HUMIDITY = 1, + BATTERY = 2, + RSSI = 3 + }; + + enum class AverageType : uint8_t { + MEAN = 0, + MINIMUM = 1, + MAXIMUM = 2 + }; + + typedef struct { + bool enabled = false; + char name[33] = {}; + char slug[33] = {}; + Purpose purpose = Purpose::NOT_CONFIGURED; + Type type = Type::NOT_CONFIGURED; + uint8_t gpio = GPIO_IS_NOT_CONFIGURED; + uint8_t address[8] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + float offset = 0.0f; + float factor = 1.0f; + bool filtering = false; + float filteringFactor = 0.15f; + } Settings; + + typedef struct { + bool connected = false; + unsigned long activityAt = 0; + unsigned long updatedAt = 0; + uint8_t signalQuality = 100; + //float raw[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + float values[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + } Result; + + struct Snapshot { + Settings settings; + Result result; + }; + + // Set the backing pointers before starting workers. + // Methods lock internally; hold mutex when accessing the arrays directly. + static Settings* settings; + static Result* results; + static std::mutex mutex; + + static std::optional getSettings(uint8_t sensorId) { + std::lock_guard lock(mutex); + if (settings == nullptr || !isValidSensorId(sensorId)) { + return std::nullopt; + } + return settings[sensorId]; + } + + static std::optional getSnapshot(uint8_t sensorId) { + std::lock_guard lock(mutex); + if (settings == nullptr || results == nullptr || !isValidSensorId(sensorId)) { + return std::nullopt; + } + return Snapshot{settings[sensorId], results[sensorId]}; + } + + static inline void setMaxSensors(uint8_t value) { + // The slot count and backing arrays are configured before starting workers. + maxSensors = value; + } + + static inline uint8_t getMaxSensors() { + return maxSensors; + } + + static uint8_t getMaxSensorId() { + uint8_t maxSensors = getMaxSensors(); + return maxSensors > 1 ? (maxSensors - 1) : 0; + } + + template + static bool isValidSensorId(const T id) { + return id >= 0 && id <= getMaxSensorId(); + } + + static std::optional parseId(const char* value) { + if (!isDigit(value)) { + return std::nullopt; + } + + errno = 0; + const unsigned long parsed = strtoul(value, nullptr, 10); + if (errno == ERANGE || !isValidSensorId(parsed)) { + return std::nullopt; + } + + return static_cast(parsed); + } + + static inline bool isValidValueId(const uint8_t id) { + return id >= (uint8_t) ValueType::TEMPERATURE && id <= (uint8_t) ValueType::RSSI; + } + + static bool isEqualAddress(const uint8_t* addr1, const uint8_t* addr2, const uint8_t length = 8) { + return memcmp(addr1, addr2, length) == 0; + } + + static bool isDifferent(const Settings& previous, const Settings& current) { + return previous.enabled != current.enabled || + strcmp(previous.name, current.name) != 0 || + strcmp(previous.slug, current.slug) != 0 || + previous.purpose != current.purpose || + previous.type != current.type || + previous.gpio != current.gpio || + !isEqualAddress(previous.address, current.address) || + isFloatDifferent(previous.offset, current.offset, 0.0001f) || + isFloatDifferent(previous.factor, current.factor, 0.0001f) || + previous.filtering != current.filtering || + isFloatDifferent(previous.filteringFactor, current.filteringFactor, 0.0001f); + } + + static bool hasEnabledAndValid(const Settings& sensor) { + return sensor.enabled && + sensor.slug[0] != '\0' && + sensor.type != Type::NOT_CONFIGURED && + sensor.purpose != Purpose::NOT_CONFIGURED; + } + + static bool hasEnabledAndValid(const uint8_t id) { + std::lock_guard lock(mutex); + if (settings == nullptr || !isValidSensorId(id)) { + return false; + } + return hasEnabledAndValid(settings[id]); + } + + static uint8_t getAmountByType(Type type, bool onlyEnabled = false) { + std::lock_guard lock(mutex); + if (settings == nullptr) { + return 0; + } + + uint8_t amount = 0; + for (uint8_t id = 0; id <= getMaxSensorId(); id++) { + if (settings[id].type == type && (!onlyEnabled || settings[id].enabled)) { + amount++; + } + } + + return amount; + } + + static std::optional getIdByName(const char* name) { + std::lock_guard lock(mutex); + if (settings == nullptr) { + return std::nullopt; + } + + for (uint8_t id = 0; id <= getMaxSensorId(); id++) { + if (strcmp(settings[id].name, name) == 0) { + return id; + } + } + + return std::nullopt; + } + + static std::optional getIdBySlug(const char* slug) { + if (slug == nullptr || !slug[0]) { + return std::nullopt; + } + + std::lock_guard lock(mutex); + if (settings == nullptr) { + return std::nullopt; + } + + for (uint8_t id = 0; id <= getMaxSensorId(); id++) { + if (strcmp(settings[id].slug, slug) == 0) { + return id; + } + } + + return std::nullopt; + } + + static float convertValue(const Settings& sensor, const ValueType valueType, float value, const UnitSystem unitFrom, const UnitSystem unitTo) { + if (valueType != ValueType::PRIMARY || unitFrom == unitTo) { + return value; + } + + if (sensor.type == Type::HEATING_SETPOINT_TEMP && value == 0) { + return 0; + } + + Purpose purpose = sensor.purpose; + if (sensor.type != Type::MANUAL) { + switch (sensor.type) { + case Type::OT_OUTDOOR_TEMP: + case Type::OT_HEATING_TEMP: + case Type::OT_HEATING_RETURN_TEMP: + case Type::OT_DHW_TEMP: + case Type::OT_DHW_TEMP2: + case Type::OT_CH2_TEMP: + case Type::OT_EXHAUST_TEMP: + case Type::OT_HEAT_EXCHANGER_TEMP: + case Type::OT_SOLAR_STORAGE_TEMP: + case Type::OT_SOLAR_COLLECTOR_TEMP: + case Type::NTC_10K_TEMP: + case Type::DALLAS_TEMP: + case Type::BLUETOOTH: + case Type::DHT11: + case Type::DHT22: + case Type::HEATING_SETPOINT_TEMP: + purpose = Purpose::TEMPERATURE; + break; + + case Type::OT_PRESSURE: + purpose = Purpose::PRESSURE; + break; + + case Type::OT_DHW_FLOW_RATE: + purpose = Purpose::DHW_FLOW_RATE; + break; + + default: + return value; + } + } + + switch (purpose) { + case Purpose::OUTDOOR_TEMP: + case Purpose::INDOOR_TEMP: + case Purpose::HEATING_TEMP: + case Purpose::HEATING_RETURN_TEMP: + case Purpose::DHW_TEMP: + case Purpose::DHW_RETURN_TEMP: + case Purpose::EXHAUST_TEMP: + case Purpose::TEMPERATURE: + return convertTemp(value, unitFrom, unitTo); + + case Purpose::PRESSURE: + return convertPressure(value, unitFrom, unitTo); + + case Purpose::DHW_FLOW_RATE: + return convertVolume(value, unitFrom, unitTo); + + default: + return value; + } + } + + static bool setValueById(const uint8_t sensorId, float value, const ValueType valueType, const bool updateActivityAt = false, const bool markConnected = false) { + const uint8_t valueId = static_cast(valueType); + char name[sizeof(Settings::name)]; + float compensatedValue = value; + float loggedValue; + bool connectedChanged; + { + std::lock_guard lock(mutex); + if (settings == nullptr || results == nullptr || !isValidSensorId(sensorId) || !isValidValueId(valueId)) { + return false; + } + const auto& sensor = settings[sensorId]; + auto& result = results[sensorId]; + if (sensor.type == Type::HEATING_SETPOINT_TEMP || sensor.type == Type::MANUAL) { + result.values[valueId] = compensatedValue; + + } else { + if (valueType == ValueType::PRIMARY) { + if (fabsf(sensor.factor) > 0.001f) { + compensatedValue *= sensor.factor; + } + if (fabsf(sensor.offset) > 0.001f) { + compensatedValue += sensor.offset; + } + + } else if (valueType == ValueType::RSSI) { + if (sensor.type == Type::BLUETOOTH) { + result.signalQuality = Sensors::bluetoothRssiToQuality(value); + } + } + + if (sensor.filtering && fabsf(result.values[valueId]) >= 0.1f) { + result.values[valueId] += (compensatedValue - result.values[valueId]) * sensor.filteringFactor; + + } else { + result.values[valueId] = compensatedValue; + } + } + + const auto now = millis(); + result.updatedAt = now; + if (updateActivityAt) { + result.activityAt = now; + } + connectedChanged = markConnected && !result.connected; + if (connectedChanged) { + result.connected = true; + } + memcpy(name, sensor.name, sizeof(name)); + loggedValue = result.values[valueId]; + } + if (connectedChanged) { + logConnectionStatus(sensorId, name, true); + } + ESP_LOGI( + L_SENSORS, "#%hhu '%s' new value %hhu: %.2f, compensated: %.2f, raw: %.2f", + sensorId, name, valueId, loggedValue, compensatedValue, value + ); + return true; + } + + static bool setManualValueById(uint8_t sensorId, float value, const UnitSystem srcUnit) { + char name[sizeof(Settings::name)]; + bool connectedChanged; + { + std::lock_guard lock(mutex); + if (settings == nullptr || results == nullptr || !isValidSensorId(sensorId)) { + return false; + } + + const auto& sensor = settings[sensorId]; + if (!sensor.enabled || sensor.type != Type::MANUAL) { + return false; + } + + value = convertValue(sensor, ValueType::PRIMARY, value, srcUnit, UnitSystem::METRIC); + if (!std::isfinite(value)) { + return false; + } + + results[sensorId].values[static_cast(ValueType::PRIMARY)] = value; + connectedChanged = applyConnectionStatus(sensorId, true, true); + memcpy(name, sensor.name, sizeof(name)); + } + if (connectedChanged) { + logConnectionStatus(sensorId, name, true); + } + ESP_LOGI( + L_SENSORS, "#%hhu '%s' new value %hhu: %.2f, compensated: %.2f, raw: %.2f", + sensorId, name, static_cast(ValueType::PRIMARY), value, value, value + ); + return true; + } + + static std::optional setManualValueBySlug(std::string_view slug, float value, const UnitSystem srcUnit) { + if (slug.empty()) { + return std::nullopt; + } + + std::optional sensorId; + char name[sizeof(Settings::name)]; + bool connectedChanged = false; + { + std::lock_guard lock(mutex); + if (settings == nullptr || results == nullptr) { + return std::nullopt; + } + + for (uint8_t id = 0; id <= getMaxSensorId(); id++) { + const auto& sensor = settings[id]; + if (!sensor.enabled || sensor.type != Type::MANUAL) { + continue; + } + + if (slug != sensor.slug) { + continue; + } + + value = convertValue(sensor, ValueType::PRIMARY, value, srcUnit, UnitSystem::METRIC); + if (!std::isfinite(value)) { + return std::nullopt; + } + + sensorId = id; + results[id].values[static_cast(ValueType::PRIMARY)] = value; + connectedChanged = applyConnectionStatus(id, true, true); + memcpy(name, sensor.name, sizeof(name)); + break; + } + } + if (!sensorId) { + return std::nullopt; + } + if (connectedChanged) { + logConnectionStatus(*sensorId, name, true); + } + ESP_LOGI( + L_SENSORS, "#%hhu '%s' new value %hhu: %.2f, compensated: %.2f, raw: %.2f", + *sensorId, name, static_cast(ValueType::PRIMARY), value, value, value + ); + return sensorId; + } + + static uint8_t setValueByType(Type type, float value, const ValueType valueType, const bool updateActivityAt = false, const bool markConnected = false) { + uint8_t updated = 0; + for (uint8_t sensorId = 0; sensorId <= getMaxSensorId(); sensorId++) { + const auto sensor = getSettings(sensorId); + if (!sensor || !sensor->enabled || sensor->type != type) { + continue; + } + if (setValueById(sensorId, value, valueType, updateActivityAt, markConnected)) { + updated++; + } + } + return updated; + } + + static bool setConnectionStatusById(const uint8_t sensorId, const bool status, const bool updateActivityAt = true) { + char name[sizeof(Settings::name)]; + bool changed; + { + std::lock_guard lock(mutex); + if (settings == nullptr || results == nullptr || !isValidSensorId(sensorId)) { + return false; + } + changed = applyConnectionStatus(sensorId, status, updateActivityAt); + memcpy(name, settings[sensorId].name, sizeof(name)); + } + if (changed) { + logConnectionStatus(sensorId, name, status); + } + return true; + } + + static uint8_t setConnectionStatusByType(Type type, const bool status, const bool updateActivityAt = true) { + uint8_t updated = 0; + for (uint8_t sensorId = 0; sensorId <= getMaxSensorId(); sensorId++) { + char name[sizeof(Settings::name)]; + bool changed; + { + std::lock_guard lock(mutex); + if (settings == nullptr || results == nullptr) { + return updated; + } + const auto& sensor = settings[sensorId]; + if (!sensor.enabled || sensor.type != type) { + continue; + } + changed = applyConnectionStatus(sensorId, status, updateActivityAt); + memcpy(name, sensor.name, sizeof(name)); + } + if (changed) { + logConnectionStatus(sensorId, name, status); + } + updated++; + } + return updated; + } + + static bool adjustSignalQuality(uint8_t sensorId, int8_t delta) { + std::lock_guard lock(mutex); + if (settings == nullptr || results == nullptr || !isValidSensorId(sensorId)) { + return false; + } + + int value = constrain(results[sensorId].signalQuality + delta, 0, 100); + if (value != results[sensorId].signalQuality) { + results[sensorId].signalQuality = static_cast(value); + results[sensorId].updatedAt = millis(); + } + return true; + } + + static bool setAddressById(uint8_t sensorId, const uint8_t* address, const std::function& onUpdated = nullptr) { + { + std::lock_guard lock(mutex); + if (settings == nullptr || address == nullptr || !isValidSensorId(sensorId)) { + return false; + } + + if (isEqualAddress(settings[sensorId].address, address)) { + return true; + } + + memcpy(settings[sensorId].address, address, sizeof(Settings::address)); + } + + if (onUpdated) { + onUpdated(); + } + + return true; + } + + static bool updateConnectionStatusById(uint8_t sensorId, unsigned long wiredTimeout, unsigned long wirelessTimeout) { + char name[sizeof(Settings::name)]; + { + std::lock_guard lock(mutex); + if (settings == nullptr || results == nullptr || !isValidSensorId(sensorId) || !results[sensorId].connected) { + return false; + } + + const auto& sensor = settings[sensorId]; + const auto& result = results[sensorId]; + bool disconnected = !hasEnabledAndValid(sensor); + if (!disconnected) { + const auto timeout = sensor.type == Type::MANUAL || sensor.type == Type::BLUETOOTH + ? wirelessTimeout + : wiredTimeout; + disconnected = millis() - result.activityAt > timeout; + } + if (!disconnected) { + return false; + } + applyConnectionStatus(sensorId, false, false); + memcpy(name, sensor.name, sizeof(name)); + } + logConnectionStatus(sensorId, name, false); + return true; + } + + static float getMeanValueByPurpose(Purpose purpose, const ValueType valueType, const AverageType avgType = AverageType::MEAN, const bool onlyConnected = true, const float defaultValue = NAN) { + std::lock_guard lock(mutex); + if (settings == nullptr || results == nullptr) { + return defaultValue; + } + + uint8_t valueId = (uint8_t) valueType; + if (!isValidValueId(valueId)) { + return defaultValue; + } + + float value = 0.0f; + uint8_t amount = 0; + + if (avgType == AverageType::MEAN) { + for (uint8_t id = 0; id <= getMaxSensorId(); id++) { + auto& sSensor = settings[id]; + auto& rSensor = results[id]; + + if (sSensor.purpose == purpose && (!onlyConnected || rSensor.connected)) { + const float reading = rSensor.values[valueId]; + amount++; + + // Opposite-sign readings can overflow when subtracted. + if ((value < 0.0f) != (reading < 0.0f)) { + value -= value / amount; + value += reading / amount; + + } else { + value += (reading - value) / amount; + } + } + } + + } else if (avgType == AverageType::MINIMUM) { + for (uint8_t id = 0; id <= getMaxSensorId(); id++) { + auto& sSensor = settings[id]; + auto& rSensor = results[id]; + + if (sSensor.purpose == purpose && (!onlyConnected || rSensor.connected)) { + if (amount == 0 || rSensor.values[valueId] < value) { + value = rSensor.values[valueId]; + amount++; + } + } + } + + } else if (avgType == AverageType::MAXIMUM) { + for (uint8_t id = 0; id <= getMaxSensorId(); id++) { + auto& sSensor = settings[id]; + auto& rSensor = results[id]; + + if (sSensor.purpose == purpose && (!onlyConnected || rSensor.connected)) { + if (amount == 0 || rSensor.values[valueId] > value) { + value = rSensor.values[valueId]; + amount++; + } + } + } + } + + return amount > 0 ? value : defaultValue; + } + + static bool existsConnectedSensorsByPurpose(Purpose purpose) { + std::lock_guard lock(mutex); + if (settings == nullptr || results == nullptr) { + return false; + } + + for (uint8_t id = 0; id <= getMaxSensorId(); id++) { + if (settings[id].purpose == purpose && results[id].connected) { + return true; + } + } + + return false; + } + + static std::string& cleanName(std::string& value, char space = ' ') { + for (char& symbol : value) { + if (symbol >= '0' && symbol <= '9') { + continue; + } + if (symbol >= 'A' && symbol <= 'Z') { + continue; + } + if (symbol >= 'a' && symbol <= 'z') { + continue; + } + if (symbol == '_' || symbol == '-' || symbol == space) { + continue; + } + symbol = space; + } + + // trim + const auto first = value.find_first_not_of(" \t\r\n\f\v"); + if (first == std::string::npos) { + value.clear(); + return value; + } + value.erase(value.find_last_not_of(" \t\r\n\f\v") + 1); + value.erase(0, first); + + return value; + } + + static std::string cleanName(std::string_view value, char space = ' ') { + std::string result(value); + cleanName(result, space); + return result; + } + + static std::string& makeSlug(std::string& result, std::string_view value, char separator = '_') { + result.assign(value); + cleanName(result); + for (char& symbol : result) { + if (symbol >= 'A' && symbol <= 'Z') { + symbol += 'a' - 'A'; + } + if (symbol == ' ') { + symbol = separator; + } + } + return result; + } + + static std::string makeSlug(std::string_view value, char separator = '_') { + std::string result; + makeSlug(result, value, separator); + return result; + } + + static uint8_t bluetoothRssiToQuality(int rssi) { + return constrain(map(rssi, -110, -50, 0, 100), 0, 100);; + } + +private: + // The caller holds mutex; the status log is emitted after it is released. + static bool applyConnectionStatus(uint8_t sensorId, bool status, bool updateActivityAt) { + auto& result = results[sensorId]; + const bool changed = result.connected != status; + result.connected = status; + if (changed || updateActivityAt) { + const auto now = millis(); + result.updatedAt = now; + if (updateActivityAt) { + result.activityAt = now; + } + } + return changed; + } + + static void logConnectionStatus(uint8_t sensorId, const char* name, bool status) { + ESP_LOGI( + L_SENSORS, "#%hhu '%s' new status: %s", + sensorId, name, status ? "CONNECTED" : "DISCONNECTED" + ); + } + + static constexpr bool isDigit(const char* value) { + if (value == nullptr || *value == '\0') { + return false; + } + + while (*value != '\0') { + if (*value < '0' || *value > '9') { + return false; + } + value++; + } + + return true; + } +}; + +inline uint8_t Sensors::maxSensors = 0; +inline Sensors::Settings* Sensors::settings = nullptr; +inline Sensors::Result* Sensors::results = nullptr; +inline std::mutex Sensors::mutex; diff --git a/include/Settings.h b/include/Settings.h new file mode 100644 index 0000000..d707881 --- /dev/null +++ b/include/Settings.h @@ -0,0 +1,405 @@ +#pragma once + +#include + +#include "macros.h" +#include "types.h" +#include "Sensors.h" + +struct NetworkSettings { + char hostname[25] = DEFAULT_HOSTNAME; + bool useDhcp = true; + + struct { + char ip[16] = "192.168.0.100"; + char gateway[16] = "192.168.0.1"; + char subnet[16] = "255.255.255.0"; + char dns[16] = "192.168.0.1"; + } staticConfig; + + struct { + struct { + char ssid[33] = DEFAULT_AP_SSID; + char password[65] = DEFAULT_AP_PASSWORD; + uint8_t channel = 6; + } ap; + + struct { + char ssid[33] = DEFAULT_STA_SSID; + char password[65] = DEFAULT_STA_PASSWORD; + uint8_t channel = 0; + } sta; + } wifi; + + struct { + EthernetType type = EthernetType::W5500; + + struct { + uint8_t clk = DEFAULT_ETH_CLK_GPIO; + uint8_t mosi = DEFAULT_ETH_MOSI_GPIO; + uint8_t miso = DEFAULT_ETH_MISO_GPIO; + uint8_t cs = DEFAULT_ETH_CS_GPIO; + uint8_t irq = DEFAULT_ETH_IRQ_GPIO; + uint8_t rst = DEFAULT_ETH_RST_GPIO; + } w5500; + } ethernet; + + NetworkMode type = NetworkMode::STA; +}; + +struct SystemSettings { + esp_log_level_t logLevel = static_cast(DEFAULT_LOG_LEVEL); + + struct { + bool enabled = DEFAULT_SERIAL_ENABLED; + unsigned int baudrate = DEFAULT_SERIAL_BAUD; + } serial; + + struct { + bool enabled = DEFAULT_WEBSERIAL_ENABLED; + } webSerial; + + struct { + char server[49] = "pool.ntp.org"; + char timezone[49] = "UTC0"; + } ntp; + + UnitSystem unitSystem = UnitSystem::METRIC; + uint8_t statusLedGpio = DEFAULT_STATUS_LED_GPIO; +}; + +struct PortalSettings { + bool auth = false; + char login[13] = DEFAULT_PORTAL_LOGIN; + char password[33] = DEFAULT_PORTAL_PASSWORD; + bool mdns = true; +}; + +struct OpenThermSettings { + uint8_t inGpio = DEFAULT_OT_IN_GPIO; + uint8_t outGpio = DEFAULT_OT_OUT_GPIO; + uint8_t rxLedGpio = DEFAULT_OT_RX_LED_GPIO; + uint8_t memberId = 0; + uint8_t flags = 0; + ChannelDisablingAction heatingDisablingAction = ChannelDisablingAction::OFF_AND_ZERO_SETPOINT; + ChannelDisablingAction dhwDisablingAction = ChannelDisablingAction::OFF_AND_ZERO_SETPOINT; + ChannelDisablingAction ch2DisablingAction = ChannelDisablingAction::OFF_AND_ZERO_SETPOINT; + float minPower = 0.0f; + float maxPower = 0.0f; + + struct { + bool dhwSupport = true; + bool coolingSupport = false; + bool summerWinterMode = false; + bool heatingStateToSummerWinterMode = false; + bool ch2AlwaysEnabled = true; + bool heatingToCh2 = false; + bool dhwToCh2 = false; + bool dhwBlocking = false; + bool dhwStateAsDhwBlocking = false; + bool maxTempSyncWithTargetTemp = true; + bool getMinMaxTemp = true; + bool ignoreDiagState = false; + bool autoFaultReset = false; + bool autoDiagReset = false; + bool setDateAndTime = false; + bool alwaysSendIndoorTemp = true; + bool nativeOTC = false; + bool immergasFix = false; + } options; +}; + +struct MqttSettings { + bool enabled = DEFAULT_MQTT_ENABLED; + char server[81] = DEFAULT_MQTT_SERVER; + unsigned short port = DEFAULT_MQTT_PORT; + char user[33] = DEFAULT_MQTT_USER; + char password[33] = DEFAULT_MQTT_PASSWORD; + char prefix[33] = DEFAULT_MQTT_PREFIX; + unsigned short interval = 60; + bool homeAssistantDiscovery = DEFAULT_HA_DISCOVERY_ENABLED; + char homeAssistantDiscoveryPrefix[33] = DEFAULT_HA_DISCOVERY_PREFIX; +}; + +struct EmergencySettings { + float target = DEFAULT_HEATING_TARGET_TEMP; + unsigned short thresholdTime = 120; +}; + +struct HeatingSettings { + bool enabled = true; + bool turbo = false; + float target = DEFAULT_HEATING_TARGET_TEMP; + float turboFactor = 7.5f; + uint8_t minTemp = DEFAULT_HEATING_MIN_TEMP; + uint8_t maxTemp = DEFAULT_HEATING_MAX_TEMP; + uint8_t maxModulation = 100; + Sensors::AverageType indoorTempAvgType = Sensors::AverageType::MEAN; + Sensors::AverageType outdoorTempAvgType = Sensors::AverageType::MEAN; + + struct { + bool enabled = true; + float value = 0.5f; + } hysteresis; + + struct { + uint8_t highTemp = 95; + uint8_t lowTemp = 90; + } overheatProtection; + + struct { + uint8_t highTemp = 15; + uint8_t lowTemp = 10; + } freezeProtection; +}; + +struct DhwSettings { + bool enabled = true; + float target = DEFAULT_DHW_TARGET_TEMP; + uint8_t minTemp = DEFAULT_DHW_MIN_TEMP; + uint8_t maxTemp = DEFAULT_DHW_MAX_TEMP; + uint8_t maxModulation = 100; + + struct { + uint8_t highTemp = 95; + uint8_t lowTemp = 90; + } overheatProtection; +}; + +struct PidSettings { + bool enabled = false; + float p_factor = 2.0f; + float i_factor = 0.002f; + float d_factor = 0.0f; + unsigned short dt = 300; + short minTemp = 0; + short maxTemp = DEFAULT_HEATING_MAX_TEMP; + + struct { + bool enabled = true; + float p_multiplier = 1.0f; + float i_multiplier = 0.05f; + float d_multiplier = 1.0f; + float thresholdHigh = 0.5f; + float thresholdLow = 1.0f; + } deadband; +}; + +struct EquithermSettings { + bool enabled = false; + float slope = 0.7f; + float exponent = 1.3f; + float shift = 0.0f; + float targetDiffFactor = 2.0f; +}; + +struct ExternalPumpSettings { + bool use = false; + uint8_t gpio = DEFAULT_EXT_PUMP_GPIO; + bool invertState = false; + unsigned short postCirculationTime = 600; + unsigned int antiStuckInterval = 2592000; + unsigned short antiStuckTime = 300; +}; + +struct CascadeControlSettings { + struct { + bool enabled = false; + uint8_t gpio = GPIO_IS_NOT_CONFIGURED; + bool invertState = false; + unsigned short thresholdTime = 60; + } input; + + struct { + bool enabled = false; + uint8_t gpio = GPIO_IS_NOT_CONFIGURED; + bool invertState = false; + unsigned short thresholdTime = 60; + bool onFault = true; + bool onLossConnection = true; + bool onEnabledHeating = false; + } output; +}; + +struct Settings { + SystemSettings system; + PortalSettings portal; + OpenThermSettings opentherm; + MqttSettings mqtt; + EmergencySettings emergency; + HeatingSettings heating; + DhwSettings dhw; + PidSettings pid; + EquithermSettings equitherm; + ExternalPumpSettings externalPump; + CascadeControlSettings cascadeControl; + + char validationValue[8] = SETTINGS_VALID_VALUE; +}; + +struct Variables { + struct { + int8_t rssi = 0; + } network; + + struct { + bool state = false; + } emergency; + + struct { + bool state = false; + unsigned long lastEnabledTime = 0; + } externalPump; + + struct { + bool input = false; + bool output = false; + } cascadeControl; + + struct { + uint8_t memberId = 0; + uint8_t flags = 0; + uint8_t type = 0x01; + uint8_t appVersion = 0x3F; + float protocolVersion = 2.2f; + + struct { + bool blocking = false; + bool enabled = false; + bool smartControl = false; + bool overheat = false; + bool freezing = false; + float setpointTemp = 0.0f; + float targetTemp = 0.0f; + float currentTemp = 0.0f; + float returnTemp = 0.0f; + float indoorTemp = 0.0f; + float outdoorTemp = 0.0f; + float minTemp = 0.0f; + float maxTemp = 0.0f; + } heating; + + struct { + bool enabled = false; + bool overheat = false; + float targetTemp = 0.0f; + float currentTemp = 0.0f; + float returnTemp = 0.0f; + uint8_t minTemp = 0; + uint8_t maxTemp = 0; + } dhw; + + struct { + bool enabled = false; + float targetTemp = 0.0f; + } ch2; + } master; + + struct { + uint8_t memberId = 0; + uint8_t flags = 0; + uint8_t type = 0; + uint8_t appVersion = 0; + float protocolVersion = 0.0f; + + bool connected = false; + bool flame = false; + float pressure = 0.0f; + float heatExchangerTemp = 0.0f; + + struct { + bool active = false; + uint8_t setpoint = 0; + } cooling; + + struct { + bool active = false; + uint8_t code = 0; + } fault; + + struct { + bool active = false; + uint16_t code = 0; + } diag; + + struct { + uint8_t current = 0; + uint8_t min = 0; + uint8_t max = 100; + } modulation; + + struct { + float current = 0.0f; + float min = 0.0f; + float max = 0.0f; + } power; + + struct { + float temp = 0.0f; + uint16_t co2 = 0; + uint16_t fanSpeed = 0; + } exhaust; + + struct { + float storage = 0.0f; + float collector = 0.0f; + } solar; + + struct { + uint8_t setpoint = 0; + uint8_t current = 0; + uint16_t supply = 0; + } fanSpeed; + + struct { + uint16_t burnerStarts = 0; + uint16_t dhwBurnerStarts = 0; + uint16_t heatingPumpStarts = 0; + uint16_t dhwPumpStarts = 0; + uint16_t coolingHours = 0; + uint16_t burnerHours = 0; + uint16_t dhwBurnerHours = 0; + uint16_t heatingPumpHours = 0; + uint16_t dhwPumpHours = 0; + } stats; + + struct { + bool active = false; + bool enabled = false; + float targetTemp = 0.0f; + float roomTargetTemp = 0.0f; + float currentTemp = 0.0f; + float returnTemp = 0.0f; + float indoorTemp = 0.0f; + float outdoorTemp = 0.0f; + uint8_t minTemp = DEFAULT_HEATING_MIN_TEMP; + uint8_t maxTemp = DEFAULT_HEATING_MAX_TEMP; + } heating; + + struct { + bool active = false; + bool enabled = false; + float targetTemp = 0.0f; + float currentTemp = 0.0f; + float currentTemp2 = 0.0f; + float returnTemp = 0.0f; + float flowRate = 0.0f; + uint8_t minTemp = DEFAULT_DHW_MIN_TEMP; + uint8_t maxTemp = DEFAULT_DHW_MAX_TEMP; + } dhw; + + struct { + bool active = false; + bool enabled = false; + float targetTemp = 0.0f; + float roomTargetTemp = 0.0f; + float currentTemp = 0.0f; + float indoorTemp = 0.0f; + } ch2; + } slave; + + struct { + bool resetFault = false; + bool resetDiagnostic = false; + } actions; +}; diff --git a/include/StructSnapshot.h b/include/StructSnapshot.h new file mode 100644 index 0000000..f9185e9 --- /dev/null +++ b/include/StructSnapshot.h @@ -0,0 +1,71 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "utils.h" + +template +class StructSnapshot { +public: + explicit StructSnapshot(const Structure& source) : source(source), snapshot(source) {} + + // Compare the live field with the corresponding field in the private snapshot. + template + bool equals(const Field* field, float tolerance = 0.0001f) const { + const auto index = offset(field); + if (index >= sizeof(Structure) || sizeof(Field) > sizeof(Structure) - index) { + return false; + } + + const auto* previous = reinterpret_cast( + reinterpret_cast(&snapshot) + index + ); + + if constexpr (std::is_array_v) { + return text(*field) == text(*previous); + + } else if constexpr (std::is_same_v) { + return !isFloatDifferent(*field, *previous, tolerance); + + } else { + return *field == *previous; + } + } + + template + void set(const Field* field, const Field* value = nullptr) { + static_assert(std::is_trivially_copyable_v, "Field must be trivially copyable"); + const auto index = offset(field); + if (index >= sizeof(Structure) || sizeof(Field) > sizeof(Structure) - index) { + return; + } + + std::memcpy(reinterpret_cast(&snapshot) + index, value != nullptr ? value : field, sizeof(Field)); + } + +private: + const Structure& source; + Structure snapshot; + + // A fixed-size settings buffer may have no terminator or have unused trailing bytes. + template + static std::string_view text(const char (&value)[N]) { + const std::string_view buffer(value, N); + return buffer.substr(0, buffer.find('\0')); + } + + std::size_t offset(const void* field) const { + const auto base = reinterpret_cast(&source); + const auto address = reinterpret_cast(field); + if (field == nullptr || address < base) { + return sizeof(Structure); + } + + return address - base; + } +}; diff --git a/include/StructTimestampMap.h b/include/StructTimestampMap.h new file mode 100644 index 0000000..8eac59b --- /dev/null +++ b/include/StructTimestampMap.h @@ -0,0 +1,47 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +template +class StructTimestampMap { +public: + // Adding a key can move entries; use the reference before the next insertion. + unsigned long& get(const void* field) { + const auto end = times.begin() + count; + const auto entry = std::lower_bound(times.begin(), end, field, [](const auto& item, const void* ptr) { + return reinterpret_cast(item.first) < reinterpret_cast(ptr); + }); + + if (entry != end && entry->first == field) { + return entry->second; + } + + assert(count < times.size()); + std::move_backward(entry, end, end + 1); + *entry = {field, 0}; + ++count; + return entry->second; + } + + void reset(std::initializer_list fields) { + for (const void* field : fields) { + get(field) = 0; + } + } + + void resetAll() { + for (std::size_t index = 0; index < count; ++index) { + times[index].second = 0; + } + } + +private: + std::array, Capacity> times{}; + std::size_t count = 0; +}; diff --git a/include/app.h b/include/app.h new file mode 100644 index 0000000..c203574 --- /dev/null +++ b/include/app.h @@ -0,0 +1,160 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "macros.h" +#include "types.h" +#include "strings_shared.h" +#include "Settings.h" +#include "utils.h" + +using namespace Mycila; + +class AsyncWebServer; +class WebSerial; + +// Configuration +extern NetworkSettings networkSettings; +extern Settings settings; +extern Sensors::Settings sensorsSettings[SENSORS_AMOUNT]; +void initConfig(); +void saveSettingsNow(); +void requestSaveNetworkSettings(); +void requestSaveSettings(); +// Call after releasing lifecycle, MQTT queue and Sensors data locks. +void requestSaveSensorsSettings(); + +JsonVariant toJson(const NetworkSettings& src, JsonVariant dst); +JsonVariant toJson(const SystemSettings& src, JsonVariant dst); +JsonVariant toJson(const PortalSettings& src, JsonVariant dst); +JsonVariant toJson(const OpenThermSettings& src, JsonVariant dst); +JsonVariant toJson(const MqttSettings& src, JsonVariant dst); +JsonVariant toJson(const EmergencySettings& src, JsonVariant dst); +JsonVariant toJson(const HeatingSettings& src, JsonVariant dst); +JsonVariant toJson(const DhwSettings& src, JsonVariant dst); +JsonVariant toJson(const PidSettings& src, JsonVariant dst); +JsonVariant toJson(const EquithermSettings& src, JsonVariant dst); +JsonVariant toJson(const ExternalPumpSettings& src, JsonVariant dst); +JsonVariant toJson(const CascadeControlSettings& src, JsonVariant dst); +SettingResult fromJson(JsonVariantConst src, NetworkSettings& dst); +SettingResult fromJson(JsonVariantConst src, SystemSettings& dst); +SettingResult fromJson(JsonVariantConst src, PortalSettings& dst); +SettingResult fromJson(JsonVariantConst src, OpenThermSettings& dst); +SettingResult fromJson(JsonVariantConst src, MqttSettings& dst); +SettingResult fromJson(JsonVariantConst src, EmergencySettings& dst); +SettingResult fromJson(JsonVariantConst src, HeatingSettings& dst); +SettingResult fromJson(JsonVariantConst src, DhwSettings& dst); +SettingResult fromJson(JsonVariantConst src, PidSettings& dst); +SettingResult fromJson(JsonVariantConst src, EquithermSettings& dst); +SettingResult fromJson(JsonVariantConst src, ExternalPumpSettings& dst); +SettingResult fromJson(JsonVariantConst src, CascadeControlSettings& dst); +SettingResult applySetting(Settings& dst, std::string_view path, bool value); +SettingResult applySetting(Settings& dst, std::string_view path, float value); +bool normalizeSettings(Settings& dst); +JsonVariant toJson(const uint8_t sensorId, const Sensors::Settings& src, JsonVariant dst); +// Caller holds Sensors::mutex while accessing shared settings and checking slug uniqueness. +SettingResult fromJson(const JsonVariantConst src, Sensors::Settings& dst); +JsonVariant toJson(const Sensors::Settings& sensor, const Sensors::Result& result, JsonVariant dst); +JsonVariant toJson(const uint8_t sensorId, JsonVariant dst); +JsonVariant toJson(const Variables& src, JsonVariant dst); +SettingResult fromJson(const JsonVariantConst src, Variables& dst); +bool applyAction(std::string_view action, bool value); + +// Application state and task managers +inline std::atomic upgrading{false}; +extern Variables vars; +extern TaskManager appTaskManager; +extern TaskManager systemTaskManager; +extern TaskManager openthermTaskManager; +extern TaskManager sensorsTaskManager; +// Schedule once with resume(delay); scheduled() also covers the delay before restart. +// Request only outside OTA and while the task is not already scheduled. +extern Task restartTask; +void initSystem(); + +std::string getResetReason(); + +// Control and regulation +void initControl(); +void initRegulator(); +void initLeds(); + +// Sensors +void initSensors(); + +// OpenTherm +extern Task writeRoomTemperatureTask; +extern Task writeRoomTemperatureCh2Task; +void initOpenTherm(); + +// Logging +extern WebSerial* webSerial; +extern Task configureLoggingTask; +bool initLogging(); +void drainLoggingSerial(); + +// Web server and MQTT +extern AsyncWebServer* webServer; +void initPortal(); +extern Task mqttConfigureTask; +// Protect MQTT client and task pointers while checking and using them. +inline std::mutex mqttMutex; +extern Task* mqttPublishSettingsTask; +extern Task* mqttPublishStateTask; +extern Task* mqttPublishSensorsTask; +void initMqtt(); +void stopMqtt(bool destroy); +bool isMqttConnected(); +void requestReconfigureMqtt(); +void requestReconfigureMqttSensor(uint8_t sensorId, std::optional previousSettings = std::nullopt); +void requestPublishMqttSensor(uint8_t sensorId); +std::string mqttTopic(std::initializer_list parts); +template +std::string mqttTopic(const Parts&... parts) { + return mqttTopic({std::string_view(parts)...}); +} + +// Home Assistant discovery +extern std::unique_ptr haDiscovery; +bool publishHaEntity(HaEntity entityId, bool remove); +void publishDynamicSensor( + const Sensors::Settings& sensor, + Sensors::ValueType valueType = Sensors::ValueType::PRIMARY, bool enabledByDefault = true +); +void publishDynamicManualSensor(const Sensors::Settings& sensor, bool enabledByDefault = true); +void deleteDynamicSensor(const Sensors::Settings& sensor, Sensors::ValueType valueType = Sensors::ValueType::PRIMARY); +void publishConnectionDynamicSensor(const Sensors::Settings& sensor, bool enabledByDefault = true); +void deleteConnectionDynamicSensor(const Sensors::Settings& sensor); +void publishSignalQualityDynamicSensor(const Sensors::Settings& sensor, bool enabledByDefault = false); +void deleteSignalQualityDynamicSensor(const Sensors::Settings& sensor); + +// Network +void initNetwork(); +// Register during setup, before starting systemTaskManager. +// Callbacks run on the system worker: only signal client owners, without blocking. +void onNetworkEvent(NetworkEventCallback callback); +void onNetworkStateChange(NetworkStateCallback callback); +NetworkState getNetworkState(NetworkMode mode = NetworkMode::STA); +NetworkMode getNetworkMode(); +const char* getNetworkConnectionType(); +IPAddress getNetworkIp(); +IPAddress getNetworkSubnet(); +IPAddress getNetworkGateway(); +IPAddress getNetworkDns(); +String getNetworkMac(); +bool isEthernetConfigured(const NetworkSettings& config = networkSettings); +bool isNetworkInterfaceStarted(NetworkMode mode); +// Last state published by the system worker, including during event callbacks. +bool isNetworkConnected(); +void reconnectNetwork(); diff --git a/include/c6_compiler_flags.h b/include/c6_compiler_flags.h new file mode 100644 index 0000000..5ba039f --- /dev/null +++ b/include/c6_compiler_flags.h @@ -0,0 +1,5 @@ +#pragma once + +// Preserve C6 size optimizations through SDK metadata and shell parsing. +#define _GLIBCXX20_CONSTEXPR __attribute__((cold)) constexpr +#define _GLIBCXX23_CONSTEXPR __attribute__((cold)) constexpr diff --git a/src/defines.h b/include/macros.h similarity index 63% rename from src/defines.h rename to include/macros.h index 5654cdb..8a345c1 100644 --- a/src/defines.h +++ b/include/macros.h @@ -1,8 +1,13 @@ +#pragma once + +#include +#include + #define PROJECT_NAME "OpenTherm Gateway" #define PROJECT_REPO "https://github.com/Laxilef/OTGateway" #define MQTT_RECONNECT_INTERVAL 15000 -#define CONFIG_URL "http://%s/" +#define MQTT_SENSOR_REPUBLISH_INTERVAL 300000u #define SETTINGS_VALID_VALUE "stvalid" // only 8 chars! #define GPIO_IS_NOT_CONFIGURED 0xff @@ -18,22 +23,22 @@ #define THERMOSTAT_INDOOR_MIN_TEMP 5 #define THERMOSTAT_INDOOR_MAX_TEMP 40 -#define DEFAULT_NTC_NOMINAL_RESISTANCE 10000.0f -#define DEFAULT_NTC_NOMINAL_TEMP 25.0f -#define DEFAULT_NTC_REF_RESISTANCE 10000.0f -#define DEFAULT_NTC_BETA_FACTOR 3950.0f -#define DEFAULT_NTC_VREF 3300.0f -#define DEFAULT_NTC_VLOW_TRESHOLD 25.0f -#define DEFAULT_NTC_VHIGH_TRESHOLD 3298.0f - #ifndef BUILD_VERSION #define BUILD_VERSION "0.0.0" #endif +#ifndef BUILD_COMMIT + #define BUILD_COMMIT "undefined" +#endif + #ifndef BUILD_ENV #define BUILD_ENV "undefined" #endif +#ifndef LOGGING_QUEUE_SIZE + #define LOGGING_QUEUE_SIZE 4096 +#endif + #ifndef DEFAULT_SERIAL_ENABLED #define DEFAULT_SERIAL_ENABLED true #endif @@ -42,19 +47,14 @@ #define DEFAULT_SERIAL_BAUD 115200 #endif -#ifndef DEFAULT_TELNET_ENABLED - #define DEFAULT_TELNET_ENABLED true -#endif - -#ifndef DEFAULT_TELNET_PORT - #define DEFAULT_TELNET_PORT 23 +#ifndef DEFAULT_WEBSERIAL_ENABLED + #define DEFAULT_WEBSERIAL_ENABLED true #endif #ifndef USE_BLE #define USE_BLE false #endif -// ethernet (W5500 over SPI) is only validated on the esp32_c6 target: off everywhere else #ifndef USE_ETHERNET #define USE_ETHERNET false #endif @@ -80,17 +80,13 @@ #endif #ifndef DEFAULT_LOG_LEVEL - #define DEFAULT_LOG_LEVEL TinyLogger::Level::VERBOSE + #define DEFAULT_LOG_LEVEL ESP_LOG_VERBOSE #endif #ifndef DEFAULT_STATUS_LED_GPIO #define DEFAULT_STATUS_LED_GPIO GPIO_IS_NOT_CONFIGURED #endif -#ifndef DEFAULT_ETHERNET_ENABLED - #define DEFAULT_ETHERNET_ENABLED false -#endif - #ifndef DEFAULT_ETH_CLK_GPIO #define DEFAULT_ETH_CLK_GPIO GPIO_IS_NOT_CONFIGURED #endif @@ -147,6 +143,14 @@ #define DEFAULT_MQTT_PREFIX "" #endif +#ifndef DEFAULT_HA_DISCOVERY_ENABLED + #define DEFAULT_HA_DISCOVERY_ENABLED false +#endif + +#ifndef DEFAULT_HA_DISCOVERY_PREFIX + #define DEFAULT_HA_DISCOVERY_PREFIX "homeassistant" +#endif + #ifndef DEFAULT_OT_IN_GPIO #define DEFAULT_OT_IN_GPIO GPIO_IS_NOT_CONFIGURED #endif @@ -171,6 +175,38 @@ #define DEFAULT_SENSOR_INDOOR_GPIO GPIO_IS_NOT_CONFIGURED #endif +#ifndef DEFAULT_SENSOR_INDOOR_TYPE + #define DEFAULT_SENSOR_INDOOR_TYPE Sensors::Type::DALLAS_TEMP +#endif + +#ifndef DEFAULT_NTC_NOMINAL_RESISTANCE + #define DEFAULT_NTC_NOMINAL_RESISTANCE 10000.0f +#endif + +#ifndef DEFAULT_NTC_NOMINAL_TEMP + #define DEFAULT_NTC_NOMINAL_TEMP 25.0f +#endif + +#ifndef DEFAULT_NTC_REF_RESISTANCE + #define DEFAULT_NTC_REF_RESISTANCE 10000.0f +#endif + +#ifndef DEFAULT_NTC_BETA_FACTOR + #define DEFAULT_NTC_BETA_FACTOR 3950.0f +#endif + +#ifndef DEFAULT_NTC_VREF + #define DEFAULT_NTC_VREF 3300.0f +#endif + +#ifndef DEFAULT_NTC_VLOW_THRESHOLD + #define DEFAULT_NTC_VLOW_THRESHOLD 25.0f +#endif + +#ifndef DEFAULT_NTC_VHIGH_THRESHOLD + #define DEFAULT_NTC_VHIGH_THRESHOLD 3298.0f +#endif + #ifndef SENSORS_AMOUNT #define SENSORS_AMOUNT 20 #endif @@ -179,31 +215,16 @@ #define DEFAULT_EXT_PUMP_GPIO GPIO_IS_NOT_CONFIGURED #endif -#ifndef PROGMEM - #define PROGMEM +#ifndef GPIO_IS_VALID_OUTPUT_GPIO + #define GPIO_IS_VALID_OUTPUT_GPIO(gpio_num) ((gpio_num) >= 0 && (gpio_num) < SOC_GPIO_PIN_COUNT && \ + (((1ULL << (gpio_num)) & SOC_GPIO_VALID_OUTPUT_GPIO_MASK) != 0)) #endif -#ifdef ARDUINO_ARCH_ESP32 - #include -#elif !defined(GPIO_IS_VALID_GPIO) - #define GPIO_IS_VALID_GPIO(gpioNum) (gpioNum >= 0 && gpioNum <= 17) +#ifndef GPIO_IS_VALID_INPUT_GPIO + // ESP-IDF uses the general GPIO mask for digital input capability. + #define GPIO_IS_VALID_INPUT_GPIO(gpio_num) GPIO_IS_VALID_GPIO(gpio_num) #endif -#define GPIO_IS_VALID(gpioNum) (gpioNum != GPIO_IS_NOT_CONFIGURED && GPIO_IS_VALID_GPIO(gpioNum)) - -enum class UnitSystem : uint8_t { - METRIC = 0, - IMPERIAL = 1 -}; - -enum class HysteresisAction : uint8_t { - DISABLE_HEATING = 0, - SET_ZERO_TARGET = 1 -}; - -enum class EthernetImplementation : uint8_t { - NONE = 0, - W5500 = 1 -}; - -char buffer[255]; +#define GPIO_IS_VALID(gpioNum) ((gpioNum) != GPIO_IS_NOT_CONFIGURED && GPIO_IS_VALID_GPIO(gpioNum)) +#define GPIO_IS_VALID_INPUT(gpioNum) ((gpioNum) != GPIO_IS_NOT_CONFIGURED && GPIO_IS_VALID_INPUT_GPIO(gpioNum)) +#define GPIO_IS_VALID_OUTPUT(gpioNum) ((gpioNum) != GPIO_IS_NOT_CONFIGURED && GPIO_IS_VALID_OUTPUT_GPIO(gpioNum)) diff --git a/include/metrics.h b/include/metrics.h new file mode 100644 index 0000000..5a37623 --- /dev/null +++ b/include/metrics.h @@ -0,0 +1,105 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include + +struct HeapMetrics : multi_heap_info_t { + size_t total; + size_t minLargestBlock = SIZE_MAX; + uint8_t fragmentation; +}; + +struct MemoryMetrics { + bool captured; + uint64_t uptime; + HeapMetrics heap; + HeapMetrics psram; +}; + +struct CrashMetrics { + bool captured; + uint32_t core; + uint64_t uptime; +}; + +struct CoreDumpBuildInfo { + char version[sizeof(BUILD_VERSION)] = BUILD_VERSION; + char date[sizeof("Mmm dd yyyy hh:mm:ss")]; + char commit[sizeof(BUILD_COMMIT)] = BUILD_COMMIT; + char env[sizeof(BUILD_ENV)] = BUILD_ENV; + char core[sizeof(ESP_ARDUINO_VERSION_STR)]; + char sdk[64]; + char chipModel[16]; + uint16_t chipRevision; + uint8_t chipCores; + uint32_t cpuFreqMHz; + uint32_t flashChipSize; +}; + +// Keep one shared instance of each record in the native core dump. +inline COREDUMP_DRAM_ATTR MemoryMetrics memoryMetrics __attribute__((used)) = {}; +inline COREDUMP_DRAM_ATTR CrashMetrics crashMetrics __attribute__((used)) = {}; +inline COREDUMP_DRAM_ATTR CoreDumpBuildInfo coreDumpBuildInfo __attribute__((used)) = {}; +inline std::mutex memoryMetricsMutex; + +// Refresh and copy under the same lock: System and HTTP run on different tasks. +inline MemoryMetrics getMemoryMetrics() { + std::lock_guard lock(memoryMetricsMutex); + + // A panic during the update must not report partially written statistics. + __atomic_store_n(&memoryMetrics.captured, false, __ATOMIC_SEQ_CST); + heap_caps_get_info(&memoryMetrics.heap, MALLOC_CAP_INTERNAL); + + if (memoryMetrics.psram.total) { + heap_caps_get_info(&memoryMetrics.psram, MALLOC_CAP_SPIRAM); + } + + if (memoryMetrics.heap.largest_free_block < memoryMetrics.heap.minLargestBlock) { + memoryMetrics.heap.minLargestBlock = memoryMetrics.heap.largest_free_block; + } + + if (memoryMetrics.psram.largest_free_block < memoryMetrics.psram.minLargestBlock) { + memoryMetrics.psram.minLargestBlock = memoryMetrics.psram.largest_free_block; + } + + memoryMetrics.heap.fragmentation = memoryMetrics.heap.total_free_bytes + ? 100 - memoryMetrics.heap.largest_free_block * 100.0 / memoryMetrics.heap.total_free_bytes + : 0; + memoryMetrics.psram.fragmentation = memoryMetrics.psram.total_free_bytes + ? 100 - memoryMetrics.psram.largest_free_block * 100.0 / memoryMetrics.psram.total_free_bytes + : 0; + memoryMetrics.uptime = esp_timer_get_time() / 1000; + __atomic_store_n(&memoryMetrics.captured, true, __ATOMIC_RELEASE); + return memoryMetrics; +} + +static void IRAM_ATTR captureCoreDumpMetrics(arduino_panic_info_t* info, void*) { + crashMetrics.core = info->core; + crashMetrics.uptime = esp_timer_get_time() / 1000; + __atomic_store_n(&crashMetrics.captured, true, __ATOMIC_RELEASE); +} + +static inline void initCoreDumpMetrics() { + // Keep the timestamp local to the calling translation unit, outside shared types. + strlcpy(coreDumpBuildInfo.date, __DATE__ " " __TIME__, sizeof(coreDumpBuildInfo.date)); + strlcpy(coreDumpBuildInfo.core, ESP.getCoreVersion(), sizeof(coreDumpBuildInfo.core)); + strlcpy(coreDumpBuildInfo.sdk, ESP.getSdkVersion(), sizeof(coreDumpBuildInfo.sdk)); + strlcpy(coreDumpBuildInfo.chipModel, ESP.getChipModel(), sizeof(coreDumpBuildInfo.chipModel)); + + coreDumpBuildInfo.chipRevision = ESP.getChipRevision(); + coreDumpBuildInfo.chipCores = ESP.getChipCores(); + coreDumpBuildInfo.cpuFreqMHz = ESP.getCpuFreqMHz(); + coreDumpBuildInfo.flashChipSize = ESP.getFlashChipSize(); + + // Arduino has registered the memory regions before this one-time initialization. + memoryMetrics.heap.total = heap_caps_get_total_size(MALLOC_CAP_INTERNAL); + memoryMetrics.psram.total = psramFound() ? heap_caps_get_total_size(MALLOC_CAP_SPIRAM) : 0; + + getMemoryMetrics(); + set_arduino_panic_handler(captureCoreDumpMetrics, nullptr); +} diff --git a/include/strings_shared.h b/include/strings_shared.h new file mode 100644 index 0000000..9fa75c0 --- /dev/null +++ b/include/strings_shared.h @@ -0,0 +1,232 @@ +#pragma once + +inline const char L_SETTINGS[] = "SETTINGS"; +inline const char L_SETTINGS_OT[] = "SETTINGS.OT"; +inline const char L_SETTINGS_DHW[] = "SETTINGS.DHW"; +inline const char L_SETTINGS_HEATING[] = "SETTINGS.HEATING"; +inline const char L_NETWORK[] = "NETWORK"; +inline const char L_NETWORK_SETTINGS[] = "NETWORK.SETTINGS"; +inline const char L_PORTAL_WEBSERVER[] = "PORTAL.WEBSERVER"; +inline const char L_PORTAL_DNSSERVER[] = "PORTAL.DNSSERVER"; +inline const char L_PORTAL_CAPTIVE[] = "PORTAL.CAPTIVE"; +inline const char L_PORTAL_OTA[] = "PORTAL.OTA"; +inline const char L_MAIN[] = "MAIN"; +inline const char L_MQTT[] = "MQTT"; +inline const char L_MQTT_MSG[] = "MQTT.MSG"; +inline const char L_OT[] = "OT"; +inline const char L_OT_DHW[] = "OT.DHW"; +inline const char L_OT_HEATING[] = "OT.HEATING"; +inline const char L_OT_CH2[] = "OT.CH2"; +inline const char L_SENSORS[] = "SENSORS"; +inline const char L_SENSORS_SETTINGS[] = "SENSORS.SETTINGS"; +inline const char L_SENSORS_DALLAS[] = "SENSORS.DALLAS"; +inline const char L_SENSORS_DHT[] = "SENSORS.DHT"; +inline const char L_SENSORS_NTC[] = "SENSORS.NTC"; +inline const char L_SENSORS_BLE[] = "SENSORS.BLE"; +inline const char L_REGULATOR[] = "REGULATOR"; +inline const char L_REGULATOR_PID[] = "REGULATOR.PID"; +inline const char L_REGULATOR_EQUITHERM[] = "REGULATOR.EQUITHERM"; +inline const char L_CASCADE_INPUT[] = "CASCADE.INPUT"; +inline const char L_CASCADE_OUTPUT[] = "CASCADE.OUTPUT"; +inline const char L_EXTPUMP[] = "EXTPUMP"; + + +inline const char S_ACTIONS[] = "actions"; +inline const char S_ACTIVE[] = "active"; +inline const char S_ADDRESS[] = "address"; +inline const char S_ANTI_STUCK_INTERVAL[] = "antistuck_interval"; +inline const char S_ANTI_STUCK_TIME[] = "antistuck_time"; +inline const char S_AP[] = "ap"; +inline const char S_APP_VERSION[] = "app_version"; +inline const char S_AUTH[] = "auth"; +inline const char S_AUTO_DIAG_RESET[] = "auto_diag_reset"; +inline const char S_AUTO_FAULT_RESET[] = "auto_fault_reset"; +inline const char S_BATTERY[] = "battery"; +inline const char S_BAUDRATE[] = "baudrate"; +inline const char S_BLOCKING[] = "blocking"; +inline const char S_BSSID[] = "bssid"; +inline const char S_BUILD[] = "build"; +inline const char S_CASCADE_CONTROL[] = "cascade_control"; +inline const char S_CHANNEL[] = "channel"; +inline const char S_CH2_ALWAYS_ENABLED[] = "ch2_always_enabled"; +inline const char S_CH2_DISABLING_ACTION[] = "ch2_disabling_action"; +inline const char S_CHIP[] = "chip"; +inline const char S_CLK[] = "clk"; +inline const char S_CODE[] = "code"; +inline const char S_COMMIT[] = "commit"; +inline const char S_CONFIGURED[] = "configured"; +inline const char S_CONNECTED[] = "connected"; +inline const char S_CONNECTION_TYPE[] = "connection_type"; +inline const char S_COOLING[] = "cooling"; +inline const char S_COOLING_SUPPORT[] = "cooling_support"; +inline const char S_CORE[] = "core"; +inline const char S_CORES[] = "cores"; +inline const char S_CS[] = "cs"; +inline const char S_CURRENT_TEMP[] = "current_temp"; +inline const char S_DATE[] = "date"; +inline const char S_DEADBAND[] = "deadband"; +inline const char S_DHW[] = "dhw"; +inline const char S_DHW_BLOCKING[] = "dhw_blocking"; +inline const char S_DHW_DISABLING_ACTION[] = "dhw_disabling_action"; +inline const char S_DHW_STATE_AS_DHW_BLOCKING[] = "dhw_state_as_dhw_blocking"; +inline const char S_DHW_SUPPORT[] = "dhw_support"; +inline const char S_DHW_TO_CH2[] = "dhw_to_ch2"; +inline const char S_DIAG[] = "diag"; +inline const char S_DNS[] = "dns"; +inline const char S_DT[] = "dt"; +inline const char S_D_FACTOR[] = "d_factor"; +inline const char S_D_MULTIPLIER[] = "d_multiplier"; +inline const char S_EMERGENCY[] = "emergency"; +inline const char S_ENABLED[] = "enabled"; +inline const char S_ENV[] = "env"; +inline const char S_EQUITHERM[] = "equitherm"; +inline const char S_ETHERNET[] = "ethernet"; +inline const char S_EXPONENT[] = "exponent"; +inline const char S_EXTERNAL_PUMP[] = "ext_pump"; +inline const char S_FACTOR[] = "factor"; +inline const char S_FALSE[] = "false"; +inline const char S_FAULT[] = "fault"; +inline const char S_FEATURES[] = "features"; +inline const char S_FREEZE_PROTECTION[] = "freeze_protection"; +inline const char S_FREEZING[] = "freezing"; +inline const char S_FILTERING[] = "filtering"; +inline const char S_FILTERING_FACTOR[] = "filtering_factor"; +inline const char S_FLAGS[] = "flags"; +inline const char S_FLAME[] = "flame"; +inline const char S_FLASH[] = "flash"; +inline const char S_FREE[] = "free"; +inline const char S_FREQ[] = "freq"; +inline const char S_GATEWAY[] = "gateway"; +inline const char S_GET_MIN_MAX_TEMP[] = "get_min_max_temp"; +inline const char S_GPIO[] = "gpio"; +inline const char S_HEAP[] = "heap"; +inline const char S_HEATING[] = "heating"; +inline const char S_HEATING_DISABLING_ACTION[] = "heating_disabling_action"; +inline const char S_HEATING_TO_CH2[] = "heating_to_ch2"; +inline const char S_HEATING_STATE_TO_SUMMER_WINTER_MODE[] = "heating_state_to_summer_winter_mode"; +inline const char S_HIDDEN[] = "hidden"; +inline const char S_HIGH_TEMP[] = "high_temp"; +inline const char S_HOME_ASSISTANT_DISCOVERY[] = "ha_discovery"; +inline const char S_HOME_ASSISTANT_DISCOVERY_PREFIX[] = "ha_discovery_prefix"; +inline const char S_HOSTNAME[] = "hostname"; +inline const char S_HUMIDITY[] = "humidity"; +inline const char S_HYSTERESIS[] = "hysteresis"; +inline const char S_ID[] = "id"; +inline const char S_IGNORE_DIAG_STATE[] = "ignore_diag_state"; +inline const char S_IMMERGAS_FIX[] = "immergas_fix"; +inline const char S_ALWAYS_SEND_INDOOR_TEMP[] = "always_send_indoor_temp"; +inline const char S_INDOOR_TEMP[] = "indoor_temp"; +inline const char S_INDOOR_TEMP_AVG_TYPE[] = "indoor_temp_avg_type"; +inline const char S_IN_GPIO[] = "in_gpio"; +inline const char S_INPUT[] = "input"; +inline const char S_INTERVAL[] = "interval"; +inline const char S_INVERT_STATE[] = "invert_state"; +inline const char S_IP[] = "ip"; +inline const char S_IRQ[] = "irq"; +inline const char S_I_FACTOR[] = "i_factor"; +inline const char S_I_MULTIPLIER[] = "i_multiplier"; +inline const char S_LOGIN[] = "login"; +inline const char S_LOG_LEVEL[] = "loglevel"; +inline const char S_LOW_TEMP[] = "low_temp"; +inline const char S_MAC[] = "mac"; +inline const char S_MASTER[] = "master"; +inline const char S_MAX[] = "max"; +inline const char S_MAX_FREE_BLOCK[] = "max_free_block"; +inline const char S_MAX_MODULATION[] = "max_modulation"; +inline const char S_MAX_POWER[] = "max_power"; +inline const char S_MAX_TEMP[] = "max_temp"; +inline const char S_MAX_TEMP_SYNC_WITH_TARGET_TEMP[] = "max_temp_sync_with_target_temp"; +inline const char S_MDNS[] = "mdns"; +inline const char S_MEMBER_ID[] = "member_id"; +inline const char S_MIN[] = "min"; +inline const char S_MIN_FREE[] = "min_free"; +inline const char S_MIN_MAX_FREE_BLOCK[] = "min_max_free_block"; +inline const char S_MIN_POWER[] = "min_power"; +inline const char S_MIN_TEMP[] = "min_temp"; +inline const char S_MISO[] = "miso"; +inline const char S_MODEL[] = "model"; +inline const char S_MODULATION[] = "modulation"; +inline const char S_MOSI[] = "mosi"; +inline const char S_MQTT[] = "mqtt"; +inline const char S_NAME[] = "name"; +inline const char S_SLUG[] = "slug"; +inline const char S_NATIVE_OTC[] = "native_otc"; +inline const char S_NETWORK[] = "network"; +inline const char S_NTP[] = "ntp"; +inline const char S_OFFSET[] = "offset"; +inline const char S_ON_ENABLED_HEATING[] = "on_enabled_heating"; +inline const char S_ON_FAULT[] = "on_fault"; +inline const char S_ON_LOSS_CONNECTION[] = "on_loss_connection"; +inline const char S_OPENTHERM[] = "opentherm"; +inline const char S_OPTIONS[] = "options"; +inline const char S_OUTDOOR_TEMP[] = "outdoor_temp"; +inline const char S_OUTDOOR_TEMP_AVG_TYPE[] = "outdoor_temp_avg_type"; +inline const char S_OUT_GPIO[] = "out_gpio"; +inline const char S_OUTPUT[] = "output"; +inline const char S_OVERHEAT[] = "overheat"; +inline const char S_OVERHEAT_PROTECTION[] = "overheat_protection"; +inline const char S_PASSWORD[] = "password"; +inline const char S_PID[] = "pid"; +inline const char S_PORT[] = "port"; +inline const char S_PORTAL[] = "portal"; +inline const char S_POST_CIRCULATION_TIME[] = "post_circulation_time"; +inline const char S_POWER[] = "power"; +inline const char S_PREFIX[] = "prefix"; +inline const char S_PROTOCOL_VERSION[] = "protocol_version"; +inline const char S_PURPOSE[] = "purpose"; +inline const char S_PSRAM[] = "psram"; +inline const char S_P_FACTOR[] = "p_factor"; +inline const char S_P_MULTIPLIER[] = "p_multiplier"; +inline const char S_RESET_DIAGNOSTIC[] = "reset_diagnostic"; +inline const char S_RESET_FAULT[] = "reset_fault"; +inline const char S_RESET_REASON[] = "reset_reason"; +inline const char S_RESTART[] = "restart"; +inline const char S_RETURN_TEMP[] = "return_temp"; +inline const char S_REV[] = "rev"; +inline const char S_RSSI[] = "rssi"; +inline const char S_RST[] = "rst"; +inline const char S_RX_LED_GPIO[] = "rx_led_gpio"; +inline const char S_SDK[] = "sdk"; +inline const char S_SENSORS[] = "sensors"; +inline const char S_SERIAL[] = "serial"; +inline const char S_SERVER[] = "server"; +inline const char S_SETTINGS[] = "settings"; +inline const char S_SET_DATE_AND_TIME[] = "set_date_and_time"; +inline const char S_SHIFT[] = "shift"; +inline const char S_SIGNAL_QUALITY[] = "signal_quality"; +inline const char S_SIZE[] = "size"; +inline const char S_SLAVE[] = "slave"; +inline const char S_SLOPE[] = "slope"; +inline const char S_SMART_CONTROL[] = "smart_control"; +inline const char S_SSID[] = "ssid"; +inline const char S_STA[] = "sta"; +inline const char S_STATE[] = "state"; +inline const char S_STATIC_CONFIG[] = "static_config"; +inline const char S_STATUS_LED_GPIO[] = "status_led_gpio"; +inline const char S_SETPOINT[] = "setpoint"; +inline const char S_SETPOINT_TEMP[] = "setpoint_temp"; +inline const char S_SUBNET[] = "subnet"; +inline const char S_SUMMER_WINTER_MODE[] = "summer_winter_mode"; +inline const char S_SYSTEM[] = "system"; +inline const char S_TARGET[] = "target"; +inline const char S_TARGET_DIFF_FACTOR[] = "target_diff_factor"; +inline const char S_TARGET_TEMP[] = "target_temp"; +inline const char S_TEMPERATURE[] = "temperature"; +inline const char S_THRESHOLD_HIGH[] = "threshold_high"; +inline const char S_THRESHOLD_LOW[] = "threshold_low"; +inline const char S_THRESHOLD_TIME[] = "threshold_time"; +inline const char S_TIMEZONE[] = "timezone"; +inline const char S_TOTAL[] = "total"; +inline const char S_TRUE[] = "true"; +inline const char S_TURBO[] = "turbo"; +inline const char S_TURBO_FACTOR[] = "turbo_factor"; +inline const char S_TYPE[] = "type"; +inline const char S_UNIT_SYSTEM[] = "unit_system"; +inline const char S_UPTIME[] = "uptime"; +inline const char S_USE[] = "use"; +inline const char S_USE_DHCP[] = "use_dhcp"; +inline const char S_USER[] = "user"; +inline const char S_VALUE[] = "value"; +inline const char S_VERSION[] = "version"; +inline const char S_WEBSERIAL[] = "web_serial"; +inline const char S_WIFI[] = "wifi"; diff --git a/include/types.h b/include/types.h new file mode 100644 index 0000000..7729cf0 --- /dev/null +++ b/include/types.h @@ -0,0 +1,142 @@ +#pragma once + +#include +#include + +enum class UnitSystem : uint8_t { + METRIC = 0, + IMPERIAL = 1 +}; + +enum class ChannelDisablingAction : uint8_t { + OFF = 0, + ZERO_SETPOINT = 1, + OFF_AND_ZERO_SETPOINT = 2 +}; + +enum class PumpStartReason { + NONE, + HEATING, + ANTISTUCK +}; + +enum class EthernetType : uint8_t { + NONE = 0, + W5500 = 1 +}; + +struct SettingResult { + bool changed = false; + bool accepted = false; +}; + +enum HaEntity : uint8_t { + HA_ENTITY_HEATING_TURBO, + HA_ENTITY_HEATING_HYSTERESIS_ENABLED, + HA_ENTITY_HEATING_HYSTERESIS_VALUE, + HA_ENTITY_HEATING_TURBO_FACTOR, + HA_ENTITY_HEATING_MIN_TEMP, + HA_ENTITY_HEATING_MAX_TEMP, + HA_ENTITY_PID_ENABLED, + HA_ENTITY_PID_P_FACTOR, + HA_ENTITY_PID_I_FACTOR, + HA_ENTITY_PID_D_FACTOR, + HA_ENTITY_PID_DT, + HA_ENTITY_PID_MIN_TEMP, + HA_ENTITY_PID_MAX_TEMP, + HA_ENTITY_EQUITHERM_ENABLED, + HA_ENTITY_EQUITHERM_SLOPE, + HA_ENTITY_EQUITHERM_EXPONENT, + HA_ENTITY_EQUITHERM_SHIFT, + HA_ENTITY_EQUITHERM_TARGET_DIFF_FACTOR, + HA_ENTITY_STATUS, + HA_ENTITY_EMERGENCY, + HA_ENTITY_OPENTHERM_STATUS, + HA_ENTITY_HEATING, + HA_ENTITY_FLAME, + HA_ENTITY_FAULT, + HA_ENTITY_DIAGNOSTIC, + HA_ENTITY_EXTERNAL_PUMP, + HA_ENTITY_FAULT_CODE, + HA_ENTITY_DIAGNOSTIC_CODE, + HA_ENTITY_RSSI, + HA_ENTITY_UPTIME, + HA_ENTITY_RESTART, + HA_ENTITY_RESET_FAULT, + HA_ENTITY_RESET_DIAGNOSTIC, + HA_ENTITY_HEATING_CLIMATE, + HA_ENTITY_DHW_MIN_TEMP, + HA_ENTITY_DHW_MAX_TEMP, + HA_ENTITY_DHW, + HA_ENTITY_DHW_CLIMATE, + HA_ENTITY_HEATING_BLOCKING, + HA_ENTITY_HEATING_OVERHEAT, + HA_ENTITY_HEATING_FREEZING, + HA_ENTITY_DHW_OVERHEAT, + HA_ENTITY_CASCADE_CONTROL_INPUT, + HA_ENTITY_CASCADE_CONTROL_OUTPUT, + HA_ENTITY_COUNT +}; + +enum class RequestInterface : uint8_t { + UNKNOWN, + AP, + STA, + ETH +}; + +enum class NetworkEvent : uint8_t { + CONNECTED, + DISCONNECTED, + STA_STARTED, + STA_STOPPED, + STA_CONNECTED, + STA_DISCONNECTED, + STA_GOT_IP, + STA_LOST_IP, + STA_GOT_IP6, + ETH_STARTED, + ETH_STOPPED, + ETH_CONNECTED, + ETH_DISCONNECTED, + ETH_GOT_IP, + ETH_LOST_IP, + ETH_GOT_IP6, + AP_STARTED, + AP_STOPPED, + AP_CLIENT_CONNECTED, + AP_CLIENT_DISCONNECTED, + AP_CLIENT_GOT_IP, + AP_GOT_IP6, + PORTAL_STARTED, + PORTAL_STOPPED, + MDNS_STARTED, + MDNS_STOPPED, + EVENTS_OVERFLOW +}; + +enum class NetworkState : uint8_t { + NETWORK_DISABLED, + NETWORK_ENABLED, + NETWORK_CONNECTING, + NETWORK_TIMEOUT, + NETWORK_CONNECTED, + NETWORK_DISCONNECTED, + NETWORK_RECONNECTING, + AP_STARTING, + AP_STARTED, + PORTAL_STARTING, + PORTAL_STARTED, + PORTAL_COMPLETE, + PORTAL_TIMEOUT +}; + +enum class NetworkMode : uint8_t { + NONE, + AP, + STA, + ETH +}; + +using NetworkEventCallback = void (*)(NetworkEvent); +using NetworkStateCallback = std::function; diff --git a/include/utils.h b/include/utils.h new file mode 100644 index 0000000..e6fbdb1 --- /dev/null +++ b/include/utils.h @@ -0,0 +1,193 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "types.h" + +inline std::string_view trimPayload(std::string_view payload) { + const auto first = payload.find_first_not_of(" \t\r\n"); + if (first == std::string_view::npos) { + return {}; + } + + return payload.substr(first, payload.find_last_not_of(" \t\r\n") - first + 1); +} + +// text must be NUL-terminated; length may exclude trailing whitespace. +inline std::optional parseNumber(const char* text, size_t length) { + if (text == nullptr || length == 0) { + return std::nullopt; + } + + const auto payload = std::string_view(text, length); + const char first = payload.front(); + + // strtof also accepts leading whitespace, '+' and hexadecimal numbers. + if ((first < '0' || first > '9') && first != '-' && first != '.') { + return std::nullopt; + } + + if (payload.find_first_of("xX") != std::string_view::npos) { + return std::nullopt; + } + + char* end; + errno = 0; + const float parsed = std::strtof(text, &end); + if (end != text + length || !std::isfinite(parsed) || (errno == ERANGE && parsed == 0.0f)) { + return std::nullopt; + } + + return parsed; +} + +inline std::optional parseNumber(std::string_view payload) { + if (payload.empty()) { + return std::nullopt; + } + + if (payload.back() == '\0') { + return parseNumber(payload.data(), payload.size() - 1); + } + + char buffer[payload.size() + 1]; + memcpy(buffer, payload.data(), payload.size()); + buffer[payload.size()] = '\0'; + + return parseNumber(buffer, payload.size()); +} + +inline std::string getChipId(const char* prefix = nullptr, const char* suffix = nullptr) { + std::string chipId; + chipId.reserve( + 6 + + (prefix != nullptr ? strlen(prefix) : 0) + + (suffix != nullptr ? strlen(suffix) : 0) + ); + + if (prefix != nullptr) { + chipId += prefix; + } + + uint32_t cid = 0; + // https://github.com/espressif/arduino-esp32/blob/master/libraries/ESP32/examples/ChipID/GetChipID/GetChipID.ino + for (uint8_t i = 0; i < 17; i = i + 8) { + cid |= ((ESP.getEfuseMac() >> (40 - i)) & 0xff) << i; + } + + char hexId[7]; + snprintf(hexId, sizeof(hexId), "%lx", static_cast(cid)); + chipId += hexId; + + if (suffix != nullptr) { + chipId += suffix; + } + + chipId.erase(chipId.find_last_not_of(" \t\n\r\f\v") + 1); + chipId.erase(0, chipId.find_first_not_of(" \t\n\r\f\v")); + return chipId; +} + +inline float liter2gallon(float value) { + return value / 3.785411784f; +} + +inline float gallon2liter(float value) { + return value * 3.785411784f; +} + +inline float convertVolume(float value, const UnitSystem unitFrom, const UnitSystem unitTo) { + if (unitFrom == UnitSystem::METRIC && unitTo == UnitSystem::IMPERIAL) { + value = liter2gallon(value); + + } else if (unitFrom == UnitSystem::IMPERIAL && unitTo == UnitSystem::METRIC) { + value = gallon2liter(value); + } + + return value; +} + +inline float bar2psi(float value) { + return value * 14.5038f; +} + +inline float psi2bar(float value) { + return value / 14.5038f; +} + +inline float convertPressure(float value, const UnitSystem unitFrom, const UnitSystem unitTo) { + if (unitFrom == UnitSystem::METRIC && unitTo == UnitSystem::IMPERIAL) { + value = bar2psi(value); + + } else if (unitFrom == UnitSystem::IMPERIAL && unitTo == UnitSystem::METRIC) { + value = psi2bar(value); + } + + return value; +} + +inline float c2f(float value) { + return (9.0f / 5.0f) * value + 32.0f; +} + +inline float f2c(float value) { + return (value - 32.0f) * 5.0f / 9.0f; +} + +inline float convertTemp(float value, const UnitSystem unitFrom, const UnitSystem unitTo) { + if (unitFrom == UnitSystem::METRIC && unitTo == UnitSystem::IMPERIAL) { + value = c2f(value); + + } else if (unitFrom == UnitSystem::IMPERIAL && unitTo == UnitSystem::METRIC) { + value = f2c(value); + } + + return value; +} + +inline bool isValidTemp(const float value, UnitSystem unit, const float min = 0.1f, const float max = 99.9f, const UnitSystem minMaxUnit = UnitSystem::METRIC) { + return value >= convertTemp(min, minMaxUnit, unit) && value <= convertTemp(max, minMaxUnit, unit); +} + +inline bool isFloatDifferent(float first, float second, float tolerance) { + if (first == second) { + return false; + } + + if (std::isnan(first) && std::isnan(second)) { + return false; + } + + if (!std::isfinite(first) || !std::isfinite(second)) { + return true; + } + + return fabsf(first - second) > tolerance; +} + +inline float roundf(float value, uint8_t decimals = 2) { + if (decimals == 0) { + return std::round(value); + + } else if (abs(value) < 0.00000001f) { + return 0.0f; + } + + const float multiplier = pow10(decimals); + const float scaled = value * multiplier; + return std::isfinite(scaled) ? std::round(scaled) / multiplier : value; +} + +inline uint8_t rssiToSignalQuality(int16_t rssi) { + return constrain(map(rssi, -100, -50, 0, 100), 0, 100); +} diff --git a/lib/BufferedWebServer/BufferedWebServer.h b/lib/BufferedWebServer/BufferedWebServer.h deleted file mode 100644 index d399272..0000000 --- a/lib/BufferedWebServer/BufferedWebServer.h +++ /dev/null @@ -1,102 +0,0 @@ -class BufferedWebServer { -public: - BufferedWebServer(WebServer* webServer, size_t bufferSize = 64) { - this->webServer = webServer; - this->bufferSize = bufferSize; - this->buffer = (uint8_t*)malloc(bufferSize * sizeof(*this->buffer)); - } - - ~BufferedWebServer() { - free(this->buffer); - } - - template - void send(int code, T contentType, const JsonVariantConst content, bool pretty = false) { - auto contentLength = pretty ? measureJsonPretty(content) : measureJson(content); - - #ifdef ARDUINO_ARCH_ESP8266 - if (!this->webServer->chunkedResponseModeStart(code, contentType)) { - this->webServer->send(505, F("text/html"), F("HTTP1.1 required")); - return; - } - - this->webServer->setContentLength(contentLength); - #else - this->webServer->setContentLength(contentLength); - this->webServer->send(code, contentType, emptyString); - #endif - - if (pretty) { - serializeJsonPretty(content, *this); - - } else { - serializeJson(content, *this); - } - - this->flush(); - - #ifdef ARDUINO_ARCH_ESP8266 - this->webServer->chunkedResponseFinalize(); - #else - this->webServer->sendContent(emptyString); - #endif - } - - size_t write(uint8_t c) { - this->buffer[this->bufferPos++] = c; - - if (this->bufferPos >= this->bufferSize) { - this->flush(); - } - - return 1; - } - - size_t write(const uint8_t* buffer, size_t length) { - size_t written = 0; - while (written < length) { - size_t copySize = this->bufferSize - this->bufferPos; - if (written + copySize > length) { - copySize = length - written; - } - - memcpy(this->buffer + this->bufferPos, buffer + written, copySize); - this->bufferPos += copySize; - - if (this->bufferPos >= this->bufferSize) { - this->flush(); - } - - written += copySize; - } - - return written; - } - - void flush() { - if (this->bufferPos == 0) { - return; - } - - #ifdef ARDUINO_ARCH_ESP8266 - ::optimistic_yield(1000); - #endif - - auto& client = this->webServer->client(); - if (client.connected()) { - this->webServer->sendContent((const char*)this->buffer, this->bufferPos); - } - - this->bufferPos = 0; - - #ifdef ARDUINO_ARCH_ESP8266 - ::optimistic_yield(1000); - #endif - } - -protected: - WebServer* webServer = nullptr; - uint8_t* buffer; - size_t bufferSize = 64; - size_t bufferPos = 0; -}; \ No newline at end of file diff --git a/lib/CustomOpenTherm/CustomOpenTherm.h b/lib/CustomOpenTherm/CustomOpenTherm.h deleted file mode 100644 index 3bef65f..0000000 --- a/lib/CustomOpenTherm/CustomOpenTherm.h +++ /dev/null @@ -1,195 +0,0 @@ -#include -#include - -class CustomOpenTherm : public OpenTherm { -public: - typedef std::function DelayCallback; - typedef std::function BeforeSendRequestCallback; - typedef std::function AfterSendRequestCallback; - - CustomOpenTherm(int inPin = 4, int outPin = 5, bool isSlave = false, bool alwaysReceive = false) : OpenTherm(inPin, outPin, isSlave, alwaysReceive) {} - ~CustomOpenTherm() {} - - CustomOpenTherm* setDelayCallback(DelayCallback callback = nullptr) { - this->delayCallback = callback; - - return this; - } - - CustomOpenTherm* setBeforeSendRequestCallback(BeforeSendRequestCallback callback = nullptr) { - this->beforeSendRequestCallback = callback; - - return this; - } - - CustomOpenTherm* setAfterSendRequestCallback(AfterSendRequestCallback callback = nullptr) { - this->afterSendRequestCallback = callback; - - return this; - } - - unsigned long sendRequest(unsigned long request) override { - this->sendRequestAttempt++; - - while (!this->isReady()) { - if (this->delayCallback) { - this->delayCallback(150); - } - - this->process(); - } - - if (this->beforeSendRequestCallback) { - this->beforeSendRequestCallback(request, this->sendRequestAttempt); - } - - if (this->sendRequestAsync(request)) { - do { - if (this->delayCallback) { - this->delayCallback(150); - } - - this->process(); - } while (this->status != OpenThermStatus::READY && this->status != OpenThermStatus::DELAY); - } - - if (this->afterSendRequestCallback) { - this->afterSendRequestCallback(request, this->response, this->responseStatus, this->sendRequestAttempt); - } - - if (this->responseStatus == OpenThermResponseStatus::SUCCESS || this->responseStatus == OpenThermResponseStatus::INVALID) { - this->sendRequestAttempt = 0; - return this->response; - - } else if (this->sendRequestAttempt >= this->sendRequestMaxAttempts) { - this->sendRequestAttempt = 0; - return this->response; - - } else { - return this->sendRequest(request); - } - } - - inline auto sendBoilerReset() { - return this->sendRequestCode(1); - } - - inline auto sendServiceReset() { - return this->sendRequestCode(10); - } - - inline auto sendWaterFilling() { - return this->sendRequestCode(2); - } - - bool sendRequestCode(const uint8_t requestCode) { - unsigned long response = this->sendRequest(buildRequest( - OpenThermMessageType::WRITE_DATA, - OpenThermMessageID::RemoteRequest, - static_cast(requestCode) << 8 - )); - - if (!isValidResponse(response) || !isValidResponseId(response, OpenThermMessageID::RemoteRequest)) { - return false; - } - - const uint8_t responseRequestCode = (response & 0xFFFF) >> 8; - const uint8_t responseCode = response & 0xFF; - if (responseRequestCode != requestCode || responseCode < 128) { - return false; - } - - // reset - this->sendRequest(buildRequest( - OpenThermMessageType::WRITE_DATA, - OpenThermMessageID::RemoteRequest, - 0u << 8 - )); - - return true; - } - - bool getStr(OpenThermMessageID id, char* buffer, uint16_t length = 50) { - if (buffer == nullptr || length == 0) { - return false; - } - - unsigned long response; - uint8_t index = 0; - uint8_t maxIndex = 255; - - while (index <= maxIndex && index < length) { - response = this->sendRequest(buildRequest( - OpenThermMessageType::READ_DATA, - id, - static_cast(index) << 8 - )); - - if (!isValidResponse(response) || !isValidResponseId(response, id)) { - break; - } - - const uint8_t character = response & 0xFF; - if (character == 0) { - break; - } - - if (index == 0) { - maxIndex = (response & 0xFFFF) >> 8; - } - - buffer[index++] = static_cast(character); - } - - buffer[index] = '\0'; - return index > 0; - } - - static bool isCh2Active(unsigned long response) { - return response & 0x20; - } - - static bool isValidResponseId(unsigned long response, OpenThermMessageID id) { - const uint8_t responseId = (response >> 16) & 0xFF; - - return static_cast(id) == responseId; - } - - static uint8_t getResponseMessageTypeId(unsigned long response) { - return (response << 1) >> 29; - } - - static const char* getResponseMessageTypeString(unsigned long response) { - uint8_t msgType = getResponseMessageTypeId(response); - - switch (msgType) { - case static_cast(OpenThermMessageType::READ_ACK): - case static_cast(OpenThermMessageType::WRITE_ACK): - case static_cast(OpenThermMessageType::DATA_INVALID): - case static_cast(OpenThermMessageType::UNKNOWN_DATA_ID): - return CustomOpenTherm::messageTypeToString( - static_cast(msgType) - ); - - default: - return "UNKNOWN"; - } - } - - // converters - template - static unsigned int toFloat(const T val) { - return (unsigned int)(val * 256); - } - - static short getInt(const unsigned long response) { - return response & 0xffff; - } - -protected: - const uint8_t sendRequestMaxAttempts = 5; - uint8_t sendRequestAttempt = 0; - DelayCallback delayCallback; - BeforeSendRequestCallback beforeSendRequestCallback; - AfterSendRequestCallback afterSendRequestCallback; -}; diff --git a/lib/HomeAssistantHelper/HomeAssistantHelper.h b/lib/HomeAssistantHelper/HomeAssistantHelper.h deleted file mode 100644 index 990cda1..0000000 --- a/lib/HomeAssistantHelper/HomeAssistantHelper.h +++ /dev/null @@ -1,180 +0,0 @@ -#pragma once -#include -#include "strings.h" - -class HomeAssistantHelper { -public: - typedef std::function PublishEventCallback; - - HomeAssistantHelper() = default; - - void setWriter() { - this->writer = nullptr; - } - - void setWriter(MqttWriter* writer) { - this->writer = writer; - } - - void setPublishEventCallback(PublishEventCallback callback) { - this->publishEventCallback = callback; - } - - void setDevicePrefix(const char* value) { - this->devicePrefix = value; - } - - void setDeviceVersion(const char* value) { - this->deviceVersion = value; - } - - void setDeviceManufacturer(const char* value) { - this->deviceManufacturer = value; - } - - void setDeviceModel(const char* value) { - this->deviceModel = value; - } - - void setDeviceName(const char* value) { - this->deviceName = value; - } - - void setDeviceConfigUrl(const char* value) { - this->deviceConfigUrl = value; - } - - bool publish(const char* topic, JsonDocument& doc) { - if (this->writer == nullptr) { - if (this->publishEventCallback) { - this->publishEventCallback(topic, false); - } - - return false; - } - - doc[FPSTR(HA_DEVICE)][FPSTR(HA_IDENTIFIERS)][0] = this->devicePrefix; - doc[FPSTR(HA_DEVICE)][FPSTR(HA_SW_VERSION)] = this->deviceVersion; - - if (this->deviceManufacturer != nullptr) { - doc[FPSTR(HA_DEVICE)][FPSTR(HA_MANUFACTURER)] = this->deviceManufacturer; - } - - if (this->deviceModel != nullptr) { - doc[FPSTR(HA_DEVICE)][FPSTR(HA_MODEL)] = this->deviceModel; - } - - if (this->deviceName != nullptr) { - doc[FPSTR(HA_DEVICE)][FPSTR(HA_NAME)] = this->deviceName; - } - - if (this->deviceConfigUrl != nullptr) { - doc[FPSTR(HA_DEVICE)][FPSTR(HA_CONF_URL)] = this->deviceConfigUrl; - } - - bool result = this->writer->publish(topic, doc, true); - doc.clear(); - doc.shrinkToFit(); - - if (this->publishEventCallback) { - this->publishEventCallback(topic, result); - } - - return result; - } - - bool publish(const char* topic) { - if (this->writer == nullptr) { - if (this->publishEventCallback) { - this->publishEventCallback(topic, false); - } - - return false; - } - - bool result = writer->publish(topic, nullptr, 0, true); - if (this->publishEventCallback) { - this->publishEventCallback(topic, result); - } - - return result; - } - - template - String makeConfigTopic(CT category, NT name, char nameSeparator = '/') { - String topic = ""; - topic.concat(this->prefix); - topic.concat('/'); - topic.concat(category); - topic.concat('/'); - topic.concat(this->devicePrefix); - topic.concat(nameSeparator); - topic.concat(name); - topic.concat(F("/config")); - return topic; - } - - template - String getDeviceTopic(T value, char dpvSeparator = '/') { - String topic = ""; - topic.concat(this->devicePrefix); - topic.concat(dpvSeparator); - topic.concat(value); - return topic; - } - - template - String getDeviceTopic(CT category, NT name, char dpcSeparator = '/', char cnSeparator = '/') { - String topic = ""; - topic.concat(this->devicePrefix); - topic.concat(dpcSeparator); - topic.concat(category); - topic.concat(cnSeparator); - topic.concat(name); - return topic; - } - - template - String getDeviceTopic(CT category, NT name, ST suffix, char dpcSeparator = '/', char cnSeparator = '/', char nsSeparator = '/') { - String topic = ""; - topic.concat(this->devicePrefix); - topic.concat(dpcSeparator); - topic.concat(category); - topic.concat(cnSeparator); - topic.concat(name); - topic.concat(nsSeparator); - topic.concat(suffix); - return topic; - } - - template - String getEntityIdWithPrefix(DT domain, VT value, char separator = '_') { - String topic = ""; - topic.concat(domain); - topic.concat('.'); - topic.concat(this->devicePrefix); - topic.concat(separator); - topic.concat(value); - return topic; - } - - template - String getUniqueIdWithPrefix(T value, char separator = '_') { - String topic = ""; - topic.concat(this->devicePrefix); - topic.concat(separator); - topic.concat(value); - return topic; - } - -protected: - PublishEventCallback publishEventCallback; - MqttWriter* writer = nullptr; - const char* prefix = "homeassistant"; - const char* devicePrefix = ""; - const char* deviceVersion = "1.0"; - const char* deviceManufacturer = nullptr; - const char* deviceModel = nullptr; - const char* deviceName = nullptr; - const char* deviceConfigUrl = nullptr; -}; diff --git a/lib/HomeAssistantHelper/strings.h b/lib/HomeAssistantHelper/strings.h deleted file mode 100644 index 6b95d01..0000000 --- a/lib/HomeAssistantHelper/strings.h +++ /dev/null @@ -1,78 +0,0 @@ -#pragma once -#ifndef PROGMEM - #define PROGMEM -#endif - -const char HA_ENTITY_BINARY_SENSOR[] PROGMEM = "binary_sensor"; -const char HA_ENTITY_BUTTON[] PROGMEM = "button"; -const char HA_ENTITY_FAN[] PROGMEM = "fan"; -const char HA_ENTITY_CLIMATE[] PROGMEM = "climate"; -const char HA_ENTITY_NUMBER[] PROGMEM = "number"; -const char HA_ENTITY_SELECT[] PROGMEM = "select"; -const char HA_ENTITY_SENSOR[] PROGMEM = "sensor"; -const char HA_ENTITY_SWITCH[] PROGMEM = "switch"; - -// https://www.home-assistant.io/integrations/mqtt/#supported-abbreviations-in-mqtt-discovery-messages -const char HA_DEFAULT_ENTITY_ID[] PROGMEM = "def_ent_id"; // "default_entity_id " -const char HA_DEVICE[] PROGMEM = "dev"; // "device" -const char HA_IDENTIFIERS[] PROGMEM = "ids"; // "identifiers" -const char HA_SW_VERSION[] PROGMEM = "sw"; // "sw_version" -const char HA_MANUFACTURER[] PROGMEM = "mf"; // "manufacturer" -const char HA_MODEL[] PROGMEM = "mdl"; // "model" -const char HA_NAME[] PROGMEM = "name"; -const char HA_CONF_URL[] PROGMEM = "cu"; // "configuration_url" -const char HA_COMMAND_TOPIC[] PROGMEM = "cmd_t"; // "command_topic" -const char HA_COMMAND_TEMPLATE[] PROGMEM = "cmd_tpl"; // "command_template" -const char HA_ENABLED_BY_DEFAULT[] PROGMEM = "en"; // "enabled_by_default" -const char HA_UNIQUE_ID[] PROGMEM = "uniq_id"; // "unique_id" -const char HA_ENTITY_CATEGORY[] PROGMEM = "ent_cat"; // "entity_category" -const char HA_ENTITY_CATEGORY_DIAGNOSTIC[] PROGMEM = "diagnostic"; -const char HA_ENTITY_CATEGORY_CONFIG[] PROGMEM = "config"; -const char HA_STATE_TOPIC[] PROGMEM = "stat_t"; // "state_topic" -const char HA_VALUE_TEMPLATE[] PROGMEM = "val_tpl"; // "value_template" -const char HA_OPTIONS[] PROGMEM = "ops"; // "options" -const char HA_AVAILABILITY[] PROGMEM = "avty"; // "availability" -const char HA_AVAILABILITY_MODE[] PROGMEM = "avty_mode"; // "availability_mode" -const char HA_TOPIC[] PROGMEM = "t"; // "topic" -const char HA_DEVICE_CLASS[] PROGMEM = "dev_cla"; // "device_class" -const char HA_UNIT_OF_MEASUREMENT[] PROGMEM = "unit_of_meas"; // "unit_of_measurement" -const char HA_UNIT_OF_MEASUREMENT_C[] PROGMEM = "°C"; -const char HA_UNIT_OF_MEASUREMENT_F[] PROGMEM = "°F"; -const char HA_UNIT_OF_MEASUREMENT_PERCENT[] PROGMEM = "%"; -const char HA_UNIT_OF_MEASUREMENT_L_MIN[] PROGMEM = "L/min"; -const char HA_UNIT_OF_MEASUREMENT_GAL_MIN[] PROGMEM = "gal/min"; -const char HA_ICON[] PROGMEM = "ic"; // "icon" -const char HA_MIN[] PROGMEM = "min"; -const char HA_MAX[] PROGMEM = "max"; -const char HA_STEP[] PROGMEM = "step"; -const char HA_MODE[] PROGMEM = "mode"; -const char HA_MODE_BOX[] PROGMEM = "box"; -const char HA_STATE_ON[] PROGMEM = "stat_on"; // "state_on" -const char HA_STATE_OFF[] PROGMEM = "stat_off"; // "state_off" -const char HA_PAYLOAD_ON[] PROGMEM = "pl_on"; // "payload_on" -const char HA_PAYLOAD_OFF[] PROGMEM = "pl_off"; // "payload_off" -const char HA_STATE_CLASS[] PROGMEM = "stat_cla"; // "state_class" -const char HA_STATE_CLASS_MEASUREMENT[] PROGMEM = "measurement"; -const char HA_EXPIRE_AFTER[] PROGMEM = "exp_aft"; // "expire_after" -const char HA_CURRENT_TEMPERATURE_TOPIC[] PROGMEM = "curr_temp_t"; // "current_temperature_topic" -const char HA_CURRENT_TEMPERATURE_TEMPLATE[] PROGMEM = "curr_temp_tpl"; // "current_temperature_template" -const char HA_TEMPERATURE_COMMAND_TOPIC[] PROGMEM = "temp_cmd_t"; // "temperature_command_topic" -const char HA_TEMPERATURE_COMMAND_TEMPLATE[] PROGMEM = "temp_cmd_tpl"; // "temperature_command_template" -const char HA_TEMPERATURE_STATE_TOPIC[] PROGMEM = "temp_stat_t"; // "temperature_state_topic" -const char HA_TEMPERATURE_STATE_TEMPLATE[] PROGMEM = "temp_stat_tpl"; // "temperature_state_template" -const char HA_TEMPERATURE_UNIT[] PROGMEM = "temp_unit"; // "temperature_unit" -const char HA_MODE_COMMAND_TOPIC[] PROGMEM = "mode_cmd_t"; // "mode_command_topic" -const char HA_MODE_COMMAND_TEMPLATE[] PROGMEM = "mode_cmd_tpl"; // "mode_command_template" -const char HA_MODE_STATE_TOPIC[] PROGMEM = "mode_stat_t"; // "mode_state_topic" -const char HA_MODE_STATE_TEMPLATE[] PROGMEM = "mode_stat_tpl"; // "mode_state_template" -const char HA_MODES[] PROGMEM = "modes"; -const char HA_ACTION_TOPIC[] PROGMEM = "act_t"; // "action_topic" -const char HA_ACTION_TEMPLATE[] PROGMEM = "act_tpl"; // "action_template" -const char HA_MIN_TEMP[] PROGMEM = "min_temp"; -const char HA_MAX_TEMP[] PROGMEM = "max_temp"; -const char HA_TEMP_STEP[] PROGMEM = "temp_step"; -const char HA_PRESET_MODE_COMMAND_TOPIC[] PROGMEM = "pr_mode_cmd_t"; // "preset_mode_command_topic" -const char HA_PRESET_MODE_COMMAND_TEMPLATE[] PROGMEM = "pr_mode_cmd_tpl"; // "preset_mode_command_template" -const char HA_PRESET_MODE_STATE_TOPIC[] PROGMEM = "pr_mode_stat_t"; // "preset_mode_state_topic" -const char HA_PRESET_MODE_VALUE_TEMPLATE[] PROGMEM = "pr_mode_val_tpl"; // "preset_mode_value_template" -const char HA_PRESET_MODES[] PROGMEM = "pr_modes"; // "preset_modes" diff --git a/lib/MqttWriter/MqttWiFiClient.h b/lib/MqttWriter/MqttWiFiClient.h deleted file mode 100644 index 843e51a..0000000 --- a/lib/MqttWriter/MqttWiFiClient.h +++ /dev/null @@ -1,24 +0,0 @@ -#include - -class MqttWiFiClient : public WiFiClient { -public: -#ifdef ARDUINO_ARCH_ESP8266 - void flush() override { - if (this->connected()) { - WiFiClient::flush(0); - } - } - - void stop() override { - this->abort(); - } -#endif - -#ifdef ARDUINO_ARCH_ESP32 - void setSync(bool) {} - - bool getSync() { - return false; - } -#endif -}; \ No newline at end of file diff --git a/lib/MqttWriter/MqttWriter.h b/lib/MqttWriter/MqttWriter.h deleted file mode 100644 index 9c0fa45..0000000 --- a/lib/MqttWriter/MqttWriter.h +++ /dev/null @@ -1,220 +0,0 @@ -#pragma once -#include -#include -#ifdef ARDUINO_ARCH_ESP32 -#include -#endif - - -class MqttWriter { -public: - typedef std::function YieldCallback; - typedef std::function PublishEventCallback; - typedef std::function FlushEventCallback; - - MqttWriter(MqttClient* client, size_t bufferSize = 64) { - this->client = client; - this->bufferSize = bufferSize; - this->buffer = (uint8_t*) malloc(bufferSize * sizeof(*this->buffer)); - -#ifdef ARDUINO_ARCH_ESP32 - this->mutex = new std::mutex(); -#endif - } - - ~MqttWriter() { - free(this->buffer); - -#ifdef ARDUINO_ARCH_ESP32 - delete this->mutex; -#endif - } - - MqttWriter* setYieldCallback(YieldCallback callback = nullptr) { - this->yieldCallback = callback; - - return this; - } - - MqttWriter* setPublishEventCallback(PublishEventCallback callback) { - this->publishEventCallback = callback; - - return this; - } - - MqttWriter* setFlushEventCallback(FlushEventCallback callback) { - this->flushEventCallback = callback; - - return this; - } - - bool lock() { -#ifdef ARDUINO_ARCH_ESP32 - if (!this->mutex->try_lock()) { - return false; - } -#else - if (this->isLocked()) { - return false; - } -#endif - - this->locked = true; - this->writeAfterLock = 0; - this->lockedTime = millis(); - - return true; - } - - bool isLocked() { - return this->locked; - } - - void unlock() { - this->locked = false; -#if defined(ARDUINO_ARCH_ESP32) - this->mutex->unlock(); -#endif - } - - bool publish(const char* topic, const JsonVariantConst doc, bool retained = false) { - if (!this->client->connected()) { - this->bufferPos = 0; - return false; - } - - while (!this->lock()) { - if (this->yieldCallback) { - this->yieldCallback(); - } - } - - this->bufferPos = 0; - size_t docSize = measureJson(doc); - size_t written = 0; - if (this->client->beginMessage(topic, docSize, retained)) { - serializeJson(doc, *this); - this->flush(); - this->client->endMessage(); - - written = this->writeAfterLock; - } - this->unlock(); - - if (this->publishEventCallback) { - this->publishEventCallback(topic, written, docSize, written == docSize); - } - - return written == docSize; - } - - bool publish(const char* topic, const char* buffer, bool retained = false) { - return this->publish(topic, (const uint8_t*) buffer, strlen(buffer), retained); - } - - bool publish(const char* topic, const uint8_t* buffer, size_t length, bool retained = false) { - if (!this->client->connected()) { - this->bufferPos = 0; - return false; - } - - while (!this->lock()) { - if (this->yieldCallback) { - this->yieldCallback(); - } - } - - this->bufferPos = 0; - size_t written = 0; - bool result = false; - if (!length || buffer == nullptr) { - result = this->client->beginMessage(topic, retained) && this->client->endMessage(); - - } else if (this->client->beginMessage(topic, length, retained)) { - this->write(buffer, length); - this->flush(); - this->client->endMessage(); - - written = this->writeAfterLock; - result = written == length; - } - this->unlock(); - - if (this->publishEventCallback) { - this->publishEventCallback(topic, written, length, result); - } - - return result; - } - - size_t write(uint8_t c) { - this->buffer[this->bufferPos++] = c; - - if (this->bufferPos >= this->bufferSize) { - this->flush(); - } - - return 1; - } - - size_t write(const uint8_t* buffer, size_t length) { - size_t written = 0; - while (written < length) { - size_t copySize = this->bufferSize - this->bufferPos; - if (written + copySize > length) { - copySize = length - written; - } - - memcpy(this->buffer + this->bufferPos, buffer + written, copySize); - this->bufferPos += copySize; - - if (this->bufferPos >= this->bufferSize) { - this->flush(); - } - - written += copySize; - } - - return written; - } - - bool flush() { - if (this->bufferPos == 0) { - return false; - } - - if (!this->client->connected()) { - this->bufferPos = 0; - } - - size_t length = this->bufferPos; - size_t written = this->client->write(this->buffer, length); - this->client->flush(); - this->bufferPos = 0; - - if (this->isLocked()) { - this->writeAfterLock += written; - } - - if (this->flushEventCallback) { - this->flushEventCallback(written, length); - } - - return written == length; - } - -protected: - YieldCallback yieldCallback; - PublishEventCallback publishEventCallback; - FlushEventCallback flushEventCallback; - MqttClient* client; - uint8_t* buffer; - size_t bufferSize = 64; - size_t bufferPos = 0; - bool locked = false; -#ifdef ARDUINO_ARCH_ESP32 - mutable std::mutex* mutex; -#endif - unsigned long lockedTime = 0; - size_t writeAfterLock = 0; -}; diff --git a/lib/NetworkUtils/NetworkAp.h b/lib/NetworkUtils/NetworkAp.h deleted file mode 100644 index ff4a0a5..0000000 --- a/lib/NetworkUtils/NetworkAp.h +++ /dev/null @@ -1,113 +0,0 @@ -#pragma once -#include -#include - -namespace NetworkUtils { - /** - * @brief Fallback AP: the setup network, raised when the station cannot carry the uplink - */ - class ApUplink : public NetworkUplink { - public: - ApUplink(UplinkContext* context, WifiUplink* wifi) : NetworkUplink(context), wifi(wifi) {} - - void loop() override { - // the association carries the traffic again: retire the AP once it is stable and idle - if (this->wifi->isActive()) { - if ( - this->isEnabled() && !this->hasClients() - && millis() - this->wifi->getConnectedTime() >= this->retireDelay - ) { - Log.sinfoln(FPSTR(L_NETWORK), F("Stop AP because STA connected")); - this->stop(); - } - - return; - } - - if (this->isEnabled()) { - this->attempt.disarm(); - - return; - } - - // a failed softAP() retries once the window runs out - if (this->attempt.isPending()) { - return; - } - - this->start(); - } - - /** - * @brief The AP interface is up, whether or not anyone is on it - * - * A parked radio means the AP is not carrying anything, whatever the mode still says. - */ - bool isActive() override { - return this->isEnabled() && !this->wifi->isSuspended(); - } - - bool isEnabled() { - return (WiFi.getMode() & WIFI_AP) != 0; - } - - bool hasClients() { - if (!this->isEnabled()) { - return false; - } - - return WiFi.softAPgetStationNum() > 0; - } - - void start() { - Log.sinfoln( - FPSTR(L_NETWORK), - this->wifi->hasCredentials() - ? F("Disconnected for a long time, start AP") - : F("No STA credentials, start AP") - ); - - WiFi.mode(WIFI_AP_STA); - this->context->delayCallback(250); - - if (!WiFi.softAP(this->context->apName, this->context->apPassword, this->context->apChannel)) { - this->attempt.arm(this->startTimeout); - } - } - - void stop() { - WiFi.mode(WIFI_STA); - this->attempt.disarm(); - } - - IPAddress localIP() override { - return WiFi.softAPIP(); - } - - IPAddress subnetMask() override { - #ifdef ARDUINO_ARCH_ESP32 - return WiFi.softAPSubnetMask(); - #else - return IPAddress(255, 255, 255, 0); - #endif - } - - IPAddress gatewayIP() override { - return WiFi.softAPIP(); - } - - IPAddress dnsIP() override { - return WiFi.softAPIP(); - } - - String macAddress() override { - return WiFi.softAPmacAddress(); - } - - protected: - const unsigned long retireDelay = 15000; - const unsigned long startTimeout = 5000; - - WifiUplink* wifi; - }; -} diff --git a/lib/NetworkUtils/NetworkConnection.cpp b/lib/NetworkUtils/NetworkConnection.cpp deleted file mode 100644 index 0f03b88..0000000 --- a/lib/NetworkUtils/NetworkConnection.cpp +++ /dev/null @@ -1,158 +0,0 @@ -#include "NetworkConnection.h" -using namespace NetworkUtils; - -void NetworkConnection::setup(bool useDhcp) { - setUseDhcp(useDhcp); - - #if defined(ARDUINO_ARCH_ESP8266) - wifi_set_event_handler_cb(NetworkConnection::onEvent); - #elif defined(ARDUINO_ARCH_ESP32) - WiFi.onEvent(NetworkConnection::onEvent); - #endif -} - -void NetworkConnection::reset() { - status = Status::NONE; - rawDisconnectReason = 0; - disconnectReason = DisconnectReason::NONE; -} - -void NetworkConnection::setUseDhcp(bool value) { - useDhcp = value; -} - -NetworkConnection::Status NetworkConnection::getStatus() { - return status; -} - -NetworkConnection::DisconnectReason NetworkConnection::getDisconnectReason() { - return disconnectReason; -} - -#if defined(ARDUINO_ARCH_ESP8266) -void NetworkConnection::onEvent(System_Event_t *event) { - switch (event->event) { - case EVENT_STAMODE_CONNECTED: - status = useDhcp ? Status::CONNECTING : Status::CONNECTED; - rawDisconnectReason = 0; - disconnectReason = DisconnectReason::NONE; - break; - - case EVENT_STAMODE_GOT_IP: - status = Status::CONNECTED; - rawDisconnectReason = 0; - disconnectReason = DisconnectReason::NONE; - break; - - case EVENT_STAMODE_DHCP_TIMEOUT: - status = Status::DISCONNECTED; - rawDisconnectReason = 0; - disconnectReason = DisconnectReason::DHCP_TIMEOUT; - break; - - case EVENT_STAMODE_DISCONNECTED: - status = Status::DISCONNECTED; - rawDisconnectReason = event->event_info.disconnected.reason; - disconnectReason = convertDisconnectReason(event->event_info.disconnected.reason); - - // https://github.com/esp8266/Arduino/blob/d5eb265f78bff9deb7063d10030a02d021c8c66c/libraries/ESP8266WiFi/src/ESP8266WiFiGeneric.cpp#L231 - if ((wifi_station_get_connect_status() == STATION_GOT_IP) && !wifi_station_get_reconnect_policy()) { - wifi_station_disconnect(); - } - break; - - case EVENT_STAMODE_AUTHMODE_CHANGE: - // https://github.com/esp8266/Arduino/blob/d5eb265f78bff9deb7063d10030a02d021c8c66c/libraries/ESP8266WiFi/src/ESP8266WiFiGeneric.cpp#L241 - { - auto& src = event->event_info.auth_change; - if ((src.old_mode != AUTH_OPEN) && (src.new_mode == AUTH_OPEN)) { - status = Status::DISCONNECTED; - rawDisconnectReason = 0; - disconnectReason = DisconnectReason::OTHER; - - wifi_station_disconnect(); - } - } - break; - - default: - break; - } -} -#elif defined(ARDUINO_ARCH_ESP32) -void NetworkConnection::onEvent(WiFiEvent_t event, WiFiEventInfo_t info) { - switch (event) { - case ARDUINO_EVENT_WIFI_STA_CONNECTED: - status = useDhcp ? Status::CONNECTING : Status::CONNECTED; - rawDisconnectReason = 0; - disconnectReason = DisconnectReason::NONE; - break; - - case ARDUINO_EVENT_WIFI_STA_GOT_IP: - case ARDUINO_EVENT_WIFI_STA_GOT_IP6: - status = Status::CONNECTED; - rawDisconnectReason = 0; - disconnectReason = DisconnectReason::NONE; - break; - - case ARDUINO_EVENT_WIFI_STA_LOST_IP: - status = Status::DISCONNECTED; - rawDisconnectReason = 0; - disconnectReason = DisconnectReason::DHCP_TIMEOUT; - break; - - case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: - status = Status::DISCONNECTED; - rawDisconnectReason = info.wifi_sta_disconnected.reason; - disconnectReason = convertDisconnectReason(info.wifi_sta_disconnected.reason); - break; - - default: - break; - } -} -#endif - -NetworkConnection::DisconnectReason NetworkConnection::convertDisconnectReason(uint8_t reason) { - switch (reason) { - #if defined(ARDUINO_ARCH_ESP8266) - case REASON_BEACON_TIMEOUT: - return DisconnectReason::BEACON_TIMEOUT; - - case REASON_NO_AP_FOUND: - return DisconnectReason::NO_AP_FOUND; - - case REASON_AUTH_FAIL: - return DisconnectReason::AUTH_FAIL; - - case REASON_ASSOC_FAIL: - return DisconnectReason::ASSOC_FAIL; - - case REASON_HANDSHAKE_TIMEOUT: - return DisconnectReason::HANDSHAKE_TIMEOUT; - #elif defined(ARDUINO_ARCH_ESP32) - case WIFI_REASON_BEACON_TIMEOUT: - return DisconnectReason::BEACON_TIMEOUT; - - case WIFI_REASON_NO_AP_FOUND: - return DisconnectReason::NO_AP_FOUND; - - case WIFI_REASON_AUTH_FAIL: - return DisconnectReason::AUTH_FAIL; - - case WIFI_REASON_ASSOC_FAIL: - return DisconnectReason::ASSOC_FAIL; - - case WIFI_REASON_HANDSHAKE_TIMEOUT: - return DisconnectReason::HANDSHAKE_TIMEOUT; - #endif - - default: - return DisconnectReason::OTHER; - } -} - -bool NetworkConnection::useDhcp = false; -NetworkConnection::Status NetworkConnection::status = Status::NONE; -NetworkConnection::DisconnectReason NetworkConnection::disconnectReason = DisconnectReason::NONE; -uint8_t NetworkConnection::rawDisconnectReason = 0; \ No newline at end of file diff --git a/lib/NetworkUtils/NetworkConnection.h b/lib/NetworkUtils/NetworkConnection.h deleted file mode 100644 index c3667ba..0000000 --- a/lib/NetworkUtils/NetworkConnection.h +++ /dev/null @@ -1,48 +0,0 @@ -#pragma once -#if defined(ARDUINO_ARCH_ESP8266) - #include - #include "lwip/etharp.h" -#elif defined(ARDUINO_ARCH_ESP32) - #include -#endif - -namespace NetworkUtils { - struct NetworkConnection { - enum class Status { - CONNECTED, - CONNECTING, - DISCONNECTED, - NONE - }; - - enum class DisconnectReason { - BEACON_TIMEOUT, - NO_AP_FOUND, - AUTH_FAIL, - ASSOC_FAIL, - HANDSHAKE_TIMEOUT, - DHCP_TIMEOUT, - OTHER, - NONE - }; - - static Status status; - static DisconnectReason disconnectReason; - static uint8_t rawDisconnectReason; - - static void setup(bool useDhcp); - static void setUseDhcp(bool value); - static void reset(); - static Status getStatus(); - static DisconnectReason getDisconnectReason(); - #if defined(ARDUINO_ARCH_ESP8266) - static void onEvent(System_Event_t *evt); - #elif defined(ARDUINO_ARCH_ESP32) - static void onEvent(WiFiEvent_t event, WiFiEventInfo_t info); - #endif - - protected: - static DisconnectReason convertDisconnectReason(uint8_t reason); - static bool useDhcp; - }; -} \ No newline at end of file diff --git a/lib/NetworkUtils/NetworkEthernet.h b/lib/NetworkUtils/NetworkEthernet.h deleted file mode 100644 index 978af7a..0000000 --- a/lib/NetworkUtils/NetworkEthernet.h +++ /dev/null @@ -1,269 +0,0 @@ -#pragma once -#include - -#ifdef NETWORK_HAS_ETHERNET - #include -#endif - -namespace NetworkUtils { - /** - * @brief Ethernet uplink: the W5500 driver, its cable and its DHCP lease - */ - class EthernetUplink : public NetworkUplink { - public: - explicit EthernetUplink(UplinkContext* context) : NetworkUplink(context) {} - - void loop() override { - #ifdef NETWORK_HAS_ETHERNET - if (this->restartFlag) { - this->restartFlag = false; - - // The W5500 driver cannot be re-initialized in place: Arduino's ETH.end() leaves - // the SPI bus allocated, so a wiring change only takes effect after a restart. - if (this->started) { - Log.swarningln(FPSTR(L_NETWORK), F("Ethernet: settings changed, restart required to apply them")); - } - } - - if (!this->enabled || !this->hasPins()) { - if (this->active || this->linkUp) { - this->active = false; - this->linkUp = false; - - Log.sinfoln(FPSTR(L_NETWORK), F("Ethernet: disabled, handing the uplink back to WiFi")); - } - - this->attempt.disarm(); - - return; - } - - if (!this->started) { - if (this->startUnavailable) { - return; - } - - Log.sinfoln( - FPSTR(L_NETWORK), - F("Ethernet: init W5500 (CS: %u, IRQ: %u, RST: %u, CLK: %u, MISO: %u, MOSI: %u)"), - this->cs, - this->irq, - this->rst, - this->clk, - this->miso, - this->mosi - ); - - if (!ETH.begin(ETH_PHY_W5500, 1, this->cs, this->irq, this->rst, SPI2_HOST, this->clk, this->miso, this->mosi, 12)) { - // A failed init leaves the SPI bus allocated, so retrying cannot succeed; - // wait for a restart instead of flapping. - this->startUnavailable = true; - this->attempt.disarm(); - - Log.serrorln(FPSTR(L_NETWORK), F("Ethernet: W5500 init failed, check the wiring and restart")); - - return; - } - - this->started = true; - this->running = true; - this->prevLinkCheck = 0; - this->attempt.arm(this->linkGrace); - - if (!this->context->useDhcp) { - ETH.config(this->context->staticIp, this->context->staticGateway, this->context->staticSubnet, this->context->staticDns); - } - - if (strlen(this->context->hostname) && UplinkContext::isHostnameValid(this->context->hostname)) { - ETH.setHostname(this->context->hostname); - } - - return; - } - - if (millis() - this->prevLinkCheck < this->linkCheckInterval) { - return; - } - - this->prevLinkCheck = millis(); - - if (!ETH.linkUp()) { - if (this->linkUp) { - this->linkUp = false; - - Log.sinfoln(FPSTR(L_NETWORK), F("Ethernet: cable disconnected")); - } - - this->attempt.disarm(); - - if (this->active) { - this->active = false; - - Log.sinfoln(FPSTR(L_NETWORK), F("Ethernet: link lost, falling back to WiFi")); - this->context->delayCallback(250); - } - - return; - } - - if (!this->linkUp) { - this->linkUp = true; - this->attempt.arm(this->leaseGrace); - - Log.sinfoln(FPSTR(L_NETWORK), F("Ethernet: cable connected")); - } - - if (!ETH.connected() || this->active) { - return; - } - - this->active = true; - this->attempt.disarm(); - - Log.sinfoln( - FPSTR(L_NETWORK), - F("Ethernet: using ethernet instead of WiFi, IP: %s, link: %u Mbps, duplex: %u"), - ETH.localIP().toString().c_str(), - ETH.linkSpeed(), - ETH.fullDuplex() ? 1 : 0 - ); - #endif - } - - /** - * @brief Ethernet carries the uplink: cable plugged in and DHCP lease obtained - */ - bool isActive() override { - #ifdef NETWORK_HAS_ETHERNET - if (!this->enabled || !this->started) { - return false; - } - - return ETH.linkUp() && ETH.connected(); - #else - return false; - #endif - } - - /** - * @brief Enable/disable the interface, taking the driver in and out of the FSM - */ - void setEnabled(bool value) { - this->enabled = value; - - #ifdef NETWORK_HAS_ETHERNET - // The driver stays installed: stop() only takes the link and the netif down, while the - // SPI bus, the MAC and the netif itself stay allocated, so start() resumes without a restart - if (this->started && ETH.handle() != nullptr && value != this->running) { - esp_err_t ret = value ? esp_eth_start(ETH.handle()) : esp_eth_stop(ETH.handle()); - - if (ret == ESP_OK) { - this->running = value; - - } else { - Log.serrorln(FPSTR(L_NETWORK), F("Ethernet: driver %s failed"), value ? "start" : "stop"); - } - } - #endif - } - - /** - * @brief Configure the W5500 wiring. Use GPIO_IS_NOT_CONFIGURED to disable - */ - void setPins(uint8_t clk, uint8_t mosi, uint8_t miso, uint8_t cs, uint8_t irq, uint8_t rst) { - if ( - clk != this->clk || mosi != this->mosi || miso != this->miso - || cs != this->cs || irq != this->irq || rst != this->rst - ) { - this->markSettingsChanged(); - } - - this->clk = clk; - this->mosi = mosi; - this->miso = miso; - this->cs = cs; - this->irq = irq; - this->rst = rst; - } - - /** - * @brief A setting the driver reads changed: applying it needs a restart - */ - void markSettingsChanged() { - if (this->started) { - this->restartFlag = true; - } - } - - bool hasPins() { - return this->clk != GPIO_IS_NOT_CONFIGURED - && this->mosi != GPIO_IS_NOT_CONFIGURED - && this->miso != GPIO_IS_NOT_CONFIGURED - && this->cs != GPIO_IS_NOT_CONFIGURED - && this->irq != GPIO_IS_NOT_CONFIGURED - && this->rst != GPIO_IS_NOT_CONFIGURED; - } - - IPAddress localIP() override { - #ifdef NETWORK_HAS_ETHERNET - return ETH.localIP(); - #else - return IPAddress(); - #endif - } - - IPAddress subnetMask() override { - #ifdef NETWORK_HAS_ETHERNET - return ETH.subnetMask(); - #else - return IPAddress(); - #endif - } - - IPAddress gatewayIP() override { - #ifdef NETWORK_HAS_ETHERNET - return ETH.gatewayIP(); - #else - return IPAddress(); - #endif - } - - IPAddress dnsIP() override { - #ifdef NETWORK_HAS_ETHERNET - return ETH.dnsIP(); - #else - return IPAddress(); - #endif - } - - String macAddress() override { - #ifdef NETWORK_HAS_ETHERNET - return ETH.macAddress(); - #else - return String(); - #endif - } - - protected: - const unsigned long linkCheckInterval = 1000; - const unsigned long linkGrace = 5000; - const unsigned long leaseGrace = 20000; - - bool enabled = false; - bool started = false; - bool running = false; - bool active = false; - bool linkUp = false; - bool restartFlag = false; - bool startUnavailable = false; - - uint8_t clk = GPIO_IS_NOT_CONFIGURED; - uint8_t mosi = GPIO_IS_NOT_CONFIGURED; - uint8_t miso = GPIO_IS_NOT_CONFIGURED; - uint8_t cs = GPIO_IS_NOT_CONFIGURED; - uint8_t irq = GPIO_IS_NOT_CONFIGURED; - uint8_t rst = GPIO_IS_NOT_CONFIGURED; - - unsigned long prevLinkCheck = 0; - }; -} diff --git a/lib/NetworkUtils/NetworkMgr.h b/lib/NetworkUtils/NetworkMgr.h deleted file mode 100644 index 1029810..0000000 --- a/lib/NetworkUtils/NetworkMgr.h +++ /dev/null @@ -1,314 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include - -namespace NetworkUtils { - /** - * @brief Picks the uplink that carries the traffic and drives it - * - * The hierarchy is ethernet > WiFi > fallback AP: the first interface able to do it owns the - * pass, and every status getter reads that decision instead of re-testing the interfaces. - */ - class NetworkMgr { - public: - NetworkMgr() : wifi(&this->context), ap(&this->context, &this->wifi), ethernet(&this->context) { - NetworkConnection::setup(this->context.useDhcp); - this->wifi.resetWifi(); - } - - NetworkMgr* setYieldCallback(YieldCallback callback = nullptr) { - this->context.yieldCallback = callback; - - return this; - } - - NetworkMgr* setDelayCallback(DelayCallback callback = nullptr) { - this->context.delayCallback = callback; - - return this; - } - - NetworkMgr* setHostname(const char* value) { - this->context.hostname = value; - - return this; - } - - NetworkMgr* setApCredentials(const char* ssid, const char* password = nullptr, uint8_t channel = 0) { - this->context.apName = ssid; - this->context.apPassword = password; - this->context.apChannel = channel; - - return this; - } - - NetworkMgr* setStaCredentials(const char* ssid = nullptr, const char* password = nullptr, uint8_t channel = 0) { - this->context.staSsid = ssid; - this->context.staPassword = password; - this->context.staChannel = channel; - - return this; - } - - NetworkMgr* setUseDhcp(bool value) { - if (value != this->context.useDhcp) { - this->ethernet.markSettingsChanged(); - } - - this->context.useDhcp = value; - NetworkConnection::setup(this->context.useDhcp); - - return this; - } - - NetworkMgr* setStaticConfig(const char* ip, const char* gateway, const char* subnet, const char* dns) { - IPAddress valueIp, valueGateway, valueSubnet, valueDns; - - valueIp.fromString(ip); - valueGateway.fromString(gateway); - valueSubnet.fromString(subnet); - valueDns.fromString(dns); - - if ( - valueIp != this->context.staticIp || valueGateway != this->context.staticGateway - || valueSubnet != this->context.staticSubnet || valueDns != this->context.staticDns - ) { - this->ethernet.markSettingsChanged(); - } - - this->context.staticIp = valueIp; - this->context.staticGateway = valueGateway; - this->context.staticSubnet = valueSubnet; - this->context.staticDns = valueDns; - - return this; - } - - NetworkMgr* setStaticConfig(IPAddress& ip, IPAddress& gateway, IPAddress& subnet, IPAddress& dns) { - if ( - ip != this->context.staticIp || gateway != this->context.staticGateway - || subnet != this->context.staticSubnet || dns != this->context.staticDns - ) { - this->ethernet.markSettingsChanged(); - } - - this->context.staticIp = ip; - this->context.staticGateway = gateway; - this->context.staticSubnet = subnet; - this->context.staticDns = dns; - - return this; - } - - /** - * @brief Enable/disable the ethernet interface (W5500 over SPI) - */ - NetworkMgr* setEthernet(bool enabled) { - this->ethernet.setEnabled(enabled); - - return this; - } - - /** - * @brief Configure W5500 wiring. Use GPIO_IS_NOT_CONFIGURED to disable - */ - NetworkMgr* setEthernetPins(uint8_t clk, uint8_t mosi, uint8_t miso, uint8_t cs, uint8_t irq, uint8_t rst) { - this->ethernet.setPins(clk, mosi, miso, cs, irq, rst); - - return this; - } - - /** - * @brief Uplinks in the order they are tried: ethernet, WiFi, fallback AP - */ - enum class Uplink : uint8_t { None = 0, Ap, Wifi, Ethernet }; - - /** - * @brief The uplink that currently carries traffic - * - * Always the first interface in the hierarchy that can do it, so every consumer reads the - * same decision instead of re-testing ethernet and overriding the WiFi answer. - */ - Uplink getUplink() { - if (this->ethernet.isActive()) { - return Uplink::Ethernet; - } - - if (this->wifi.isActive()) { - return Uplink::Wifi; - } - - if (this->ap.isActive()) { - return Uplink::Ap; - } - - return Uplink::None; - } - - bool isConnected() { - return this->getUplink() >= Uplink::Wifi; - } - - /** - * @brief WiFi signal quality in percent, 0 when WiFi is not carrying the uplink - */ - uint8_t getSignalQuality() { - return this->getUplink() == Uplink::Wifi ? rssiToSignalQuality(this->wifi.rssi()) : 0; - } - - /** - * @return "ethernet", "wifi", "wifi-ap" or "none" - */ - const char* getConnectionType() { - return uplinkName(this->getUplink()); - } - - /** - * @brief Uplink token, already in locale-key shape - */ - static const char* uplinkName(Uplink uplink) { - switch (uplink) { - case Uplink::Ethernet: - return "ethernet"; - - case Uplink::Wifi: - return "wifi"; - - case Uplink::Ap: - return "wifi-ap"; - - default: - return "none"; - } - } - - bool isApEnabled() { - return this->ap.isEnabled(); - } - - short int getRssi() { - return this->station()->rssi(); - } - - IPAddress getApIp() { - return this->ap.localIP(); - } - - IPAddress getStaIp() { - return this->station()->localIP(); - } - - IPAddress getStaSubnet() { - return this->station()->subnetMask(); - } - - IPAddress getStaGateway() { - return this->station()->gatewayIP(); - } - - IPAddress getStaDns() { - return this->station()->dnsIP(); - } - - String getStaMac() { - return this->station()->macAddress(); - } - - const char* getStaSsid() { - return this->context.staSsid; - } - - uint8_t getStaChannel() { - return this->context.staChannel; - } - - void reconnect() { - this->wifi.reconnect(); - } - - void loop() { - // The top of the hierarchy polls every pass so it can take the uplink whenever it can - this->ethernet.loop(); - - this->trackUplink(); - this->updateWifiRadio(); - - if (this->getUplink() == Uplink::Ethernet) { - return; - } - - // a pending ethernet attempt holds the hierarchy: nothing below it starts until it resolves - if (this->ethernet.isPending() && !this->wifi.isActive() && !this->ap.isActive()) { - return; - } - - this->wifi.loop(); - - // the ladder only reaches the AP once the station is out of the running - if (!this->wifi.isActive() && this->wifi.isPending()) { - return; - } - - this->ap.loop(); - } - - static uint8_t rssiToSignalQuality(short int rssi) { - return constrain(map(rssi, -100, -50, 0, 100), 0, 100); - } - - protected: - UplinkContext context; - WifiUplink wifi; - ApUplink ap; - EthernetUplink ethernet; - - Uplink uplink = Uplink::None; - - /** - * @brief The interface holding the station address: the wired one while it carries the - * uplink, the station otherwise - */ - NetworkUplink* station() { - if (this->getUplink() == Uplink::Ethernet) { - return &this->ethernet; - } - - return &this->wifi; - } - - /** - * @brief Notice an uplink change so the hierarchy is walked from the top again - */ - void trackUplink() { - const Uplink current = this->getUplink(); - - if (current == this->uplink) { - return; - } - - Log.sinfoln(FPSTR(L_NETWORK), F("Uplink: %s -> %s"), uplinkName(this->uplink), uplinkName(current)); - - this->uplink = current; - } - - /** - * @brief Keep the WiFi radio in step with the uplink - * - * WiFi is only in service while it carries the traffic. The AP is for first configuration: - * once a cable carries the uplink the radio goes off, and if that uplink never comes up the - * ladder falls back to the AP again on its own. - */ - void updateWifiRadio() { - if (this->ethernet.isActive()) { - this->wifi.suspend(); - - return; - } - - this->wifi.resume(); - } - }; -} diff --git a/lib/NetworkUtils/NetworkUplink.h b/lib/NetworkUtils/NetworkUplink.h deleted file mode 100644 index 06e3f70..0000000 --- a/lib/NetworkUtils/NetworkUplink.h +++ /dev/null @@ -1,143 +0,0 @@ -#pragma once -#if defined(ARDUINO_ARCH_ESP8266) - #include - #include "lwip/etharp.h" -#elif defined(ARDUINO_ARCH_ESP32) - #include - #include -#endif - -// W5500 support needs both the ESP32 core (for ETH.h) and the per-env USE_ETHERNET flag. -// USE_ETHERNET defaults to false in defines.h, so this must be a value test, not #ifdef. -#if USE_ETHERNET && defined(ARDUINO_ARCH_ESP32) - #define NETWORK_HAS_ETHERNET -#endif - -namespace NetworkUtils { - typedef std::function YieldCallback; - typedef std::function DelayCallback; - - /** - * @brief Settings and callbacks every uplink reads - */ - struct UplinkContext { - const char* hostname = "esp"; - - const char* staSsid = nullptr; - const char* staPassword = nullptr; - uint8_t staChannel = 0; - - const char* apName = "ESP"; - const char* apPassword = nullptr; - uint8_t apChannel = 1; - - bool useDhcp = true; - IPAddress staticIp; - IPAddress staticGateway; - IPAddress staticSubnet; - IPAddress staticDns; - - YieldCallback yieldCallback = []() { - ::yield(); - }; - DelayCallback delayCallback = [](unsigned int time) { - ::delay(time); - }; - - /** - * @brief check RFC compliance - * - * @param value - * @return true - * @return false - */ - static bool isHostnameValid(const char* value) { - size_t len = strlen(value); - if (len > 24) { - return false; - } else if (value[len - 1] == '-') { - return false; - } - - for (size_t i = 0; i < len; i++) { - if (!isalnum(value[i]) && value[i] != '-') { - return false; - } - } - - return true; - } - }; - - /** - * @brief How long an uplink may still take the pass - * - * Armed when the uplink starts trying, disarmed when it resolves either way. A window that has - * run out means the uplink gave up, which lets the class below it take over. - */ - class UplinkAttempt { - public: - void arm(unsigned long window) { - this->start = millis() ? millis() : 1; - this->window = window; - } - - void disarm() { - this->start = 0; - this->window = 0; - } - - bool isArmed() const { - return this->window > 0; - } - - bool isPending() const { - return this->window > 0 && (millis() - this->start) < this->window; - } - - protected: - unsigned long start = 0; - unsigned long window = 0; - }; - - /** - * @brief One interface that is able to carry the uplink - */ - class NetworkUplink { - public: - explicit NetworkUplink(UplinkContext* context) : context(context) {} - - virtual ~NetworkUplink() {} - - /** - * @brief Run one pass of this interface's state machine - */ - virtual void loop() = 0; - - /** - * @brief The interface is able to carry traffic right now - */ - virtual bool isActive() = 0; - - /** - * @brief The interface may still become active, so nothing below it should start - */ - virtual bool isPending() { - return !this->isActive() && this->attempt.isPending(); - } - - virtual IPAddress localIP() = 0; - virtual IPAddress subnetMask() = 0; - virtual IPAddress gatewayIP() = 0; - virtual IPAddress dnsIP() = 0; - virtual String macAddress() = 0; - - virtual short int rssi() { - return 0; - } - - protected: - UplinkContext* context; - UplinkAttempt attempt; - }; -} diff --git a/lib/NetworkUtils/NetworkWifi.h b/lib/NetworkUtils/NetworkWifi.h deleted file mode 100644 index 8d6fe12..0000000 --- a/lib/NetworkUtils/NetworkWifi.h +++ /dev/null @@ -1,431 +0,0 @@ -#pragma once -#include -#include - -namespace NetworkUtils { - /** - * @brief WiFi uplink: the station association, its radio, and the fallback AP - */ - class WifiUplink : public NetworkUplink { - public: - explicit WifiUplink(UplinkContext* context) : NetworkUplink(context) {} - - void loop() override { - if (this->reconnectFlag) { - this->context->delayCallback(5000); - - Log.sinfoln(FPSTR(L_NETWORK), F("Reconnecting...")); - this->reconnectFlag = false; - this->disconnect(); - NetworkConnection::reset(); - this->context->delayCallback(1000); - - return; - } - - if (this->isAssociated() && !this->hasCredentials()) { - Log.sinfoln(FPSTR(L_NETWORK), F("Reset")); - this->resetWifi(); - NetworkConnection::reset(); - this->context->delayCallback(1000); - - return; - } - - if (this->isAssociated()) { - this->attempt.disarm(); - - if (!this->connected) { - this->connectedTime = millis(); - this->connected = true; - - Log.sinfoln( - FPSTR(L_NETWORK), - F("Connected, downtime: %lu s., IP: %s, RSSI: %hhd"), - (millis() - this->disconnectedTime) / 1000, - WiFi.localIP().toString().c_str(), - WiFi.RSSI() - ); - } - - #ifdef ARDUINO_ARCH_ESP8266 - if (millis() - this->prevArpGratuitous > 60000) { - this->stationKeepAliveNow(); - this->prevArpGratuitous = millis(); - } - #endif - - return; - } - - // the association is down: track the downtime and keep asking for the network - if (this->connected) { - this->disconnectedTime = millis(); - this->connected = false; - this->attempt.arm(this->failedConnectTimeout); - - Log.sinfoln( - FPSTR(L_NETWORK), - F("Disconnected, reason: %d, uptime: %lu s."), - NetworkConnection::getDisconnectReason(), - (millis() - this->connectedTime) / 1000 - ); - } - - if (!this->hasCredentials()) { - this->attempt.disarm(); - - return; - } - - if (!this->attempt.isArmed()) { - this->attempt.arm(this->failedConnectTimeout); - } - - if (this->isConnecting() && millis() - this->prevReconnectingTime > this->resetConnectionTimeout) { - Log.swarningln(FPSTR(L_NETWORK), F("Connection timeout, reset wifi...")); - this->resetWifi(); - NetworkConnection::reset(); - this->context->delayCallback(250); - - return; - } - - if (!this->isConnecting() && (!this->prevReconnectingTime || millis() - this->prevReconnectingTime > this->reconnectInterval)) { - Log.sinfoln(FPSTR(L_NETWORK), F("Try connect...")); - - NetworkConnection::reset(); - if (!this->connect(true, this->connectionTimeout)) { - Log.straceln(FPSTR(L_NETWORK), F("Connection failed. Status: %d, reason: %d, raw reason: %d"), NetworkConnection::getStatus(), NetworkConnection::getDisconnectReason(), NetworkConnection::rawDisconnectReason); - } - - this->prevReconnectingTime = millis(); - } - } - - /** - * @brief WiFi carries the uplink: radio running and associated - */ - bool isActive() override { - return !this->suspended && this->isAssociated(); - } - - bool isAssociated() { - return this->isStaEnabled() && NetworkConnection::getStatus() == NetworkConnection::Status::CONNECTED; - } - - bool isConnecting() { - return this->isStaEnabled() && NetworkConnection::getStatus() == NetworkConnection::Status::CONNECTING; - } - - bool isStaEnabled() { - return (WiFi.getMode() & WIFI_STA) != 0; - } - - bool isApEnabled() { - return (WiFi.getMode() & WIFI_AP) != 0; - } - - /** - * @brief When the association first came up, for the fallback AP's retirement delay - */ - unsigned long getConnectedTime() { - return this->connectedTime; - } - - /** - * @brief Stop the radio while another uplink carries the traffic - * - * esp_wifi_stop() parks the radio without tearing the driver and its netifs down. - * WiFi.mode(WIFI_OFF) does the same job but also deinitialises, which panicked when it - * was called from this task with lwIP live — keep the driver allocated. - */ - void suspend() { - #ifdef ARDUINO_ARCH_ESP32 - if (this->suspended) { - return; - } - - if (WiFi.getMode() == WIFI_MODE_NULL) { - return; - } - - // a scan holds the radio: parking it mid-scan leaves the driver half torn down - if (WiFi.scanComplete() == WIFI_SCAN_RUNNING) { - return; - } - - Log.sinfoln(FPSTR(L_NETWORK), F("Ethernet: uplink active, switching the WiFi radio off")); - - esp_wifi_stop(); - this->suspended = true; - #endif - } - - /** - * @brief Bring the radio back when no other uplink carries the traffic - */ - void resume() { - #ifdef ARDUINO_ARCH_ESP32 - if (!this->suspended) { - return; - } - - this->suspended = false; - - Log.sinfoln(FPSTR(L_NETWORK), F("Ethernet: uplink lost, switching the WiFi radio back on")); - - esp_wifi_start(); - - this->connected = false; - this->disconnectedTime = millis(); - this->prevReconnectingTime = 0; - this->attempt.arm(this->failedConnectTimeout); - - NetworkConnection::reset(); - - if (this->hasCredentials()) { - WiFi.begin(this->context->staSsid, this->context->staPassword); - - Log.sinfoln(FPSTR(L_NETWORK), F("Ethernet: reconnecting to WiFi \"%s\""), this->context->staSsid); - } - #endif - } - - bool isSuspended() { - return this->suspended; - } - - bool resetWifi() { - // set policy manual for work 13 ch - { - #ifdef ARDUINO_ARCH_ESP8266 - wifi_country_t country = {"JP", 1, 14, WIFI_COUNTRY_POLICY_MANUAL}; - wifi_set_country(&country); - #elif defined(ARDUINO_ARCH_ESP32) - const wifi_country_t country = {"JP", 1, 14, CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER, WIFI_COUNTRY_POLICY_MANUAL}; - esp_wifi_set_country(&country); - #endif - } - - WiFi.persistent(false); - #if !defined(ESP_ARDUINO_VERSION_MAJOR) || ESP_ARDUINO_VERSION_MAJOR < 3 - WiFi.setAutoConnect(false); - #endif - WiFi.setAutoReconnect(false); - - #ifdef ARDUINO_ARCH_ESP8266 - WiFi.setSleepMode(WIFI_NONE_SLEEP); - #elif defined(ARDUINO_ARCH_ESP32) - WiFi.setSleep(USE_BLE ? WIFI_PS_MIN_MODEM : WIFI_PS_NONE); - #endif - - WiFi.softAPdisconnect(); - #ifdef ARDUINO_ARCH_ESP8266 - /*if (wifi_softap_dhcps_status() == DHCP_STARTED) { - wifi_softap_dhcps_stop(); - }*/ - #endif - - WiFi.disconnect(false, true); - #ifdef ARDUINO_ARCH_ESP8266 - /*if (wifi_station_dhcpc_status() == DHCP_STARTED) { - wifi_station_dhcpc_stop(); - }*/ - - wifi_station_dhcpc_set_maxtry(5); - #endif - - #if defined(ARDUINO_ARCH_ESP32) && ESP_ARDUINO_VERSION_MAJOR < 3 - // Nothing. Because memory leaks when turn off WiFi on ESP32 SDK < 3.0.0 - return true; - #else - return WiFi.mode(WIFI_OFF); - #endif - } - - /** - * @brief Ask for a fresh connect - * - * The attempt window is armed here so the ladder keeps the fallback AP out of the way while - * the station works on this reconnect; it expires like any other failed attempt. - */ - void reconnect() { - this->attempt.arm(this->failedConnectTimeout); - - this->reconnectFlag = true; - } - - bool connect(bool force = false, unsigned int timeout = 1000u) { - if (this->isAssociated() && !force) { - return true; - } - - if (force && !this->isApEnabled()) { - this->resetWifi(); - NetworkConnection::reset(); - - } else { - /*#ifdef ARDUINO_ARCH_ESP8266 - if (wifi_station_dhcpc_status() == DHCP_STARTED) { - wifi_station_dhcpc_stop(); - } - #endif*/ - - this->disconnect(); - } - - if (!this->hasCredentials()) { - return false; - } - - this->context->delayCallback(250); - - #ifdef ARDUINO_ARCH_ESP32 - if (this->setHostname(this->context->hostname)) { - Log.straceln(FPSTR(L_NETWORK), F("Set hostname '%s': success"), this->context->hostname); - - } else { - Log.serrorln(FPSTR(L_NETWORK), F("Set hostname '%s': fail"), this->context->hostname); - } - #endif - - if (!WiFi.mode((WiFiMode_t)(WiFi.getMode() | WIFI_STA))) { - return false; - } - - this->context->delayCallback(250); - - #ifdef ARDUINO_ARCH_ESP8266 - if (this->setHostname(this->context->hostname)) { - Log.straceln(FPSTR(L_NETWORK), F("Set hostname '%s': success"), this->context->hostname); - - } else { - Log.serrorln(FPSTR(L_NETWORK), F("Set hostname '%s': fail"), this->context->hostname); - } - - this->context->delayCallback(250); - #endif - - #ifdef ARDUINO_ARCH_ESP32 - WiFi.setScanMethod(WIFI_ALL_CHANNEL_SCAN); - WiFi.setSortMethod(WIFI_CONNECT_AP_BY_SIGNAL); - #endif - - if (!this->context->useDhcp) { - WiFi.begin(this->context->staSsid, this->context->staPassword, this->context->staChannel, nullptr, false); - WiFi.config(this->context->staticIp, this->context->staticGateway, this->context->staticSubnet, this->context->staticDns); - WiFi.reconnect(); - - } else { - #ifdef ARDUINO_ARCH_ESP32 - // the interface keeps a static address from an earlier association, so the addressing has - // to be reset before the station reconnects or the switch back to DHCP never takes effect - const IPAddress noIp(0, 0, 0, 0); - WiFi.config(noIp, noIp, noIp); - #endif - - WiFi.begin(this->context->staSsid, this->context->staPassword, this->context->staChannel, nullptr, true); - } - - unsigned long beginConnectionTime = millis(); - while (millis() - beginConnectionTime < timeout) { - this->context->delayCallback(100); - - NetworkConnection::Status status = NetworkConnection::getStatus(); - if (status != NetworkConnection::Status::CONNECTING && status != NetworkConnection::Status::NONE) { - return status == NetworkConnection::Status::CONNECTED; - } - } - - return false; - } - - void disconnect() { - #ifdef ARDUINO_ARCH_ESP32 - WiFi.disconnectAsync(false, true); - - const unsigned long start = millis(); - while (WiFi.isConnected() && (millis() - start) < 5000) { - this->context->delayCallback(100); - } - #else - WiFi.disconnect(false, true); - #endif - } - - bool setHostname(const char* hostname) { - if (!UplinkContext::isHostnameValid(hostname)) { - return false; - } - - if (strcmp(WiFi.getHostname(), hostname) == 0) { - return true; - } - - return WiFi.setHostname(hostname); - } - - bool hasCredentials() { - return this->context->staSsid != nullptr; - } - - IPAddress localIP() override { - return WiFi.localIP(); - } - - IPAddress subnetMask() override { - return WiFi.subnetMask(); - } - - IPAddress gatewayIP() override { - return WiFi.gatewayIP(); - } - - IPAddress dnsIP() override { - return WiFi.dnsIP(); - } - - String macAddress() override { - return WiFi.macAddress(); - } - - short int rssi() override { - return WiFi.RSSI(); - } - - protected: - const unsigned int reconnectInterval = 15000; - const unsigned int failedConnectTimeout = 185000; - const unsigned int connectionTimeout = 10000; - const unsigned int resetConnectionTimeout = 90000; - - bool connected = false; - bool reconnectFlag = false; - bool suspended = false; - unsigned long prevArpGratuitous = 0; - unsigned long prevReconnectingTime = 0; - unsigned long connectedTime = 0; - unsigned long disconnectedTime = 0; - - #ifdef ARDUINO_ARCH_ESP8266 - /** - * @brief - * https://github.com/arendst/Tasmota/blob/e6515883f0ee5451931b6280ff847b117de5a231/tasmota/tasmota_support/support_wifi.ino#L1196 - */ - static void stationKeepAliveNow(void) { - for (netif* interface = netif_list; interface != nullptr; interface = interface->next) { - if ( - (interface->flags & NETIF_FLAG_LINK_UP) - && (interface->flags & NETIF_FLAG_UP) - && interface->num == STATION_IF - && (!ip4_addr_isany_val(*netif_ip4_addr(interface))) - ) { - etharp_gratuitous(interface); - break; - } - } - } - #endif - }; -} diff --git a/lib/WebServerHandlers/DynamicPage.h b/lib/WebServerHandlers/DynamicPage.h deleted file mode 100644 index 021f0f3..0000000 --- a/lib/WebServerHandlers/DynamicPage.h +++ /dev/null @@ -1,224 +0,0 @@ -#include - - -class DynamicPage : public RequestHandler { -public: - typedef std::function CanHandleCallback; - typedef std::function BeforeSendCallback; - typedef std::function TemplateCallback; - - DynamicPage(const char* uri, FS* fs, const char* path, const char* cacheHeader = nullptr) { - this->uri = uri; - this->fs = fs; - this->path = path; - this->cacheHeader = cacheHeader; - } - - DynamicPage* setCanHandleCallback(CanHandleCallback callback = nullptr) { - this->canHandleCallback = callback; - - return this; - } - - DynamicPage* setBeforeSendCallback(BeforeSendCallback callback = nullptr) { - this->beforeSendCallback = callback; - - return this; - } - - DynamicPage* setTemplateCallback(TemplateCallback callback = nullptr) { - this->templateCallback = callback; - - return this; - } - - #if defined(ARDUINO_ARCH_ESP32) - bool canHandle(WebServer &server, HTTPMethod method, const String &uri) override { - return this->canHandle(method, uri); - } - #endif - - bool canHandle(HTTPMethod method, const String& uri) override { - return uri.equals(this->uri) && (!this->canHandleCallback || this->canHandleCallback(method, uri)); - } - - bool handle(WebServer& server, HTTPMethod method, const String& uri) override { - if (!this->canHandle(method, uri)) { - return false; - } - - if (this->beforeSendCallback && !this->beforeSendCallback()) { - return true; - } - - File file = this->fs->open(this->path, "r"); - if (!file) { - return false; - - } else if (file.isDirectory()) { - file.close(); - return false; - } - - if (this->cacheHeader != nullptr) { - server.sendHeader(F("Cache-Control"), this->cacheHeader); - } - - #ifdef ARDUINO_ARCH_ESP8266 - if (!server.chunkedResponseModeStart(200, F("text/html"))) { - server.send(505, F("text/html"), F("HTTP1.1 required")); - return true; - } - #else - server.setContentLength(CONTENT_LENGTH_UNKNOWN); - server.send(200, "text/html", emptyString); - #endif - - uint8_t* argStartPos = nullptr; - uint8_t* argEndPos = nullptr; - uint8_t argName[16]; - size_t sizeArgName = 0; - bool argNameProcess = false; - while (file.available()) { - uint8_t buf[64]; - size_t length = file.read(buf, sizeof(buf)); - size_t offset = 0; - - if (argNameProcess) { - argEndPos = (uint8_t*) memchr(buf, '}', length); - - if (argEndPos != nullptr) { - size_t fullSizeArgName = sizeArgName + (argEndPos - buf); - if (fullSizeArgName < sizeof(argName)) { - // copy full arg name - if (argEndPos - buf > 0) { - memcpy(argName + sizeArgName, buf, argEndPos - buf); - } - argName[fullSizeArgName] = '\0'; - - // send arg value - String argValue = this->templateCallback((const char*) argName); - if (argValue.length()) { - server.sendContent(argValue.c_str()); - - } else if (fullSizeArgName > 0) { - server.sendContent("{"); - server.sendContent((const char*) argName); - server.sendContent("}"); - } - - offset = size_t(argEndPos - buf + 1); - sizeArgName = 0; - argNameProcess = false; - } - } - - if (argNameProcess) { - server.sendContent("{"); - - if (sizeArgName > 0) { - argName[sizeArgName] = '\0'; - server.sendContent((const char*) argName); - } - - argNameProcess = false; - } - } - - do { - uint8_t* currentBuf = buf + offset; - size_t currentLength = length - offset; - - argStartPos = (uint8_t*) memchr(currentBuf, '{', currentLength); - - // send all content - if (argStartPos == nullptr) { - if (currentLength > 0) { - server.sendContent((const char*) currentBuf, currentLength); - } - - break; - } - - argEndPos = (uint8_t*) memchr(argStartPos, '}', length - (argStartPos - buf)); - if (argEndPos != nullptr) { - sizeArgName = argEndPos - argStartPos - 1; - - // send all content if arg len > space - if (sizeArgName >= sizeof(argName)) { - if (currentLength > 0) { - server.sendContent((const char*) currentBuf, currentLength); - } - - break; - } - - // arg name - memcpy(argName, argStartPos + 1, sizeArgName); - argName[sizeArgName] = '\0'; - - // send arg value - String argValue = this->templateCallback((const char*) argName); - if (argValue.length()) { - // send content before var - if (argStartPos - buf > 0) { - server.sendContent((const char*) currentBuf, argStartPos - buf); - } - - server.sendContent(argValue.c_str()); - - } else { - server.sendContent((const char*) currentBuf, argEndPos - currentBuf + 1); - } - - offset = size_t(argEndPos - currentBuf + 1); - - } else { - sizeArgName = length - size_t(argStartPos - currentBuf) - 1; - - // send all content if arg len > space - if (sizeArgName >= sizeof(argName)) { - if (currentLength) { - server.sendContent((const char*) currentBuf, currentLength); - } - - break; - } - - // send content before var - if (argStartPos - buf > 0) { - server.sendContent((const char*) currentBuf, argStartPos - buf); - } - - // copy arg name chunk - if (sizeArgName > 0) { - memcpy(argName, argStartPos + 1, sizeArgName); - } - - argNameProcess = true; - - break; - } - } while(true); - } - - file.close(); - - #ifdef ARDUINO_ARCH_ESP8266 - server.chunkedResponseFinalize(); - #else - server.sendContent(emptyString); - #endif - - return true; - } - -protected: - FS* fs = nullptr; - CanHandleCallback canHandleCallback; - BeforeSendCallback beforeSendCallback; - TemplateCallback templateCallback; - const char* uri = nullptr; - const char* path = nullptr; - const char* cacheHeader = nullptr; -}; \ No newline at end of file diff --git a/lib/WebServerHandlers/StaticPage.h b/lib/WebServerHandlers/StaticPage.h deleted file mode 100644 index 51ca630..0000000 --- a/lib/WebServerHandlers/StaticPage.h +++ /dev/null @@ -1,105 +0,0 @@ -#include -#include - -using namespace mime; - -class StaticPage : public RequestHandler { -public: - typedef std::function CanHandleCallback; - typedef std::function BeforeSendCallback; - - template - StaticPage(const char* uri, FS* fs, T path, const char* cacheHeader = nullptr) { - this->uri = uri; - this->fs = fs; - this->path = path; - this->cacheHeader = cacheHeader; - } - - StaticPage* setCanHandleCallback(CanHandleCallback callback = nullptr) { - this->canHandleCallback = callback; - - return this; - } - - StaticPage* setBeforeSendCallback(BeforeSendCallback callback = nullptr) { - this->beforeSendCallback = callback; - - return this; - } - - #if defined(ARDUINO_ARCH_ESP32) - bool canHandle(WebServer &server, HTTPMethod method, const String &uri) override { - return this->canHandle(method, uri); - } - #endif - - bool canHandle(HTTPMethod method, const String& uri) override { - return method == HTTP_GET && uri.equals(this->uri) && (!this->canHandleCallback || this->canHandleCallback(method, uri)); - } - - bool handle(WebServer& server, HTTPMethod method, const String& uri) override { - if (!this->canHandle(method, uri)) { - return false; - } - - if (this->beforeSendCallback && !this->beforeSendCallback()) { - return true; - } - - if (server._eTagEnabled) { - if (this->eTag.isEmpty()) { - if (server._eTagFunction) { - this->eTag = (server._eTagFunction)(*this->fs, this->path); - } - } - - if (!this->eTag.isEmpty() && server.header(F("If-None-Match")).equals(this->eTag.c_str())) { - server.send(304); - return true; - } - } - - if (!this->path.endsWith(FPSTR(mimeTable[gz].endsWith)) && !this->fs->exists(path)) { - String pathWithGz = this->path + FPSTR(mimeTable[gz].endsWith); - - if (this->fs->exists(pathWithGz)) { - this->path += FPSTR(mimeTable[gz].endsWith); - } - } - - File file = this->fs->open(this->path, "r"); - if (!file) { - return false; - - } else if (file.isDirectory()) { - file.close(); - return false; - } - - if (this->cacheHeader != nullptr) { - server.sendHeader(F("Cache-Control"), this->cacheHeader); - } - - if (server._eTagEnabled && !this->eTag.isEmpty()) { - server.sendHeader(F("ETag"), this->eTag); - } - - #if defined(ARDUINO_ARCH_ESP8266) - server.streamFile(file, F("text/html"), method); - #else - server.streamFile(file, F("text/html"), 200); - #endif - - return true; - } - -protected: - FS* fs = nullptr; - CanHandleCallback canHandleCallback; - BeforeSendCallback beforeSendCallback; - String eTag; - const char* uri = nullptr; - String path; - const char* cacheHeader = nullptr; -}; \ No newline at end of file diff --git a/lib/WebServerHandlers/UpgradeHandler.h b/lib/WebServerHandlers/UpgradeHandler.h index 14c7f93..e49a653 100644 --- a/lib/WebServerHandlers/UpgradeHandler.h +++ b/lib/WebServerHandlers/UpgradeHandler.h @@ -1,6 +1,8 @@ #include +#include +#include -class UpgradeHandler : public RequestHandler { +class UpgradeHandler : public AsyncWebHandler { public: enum class UpgradeType { FIRMWARE = 0, @@ -12,7 +14,7 @@ public: NO_FILE, SUCCESS, PROHIBITED, - ABORTED, + SIZE_MISMATCH, ERROR_ON_START, ERROR_ON_WRITE, ERROR_ON_FINISH @@ -22,27 +24,22 @@ public: UpgradeType type; UpgradeStatus status; String error; + size_t progress = 0; + size_t size = 0; } UpgradeResult; - typedef std::function CanHandleCallback; - typedef std::function CanUploadCallback; - typedef std::function BeforeUpgradeCallback; - typedef std::function AfterUpgradeCallback; - - UpgradeHandler(const char* uri) { - this->uri = uri; - } + typedef std::function BeforeUpgradeCallback; + // A null request reports an upload disconnected after preparation was accepted. + typedef std::function AfterUpgradeCallback; - UpgradeHandler* setCanHandleCallback(CanHandleCallback callback = nullptr) { - this->canHandleCallback = callback; + explicit UpgradeHandler(AsyncURIMatcher uri) : uri(uri) {} - return this; - } + bool canHandle(AsyncWebServerRequest *request) const final { + if (!request->isHTTP() || request->method() != HTTP_POST) { + return false; + } - UpgradeHandler* setCanUploadCallback(CanUploadCallback callback = nullptr) { - this->canUploadCallback = callback; - - return this; + return this->uri.matches(request); } UpgradeHandler* setBeforeUpgradeCallback(BeforeUpgradeCallback callback = nullptr) { @@ -57,160 +54,199 @@ public: return this; } - #if defined(ARDUINO_ARCH_ESP32) - bool canHandle(WebServer &server, HTTPMethod method, const String &uri) override { - return this->canHandle(method, uri); - } - #endif - - bool canHandle(HTTPMethod method, const String& uri) override { - return method == HTTP_POST && uri.equals(this->uri) && (!this->canHandleCallback || this->canHandleCallback(method, uri)); - } - - #if defined(ARDUINO_ARCH_ESP32) - bool canUpload(WebServer &server, const String &uri) override { - return this->canUpload(uri); - } - #endif - - bool canUpload(const String& uri) override { - return uri.equals(this->uri) && (!this->canUploadCallback || this->canUploadCallback(uri)); - } - - bool handle(WebServer& server, HTTPMethod method, const String& uri) override { - if (this->afterUpgradeCallback) { - this->afterUpgradeCallback(this->firmwareResult, this->filesystemResult); - } - - this->firmwareResult.status = UpgradeStatus::NONE; - this->firmwareResult.error.clear(); - - this->filesystemResult.status = UpgradeStatus::NONE; - this->filesystemResult.error.clear(); - - return true; - } - - void upload(WebServer& server, const String& uri, HTTPUpload& upload) override { - UpgradeResult* result; - if (upload.name.equals(F("firmware"))) { - result = &this->firmwareResult; - - } else if (upload.name.equals(F("filesystem"))) { - result = &this->filesystemResult; - - } else { + void handleRequest(AsyncWebServerRequest *request) final { + if (request->getResponse()) { return; } + if (this->activeRequest != request) { + request->send(this->activeRequest ? 409 : 400); + return; + } + + finishRequest(request); + } + + void handleUpload(AsyncWebServerRequest *request, const String &fileName, size_t index, uint8_t *data, size_t dataLength, bool isFinal) final { + if (request->getResponse()) { + return; + } + if (this->activeRequest && this->activeRequest != request) { + // Keep the rejection on this request even if the active upload finishes first. + request->send(409); + return; + } + + UpgradeResult* result = nullptr; + + if (!request->hasParam(asyncsrv::T_name, true, true)) { + // Missing content-disposition 'name' parameter + return; + } + + const auto& pName = request->getParam(asyncsrv::T_name, true, true)->value(); + if (pName.equals("fw")) { + result = &this->firmwareResult; + + if (!index) { + result->progress = 0; + result->size = request->hasParam("fw_size", true) + ? request->getParam("fw_size", true)->value().toInt() + : 0; + } + + } else if (pName.equals("fs")) { + result = &this->filesystemResult; + + if (!index) { + result->progress = 0; + result->size = request->hasParam("fs_size", true) + ? request->getParam("fs_size", true)->value().toInt() + : 0; + } + + } else { + // Unknown parameter name + return; + } + + if (!this->activeRequest) { + this->activeRequest = request; + request->onDisconnect([this, request] { + if (this->activeRequest == request) { + finishRequest(nullptr); + } + }); + } + + // check result status if (result->status != UpgradeStatus::NONE) { return; } - if (this->beforeUpgradeCallback && !this->beforeUpgradeCallback(result->type)) { + if (this->beforeUpgradeCallback && !this->beforeUpgradeCallback(request, result->type)) { result->status = UpgradeStatus::PROHIBITED; return; } + this->preparationAccepted = true; - if (!upload.filename.length()) { + if (!fileName.length()) { result->status = UpgradeStatus::NO_FILE; return; } - if (upload.status == UPLOAD_FILE_START) { + if (!index) { // reset if (Update.isRunning()) { Update.end(false); Update.clearError(); } + // try begin bool begin = false; - #ifdef ARDUINO_ARCH_ESP8266 - Update.runAsync(true); - - if (result->type == UpgradeType::FIRMWARE) { - begin = Update.begin((ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000, U_FLASH); - - } else if (result->type == UpgradeType::FILESYSTEM) { - close_all_fs(); - begin = Update.begin((size_t)FS_end - (size_t)FS_start, U_FS); - } - #elif defined(ARDUINO_ARCH_ESP32) if (result->type == UpgradeType::FIRMWARE) { begin = Update.begin(UPDATE_SIZE_UNKNOWN, U_FLASH); - + } else if (result->type == UpgradeType::FILESYSTEM) { begin = Update.begin(UPDATE_SIZE_UNKNOWN, U_SPIFFS); } - #endif if (!begin || Update.hasError()) { result->status = UpgradeStatus::ERROR_ON_START; - #ifdef ARDUINO_ARCH_ESP8266 - result->error = Update.getErrorString(); - #else result->error = Update.errorString(); - #endif - Log.serrorln(FPSTR(L_PORTAL_OTA), F("File '%s', on start: %s"), upload.filename.c_str(), result->error.c_str()); + ESP_LOGE(L_PORTAL_OTA, "File '%s', on start: %s", fileName.c_str(), result->error.c_str()); return; } - - Log.sinfoln(FPSTR(L_PORTAL_OTA), F("File '%s', started"), upload.filename.c_str()); - } else if (upload.status == UPLOAD_FILE_WRITE) { - if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) { + ESP_LOGI(L_PORTAL_OTA, "File '%s', started", fileName.c_str()); + } + + if (dataLength) { + if (Update.write(data, dataLength) != dataLength) { Update.end(false); - result->status = UpgradeStatus::ERROR_ON_WRITE; - #ifdef ARDUINO_ARCH_ESP8266 - result->error = Update.getErrorString(); - #else result->error = Update.errorString(); - #endif - Log.serrorln( - FPSTR(L_PORTAL_OTA), - F("File '%s', on writing %d bytes: %s"), - upload.filename.c_str(), upload.totalSize, result->error.c_str() + ESP_LOGE( + L_PORTAL_OTA, "File '%s', on write %d bytes, %d of %d bytes", + fileName.c_str(), + dataLength, + result->progress + dataLength, + result->size ); - - } else { - Log.sinfoln(FPSTR(L_PORTAL_OTA), F("File '%s', writed %d bytes"), upload.filename.c_str(), upload.totalSize); + return; } - } else if (upload.status == UPLOAD_FILE_END) { - if (Update.end(true)) { - result->status = UpgradeStatus::SUCCESS; + result->progress += dataLength; + ESP_LOGI( + L_PORTAL_OTA, "File '%s', write %d bytes, %d of %d bytes", + fileName.c_str(), + dataLength, + result->progress, + result->size + ); + } - Log.sinfoln(FPSTR(L_PORTAL_OTA), F("File '%s': finish"), upload.filename.c_str()); + if (result->size > 0) { + if (result->progress > result->size || (isFinal && result->progress < result->size)) { + Update.end(false); + result->status = UpgradeStatus::SIZE_MISMATCH; - } else { + ESP_LOGE( + L_PORTAL_OTA, "File '%s', size mismatch: %d of %d bytes", + fileName.c_str(), + result->progress, + result->size + ); + return; + } + } + + if (isFinal) { + if (!Update.end(true)) { result->status = UpgradeStatus::ERROR_ON_FINISH; - #ifdef ARDUINO_ARCH_ESP8266 - result->error = Update.getErrorString(); - #else result->error = Update.errorString(); - #endif - Log.serrorln(FPSTR(L_PORTAL_OTA), F("File '%s', on finish: %s"), upload.filename.c_str(), result->error); + ESP_LOGE(L_PORTAL_OTA, "File '%s', on finish: %s", fileName.c_str(), result->error.c_str()); + return; } - } else if (upload.status == UPLOAD_FILE_ABORTED) { - Update.end(false); - result->status = UpgradeStatus::ABORTED; - - Log.serrorln(FPSTR(L_PORTAL_OTA), F("File '%s': aborted"), upload.filename.c_str()); + result->status = UpgradeStatus::SUCCESS; + ESP_LOGI(L_PORTAL_OTA, "File '%s': finish", fileName.c_str()); } } + bool isRequestHandlerTrivial() const final { + return false; + } + protected: - CanHandleCallback canHandleCallback; - CanUploadCallback canUploadCallback; + void finishRequest(AsyncWebServerRequest *request) { + if (request) { + request->onDisconnect(nullptr); + } + if (Update.isRunning()) { + // Abort only the unfinished file; an earlier successful firmware still needs a restart. + Update.abort(); + } + if (this->afterUpgradeCallback && (request || this->preparationAccepted)) { + this->afterUpgradeCallback(request, this->firmwareResult, this->filesystemResult); + } + + this->activeRequest = nullptr; + this->preparationAccepted = false; + this->firmwareResult = {UpgradeType::FIRMWARE, UpgradeStatus::NONE}; + this->filesystemResult = {UpgradeType::FILESYSTEM, UpgradeStatus::NONE}; + } + BeforeUpgradeCallback beforeUpgradeCallback; AfterUpgradeCallback afterUpgradeCallback; - const char* uri = nullptr; + AsyncURIMatcher uri; + // Upload, completion and disconnect callbacks share the AsyncTCP worker. + AsyncWebServerRequest* activeRequest = nullptr; + bool preparationAccepted = false; UpgradeResult firmwareResult{UpgradeType::FIRMWARE, UpgradeStatus::NONE}; UpgradeResult filesystemResult{UpgradeType::FILESYSTEM, UpgradeStatus::NONE}; -}; \ No newline at end of file +}; diff --git a/platformio.ini b/platformio.ini index f62b5fd..0bc0c55 100644 --- a/platformio.ini +++ b/platformio.ini @@ -1,384 +1,375 @@ -; PlatformIO Project Configuration File -; -; Build options: build flags, source filter -; Upload options: custom upload port, speed and extra flags -; Library options: dependencies, extra library storages -; Advanced options: extra scripting -; -; Please visit documentation for the other options and examples -; https://docs.platformio.org/page/projectconf.html - [platformio] -;extra_configs = secrets.ini -extra_configs = secrets.default.ini -core_dir = .pio +;extra_configs = secrets.ini +extra_configs = secrets.default.ini +;core_dir = .pio [env] -version = 1.6.0 -framework = arduino -lib_deps = - bblanchon/ArduinoJson@^7.4.2 - ;ihormelnyk/OpenTherm Library@^1.1.5 - https://github.com/Laxilef/opentherm_library#esp32_timer - arduino-libraries/ArduinoMqttClient@^0.1.8 - lennarthennigs/ESP Telnet@^2.2.3 - gyverlibs/FileData@^1.0.3 - gyverlibs/GyverPID@^3.3.2 - gyverlibs/GyverBlinker@^1.1.1 - pstolarz/OneWireNg@^0.14.1 - milesburton/DallasTemperature@^4.0.6 - laxilef/TinyLogger@^1.1.1 -lib_ignore = OneWire -build_type = ${secrets.build_type} -build_flags = - -mtext-section-literals - -D MQTT_CLIENT_STD_FUNCTION_CALLBACK=1 - ;-D DEBUG_ESP_CORE -D DEBUG_ESP_WIFI -D DEBUG_ESP_HTTP_SERVER -D DEBUG_ESP_PORT=Serial - -D BUILD_VERSION='"${this.version}"' - -D BUILD_ENV='"$PIOENV"' - -D DEFAULT_SERIAL_ENABLED=${secrets.serial_enabled} - -D DEFAULT_SERIAL_BAUD=${secrets.serial_baud} - -D DEFAULT_TELNET_ENABLED=${secrets.telnet_enabled} - -D DEFAULT_TELNET_PORT=${secrets.telnet_port} - -D DEFAULT_LOG_LEVEL=${secrets.log_level} - -D DEFAULT_HOSTNAME='"${secrets.hostname}"' - -D DEFAULT_AP_SSID='"${secrets.ap_ssid}"' - -D DEFAULT_AP_PASSWORD='"${secrets.ap_password}"' - -D DEFAULT_STA_SSID='"${secrets.sta_ssid}"' - -D DEFAULT_STA_PASSWORD='"${secrets.sta_password}"' - -D DEFAULT_PORTAL_LOGIN='"${secrets.portal_login}"' - -D DEFAULT_PORTAL_PASSWORD='"${secrets.portal_password}"' - -D DEFAULT_MQTT_ENABLED=${secrets.mqtt_enabled} - -D DEFAULT_MQTT_SERVER='"${secrets.mqtt_server}"' - -D DEFAULT_MQTT_PORT=${secrets.mqtt_port} - -D DEFAULT_MQTT_USER='"${secrets.mqtt_user}"' - -D DEFAULT_MQTT_PASSWORD='"${secrets.mqtt_password}"' - -D DEFAULT_MQTT_PREFIX='"${secrets.mqtt_prefix}"' -upload_speed = 921600 -monitor_speed = 115200 -;monitor_filters = direct -monitor_filters = - esp32_exception_decoder - esp8266_exception_decoder -board_build.flash_mode = dio -board_build.filesystem = littlefs -check_tool = ; pvs-studio -check_flags = -; pvs-studio: -; --analysis-mode=4 -; --exclude-path=./.pio/libdeps +custom_version = 2.0.0-dev +framework = arduino +lib_deps = ESP32Async/AsyncTCP@^3.5.0 + ESP32Async/ESPAsyncWebServer@^3.12.1 + mathieucarbou/MycilaTaskManager@^5.0.0 + mathieucarbou/MycilaMQTT@^6.1.4 + mathieucarbou/MycilaHADiscovery@^9.0.1 + mathieucarbou/MycilaWebSerial@^8.2.3 + mathieucarbou/MycilaUtilities@^5.0.0 + laxilef/ESP32OT@^1.0.1 + ;pstolarz/OneWireNg@^0.14.1 + https://github.com/pstolarz/OneWireNg.git + milesburton/DallasTemperature@^4.0.6 + https://github.com/Laxilef/esp32DHT#idf5 + bblanchon/ArduinoJson@^7.4.3 + gyverlibs/FileData@^1.0.3 + gyverlibs/GyverBlinker@^1.1.1 +lib_ignore = OneWire +build_type = ${secrets.build_type} +build_flags = ;-mtext-section-literals + ;-D DEBUG_ESP_CORE -D DEBUG_ESP_WIFI -D DEBUG_ESP_HTTP_SERVER -D DEBUG_ESP_PORT=Serial + -D BUILD_VERSION='"${this.custom_version}"' + -D BUILD_ENV='"$PIOENV"' + -D DEFAULT_SERIAL_ENABLED=${secrets.serial_enabled} + -D DEFAULT_SERIAL_BAUD=${secrets.serial_baud} + -D DEFAULT_WEBSERIAL_ENABLED=${secrets.webserial_enabled} + -D DEFAULT_LOG_LEVEL=${secrets.log_level} + -D DEFAULT_HOSTNAME='"${secrets.hostname}"' + -D DEFAULT_AP_SSID='"${secrets.ap_ssid}"' + -D DEFAULT_AP_PASSWORD='"${secrets.ap_password}"' + -D DEFAULT_STA_SSID='"${secrets.sta_ssid}"' + -D DEFAULT_STA_PASSWORD='"${secrets.sta_password}"' + -D DEFAULT_PORTAL_LOGIN='"${secrets.portal_login}"' + -D DEFAULT_PORTAL_PASSWORD='"${secrets.portal_password}"' + -D DEFAULT_MQTT_ENABLED=${secrets.mqtt_enabled} + -D DEFAULT_MQTT_SERVER='"${secrets.mqtt_server}"' + -D DEFAULT_MQTT_PORT=${secrets.mqtt_port} + -D DEFAULT_MQTT_USER='"${secrets.mqtt_user}"' + -D DEFAULT_MQTT_PASSWORD='"${secrets.mqtt_password}"' + -D DEFAULT_MQTT_PREFIX='"${secrets.mqtt_prefix}"' + -D DEFAULT_HA_DISCOVERY_ENABLED=${secrets.ha_discovery_enabled} + -D DEFAULT_HA_DISCOVERY_PREFIX='"${secrets.ha_discovery_prefix}"' +upload_speed = 921600 +monitor_speed = 115200 +;monitor_filters = direct +monitor_filters = esp32_exception_decoder +board_build.flash_mode = dio +board_build.filesystem = littlefs +check_tool = ;pvs-studio +check_flags = ;pvs-studio: --analysis-mode=4 --exclude-path=./.pio/libdeps ; Defaults -[esp8266_defaults] -platform = espressif8266@^4.2.1 -platform_packages = ${env.platform_packages} -lib_deps = - ${env.lib_deps} - nrwiersma/ESP8266Scheduler@^1.2 -lib_ignore = ${env.lib_ignore} -extra_scripts = - post:tools/build.py -build_type = ${env.build_type} -build_flags = - ${env.build_flags} - -D PIO_FRAMEWORK_ARDUINO_LWIP2_LOW_MEMORY - ;-D PIO_FRAMEWORK_ARDUINO_LWIP2_HIGHER_BANDWIDTH_LOW_FLASH - -D PIO_FRAMEWORK_ARDUINO_ESPRESSIF_SDK305 -board_build.ldscript = eagle.flash.4m1m.ld -check_tool = ${env.check_tool} -check_flags = ${env.check_flags} - [esp32_defaults] -;platform = espressif32@^6.7 -;platform = https://github.com/platformio/platform-espressif32.git -;platform_packages = -; framework-arduinoespressif32 @ https://github.com/espressif/arduino-esp32.git#3.0.5 -; framework-arduinoespressif32-libs @ https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.1/esp32-arduino-libs-idf-release_v5.1-33fbade6.zip -platform = https://github.com/pioarduino/platform-espressif32/releases/download/55.03.36/platform-espressif32.zip -platform_packages = ${env.platform_packages} -board_build.partitions = esp32_partitions.csv -lib_deps = - ${env.lib_deps} - laxilef/ESP32Scheduler@^1.0.1 -nimble_lib = h2zero/NimBLE-Arduino@2.3.7 -lib_ignore = ${env.lib_ignore} -extra_scripts = - post:tools/esp32.py - post:tools/build.py -build_type = ${env.build_type} -build_flags = - ${env.build_flags} - -D CORE_DEBUG_LEVEL=0 - -Wl,--wrap=esp_panic_handler -check_tool = ${env.check_tool} -check_flags = ${env.check_flags} +platform = https://github.com/pioarduino/platform-espressif32/releases/download/61.04.00/platform-espressif32.zip +platform_packages = ${env.platform_packages} +board_build.partitions = esp32_partitions.csv +lib_deps = ${env.lib_deps} +nimble_lib = https://github.com/h2zero/NimBLE-Arduino#master +lib_ignore = ${env.lib_ignore} + BluetoothSerial + SimpleBLE + ESP RainMaker + RainMaker + ESP Insights + Insights + Zigbee + Matter + OpenThread + dsp +; No release includes the stop/reconnect wakeup fix yet (2026-11-21). +; With the broker unavailable, stop() can wait for reconnect backoff to expire, delaying OTA/restart. +; Fix: https://github.com/espressif/esp-mqtt/commit/c29cdda15f2812207a5740e7ec8f6efdd59d8e77 +custom_component_add = espressif/mqtt@1.1.0 +custom_component_remove = espressif/esp_hosted + espressif/esp_wifi_remote + espressif/esp-dsp + espressif/esp_modem + espressif/esp_rainmaker + espressif/rmaker_common + espressif/esp_insights + espressif/esp_diag_data_store + espressif/esp_diagnostics + espressif/libsodium + espressif/esp-modbus + espressif/esp-cbor + espressif/esp-sr + espressif/esp32-camera + espressif/qrcode + espressif/esp-zboss-lib + espressif/esp-zigbee-lib + chmorgan/esp-libhelix-mp3 + espressif/cjson +extra_scripts = pre:tools/after_build_sdk.py + pre:tools/add_build_commit.py + post:tools/esp32.py + post:tools/build.py +build_type = ${env.build_type} +build_unflags = -fno-lto +build_flags = ${env.build_flags} + -Os + -Wno-deprecated-declarations + -D WSL_CUSTOM_PAGE + ; Log transport runs on the System worker instead of producer stacks. + -D CONFIG_ASYNC_TCP_STACK_SIZE=5120 + -D ARDUINOJSON_USE_DOUBLE=0 + -D ARDUINOJSON_USE_LONG_LONG=0 + -D DHT_TASK_STACK_SIZE=4096 + -D MYCILA_TASK_MANAGER_NO_STATS + -D MYCILA_MQTT_DEBUG + -D MYNEWT_VAL_BLE_MAX_CONNECTIONS=1 + -D MYNEWT_VAL_BLE_STORE_MAX_BONDS=1 + -D MYNEWT_VAL_BLE_STORE_CONFIG_PERSIST=0 + -D MYNEWT_VAL_BLE_STORE_MAX_CCCDS=0 + -D MYNEWT_VAL_BLE_ROLE_CENTRAL=0 + ; Sensors only advertise. Classic ESP32 still needs SM crypto to resolve private addresses. + -D MYNEWT_VAL_BLE_SM_LEGACY=MYNEWT_VAL_BLE_HOST_BASED_PRIVACY + -D MYNEWT_VAL_BLE_SM_SC=0 + ; BLE callbacks format logs; System sends them to transports. + -D MYNEWT_VAL_NIMBLE_HOST_TASK_STACK_SIZE=4608 + -D CORE_DEBUG_LEVEL=ESP_LOG_ERROR + -D USE_ESP_IDF_LOG + -Wl,--wrap=esp_panic_handler + -Wl,--wrap=esp_log_format +custom_app_flags = -D LOG_LOCAL_LEVEL=ESP_LOG_VERBOSE +custom_sdkconfig = '# CONFIG_AUTOSTART_ARDUINO is not set' + ; Async scalar publications must drain faster than the default 1 s MQTT poll. + CONFIG_MQTT_USE_CUSTOM_CONFIG=y + CONFIG_MQTT_PROTOCOL_311=y + CONFIG_MQTT_POLL_READ_TIMEOUT_MS=5 + ; Initialization now runs on the IDF main task instead of loopTask. + CONFIG_ESP_MAIN_TASK_STACK_SIZE=8192 + CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL=1024 + '# CONFIG_LOG_VERSION_1 is not set' + CONFIG_LOG_VERSION_2=y + CONFIG_LOG_VERSION=2 + CONFIG_LOG_COLORS=y + '# CONFIG_LOG_TIMESTAMP_SOURCE_RTOS is not set' + CONFIG_LOG_TIMESTAMP_SOURCE_SYSTEM=y + '# CONFIG_OPENTHREAD_ENABLED is not set' + '# CONFIG_ZB_ENABLED is not set' + '# CONFIG_ESP_WIFI_ENTERPRISE_SUPPORT is not set' + '# CONFIG_LWIP_IPV6 is not set' + '# CONFIG_LWIP_IPV6_AUTOCONFIG is not set' + '# CONFIG_LWIP_PPP_SUPPORT is not set' + '# CONFIG_MQTT_TRANSPORT_WEBSOCKET is not set' + '# CONFIG_LWIP_IP_FORWARD is not set' + '# CONFIG_ESP_WIFI_FTM_ENABLE is not set' + '# CONFIG_ESP_WIFI_CSI_ENABLED is not set' + ; MQTT uses TLS as a client, and the portal serves HTTP. + '# CONFIG_MBEDTLS_TLS_SERVER_AND_CLIENT is not set' + '# CONFIG_MBEDTLS_TLS_SERVER_ONLY is not set' + CONFIG_MBEDTLS_TLS_CLIENT_ONLY=y + '# CONFIG_MBEDTLS_SSL_PROTO_DTLS is not set' + '# CONFIG_ESP_HTTPS_SERVER_ENABLE is not set' + ; mDNS only advertises the gateway's HTTP service. + '# CONFIG_MDNS_ENABLE_BROWSE is not set' + '# CONFIG_MDNS_ENABLE_CONSOLE_CLI is not set' +check_tool = ${env.check_tool} +check_flags = ${env.check_flags} ; Boards -[env:d1_mini] -platform = ${esp8266_defaults.platform} -platform_packages = ${esp8266_defaults.platform_packages} -board = d1_mini -lib_deps = ${esp8266_defaults.lib_deps} -lib_ignore = ${esp8266_defaults.lib_ignore} -extra_scripts = ${esp8266_defaults.extra_scripts} -board_build.ldscript = ${esp8266_defaults.board_build.ldscript} -build_type = ${esp8266_defaults.build_type} -build_flags = - ${esp8266_defaults.build_flags} - -D DEFAULT_OT_IN_GPIO=4 - -D DEFAULT_OT_OUT_GPIO=5 - -D DEFAULT_SENSOR_OUTDOOR_GPIO=12 - -D DEFAULT_SENSOR_INDOOR_GPIO=14 - -D DEFAULT_STATUS_LED_GPIO=13 - -D DEFAULT_OT_RX_LED_GPIO=15 -check_tool = ${esp8266_defaults.check_tool} -check_flags = ${esp8266_defaults.check_flags} - -[env:d1_mini_lite] -platform = ${esp8266_defaults.platform} -platform_packages = ${esp8266_defaults.platform_packages} -board = d1_mini_lite -lib_deps = ${esp8266_defaults.lib_deps} -lib_ignore = ${esp8266_defaults.lib_ignore} -extra_scripts = ${esp8266_defaults.extra_scripts} -board_build.ldscript = ${esp8266_defaults.board_build.ldscript} -build_type = ${esp8266_defaults.build_type} -build_flags = - ${esp8266_defaults.build_flags} - -D DEFAULT_OT_IN_GPIO=4 - -D DEFAULT_OT_OUT_GPIO=5 - -D DEFAULT_SENSOR_OUTDOOR_GPIO=12 - -D DEFAULT_SENSOR_INDOOR_GPIO=14 - -D DEFAULT_STATUS_LED_GPIO=13 - -D DEFAULT_OT_RX_LED_GPIO=15 -check_tool = ${esp8266_defaults.check_tool} -check_flags = ${esp8266_defaults.check_flags} - -[env:d1_mini_pro] -platform = ${esp8266_defaults.platform} -platform_packages = ${esp8266_defaults.platform_packages} -board = d1_mini_pro -lib_deps = ${esp8266_defaults.lib_deps} -lib_ignore = ${esp8266_defaults.lib_ignore} -extra_scripts = ${esp8266_defaults.extra_scripts} -board_build.ldscript = ${esp8266_defaults.board_build.ldscript} -build_type = ${esp8266_defaults.build_type} -build_flags = - ${esp8266_defaults.build_flags} - -D DEFAULT_OT_IN_GPIO=4 - -D DEFAULT_OT_OUT_GPIO=5 - -D DEFAULT_SENSOR_OUTDOOR_GPIO=12 - -D DEFAULT_SENSOR_INDOOR_GPIO=14 - -D DEFAULT_STATUS_LED_GPIO=13 - -D DEFAULT_OT_RX_LED_GPIO=15 -check_tool = ${esp8266_defaults.check_tool} -check_flags = ${esp8266_defaults.check_flags} - -[env:nodemcu_8266] -platform = ${esp8266_defaults.platform} -platform_packages = ${esp8266_defaults.platform_packages} -board = nodemcuv2 -lib_deps = ${esp8266_defaults.lib_deps} -lib_ignore = ${esp8266_defaults.lib_ignore} -extra_scripts = ${esp8266_defaults.extra_scripts} -board_build.ldscript = ${esp8266_defaults.board_build.ldscript} -build_type = ${esp8266_defaults.build_type} -build_flags = - ${esp8266_defaults.build_flags} - -D DEFAULT_OT_IN_GPIO=13 - -D DEFAULT_OT_OUT_GPIO=15 - -D DEFAULT_SENSOR_OUTDOOR_GPIO=12 - -D DEFAULT_SENSOR_INDOOR_GPIO=4 - -D DEFAULT_STATUS_LED_GPIO=2 - -D DEFAULT_OT_RX_LED_GPIO=16 -check_tool = ${esp8266_defaults.check_tool} -check_flags = ${esp8266_defaults.check_flags} - [env:s2_mini] -platform = ${esp32_defaults.platform} -platform_packages = ${esp32_defaults.platform_packages} -board = lolin_s2_mini -board_build.partitions = ${esp32_defaults.board_build.partitions} -lib_deps = ${esp32_defaults.lib_deps} -lib_ignore = ${esp32_defaults.lib_ignore} -extra_scripts = ${esp32_defaults.extra_scripts} -build_unflags = - -DARDUINO_USB_MODE=1 -build_type = ${esp32_defaults.build_type} -build_flags = - ${esp32_defaults.build_flags} - -D ARDUINO_USB_MODE=0 - -D ARDUINO_USB_CDC_ON_BOOT=1 - -D DEFAULT_OT_IN_GPIO=33 - -D DEFAULT_OT_OUT_GPIO=35 - -D DEFAULT_SENSOR_OUTDOOR_GPIO=9 - -D DEFAULT_SENSOR_INDOOR_GPIO=7 - -D DEFAULT_STATUS_LED_GPIO=11 - -D DEFAULT_OT_RX_LED_GPIO=12 -check_tool = ${esp32_defaults.check_tool} -check_flags = ${esp32_defaults.check_flags} +custom_title = Wemos S2 mini (ESP32 S2) +extends = esp32_defaults +board = lolin_s2_mini +extra_scripts = ${esp32_defaults.extra_scripts} + pre:tools/tinyusb_s2.py +custom_sdkconfig = ${esp32_defaults.custom_sdkconfig} + '# CONFIG_BT_ENABLED is not set' + CONFIG_TINYUSB_ENABLED=y + CONFIG_TINYUSB_CDC_ENABLED=y + CONFIG_TINYUSB_CDC_MAX_PORTS=1 + ; Only the USB CDC console is used on S2. + '# CONFIG_TINYUSB_MSC_ENABLED is not set' + '# CONFIG_TINYUSB_HID_ENABLED is not set' + '# CONFIG_TINYUSB_MIDI_ENABLED is not set' + '# CONFIG_TINYUSB_AUDIO_ENABLED is not set' + '# CONFIG_TINYUSB_VIDEO_ENABLED is not set' + '# CONFIG_TINYUSB_DFU_RT_ENABLED is not set' + '# CONFIG_TINYUSB_DFU_ENABLED is not set' + '# CONFIG_TINYUSB_VENDOR_ENABLED is not set' + '# CONFIG_TINYUSB_NCM_ENABLED is not set' +build_flags = ${esp32_defaults.build_flags} + ${this.custom_board_flags} +custom_board_flags = -D DEFAULT_OT_IN_GPIO=33 + -D DEFAULT_OT_OUT_GPIO=35 + -D DEFAULT_SENSOR_OUTDOOR_GPIO=9 + -D DEFAULT_SENSOR_INDOOR_GPIO=7 + -D DEFAULT_STATUS_LED_GPIO=11 + -D DEFAULT_OT_RX_LED_GPIO=12 -[env:s3_mini] -platform = ${esp32_defaults.platform} -platform_packages = ${esp32_defaults.platform_packages} -board = lolin_s3_mini -board_build.partitions = ${esp32_defaults.board_build.partitions} -lib_deps = - ${esp32_defaults.lib_deps} - ${esp32_defaults.nimble_lib} -lib_ignore = ${esp32_defaults.lib_ignore} -extra_scripts = ${esp32_defaults.extra_scripts} -build_unflags = - -DARDUINO_USB_MODE=1 -build_type = ${esp32_defaults.build_type} -build_flags = - ${esp32_defaults.build_flags} - -D ARDUINO_USB_MODE=0 - -D ARDUINO_USB_CDC_ON_BOOT=1 - -D MYNEWT_VAL_BLE_EXT_ADV=1 - -D USE_BLE=1 - -D DEFAULT_OT_IN_GPIO=35 - -D DEFAULT_OT_OUT_GPIO=36 - -D DEFAULT_SENSOR_OUTDOOR_GPIO=13 - -D DEFAULT_SENSOR_INDOOR_GPIO=12 - -D DEFAULT_STATUS_LED_GPIO=11 - -D DEFAULT_OT_RX_LED_GPIO=10 -check_tool = ${esp32_defaults.check_tool} -check_flags = ${esp32_defaults.check_flags} +[env:s3_mini] +custom_title = Wemos S3 mini (ESP32 S3) +extends = esp32_defaults +board = lolin_s3_mini +custom_sdkconfig = ${esp32_defaults.custom_sdkconfig} + '# CONFIG_TINYUSB_ENABLED is not set' + CONFIG_ETH_USE_SPI_ETHERNET=y + CONFIG_ESP_NETIF_SET_DNS_PER_DEFAULT_NETIF=y +lib_deps = ${esp32_defaults.lib_deps} + ${esp32_defaults.nimble_lib} +build_flags = ${esp32_defaults.build_flags} + -D ARDUINO_USB_MODE=1 + -D ARDUINO_USB_CDC_ON_BOOT=1 + -D MYNEWT_VAL_BLE_EXT_ADV=1 + -D USE_BLE=1 + -D USE_ETHERNET=1 + ${this.custom_board_flags} +custom_board_flags = -D DEFAULT_OT_IN_GPIO=35 + -D DEFAULT_OT_OUT_GPIO=36 + -D DEFAULT_SENSOR_OUTDOOR_GPIO=13 + -D DEFAULT_SENSOR_INDOOR_GPIO=12 + -D DEFAULT_STATUS_LED_GPIO=11 + -D DEFAULT_OT_RX_LED_GPIO=10 -[env:c3_mini] -platform = ${esp32_defaults.platform} -platform_packages = ${esp32_defaults.platform_packages} -board = lolin_c3_mini -board_build.partitions = ${esp32_defaults.board_build.partitions} -lib_deps = - ${esp32_defaults.lib_deps} - ${esp32_defaults.nimble_lib} -lib_ignore = ${esp32_defaults.lib_ignore} -extra_scripts = ${esp32_defaults.extra_scripts} -build_unflags = - -mtext-section-literals -build_type = ${esp32_defaults.build_type} -build_flags = - ${esp32_defaults.build_flags} - -D MYNEWT_VAL_BLE_EXT_ADV=1 - -D USE_BLE=1 - -D DEFAULT_OT_IN_GPIO=8 - -D DEFAULT_OT_OUT_GPIO=10 - -D DEFAULT_SENSOR_OUTDOOR_GPIO=0 - -D DEFAULT_SENSOR_INDOOR_GPIO=1 - -D DEFAULT_STATUS_LED_GPIO=4 - -D DEFAULT_OT_RX_LED_GPIO=5 -check_tool = ${esp32_defaults.check_tool} -check_flags = ${esp32_defaults.check_flags} +;[env:s3_mini_no_psram] ; FOR TESTS +;extends = env:s3_mini +;build_unflags = ${esp32_defaults.build_unflags} +; -DBOARD_HAS_PSRAM +; -mdisable-hardware-atomics +;custom_sdkconfig = ${env:s3_mini.custom_sdkconfig} +; '# CONFIG_SPIRAM is not set' + +[env:c3_mini] +custom_title = Wemos C3 mini (ESP32 C3) +extends = esp32_defaults +board = lolin_c3_mini +lib_deps = ${esp32_defaults.lib_deps} + ${esp32_defaults.nimble_lib} +build_unflags = ${esp32_defaults.build_unflags} + -mno-save-restore +custom_link_flags = -msave-restore +build_flags = ${esp32_defaults.build_flags} + -msave-restore + -D MYNEWT_VAL_BLE_EXT_ADV=1 + -D USE_BLE=1 + ${this.custom_board_flags} +custom_board_flags = -D DEFAULT_OT_IN_GPIO=8 + -D DEFAULT_OT_OUT_GPIO=10 + -D DEFAULT_SENSOR_OUTDOOR_GPIO=0 + -D DEFAULT_SENSOR_INDOOR_GPIO=1 + -D DEFAULT_STATUS_LED_GPIO=4 + -D DEFAULT_OT_RX_LED_GPIO=5 +custom_sdkconfig = ${esp32_defaults.custom_sdkconfig} + CONFIG_COMPILER_SAVE_RESTORE_LIBCALLS=y [env:nodemcu_32] -platform = ${esp32_defaults.platform} -platform_packages = ${esp32_defaults.platform_packages} -board = nodemcu-32s -board_build.partitions = ${esp32_defaults.board_build.partitions} -lib_deps = - ${esp32_defaults.lib_deps} - ${esp32_defaults.nimble_lib} -lib_ignore = ${esp32_defaults.lib_ignore} -extra_scripts = ${esp32_defaults.extra_scripts} -build_type = ${esp32_defaults.build_type} -build_flags = - ${esp32_defaults.build_flags} - -D USE_BLE=1 - -D DEFAULT_OT_IN_GPIO=16 - -D DEFAULT_OT_OUT_GPIO=4 - -D DEFAULT_SENSOR_OUTDOOR_GPIO=15 - -D DEFAULT_SENSOR_INDOOR_GPIO=26 - -D DEFAULT_STATUS_LED_GPIO=2 - -D DEFAULT_OT_RX_LED_GPIO=19 -check_tool = ${esp32_defaults.check_tool} -check_flags = ${esp32_defaults.check_flags} +custom_title = NodeMCU (ESP32) +extends = esp32_defaults +board = nodemcu-32s +lib_deps = ${esp32_defaults.lib_deps} + ${esp32_defaults.nimble_lib} +build_flags = ${esp32_defaults.build_flags} + -D USE_BLE=1 + ${this.custom_board_flags} +custom_board_flags = -D DEFAULT_OT_IN_GPIO=16 + -D DEFAULT_OT_OUT_GPIO=4 + -D DEFAULT_SENSOR_OUTDOOR_GPIO=15 + -D DEFAULT_SENSOR_INDOOR_GPIO=26 + -D DEFAULT_STATUS_LED_GPIO=2 + -D DEFAULT_OT_RX_LED_GPIO=19 -[env:nodemcu_32_160mhz] -extends = env:nodemcu_32 -board_build.f_cpu = 160000000L ; set frequency to 160MHz +[env:nodemcu_32_160mhz] +custom_title = NodeMCU (ESP32, 160 mhz) +extends = env:nodemcu_32 +board_build.f_cpu = 160000000L ; set frequency to 160MHz [env:d1_mini32] -platform = ${esp32_defaults.platform} -platform_packages = ${esp32_defaults.platform_packages} -board = wemos_d1_mini32 -board_build.partitions = ${esp32_defaults.board_build.partitions} -lib_deps = - ${esp32_defaults.lib_deps} - ${esp32_defaults.nimble_lib} -lib_ignore = ${esp32_defaults.lib_ignore} -extra_scripts = ${esp32_defaults.extra_scripts} -build_type = ${esp32_defaults.build_type} -build_flags = - ${esp32_defaults.build_flags} - -D USE_BLE=1 - -D DEFAULT_OT_IN_GPIO=21 - -D DEFAULT_OT_OUT_GPIO=22 - -D DEFAULT_SENSOR_OUTDOOR_GPIO=12 - -D DEFAULT_SENSOR_INDOOR_GPIO=18 - -D DEFAULT_STATUS_LED_GPIO=2 - -D DEFAULT_OT_RX_LED_GPIO=19 -check_tool = ${esp32_defaults.check_tool} -check_flags = ${esp32_defaults.check_flags} +custom_title = Wemos D1 mini32 (ESP32) +extends = esp32_defaults +board = wemos_d1_mini32 +lib_deps = ${esp32_defaults.lib_deps} + ${esp32_defaults.nimble_lib} +build_flags = ${esp32_defaults.build_flags} + -D USE_BLE=1 + ${this.custom_board_flags} +custom_board_flags = -D DEFAULT_OT_IN_GPIO=21 + -D DEFAULT_OT_OUT_GPIO=22 + -D DEFAULT_SENSOR_OUTDOOR_GPIO=12 + -D DEFAULT_SENSOR_INDOOR_GPIO=18 + -D DEFAULT_STATUS_LED_GPIO=2 + -D DEFAULT_OT_RX_LED_GPIO=19 [env:esp32_c6] -; W5500 ethernet (USE_ETHERNET) is hardware-validated on this target only; every other env -; inherits the `false` default from src/defines.h and compiles the driver out. -platform = ${esp32_defaults.platform} -framework = arduino, espidf -platform_packages = ${esp32_defaults.platform_packages} -board = esp32-c6-devkitm-1 -board_build.partitions = ${esp32_defaults.board_build.partitions} -board_build.embed_txtfiles = - managed_components/espressif__esp_insights/server_certs/https_server.crt - managed_components/espressif__esp_rainmaker/server_certs/rmaker_mqtt_server.crt - managed_components/espressif__esp_rainmaker/server_certs/rmaker_claim_service_server.crt - managed_components/espressif__esp_rainmaker/server_certs/rmaker_ota_server.crt -lib_deps = ${esp32_defaults.lib_deps} -lib_ignore = - ${esp32_defaults.lib_ignore} -extra_scripts = ${esp32_defaults.extra_scripts} -build_unflags = - -mtext-section-literals -build_type = ${esp32_defaults.build_type} -build_flags = - ${esp32_defaults.build_flags} - -D USE_BLE=1 - -D USE_ETHERNET=1 - -D DEFAULT_OT_IN_GPIO=15 - -D DEFAULT_OT_OUT_GPIO=23 - -D DEFAULT_SENSOR_OUTDOOR_GPIO=0 - -D DEFAULT_SENSOR_INDOOR_GPIO=0 - -D DEFAULT_STATUS_LED_GPIO=11 - -D DEFAULT_OT_RX_LED_GPIO=10 -check_tool = ${esp32_defaults.check_tool} -check_flags = ${esp32_defaults.check_flags} +custom_title = ESP32 C6 +extends = esp32_defaults +board = esp32-c6-devkitm-1 +lib_deps = ${esp32_defaults.lib_deps} + ${esp32_defaults.nimble_lib} +build_unflags = ${esp32_defaults.build_unflags} + -mno-save-restore + -fexceptions + -Os +custom_link_flags = -msave-restore + -Oz + ; https://github.com/pioarduino/platform-espressif32/issues/586 + -Tesp32c6.rom.libc-suboptimal_for_misaligned_mem.ld +build_flags = ${esp32_defaults.build_flags} + -msave-restore + -fno-exceptions + -Oz + -include "$PROJECT_DIR/include/c6_compiler_flags.h" + -D USE_BLE=1 + ${this.custom_board_flags} +custom_board_flags = -D DEFAULT_OT_IN_GPIO=15 + -D DEFAULT_OT_OUT_GPIO=23 + -D DEFAULT_SENSOR_OUTDOOR_GPIO=0 + -D DEFAULT_SENSOR_INDOOR_GPIO=0 + -D DEFAULT_STATUS_LED_GPIO=11 + -D DEFAULT_OT_RX_LED_GPIO=10 +custom_sdkconfig = ${esp32_defaults.custom_sdkconfig} + CONFIG_COMPILER_SAVE_RESTORE_LIBCALLS=y + '# CONFIG_LIBC_OPTIMIZED_MISALIGNED_ACCESS is not set' + '# CONFIG_COMPILER_CXX_EXCEPTIONS is not set' + ; Assertions still abort; detailed failure messages are omitted. + '# CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_ENABLE is not set' + '# CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_DISABLE is not set' + CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT=y + ; Constexpr attributes are supplied by the forced compiler header. + '# CONFIG_COMPILER_CXX_GLIBCXX_CONSTEXPR_COLD_CONSTEXPR is not set' + '# CONFIG_COMPILER_CXX_GLIBCXX_CONSTEXPR_COLD is not set' + CONFIG_COMPILER_CXX_GLIBCXX_CONSTEXPR_NO_CHANGE=y -[env:otthing] -platform = ${esp32_defaults.platform} -platform_packages = ${esp32_defaults.platform_packages} -board = lolin_c3_mini -board_build.partitions = ${esp32_defaults.board_build.partitions} -lib_deps = - ${esp32_defaults.lib_deps} - ${esp32_defaults.nimble_lib} -lib_ignore = ${esp32_defaults.lib_ignore} -extra_scripts = ${esp32_defaults.extra_scripts} -build_unflags = - -mtext-section-literals -build_type = ${esp32_defaults.build_type} -build_flags = - ${esp32_defaults.build_flags} - -D MYNEWT_VAL_BLE_EXT_ADV=1 - -D USE_BLE=1 - -D DEFAULT_OT_IN_GPIO=3 - -D DEFAULT_OT_OUT_GPIO=1 -; -D DEFAULT_SENSOR_OUTDOOR_GPIO=0 -; -D DEFAULT_SENSOR_INDOOR_GPIO=1 - -D DEFAULT_STATUS_LED_GPIO=8 - -D DEFAULT_OT_RX_LED_GPIO=2 - -D OT_BYPASS_RELAY_GPIO=20 -check_tool = ${esp32_defaults.check_tool} -check_flags = ${esp32_defaults.check_flags} +; W5500 support uses a separate build to fit the existing OTA slot. +[env:esp32_c6_ethernet] +custom_title = ESP32 C6 (Ethernet) +extends = env:esp32_c6 +lib_deps = ${esp32_defaults.lib_deps} +build_flags = ${esp32_defaults.build_flags} + -msave-restore + -fno-exceptions + -Oz + -include "$PROJECT_DIR/include/c6_compiler_flags.h" + -D USE_ETHERNET=1 + ${this.custom_board_flags} +custom_sdkconfig = ${env:esp32_c6.custom_sdkconfig} + '# CONFIG_BT_ENABLED is not set' + CONFIG_ETH_USE_SPI_ETHERNET=y + CONFIG_ESP_NETIF_SET_DNS_PER_DEFAULT_NETIF=y + +[env:elvinhome_thrm_one] +custom_title = Elvinhome THRM ONE (ESP32 C6, NO BLE) +extends = env:esp32_c6_ethernet +custom_board_flags = -D DEFAULT_ETH_CLK_GPIO=22 + -D DEFAULT_ETH_MOSI_GPIO=20 + -D DEFAULT_ETH_MISO_GPIO=21 + -D DEFAULT_ETH_CS_GPIO=23 + -D DEFAULT_ETH_IRQ_GPIO=19 + -D DEFAULT_ETH_RST_GPIO=18 + -D DEFAULT_OT_IN_GPIO=6 + -D DEFAULT_OT_OUT_GPIO=7 + -D DEFAULT_STATUS_LED_GPIO=1 + -D DEFAULT_SENSOR_INDOOR_GPIO=4 + -D DEFAULT_SENSOR_INDOOR_TYPE=Sensors::Type::NTC_10K_TEMP + -D DEFAULT_OT_RX_LED_GPIO=GPIO_IS_NOT_CONFIGURED + -D DEFAULT_SENSOR_OUTDOOR_GPIO=GPIO_IS_NOT_CONFIGURED + -D DEFAULT_NTC_VREF=3200.0f + +[env:otthing] +custom_title = OT Thing board (ESP32 C3) +extends = env:c3_mini +custom_board_flags = -D DEFAULT_OT_IN_GPIO=3 + -D DEFAULT_OT_OUT_GPIO=1 + ;-D DEFAULT_SENSOR_OUTDOOR_GPIO=0 + ;-D DEFAULT_SENSOR_INDOOR_GPIO=1 + -D DEFAULT_STATUS_LED_GPIO=8 + -D DEFAULT_OT_RX_LED_GPIO=2 + -D OT_BYPASS_RELAY_GPIO=20 diff --git a/sdkconfig.defaults b/sdkconfig.defaults deleted file mode 100644 index 609263d..0000000 --- a/sdkconfig.defaults +++ /dev/null @@ -1,38 +0,0 @@ -# Source: -# https://github.com/pioarduino/platform-espressif32/tree/main/examples/espidf-arduino-h2zero-BLE_scan - -CONFIG_FREERTOS_HZ=1000 -CONFIG_MBEDTLS_PSK_MODES=y -CONFIG_MBEDTLS_KEY_EXCHANGE_PSK=y -CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_SIZE=y -CONFIG_COMPILER_OPTIMIZATION_SIZE=y -CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y -CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE=y - -# -# Ethernet (W5500 over SPI) -CONFIG_ETH_USE_SPI_ETHERNET=y -CONFIG_ETH_SPI_ETHERNET_W5500=y - -# -# BT config -CONFIG_BT_ENABLED=y -CONFIG_BTDM_CTRL_MODE_BLE_ONLY=y -CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY=n -CONFIG_BTDM_CTRL_MODE_BTDM=n -CONFIG_BT_BLUEDROID_ENABLED=n -CONFIG_BT_NIMBLE_ENABLED=y - -# -# Arduino Configuration -CONFIG_AUTOSTART_ARDUINO=y -CONFIG_ARDUINO_SELECTIVE_COMPILATION=y -CONFIG_ARDUINO_SELECTIVE_Zigbee=n -CONFIG_ARDUINO_SELECTIVE_Matter=n -CONFIG_ARDUINO_SELECTIVE_WiFiProv=n -CONFIG_ARDUINO_SELECTIVE_BLE=n -CONFIG_ARDUINO_SELECTIVE_BluetoothSerial=n -CONFIG_ARDUINO_SELECTIVE_SimpleBLE=n -CONFIG_ARDUINO_SELECTIVE_RainMaker=n -CONFIG_ARDUINO_SELECTIVE_OpenThread=n -CONFIG_ARDUINO_SELECTIVE_Insights=n \ No newline at end of file diff --git a/secrets.default.ini b/secrets.default.ini index f478977..f3ad3a6 100644 --- a/secrets.default.ini +++ b/secrets.default.ini @@ -3,10 +3,9 @@ build_type = release serial_enabled = true serial_baud = 115200 -telnet_enabled = true -telnet_port = 23 -log_level = 5 -hostname = opentherm +webserial_enabled = true +log_level = ESP_LOG_INFO +hostname = ap_ssid = OpenTherm Gateway ap_password = otgateway123456 @@ -22,4 +21,6 @@ mqtt_server = mqtt_port = 1883 mqtt_user = mqtt_password = -mqtt_prefix = opentherm \ No newline at end of file +mqtt_prefix = +ha_discovery_enabled = true +ha_discovery_prefix = homeassistant diff --git a/src/CrashRecorder.h b/src/CrashRecorder.h deleted file mode 100644 index e795b2a..0000000 --- a/src/CrashRecorder.h +++ /dev/null @@ -1,132 +0,0 @@ -#pragma once -#include - -#ifdef ARDUINO_ARCH_ESP32 - #include "esp_err.h" -#endif - -#ifdef ARDUINO_ARCH_ESP8266 - extern "C" { - #include - } - - // https://github.com/espressif/ESP8266_RTOS_SDK/blob/master/components/esp8266/include/esp_attr.h - #define _COUNTER_STRINGIFY(COUNTER) #COUNTER - #define _SECTION_ATTR_IMPL(SECTION, COUNTER) __attribute__((section(SECTION "." _COUNTER_STRINGIFY(COUNTER)))) - #define __NOINIT_ATTR _SECTION_ATTR_IMPL(".noinit", __COUNTER__) -#endif - -namespace CrashRecorder { - typedef struct { - unsigned int data[32]; - uint8_t length; - bool continues; - } backtrace_t; - - typedef struct { - unsigned int data[4]; - uint8_t length; - } epc_t; - - typedef struct { - uint8_t core; - size_t heap; - unsigned long uptime; - } ext_t; - - - __NOINIT_ATTR volatile static backtrace_t backtrace; - __NOINIT_ATTR volatile static epc_t epc; - __NOINIT_ATTR volatile static ext_t ext; - - uint8_t backtraceMaxLength = sizeof(backtrace.data) / sizeof(*backtrace.data); - uint8_t epcMaxLength = sizeof(epc.data) / sizeof(*epc.data); - - #ifdef ARDUINO_ARCH_ESP32 - void IRAM_ATTR panicHandler(arduino_panic_info_t *info, void *arg) {; - ext.core = info->core; - ext.heap = ESP.getFreeHeap(); - ext.uptime = millis() / 1000u; - - // Backtrace - backtrace.length = info->backtrace_len < backtraceMaxLength ? info->backtrace_len : backtraceMaxLength; - backtrace.continues = false; - for (unsigned int i = 0; i < info->backtrace_len; i++) { - if (i >= backtraceMaxLength) { - backtrace.continues = true; - break; - } - - backtrace.data[i] = info->backtrace[i]; - } - - // EPC - if (info->pc) { - epc.data[0] = (unsigned int) info->pc; - epc.length = 1; - - } else { - epc.length = 0; - } - } - #endif - - void init() { - if (backtrace.length > backtraceMaxLength) { - backtrace.length = 0; - } - - if (epc.length > epcMaxLength) { - epc.length = 0; - } - - #ifdef ARDUINO_ARCH_ESP32 - set_arduino_panic_handler(panicHandler, nullptr); - #endif - } -} - -#ifdef ARDUINO_ARCH_ESP8266 -extern "C" void custom_crash_callback(struct rst_info *info, uint32_t stack, uint32_t stack_end) { - uint8_t _length = 0; - - CrashRecorder::ext.core = 0; - CrashRecorder::ext.heap = ESP.getFreeHeap(); - CrashRecorder::ext.uptime = millis() / 1000u; - - // Backtrace - CrashRecorder::backtrace.continues = false; - uint32_t value; - for (uint32_t i = stack; i < stack_end; i += 4) { - value = *((uint32_t*) i); - - // keep only addresses in code area - if ((value >= 0x40000000) && (value < 0x40300000)) { - if (_length >= CrashRecorder::backtraceMaxLength) { - CrashRecorder::backtrace.continues = true; - break; - } - - CrashRecorder::backtrace.data[_length++] = value; - } - } - - CrashRecorder::backtrace.length = _length; - - // EPC - _length = 0; - if (info->epc1 > 0) { - CrashRecorder::epc.data[_length++] = info->epc1; - } - - if (info->epc2 > 0) { - CrashRecorder::epc.data[_length++] = info->epc2; - } - - if (info->epc3 > 0) { - CrashRecorder::epc.data[_length++] = info->epc3; - } - - CrashRecorder::epc.length = _length; -} -#endif \ No newline at end of file diff --git a/src/HaHelper.h b/src/HaHelper.h deleted file mode 100644 index 3e82e28..0000000 --- a/src/HaHelper.h +++ /dev/null @@ -1,1419 +0,0 @@ -#pragma once -#include - -class HaHelper : public HomeAssistantHelper { -public: - static const uint8_t TEMP_SOURCE_HEATING = 0; - static const uint8_t TEMP_SOURCE_INDOOR = 1; - static const char AVAILABILITY_OT_CONN[]; - static const char AVAILABILITY_SENSOR_CONN[]; - - void updateCachedTopics() { - this->statusTopic = this->getDeviceTopic(F("status")); - this->stateTopic = this->getDeviceTopic(F("state")); - this->setStateTopic = this->getDeviceTopic(F("state/set")); - this->settingsTopic = this->getDeviceTopic(F("settings")); - this->setSettingsTopic = this->getDeviceTopic(F("settings/set")); - } - - void setExpireAfter(unsigned short value) { - this->expireAfter = value; - } - - auto getExpireAfter() { - return this->expireAfter; - } - - bool publishDynamicSensor(Sensors::Settings& sSensor, Sensors::ValueType vType = Sensors::ValueType::PRIMARY, UnitSystem unit = UnitSystem::METRIC, bool enabledByDefault = true) { - #if !USE_BLE - if (sSensor.type == Sensors::Type::BLUETOOTH) { - return false; - } - #endif - - JsonDocument doc; - - // set device class & unit of measurement - switch (sSensor.purpose) { - case Sensors::Purpose::OUTDOOR_TEMP: - case Sensors::Purpose::INDOOR_TEMP: - case Sensors::Purpose::HEATING_TEMP: - case Sensors::Purpose::HEATING_RETURN_TEMP: - case Sensors::Purpose::DHW_TEMP: - case Sensors::Purpose::DHW_RETURN_TEMP: - case Sensors::Purpose::EXHAUST_TEMP: - case Sensors::Purpose::TEMPERATURE: - doc[FPSTR(HA_DEVICE_CLASS)] = FPSTR(S_TEMPERATURE); - if (unit == UnitSystem::METRIC) { - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = FPSTR(HA_UNIT_OF_MEASUREMENT_C); - - if (sSensor.type == Sensors::Type::MANUAL) { - doc[FPSTR(HA_MIN)] = -99; - doc[FPSTR(HA_MAX)] = 99; - } - - } else if (unit == UnitSystem::IMPERIAL) { - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = FPSTR(HA_UNIT_OF_MEASUREMENT_F); - - if (sSensor.type == Sensors::Type::MANUAL) { - doc[FPSTR(HA_MIN)] = -147; - doc[FPSTR(HA_MAX)] = 211; - } - } - break; - - case Sensors::Purpose::DHW_FLOW_RATE: - doc[FPSTR(HA_DEVICE_CLASS)] = F("volume_flow_rate"); - if (unit == UnitSystem::METRIC) { - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = FPSTR(HA_UNIT_OF_MEASUREMENT_L_MIN); - - } else if (unit == UnitSystem::IMPERIAL) { - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = FPSTR(HA_UNIT_OF_MEASUREMENT_GAL_MIN); - } - break; - - case Sensors::Purpose::MODULATION_LEVEL: - case Sensors::Purpose::POWER_FACTOR: - doc[FPSTR(HA_DEVICE_CLASS)] = F("power_factor"); - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = FPSTR(HA_UNIT_OF_MEASUREMENT_PERCENT); - break; - - case Sensors::Purpose::POWER: - doc[FPSTR(HA_DEVICE_CLASS)] = F("power"); - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = F("kW"); - break; - - case Sensors::Purpose::FAN_SPEED: - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = F("RPM"); - break; - - case Sensors::Purpose::CO2: - doc[FPSTR(HA_DEVICE_CLASS)] = F("carbon_dioxide"); - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = F("ppm"); - break; - - case Sensors::Purpose::PRESSURE: - doc[FPSTR(HA_DEVICE_CLASS)] = F("pressure"); - if (unit == UnitSystem::METRIC) { - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = F("bar"); - - } else if (unit == UnitSystem::IMPERIAL) { - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = F("psi"); - } - break; - - case Sensors::Purpose::HUMIDITY: - doc[FPSTR(HA_DEVICE_CLASS)] = FPSTR(S_HUMIDITY); - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = FPSTR(HA_UNIT_OF_MEASUREMENT_PERCENT); - break; - - default: - break; - } - - // set icon - switch (sSensor.purpose) { - case Sensors::Purpose::OUTDOOR_TEMP: - doc[FPSTR(HA_ICON)] = F("mdi:home-thermometer-outline"); - break; - - case Sensors::Purpose::INDOOR_TEMP: - doc[FPSTR(HA_ICON)] = F("mdi:home-thermometer"); - break; - - case Sensors::Purpose::HEATING_TEMP: - doc[FPSTR(HA_ICON)] = F("mdi:radiator"); - break; - - case Sensors::Purpose::HEATING_RETURN_TEMP: - doc[FPSTR(HA_ICON)] = F("mdi:heating-coil"); - break; - - case Sensors::Purpose::DHW_TEMP: - doc[FPSTR(HA_ICON)] = F("mdi:faucet"); - break; - - case Sensors::Purpose::DHW_RETURN_TEMP: - doc[FPSTR(HA_ICON)] = F("mdi:heating-coil"); - break; - - case Sensors::Purpose::EXHAUST_TEMP: - doc[FPSTR(HA_ICON)] = F("mdi:smoke"); - break; - - case Sensors::Purpose::TEMPERATURE: - doc[FPSTR(HA_ICON)] = F("mdi:thermometer-lines"); - break; - - case Sensors::Purpose::DHW_FLOW_RATE: - doc[FPSTR(HA_ICON)] = F("mdi:faucet"); - break; - - case Sensors::Purpose::MODULATION_LEVEL: - doc[FPSTR(HA_ICON)] = F("mdi:fire-circle"); - break; - - case Sensors::Purpose::POWER_FACTOR: - case Sensors::Purpose::POWER: - doc[FPSTR(HA_ICON)] = F("mdi:chart-bar"); - break; - - case Sensors::Purpose::FAN_SPEED: - doc[FPSTR(HA_ICON)] = F("mdi:fan"); - break; - - case Sensors::Purpose::PRESSURE: - doc[FPSTR(HA_ICON)] = F("mdi:gauge"); - break; - - case Sensors::Purpose::HUMIDITY: - doc[FPSTR(HA_ICON)] = F("mdi:water-percent"); - break; - - default: - break; - } - - String objId = Sensors::makeObjectId(sSensor.name); - - // state topic - doc[FPSTR(HA_STATE_TOPIC)] = this->getDeviceTopic( - F("sensors"), - objId.c_str() - ); - - // set device class, name, value template for bluetooth sensors - // or name & value template for another sensors - if (sSensor.type == Sensors::Type::BLUETOOTH) { - // available state topic - doc[FPSTR(HA_AVAILABILITY)][1][FPSTR(HA_TOPIC)] = doc[FPSTR(HA_STATE_TOPIC)]; - doc[FPSTR(HA_AVAILABILITY)][1][FPSTR(HA_VALUE_TEMPLATE)] = JsonString(AVAILABILITY_SENSOR_CONN, true); - - String sName = sSensor.name; - switch (vType) { - case Sensors::ValueType::TEMPERATURE: - Sensors::makeObjectIdWithSuffix(objId, sSensor.name, F("temp")); - sName += F(" temperature"); - - doc[FPSTR(HA_DEVICE_CLASS)] = FPSTR(S_TEMPERATURE); - if (unit == UnitSystem::METRIC) { - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = FPSTR(HA_UNIT_OF_MEASUREMENT_C); - - } else if (unit == UnitSystem::IMPERIAL) { - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = FPSTR(HA_UNIT_OF_MEASUREMENT_F); - } - doc[FPSTR(HA_NAME)] = sName; - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.temperature|float(0)|round(2) }}"); - break; - - case Sensors::ValueType::HUMIDITY: - Sensors::makeObjectIdWithSuffix(objId, sSensor.name, FPSTR(S_HUMIDITY)); - sName += F(" humidity"); - - doc[FPSTR(HA_DEVICE_CLASS)] = FPSTR(S_HUMIDITY); - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = FPSTR(HA_UNIT_OF_MEASUREMENT_PERCENT); - doc[FPSTR(HA_NAME)] = sName; - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.humidity|float(0)|round(2) }}"); - break; - - case Sensors::ValueType::BATTERY: - Sensors::makeObjectIdWithSuffix(objId, sSensor.name, FPSTR(S_BATTERY)); - sName += F(" battery"); - - doc[FPSTR(HA_DEVICE_CLASS)] = FPSTR(S_BATTERY); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_DIAGNOSTIC); - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = FPSTR(HA_UNIT_OF_MEASUREMENT_PERCENT); - doc[FPSTR(HA_NAME)] = sName; - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.battery|float(0)|round(2) }}"); - break; - - case Sensors::ValueType::RSSI: - Sensors::makeObjectIdWithSuffix(objId, sSensor.name, FPSTR(S_RSSI)); - sName += F(" RSSI"); - - doc[FPSTR(HA_DEVICE_CLASS)] = F("signal_strength"); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_DIAGNOSTIC); - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = F("dBm"); - doc[FPSTR(HA_NAME)] = sName; - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.rssi|float(0)|round(2) }}"); - break; - - default: - return false; - } - - } else if (sSensor.type == Sensors::Type::MANUAL) { - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_CONFIG); - doc[FPSTR(HA_STEP)] = 0.01f; - doc[FPSTR(HA_MODE)] = FPSTR(HA_MODE_BOX); - - doc[FPSTR(HA_COMMAND_TOPIC)] = this->getDeviceTopic( - F("sensors"), - objId.c_str(), - F("set") - ); - doc[FPSTR(HA_COMMAND_TEMPLATE)] = F("{\"value\": {{ value }}}"); - - doc[FPSTR(HA_NAME)] = sSensor.name; - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.value|float(0)|round(2) }}"); - - } else { - // available state topic - doc[FPSTR(HA_AVAILABILITY)][1][FPSTR(HA_TOPIC)] = doc[FPSTR(HA_STATE_TOPIC)]; - doc[FPSTR(HA_AVAILABILITY)][1][FPSTR(HA_VALUE_TEMPLATE)] = JsonString(AVAILABILITY_SENSOR_CONN, true); - - doc[FPSTR(HA_NAME)] = sSensor.name; - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.value|float(0)|round(2) }}"); - } - - // object id's - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(objId.c_str()); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix( - sSensor.type == Sensors::Type::MANUAL - ? FPSTR(HA_ENTITY_NUMBER) - : FPSTR(HA_ENTITY_SENSOR), - objId.c_str() - ); - - const String& configTopic = this->makeConfigTopic( - sSensor.type == Sensors::Type::MANUAL ? FPSTR(HA_ENTITY_NUMBER) : FPSTR(HA_ENTITY_SENSOR), - objId.c_str() - ); - objId.clear(); - - doc[FPSTR(HA_AVAILABILITY)][0][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_AVAILABILITY_MODE)] = F("all"); - doc[FPSTR(HA_STATE_CLASS)] = FPSTR(HA_STATE_CLASS_MEASUREMENT); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(configTopic.c_str(), doc); - } - - bool deleteDynamicSensor(Sensors::Settings& sSensor, Sensors::ValueType vType = Sensors::ValueType::PRIMARY) { - String objId; - - if (sSensor.type == Sensors::Type::BLUETOOTH) { - switch (vType) { - case Sensors::ValueType::TEMPERATURE: - Sensors::makeObjectIdWithSuffix(objId, sSensor.name, F("temp")); - break; - - case Sensors::ValueType::HUMIDITY: - Sensors::makeObjectIdWithSuffix(objId, sSensor.name, FPSTR(S_HUMIDITY)); - break; - - case Sensors::ValueType::BATTERY: - Sensors::makeObjectIdWithSuffix(objId, sSensor.name, FPSTR(S_BATTERY)); - break; - - case Sensors::ValueType::RSSI: - Sensors::makeObjectIdWithSuffix(objId, sSensor.name, FPSTR(S_RSSI)); - break; - - default: - return false; - } - - } else { - Sensors::makeObjectId(objId, sSensor.name); - } - - const String& configTopic = this->makeConfigTopic( - sSensor.type == Sensors::Type::MANUAL ? FPSTR(HA_ENTITY_NUMBER) : FPSTR(HA_ENTITY_SENSOR), - objId.c_str() - ); - objId.clear(); - - return this->publish(configTopic.c_str()); - } - - bool publishConnectionDynamicSensor(Sensors::Settings& sSensor, bool enabledByDefault = true) { - JsonDocument doc; - String objId = Sensors::makeObjectIdWithSuffix(sSensor.name, F("connected")); - - // object id's - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(objId.c_str()); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_BINARY_SENSOR), objId.c_str()); - - // state topic - doc[FPSTR(HA_STATE_TOPIC)] = this->getDeviceTopic( - F("sensors"), - Sensors::makeObjectId(sSensor.name).c_str() - ); - - // sensor name - { - String sName = sSensor.name; - sName.trim(); - sName += F(" connected"); - - doc[FPSTR(HA_NAME)] = sName; - } - - const String& configTopic = this->makeConfigTopic(FPSTR(HA_ENTITY_BINARY_SENSOR), objId.c_str()); - objId.clear(); - - - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_DIAGNOSTIC); - doc[FPSTR(HA_DEVICE_CLASS)] = F("connectivity"); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ iif(value_json.connected, 'ON', 'OFF') }}"); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(configTopic.c_str(), doc); - } - - bool deleteConnectionDynamicSensor(Sensors::Settings& sSensor) { - const String& configTopic = this->makeConfigTopic( - FPSTR(HA_ENTITY_BINARY_SENSOR), - Sensors::makeObjectIdWithSuffix(sSensor.name, F("connected")).c_str() - ); - - return this->publish(configTopic.c_str()); - } - - bool publishSignalQualityDynamicSensor(Sensors::Settings& sSensor, bool enabledByDefault = true) { - JsonDocument doc; - String objId = Sensors::makeObjectIdWithSuffix(sSensor.name, F("signal_quality")); - - // object id's - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(objId.c_str()); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_SENSOR), objId.c_str()); - - // state topic - doc[FPSTR(HA_STATE_TOPIC)] = this->getDeviceTopic( - F("sensors"), - Sensors::makeObjectId(sSensor.name).c_str() - ); - - // sensor name - { - String sName = sSensor.name; - sName.trim(); - sName += F(" signal quality"); - - doc[FPSTR(HA_NAME)] = sName; - } - - const String& configTopic = this->makeConfigTopic(FPSTR(HA_ENTITY_SENSOR), objId.c_str()); - objId.clear(); - - - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_DIAGNOSTIC); - //doc[FPSTR(HA_DEVICE_CLASS)] = F("signal_strength"); - doc[FPSTR(HA_STATE_CLASS)] = FPSTR(HA_STATE_CLASS_MEASUREMENT); - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = FPSTR(HA_UNIT_OF_MEASUREMENT_PERCENT); - doc[FPSTR(HA_ICON)] = F("mdi:signal"); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.signalQuality|float(0)|round(0) }}"); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(configTopic.c_str(), doc); - } - - bool deleteSignalQualityDynamicSensor(Sensors::Settings& sSensor) { - const String& configTopic = this->makeConfigTopic( - FPSTR(HA_ENTITY_SENSOR), - Sensors::makeObjectIdWithSuffix(sSensor.name, F("signal_quality")).c_str() - ); - - return this->publish(configTopic.c_str()); - } - - - bool publishSwitchHeatingTurbo(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("heating_turbo")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_SWITCH), F("heating_turbo")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_CONFIG); - doc[FPSTR(HA_NAME)] = F("Turbo heating"); - doc[FPSTR(HA_ICON)] = F("mdi:rocket-launch-outline"); - doc[FPSTR(HA_STATE_TOPIC)] = this->settingsTopic.c_str(); - doc[FPSTR(HA_STATE_ON)] = true; - doc[FPSTR(HA_STATE_OFF)] = false; - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.heating.turbo }}"); - doc[FPSTR(HA_COMMAND_TOPIC)] = this->setSettingsTopic.c_str(); - doc[FPSTR(HA_PAYLOAD_ON)] = F("{\"heating\": {\"turbo\" : true}}"); - doc[FPSTR(HA_PAYLOAD_OFF)] = F("{\"heating\": {\"turbo\" : false}}"); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_SWITCH), F("heating_turbo")).c_str(), doc); - } - - bool publishSwitchHeatingHysteresis(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("heating_hysteresis")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_SWITCH), F("heating_hysteresis")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_CONFIG); - doc[FPSTR(HA_NAME)] = F("Use heating hysteresis"); - doc[FPSTR(HA_ICON)] = F("mdi:altimeter"); - doc[FPSTR(HA_STATE_TOPIC)] = this->settingsTopic.c_str(); - doc[FPSTR(HA_STATE_ON)] = true; - doc[FPSTR(HA_STATE_OFF)] = false; - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.heating.hysteresis.enabled }}"); - doc[FPSTR(HA_COMMAND_TOPIC)] = this->setSettingsTopic.c_str(); - doc[FPSTR(HA_PAYLOAD_ON)] = F("{\"heating\": {\"hysteresis\" : {\"enabled\" : true}}}"); - doc[FPSTR(HA_PAYLOAD_OFF)] = F("{\"heating\": {\"hysteresis\" : {\"enabled\" : false}}}"); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_SWITCH), F("heating_hysteresis")).c_str(), doc); - } - - bool publishInputHeatingHysteresis(UnitSystem unit = UnitSystem::METRIC, bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("heating_hysteresis")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_NUMBER), F("heating_hysteresis")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_CONFIG); - doc[FPSTR(HA_DEVICE_CLASS)] = FPSTR(S_TEMPERATURE); - - if (unit == UnitSystem::METRIC) { - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = FPSTR(HA_UNIT_OF_MEASUREMENT_C); - - } else if (unit == UnitSystem::IMPERIAL) { - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = FPSTR(HA_UNIT_OF_MEASUREMENT_F); - } - - doc[FPSTR(HA_NAME)] = F("Heating hysteresis"); - doc[FPSTR(HA_ICON)] = F("mdi:altimeter"); - doc[FPSTR(HA_STATE_TOPIC)] = this->settingsTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.heating.hysteresis.value|float(0)|round(2) }}"); - doc[FPSTR(HA_COMMAND_TOPIC)] = this->setSettingsTopic.c_str(); - doc[FPSTR(HA_COMMAND_TEMPLATE)] = F("{\"heating\": {\"hysteresis\" : {\"value\" : {{ value }}}}}"); - doc[FPSTR(HA_MIN)] = 0; - doc[FPSTR(HA_MAX)] = 15; - doc[FPSTR(HA_STEP)] = 0.01f; - doc[FPSTR(HA_MODE)] = FPSTR(HA_MODE_BOX); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_NUMBER), F("heating_hysteresis")).c_str(), doc); - } - - bool publishInputHeatingTurboFactor(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("heating_turbo_factor")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_NUMBER), F("heating_turbo_factor")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_CONFIG); - doc[FPSTR(HA_DEVICE_CLASS)] = F("power_factor"); - doc[FPSTR(HA_NAME)] = F("Heating turbo factor"); - doc[FPSTR(HA_ICON)] = F("mdi:multiplication-box"); - doc[FPSTR(HA_STATE_TOPIC)] = this->settingsTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.heating.turboFactor|float(0)|round(2) }}"); - doc[FPSTR(HA_COMMAND_TOPIC)] = this->setSettingsTopic.c_str(); - doc[FPSTR(HA_COMMAND_TEMPLATE)] = F("{\"heating\": {\"turboFactor\" : {{ value }}}}"); - doc[FPSTR(HA_MIN)] = 1.5; - doc[FPSTR(HA_MAX)] = 10; - doc[FPSTR(HA_STEP)] = 0.01f; - doc[FPSTR(HA_MODE)] = FPSTR(HA_MODE_BOX); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_NUMBER), F("heating_turbo_factor")).c_str(), doc); - } - - bool publishInputHeatingMinTemp(UnitSystem unit = UnitSystem::METRIC, bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("heating_min_temp")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_NUMBER), F("heating_min_temp")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_CONFIG); - doc[FPSTR(HA_DEVICE_CLASS)] = FPSTR(S_TEMPERATURE); - - if (unit == UnitSystem::METRIC) { - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = FPSTR(HA_UNIT_OF_MEASUREMENT_C); - doc[FPSTR(HA_MIN)] = 0; - doc[FPSTR(HA_MAX)] = 99; - - } else if (unit == UnitSystem::IMPERIAL) { - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = FPSTR(HA_UNIT_OF_MEASUREMENT_F); - doc[FPSTR(HA_MIN)] = 32; - doc[FPSTR(HA_MAX)] = 211; - } - - doc[FPSTR(HA_NAME)] = F("Heating min temp"); - doc[FPSTR(HA_ICON)] = F("mdi:thermometer-chevron-down"); - doc[FPSTR(HA_STATE_TOPIC)] = this->settingsTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.heating.minTemp|float(0)|round(1) }}"); - doc[FPSTR(HA_COMMAND_TOPIC)] = this->setSettingsTopic.c_str(); - doc[FPSTR(HA_COMMAND_TEMPLATE)] = F("{\"heating\": {\"minTemp\" : {{ value }}}}"); - doc[FPSTR(HA_STEP)] = 1; - doc[FPSTR(HA_MODE)] = FPSTR(HA_MODE_BOX); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_NUMBER), F("heating_min_temp")).c_str(), doc); - } - - bool publishInputHeatingMaxTemp(UnitSystem unit = UnitSystem::METRIC, bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("heating_max_temp")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_NUMBER), F("heating_max_temp")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_CONFIG); - doc[FPSTR(HA_DEVICE_CLASS)] = FPSTR(S_TEMPERATURE); - - if (unit == UnitSystem::METRIC) { - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = FPSTR(HA_UNIT_OF_MEASUREMENT_C); - doc[FPSTR(HA_MIN)] = 1; - doc[FPSTR(HA_MAX)] = 100; - - } else if (unit == UnitSystem::IMPERIAL) { - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = FPSTR(HA_UNIT_OF_MEASUREMENT_F); - doc[FPSTR(HA_MIN)] = 33; - doc[FPSTR(HA_MAX)] = 212; - } - - doc[FPSTR(HA_NAME)] = F("Heating max temp"); - doc[FPSTR(HA_ICON)] = F("mdi:thermometer-chevron-up"); - doc[FPSTR(HA_STATE_TOPIC)] = this->settingsTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.heating.maxTemp|float(0)|round(1) }}"); - doc[FPSTR(HA_COMMAND_TOPIC)] = this->setSettingsTopic.c_str(); - doc[FPSTR(HA_COMMAND_TEMPLATE)] = F("{\"heating\": {\"maxTemp\" : {{ value }}}}"); - doc[FPSTR(HA_STEP)] = 1; - doc[FPSTR(HA_MODE)] = FPSTR(HA_MODE_BOX); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_NUMBER), F("heating_max_temp")).c_str(), doc); - } - - - bool publishInputDhwMinTemp(UnitSystem unit = UnitSystem::METRIC, bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("dhw_min_temp")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_NUMBER), F("dhw_min_temp")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_CONFIG); - doc[FPSTR(HA_DEVICE_CLASS)] = FPSTR(S_TEMPERATURE); - - if (unit == UnitSystem::METRIC) { - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = FPSTR(HA_UNIT_OF_MEASUREMENT_C); - doc[FPSTR(HA_MIN)] = 0; - doc[FPSTR(HA_MAX)] = 99; - - } else if (unit == UnitSystem::IMPERIAL) { - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = FPSTR(HA_UNIT_OF_MEASUREMENT_F); - doc[FPSTR(HA_MIN)] = 32; - doc[FPSTR(HA_MAX)] = 211; - } - - doc[FPSTR(HA_NAME)] = F("DHW min temp"); - doc[FPSTR(HA_ICON)] = F("mdi:thermometer-chevron-down"); - doc[FPSTR(HA_STATE_TOPIC)] = this->settingsTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.dhw.minTemp|float(0)|round(1) }}"); - doc[FPSTR(HA_COMMAND_TOPIC)] = this->setSettingsTopic.c_str(); - doc[FPSTR(HA_COMMAND_TEMPLATE)] = F("{\"dhw\": {\"minTemp\" : {{ value }}}}"); - doc[FPSTR(HA_STEP)] = 1; - doc[FPSTR(HA_MODE)] = FPSTR(HA_MODE_BOX); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_NUMBER), F("dhw_min_temp")).c_str(), doc); - } - - bool publishInputDhwMaxTemp(UnitSystem unit = UnitSystem::METRIC, bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("dhw_max_temp")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_NUMBER), F("dhw_max_temp")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_CONFIG); - doc[FPSTR(HA_DEVICE_CLASS)] = FPSTR(S_TEMPERATURE); - - if (unit == UnitSystem::METRIC) { - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = FPSTR(HA_UNIT_OF_MEASUREMENT_C); - doc[FPSTR(HA_MIN)] = 1; - doc[FPSTR(HA_MAX)] = 100; - - } else if (unit == UnitSystem::IMPERIAL) { - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = FPSTR(HA_UNIT_OF_MEASUREMENT_F); - doc[FPSTR(HA_MIN)] = 33; - doc[FPSTR(HA_MAX)] = 212; - } - - doc[FPSTR(HA_NAME)] = F("DHW max temp"); - doc[FPSTR(HA_ICON)] = F("mdi:thermometer-chevron-up"); - doc[FPSTR(HA_STATE_TOPIC)] = this->settingsTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.dhw.maxTemp|float(0)|round(1) }}"); - doc[FPSTR(HA_COMMAND_TOPIC)] = this->setSettingsTopic.c_str(); - doc[FPSTR(HA_COMMAND_TEMPLATE)] = F("{\"dhw\": {\"maxTemp\" : {{ value }}}}"); - doc[FPSTR(HA_STEP)] = 1; - doc[FPSTR(HA_MODE)] = FPSTR(HA_MODE_BOX); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_NUMBER), F("dhw_max_temp")).c_str(), doc); - } - - - bool publishSwitchPid(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("pid")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_SWITCH), F("pid")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_CONFIG); - doc[FPSTR(HA_NAME)] = F("PID"); - doc[FPSTR(HA_ICON)] = F("mdi:chart-bar-stacked"); - doc[FPSTR(HA_STATE_TOPIC)] = this->settingsTopic.c_str(); - doc[FPSTR(HA_STATE_ON)] = true; - doc[FPSTR(HA_STATE_OFF)] = false; - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.pid.enabled }}"); - doc[FPSTR(HA_COMMAND_TOPIC)] = this->setSettingsTopic.c_str(); - doc[FPSTR(HA_PAYLOAD_ON)] = F("{\"pid\": {\"enabled\" : true}}"); - doc[FPSTR(HA_PAYLOAD_OFF)] = F("{\"pid\": {\"enabled\" : false}}"); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_SWITCH), F("pid")).c_str(), doc); - } - - bool publishInputPidFactorP(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("pid_p")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_NUMBER), F("pid_p")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_CONFIG); - doc[FPSTR(HA_NAME)] = F("PID factor P"); - doc[FPSTR(HA_ICON)] = F("mdi:alpha-p-circle-outline"); - doc[FPSTR(HA_STATE_TOPIC)] = this->settingsTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.pid.p_factor|float(0)|round(3) }}"); - doc[FPSTR(HA_COMMAND_TOPIC)] = this->setSettingsTopic.c_str(); - doc[FPSTR(HA_COMMAND_TEMPLATE)] = F("{\"pid\": {\"p_factor\" : {{ value }}}}"); - doc[FPSTR(HA_MIN)] = 0.1f; - doc[FPSTR(HA_MAX)] = 1000; - doc[FPSTR(HA_STEP)] = 0.1f; - doc[FPSTR(HA_MODE)] = FPSTR(HA_MODE_BOX); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_NUMBER), F("pid_p_factor")).c_str(), doc); - } - - bool publishInputPidFactorI(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("pid_i")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_NUMBER), F("pid_i")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_CONFIG); - doc[FPSTR(HA_NAME)] = F("PID factor I"); - doc[FPSTR(HA_ICON)] = F("mdi:alpha-i-circle-outline"); - doc[FPSTR(HA_STATE_TOPIC)] = this->settingsTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.pid.i_factor|float(0)|round(4) }}"); - doc[FPSTR(HA_COMMAND_TOPIC)] = this->setSettingsTopic.c_str(); - doc[FPSTR(HA_COMMAND_TEMPLATE)] = F("{\"pid\": {\"i_factor\" : {{ value }}}}"); - doc[FPSTR(HA_MIN)] = 0; - doc[FPSTR(HA_MAX)] = 100; - doc[FPSTR(HA_STEP)] = 0.001f; - doc[FPSTR(HA_MODE)] = FPSTR(HA_MODE_BOX); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_NUMBER), F("pid_i_factor")).c_str(), doc); - } - - bool publishInputPidFactorD(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("pid_d")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_NUMBER), F("pid_d")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_CONFIG); - doc[FPSTR(HA_NAME)] = F("PID factor D"); - doc[FPSTR(HA_ICON)] = F("mdi:alpha-d-circle-outline"); - doc[FPSTR(HA_STATE_TOPIC)] = this->settingsTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.pid.d_factor|float(0)|round(3) }}"); - doc[FPSTR(HA_COMMAND_TOPIC)] = this->setSettingsTopic.c_str(); - doc[FPSTR(HA_COMMAND_TEMPLATE)] = F("{\"pid\": {\"d_factor\" : {{ value }}}}"); - doc[FPSTR(HA_MIN)] = 0; - doc[FPSTR(HA_MAX)] = 100000; - doc[FPSTR(HA_STEP)] = 1; - doc[FPSTR(HA_MODE)] = FPSTR(HA_MODE_BOX); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_NUMBER), F("pid_d_factor")).c_str(), doc); - } - - bool publishInputPidDt(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("pid_dt")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_NUMBER), F("pid_dt")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_CONFIG); - doc[FPSTR(HA_DEVICE_CLASS)] = F("duration"); - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = F("s"); - doc[FPSTR(HA_NAME)] = F("PID DT"); - doc[FPSTR(HA_ICON)] = F("mdi:timer-cog-outline"); - doc[FPSTR(HA_STATE_TOPIC)] = this->settingsTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.pid.dt|int(0) }}"); - doc[FPSTR(HA_COMMAND_TOPIC)] = this->setSettingsTopic.c_str(); - doc[FPSTR(HA_COMMAND_TEMPLATE)] = F("{\"pid\": {\"dt\" : {{ value }}}}"); - doc[FPSTR(HA_MIN)] = 30; - doc[FPSTR(HA_MAX)] = 1800; - doc[FPSTR(HA_STEP)] = 1; - doc[FPSTR(HA_MODE)] = FPSTR(HA_MODE_BOX); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_NUMBER), F("pid_dt")).c_str(), doc); - } - - bool publishInputPidMinTemp(UnitSystem unit = UnitSystem::METRIC, bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("pid_min_temp")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_NUMBER), F("pid_min_temp")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_CONFIG); - doc[FPSTR(HA_DEVICE_CLASS)] = FPSTR(S_TEMPERATURE); - - if (unit == UnitSystem::METRIC) { - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = FPSTR(HA_UNIT_OF_MEASUREMENT_C); - doc[FPSTR(HA_MIN)] = -99; - doc[FPSTR(HA_MAX)] = 99; - - } else if (unit == UnitSystem::IMPERIAL) { - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = FPSTR(HA_UNIT_OF_MEASUREMENT_F); - doc[FPSTR(HA_MIN)] = -146; - doc[FPSTR(HA_MAX)] = 211; - } - - doc[FPSTR(HA_NAME)] = F("PID min temp"); - doc[FPSTR(HA_ICON)] = F("mdi:thermometer-chevron-down"); - doc[FPSTR(HA_STATE_TOPIC)] = this->settingsTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.pid.minTemp|float(0)|round(1) }}"); - doc[FPSTR(HA_COMMAND_TOPIC)] = this->setSettingsTopic.c_str(); - doc[FPSTR(HA_COMMAND_TEMPLATE)] = F("{\"pid\": {\"minTemp\" : {{ value }}}}"); - doc[FPSTR(HA_STEP)] = 1; - doc[FPSTR(HA_MODE)] = FPSTR(HA_MODE_BOX); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_NUMBER), F("pid_min_temp")).c_str(), doc); - } - - bool publishInputPidMaxTemp(UnitSystem unit = UnitSystem::METRIC, bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("pid_max_temp")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_NUMBER), F("pid_max_temp")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_CONFIG); - doc[FPSTR(HA_DEVICE_CLASS)] = FPSTR(S_TEMPERATURE); - - if (unit == UnitSystem::METRIC) { - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = FPSTR(HA_UNIT_OF_MEASUREMENT_C); - doc[FPSTR(HA_MIN)] = 1; - doc[FPSTR(HA_MAX)] = 100; - - } else if (unit == UnitSystem::IMPERIAL) { - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = FPSTR(HA_UNIT_OF_MEASUREMENT_F); - doc[FPSTR(HA_MIN)] = 1; - doc[FPSTR(HA_MAX)] = 212; - } - - doc[FPSTR(HA_NAME)] = F("PID max temp"); - doc[FPSTR(HA_ICON)] = F("mdi:thermometer-chevron-up"); - doc[FPSTR(HA_STATE_TOPIC)] = this->settingsTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.pid.maxTemp|float(0)|round(1) }}"); - doc[FPSTR(HA_COMMAND_TOPIC)] = this->setSettingsTopic.c_str(); - doc[FPSTR(HA_COMMAND_TEMPLATE)] = F("{\"pid\": {\"maxTemp\" : {{ value }}}}"); - doc[FPSTR(HA_STEP)] = 1; - doc[FPSTR(HA_MODE)] = FPSTR(HA_MODE_BOX); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_NUMBER), F("pid_max_temp")).c_str(), doc); - } - - - bool publishSwitchEquitherm(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("equitherm")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_SWITCH), F("equitherm")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_CONFIG); - doc[FPSTR(HA_NAME)] = F("Equitherm"); - doc[FPSTR(HA_ICON)] = F("mdi:sun-snowflake-variant"); - doc[FPSTR(HA_STATE_TOPIC)] = this->settingsTopic.c_str(); - doc[FPSTR(HA_STATE_ON)] = true; - doc[FPSTR(HA_STATE_OFF)] = false; - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.equitherm.enabled }}"); - doc[FPSTR(HA_COMMAND_TOPIC)] = this->setSettingsTopic.c_str(); - doc[FPSTR(HA_PAYLOAD_ON)] = F("{\"equitherm\": {\"enabled\" : true}}"); - doc[FPSTR(HA_PAYLOAD_OFF)] = F("{\"equitherm\": {\"enabled\" : false}}"); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_SWITCH), F("equitherm")).c_str(), doc); - } - - bool publishInputEquithermSlope(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("equitherm_slope")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_NUMBER), F("equitherm_slope")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_CONFIG); - doc[FPSTR(HA_NAME)] = F("Equitherm slope"); - doc[FPSTR(HA_ICON)] = F("mdi:slope-uphill"); - doc[FPSTR(HA_STATE_TOPIC)] = this->settingsTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.equitherm.slope|float(0)|round(3) }}"); - doc[FPSTR(HA_COMMAND_TOPIC)] = this->setSettingsTopic.c_str(); - doc[FPSTR(HA_COMMAND_TEMPLATE)] = F("{\"equitherm\": {\"slope\" : {{ value }}}}"); - doc[FPSTR(HA_MIN)] = 0.001f; - doc[FPSTR(HA_MAX)] = 10; - doc[FPSTR(HA_STEP)] = 0.001f; - doc[FPSTR(HA_MODE)] = FPSTR(HA_MODE_BOX); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_NUMBER), F("equitherm_slope")).c_str(), doc); - } - - bool publishInputEquithermExponent(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("equitherm_exponent")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_NUMBER), F("equitherm_exponent")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_CONFIG); - doc[FPSTR(HA_NAME)] = F("Equitherm exponent"); - doc[FPSTR(HA_ICON)] = F("mdi:exponent"); - doc[FPSTR(HA_STATE_TOPIC)] = this->settingsTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.equitherm.exponent|float(0)|round(3) }}"); - doc[FPSTR(HA_COMMAND_TOPIC)] = this->setSettingsTopic.c_str(); - doc[FPSTR(HA_COMMAND_TEMPLATE)] = F("{\"equitherm\": {\"exponent\" : {{ value }}}}"); - doc[FPSTR(HA_MIN)] = 0.1; - doc[FPSTR(HA_MAX)] = 2; - doc[FPSTR(HA_STEP)] = 0.001f; - doc[FPSTR(HA_MODE)] = FPSTR(HA_MODE_BOX); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_NUMBER), F("equitherm_exponent")).c_str(), doc); - } - - bool publishInputEquithermShift(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("equitherm_shift")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_NUMBER), F("equitherm_shift")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_CONFIG); - doc[FPSTR(HA_DEVICE_CLASS)] = FPSTR(S_TEMPERATURE); - doc[FPSTR(HA_NAME)] = F("Equitherm shift"); - doc[FPSTR(HA_ICON)] = F("mdi:chart-areaspline"); - doc[FPSTR(HA_STATE_TOPIC)] = this->settingsTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.equitherm.shift|float(0)|round(2) }}"); - doc[FPSTR(HA_COMMAND_TOPIC)] = this->setSettingsTopic.c_str(); - doc[FPSTR(HA_COMMAND_TEMPLATE)] = F("{\"equitherm\": {\"shift\" : {{ value }}}}"); - doc[FPSTR(HA_MIN)] = -15; - doc[FPSTR(HA_MAX)] = 15; - doc[FPSTR(HA_STEP)] = 0.01f; - doc[FPSTR(HA_MODE)] = FPSTR(HA_MODE_BOX); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_NUMBER), F("equitherm_shift")).c_str(), doc); - } - - bool publishInputEquithermTargetDiffFactor(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][0][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_AVAILABILITY)][1][FPSTR(HA_TOPIC)] = this->settingsTopic.c_str(); - doc[FPSTR(HA_AVAILABILITY)][1][FPSTR(HA_VALUE_TEMPLATE)] = F("{{ iif(value_json.pid.enabled, 'offline', 'online') }}"); - doc[FPSTR(HA_AVAILABILITY_MODE)] = F("all"); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("equitherm_target_diff_factor")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_NUMBER), F("equitherm_target_diff_factor")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_CONFIG); - doc[FPSTR(HA_NAME)] = F("Equitherm target diff factor"); - doc[FPSTR(HA_ICON)] = F("mdi:chart-timeline-variant-shimmer"); - doc[FPSTR(HA_STATE_TOPIC)] = this->settingsTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.equitherm.targetDiffFactor|float(0)|round(3) }}"); - doc[FPSTR(HA_COMMAND_TOPIC)] = this->setSettingsTopic.c_str(); - doc[FPSTR(HA_COMMAND_TEMPLATE)] = F("{\"equitherm\": {\"targetDiffFactor\" : {{ value }}}}"); - doc[FPSTR(HA_MIN)] = 0; - doc[FPSTR(HA_MAX)] = 10; - doc[FPSTR(HA_STEP)] = 0.001f; - doc[FPSTR(HA_MODE)] = FPSTR(HA_MODE_BOX); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_NUMBER), F("equitherm_target_diff_factor")).c_str(), doc); - } - - - bool publishStatusState(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("status")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_BINARY_SENSOR), F("status")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_DIAGNOSTIC); - doc[FPSTR(HA_DEVICE_CLASS)] = F("problem"); - doc[FPSTR(HA_NAME)] = F("Status"); - doc[FPSTR(HA_ICON)] = F("mdi:list-status"); - doc[FPSTR(HA_STATE_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ iif(value == 'online', 'OFF', 'ON') }}"); - doc[FPSTR(HA_EXPIRE_AFTER)] = 60; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_BINARY_SENSOR), F("status")).c_str(), doc); - } - - bool publishEmergencyState(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("emergency")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_BINARY_SENSOR), F("emergency")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_DIAGNOSTIC); - doc[FPSTR(HA_DEVICE_CLASS)] = F("problem"); - doc[FPSTR(HA_NAME)] = F("Emergency"); - doc[FPSTR(HA_ICON)] = F("mdi:alert-rhombus-outline"); - doc[FPSTR(HA_STATE_TOPIC)] = this->stateTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ iif(value_json.master.emergency.state, 'ON', 'OFF') }}"); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_BINARY_SENSOR), F("emergency")).c_str(), doc); - } - - bool publishOpenthermConnectedState(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("ot_status")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_BINARY_SENSOR), F("ot_status")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_DIAGNOSTIC); - doc[FPSTR(HA_DEVICE_CLASS)] = F("connectivity"); - doc[FPSTR(HA_NAME)] = F("Opentherm status"); - doc[FPSTR(HA_ICON)] = F("mdi:list-status"); - doc[FPSTR(HA_STATE_TOPIC)] = this->stateTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ iif(value_json.slave.connected, 'ON', 'OFF') }}"); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_BINARY_SENSOR), F("ot_status")).c_str(), doc); - } - - bool publishHeatingState(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][0][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_AVAILABILITY)][1][FPSTR(HA_TOPIC)] = this->stateTopic.c_str(); - doc[FPSTR(HA_AVAILABILITY)][1][FPSTR(HA_VALUE_TEMPLATE)] = JsonString(AVAILABILITY_OT_CONN, true); - doc[FPSTR(HA_AVAILABILITY_MODE)] = F("all"); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("heating")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_BINARY_SENSOR), F("heating")); - doc[FPSTR(HA_DEVICE_CLASS)] = F("running"); - doc[FPSTR(HA_NAME)] = F("Heating"); - doc[FPSTR(HA_ICON)] = F("mdi:radiator"); - doc[FPSTR(HA_STATE_TOPIC)] = this->stateTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ iif(value_json.slave.heating.active, 'ON', 'OFF') }}"); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_BINARY_SENSOR), F("heating")).c_str(), doc); - } - - bool publishDhwState(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][0][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_AVAILABILITY)][1][FPSTR(HA_TOPIC)] = this->stateTopic.c_str(); - doc[FPSTR(HA_AVAILABILITY)][1][FPSTR(HA_VALUE_TEMPLATE)] = JsonString(AVAILABILITY_OT_CONN, true); - doc[FPSTR(HA_AVAILABILITY_MODE)] = F("all"); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("dhw")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_BINARY_SENSOR), F("dhw")); - doc[FPSTR(HA_DEVICE_CLASS)] = F("running"); - doc[FPSTR(HA_NAME)] = F("DHW"); - doc[FPSTR(HA_ICON)] = F("mdi:faucet"); - doc[FPSTR(HA_STATE_TOPIC)] = this->stateTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ iif(value_json.slave.dhw.active, 'ON', 'OFF') }}"); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_BINARY_SENSOR), F("dhw")).c_str(), doc); - } - - bool publishFlameState(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][0][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_AVAILABILITY)][1][FPSTR(HA_TOPIC)] = this->stateTopic.c_str(); - doc[FPSTR(HA_AVAILABILITY)][1][FPSTR(HA_VALUE_TEMPLATE)] = JsonString(AVAILABILITY_OT_CONN, true); - doc[FPSTR(HA_AVAILABILITY_MODE)] = F("all"); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("flame")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_BINARY_SENSOR), F("flame")); - doc[FPSTR(HA_DEVICE_CLASS)] = F("running"); - doc[FPSTR(HA_NAME)] = F("Flame"); - doc[FPSTR(HA_ICON)] = F("mdi:gas-burner"); - doc[FPSTR(HA_STATE_TOPIC)] = this->stateTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ iif(value_json.slave.flame, 'ON', 'OFF') }}"); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_BINARY_SENSOR), F("flame")).c_str(), doc); - } - - bool publishFaultState(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][0][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_AVAILABILITY)][1][FPSTR(HA_TOPIC)] = this->stateTopic.c_str(); - doc[FPSTR(HA_AVAILABILITY)][1][FPSTR(HA_VALUE_TEMPLATE)] = JsonString(AVAILABILITY_OT_CONN, true); - doc[FPSTR(HA_AVAILABILITY_MODE)] = F("all"); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("fault")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_BINARY_SENSOR), F("fault")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_DIAGNOSTIC); - doc[FPSTR(HA_DEVICE_CLASS)] = F("problem"); - doc[FPSTR(HA_NAME)] = F("Fault"); - doc[FPSTR(HA_ICON)] = F("mdi:alert-remove-outline"); - doc[FPSTR(HA_STATE_TOPIC)] = this->stateTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ iif(value_json.slave.fault.active, 'ON', 'OFF') }}"); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_BINARY_SENSOR), F("fault")).c_str(), doc); - } - - bool publishDiagState(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][0][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_AVAILABILITY)][1][FPSTR(HA_TOPIC)] = this->stateTopic.c_str(); - doc[FPSTR(HA_AVAILABILITY)][1][FPSTR(HA_VALUE_TEMPLATE)] = JsonString(AVAILABILITY_OT_CONN, true); - doc[FPSTR(HA_AVAILABILITY_MODE)] = F("all"); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(FPSTR(HA_ENTITY_CATEGORY_DIAGNOSTIC)); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_BINARY_SENSOR), FPSTR(HA_ENTITY_CATEGORY_DIAGNOSTIC)); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_DIAGNOSTIC); - doc[FPSTR(HA_DEVICE_CLASS)] = F("problem"); - doc[FPSTR(HA_NAME)] = F("Diagnostic"); - doc[FPSTR(HA_ICON)] = F("mdi:account-wrench"); - doc[FPSTR(HA_STATE_TOPIC)] = this->stateTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ iif(value_json.slave.diag.active, 'ON', 'OFF') }}"); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_BINARY_SENSOR), FPSTR(HA_ENTITY_CATEGORY_DIAGNOSTIC)).c_str(), doc); - } - - bool publishExternalPumpState(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("ext_pump")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_BINARY_SENSOR), F("ext_pump")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_DIAGNOSTIC); - doc[FPSTR(HA_DEVICE_CLASS)] = F("running"); - doc[FPSTR(HA_NAME)] = F("External pump"); - doc[FPSTR(HA_ICON)] = F("mdi:pump"); - doc[FPSTR(HA_STATE_TOPIC)] = this->stateTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ iif(value_json.master.externalPump.state, 'ON', 'OFF') }}"); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_BINARY_SENSOR), F("ext_pump")).c_str(), doc); - } - - bool publishFaultCode(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][0][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_AVAILABILITY)][1][FPSTR(HA_TOPIC)] = this->stateTopic.c_str(); - doc[FPSTR(HA_AVAILABILITY)][1][FPSTR(HA_VALUE_TEMPLATE)] = F("{{ iif(value_json.slave.connected and value_json.slave.fault.active, 'online', 'offline') }}"); - doc[FPSTR(HA_AVAILABILITY_MODE)] = F("all"); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("fault_code")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_SENSOR), F("fault_code")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_DIAGNOSTIC); - doc[FPSTR(HA_NAME)] = F("Fault code"); - doc[FPSTR(HA_ICON)] = F("mdi:cog-box"); - doc[FPSTR(HA_STATE_TOPIC)] = this->stateTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ \"%02d (0x%02X)\"|format(value_json.slave.fault.code, value_json.slave.fault.code) }}"); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_SENSOR), F("fault_code")).c_str(), doc); - } - - bool publishDiagCode(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][0][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_AVAILABILITY)][1][FPSTR(HA_TOPIC)] = this->stateTopic.c_str(); - doc[FPSTR(HA_AVAILABILITY)][1][FPSTR(HA_VALUE_TEMPLATE)] = F("{{ iif(value_json.slave.connected and value_json.slave.fault.active or value_json.slave.diag.active, 'online', 'offline') }}"); - doc[FPSTR(HA_AVAILABILITY_MODE)] = F("all"); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("diagnostic_code")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_SENSOR), F("diagnostic_code")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_DIAGNOSTIC); - doc[FPSTR(HA_NAME)] = F("Diagnostic code"); - doc[FPSTR(HA_ICON)] = F("mdi:information-box"); - doc[FPSTR(HA_STATE_TOPIC)] = this->stateTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ \"%02d (0x%02X)\"|format(value_json.slave.diag.code, value_json.slave.diag.code) }}"); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_SENSOR), F("diagnostic_code")).c_str(), doc); - } - - bool publishNetworkRssi(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][0][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_AVAILABILITY)][1][FPSTR(HA_TOPIC)] = this->stateTopic.c_str(); - doc[FPSTR(HA_AVAILABILITY)][1][FPSTR(HA_VALUE_TEMPLATE)] = F("{{ iif(value_json.master.network.connectionType == 'wifi', 'online', 'offline') }}"); - doc[FPSTR(HA_AVAILABILITY_MODE)] = F("all"); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(FPSTR(S_RSSI)); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_SENSOR), FPSTR(S_RSSI)); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_DIAGNOSTIC); - doc[FPSTR(HA_DEVICE_CLASS)] = F("signal_strength"); - doc[FPSTR(HA_STATE_CLASS)] = FPSTR(HA_STATE_CLASS_MEASUREMENT); - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = F("dBm"); - doc[FPSTR(HA_NAME)] = F("RSSI"); - doc[FPSTR(HA_ICON)] = F("mdi:signal"); - doc[FPSTR(HA_STATE_TOPIC)] = this->stateTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.master.network.rssi|float(0)|round(1) }}"); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_SENSOR), FPSTR(S_RSSI)).c_str(), doc); - } - - bool publishUptime(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("uptime")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_SENSOR), F("uptime")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_DIAGNOSTIC); - doc[FPSTR(HA_DEVICE_CLASS)] = F("duration"); - doc[FPSTR(HA_STATE_CLASS)] = F("total_increasing"); - doc[FPSTR(HA_UNIT_OF_MEASUREMENT)] = F("s"); - doc[FPSTR(HA_NAME)] = F("Uptime"); - doc[FPSTR(HA_ICON)] = F("mdi:clock-start"); - doc[FPSTR(HA_STATE_TOPIC)] = this->stateTopic.c_str(); - doc[FPSTR(HA_VALUE_TEMPLATE)] = F("{{ value_json.master.uptime|int(0) }}"); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_SENSOR), F("uptime")).c_str(), doc); - } - - - bool publishClimateHeating(UnitSystem unit = UnitSystem::METRIC, uint8_t minTemp = 20, uint8_t maxTemp = 90, bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("heating")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_CLIMATE), F("heating")); - doc[FPSTR(HA_NAME)] = F("Heating"); - doc[FPSTR(HA_ICON)] = F("mdi:radiator"); - - doc[FPSTR(HA_CURRENT_TEMPERATURE_TOPIC)] = this->stateTopic.c_str(); - doc[FPSTR(HA_CURRENT_TEMPERATURE_TEMPLATE)] = F("{{ iif(value_json.master.heating.indoorTempControl, value_json.master.heating.indoorTemp, value_json.master.heating.currentTemp, 0)|float(0)|round(2) }}"); - - doc[FPSTR(HA_TEMPERATURE_COMMAND_TOPIC)] = this->setSettingsTopic.c_str(); - doc[FPSTR(HA_TEMPERATURE_COMMAND_TEMPLATE)] = F("{\"heating\": {\"target\" : {{ value }}}}"); - - doc[FPSTR(HA_TEMPERATURE_STATE_TOPIC)] = this->settingsTopic.c_str(); - doc[FPSTR(HA_TEMPERATURE_STATE_TEMPLATE)] = F("{{ value_json.heating.target|float(0)|round(1) }}"); - - if (unit == UnitSystem::METRIC) { - doc[FPSTR(HA_TEMPERATURE_UNIT)] = "C"; - - } else if (unit == UnitSystem::IMPERIAL) { - doc[FPSTR(HA_TEMPERATURE_UNIT)] = "F"; - } - - doc[FPSTR(HA_MODE_COMMAND_TOPIC)] = this->setSettingsTopic.c_str(); - doc[FPSTR(HA_MODE_COMMAND_TEMPLATE)] = F("{% if value == 'heat' %}{\"heating\": {\"enabled\" : true}}" - "{% elif value == 'off' %}{\"heating\": {\"enabled\" : false}}{% endif %}"); - doc[FPSTR(HA_MODE_STATE_TOPIC)] = this->settingsTopic.c_str(); - doc[FPSTR(HA_MODE_STATE_TEMPLATE)] = F("{{ iif(value_json.heating.enabled, 'heat', 'off') }}"); - doc[FPSTR(HA_MODES)][0] = F("off"); - doc[FPSTR(HA_MODES)][1] = F("heat"); - - doc[FPSTR(HA_ACTION_TOPIC)] = this->stateTopic.c_str(); - doc[FPSTR(HA_ACTION_TEMPLATE)] = F("{{ iif(value_json.slave.heating.active, 'heating', 'idle') }}"); - - doc[FPSTR(HA_PRESET_MODE_COMMAND_TOPIC)] = this->setSettingsTopic.c_str(); - doc[FPSTR(HA_PRESET_MODE_COMMAND_TEMPLATE)] = F("{% if value == 'boost' %}{\"heating\": {\"turbo\" : true}}" - "{% elif value == 'none' %}{\"heating\": {\"turbo\" : false}}{% endif %}"); - doc[FPSTR(HA_PRESET_MODE_STATE_TOPIC)] = this->settingsTopic.c_str(); - doc[FPSTR(HA_PRESET_MODE_VALUE_TEMPLATE)] = F("{{ iif(value_json.heating.turbo, 'boost', 'none') }}"); - doc[FPSTR(HA_PRESET_MODES)][0] = F("boost"); - - doc[FPSTR(HA_MIN_TEMP)] = minTemp; - doc[FPSTR(HA_MAX_TEMP)] = maxTemp; - doc[FPSTR(HA_TEMP_STEP)] = 0.1f; - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_CLIMATE), F("heating"), '_').c_str(), doc); - } - - bool publishClimateDhw(UnitSystem unit = UnitSystem::METRIC, uint8_t minTemp = 40, uint8_t maxTemp = 60, bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("dhw")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_CLIMATE), F("dhw")); - doc[FPSTR(HA_NAME)] = F("DHW"); - doc[FPSTR(HA_ICON)] = F("mdi:faucet"); - - doc[FPSTR(HA_CURRENT_TEMPERATURE_TOPIC)] = this->stateTopic.c_str(); - doc[FPSTR(HA_CURRENT_TEMPERATURE_TEMPLATE)] = F("{{ value_json.master.dhw.currentTemp|float(0)|round(1) }}"); - - doc[FPSTR(HA_TEMPERATURE_COMMAND_TOPIC)] = this->setSettingsTopic.c_str(); - doc[FPSTR(HA_TEMPERATURE_COMMAND_TEMPLATE)] = F("{\"dhw\": {\"target\" : {{ value|int(0) }}}}"); - - doc[FPSTR(HA_TEMPERATURE_STATE_TOPIC)] = this->settingsTopic.c_str(); - doc[FPSTR(HA_TEMPERATURE_STATE_TEMPLATE)] = F("{{ value_json.dhw.target|float(0)|round(1) }}"); - - if (unit == UnitSystem::METRIC) { - doc[FPSTR(HA_TEMPERATURE_UNIT)] = "C"; - - } else if (unit == UnitSystem::IMPERIAL) { - doc[FPSTR(HA_TEMPERATURE_UNIT)] = "F"; - } - - doc[FPSTR(HA_MODE_COMMAND_TOPIC)] = this->setSettingsTopic.c_str(); - doc[FPSTR(HA_MODE_COMMAND_TEMPLATE)] = F("{% if value == 'heat' %}{\"dhw\": {\"enabled\" : true}}" - "{% elif value == 'off' %}{\"dhw\": {\"enabled\" : false}}{% endif %}"); - doc[FPSTR(HA_MODE_STATE_TOPIC)] = this->settingsTopic.c_str(); - doc[FPSTR(HA_MODE_STATE_TEMPLATE)] = F("{{ iif(value_json.dhw.enabled, 'heat', 'off') }}"); - doc[FPSTR(HA_MODES)][0] = F("off"); - doc[FPSTR(HA_MODES)][1] = F("heat"); - - doc[FPSTR(HA_ACTION_TOPIC)] = this->stateTopic.c_str(); - doc[FPSTR(HA_ACTION_TEMPLATE)] = F("{{ iif(value_json.slave.dhw.active, 'heating', 'idle') }}"); - - doc[FPSTR(HA_MIN_TEMP)] = minTemp; - doc[FPSTR(HA_MAX_TEMP)] = maxTemp; - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_CLIMATE), F("dhw"), '_').c_str(), doc); - } - - - bool publishRestartButton(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(FPSTR(S_RESTART)); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_BUTTON), FPSTR(S_RESTART)); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_CONFIG); - doc[FPSTR(HA_DEVICE_CLASS)] = FPSTR(S_RESTART); - doc[FPSTR(HA_NAME)] = F("Restart"); - doc[FPSTR(HA_COMMAND_TOPIC)] = this->setStateTopic.c_str(); - doc[FPSTR(HA_COMMAND_TEMPLATE)] = F("{\"actions\": {\"restart\": true}}"); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_BUTTON), FPSTR(S_RESTART)).c_str(), doc); - } - - bool publishResetFaultButton(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][0][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_AVAILABILITY)][1][FPSTR(HA_TOPIC)] = this->stateTopic.c_str(); - doc[FPSTR(HA_AVAILABILITY)][1][FPSTR(HA_VALUE_TEMPLATE)] = F("{{ iif(value_json.slave.fault.active, 'online', 'offline') }}"); - doc[FPSTR(HA_AVAILABILITY_MODE)] = F("all"); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("reset_fault")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_BUTTON), F("reset_fault")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_CONFIG); - doc[FPSTR(HA_DEVICE_CLASS)] = FPSTR(S_RESTART); - doc[FPSTR(HA_NAME)] = F("Reset fault"); - doc[FPSTR(HA_COMMAND_TOPIC)] = this->setStateTopic.c_str(); - doc[FPSTR(HA_COMMAND_TEMPLATE)] = F("{\"actions\": {\"resetFault\": true}}"); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_BUTTON), F("reset_fault")).c_str(), doc); - } - - bool publishResetDiagButton(bool enabledByDefault = true) { - JsonDocument doc; - doc[FPSTR(HA_AVAILABILITY)][0][FPSTR(HA_TOPIC)] = this->statusTopic.c_str(); - doc[FPSTR(HA_AVAILABILITY)][1][FPSTR(HA_TOPIC)] = this->stateTopic.c_str(); - doc[FPSTR(HA_AVAILABILITY)][1][FPSTR(HA_VALUE_TEMPLATE)] = F("{{ iif(value_json.slave.diag.active, 'online', 'offline') }}"); - doc[FPSTR(HA_AVAILABILITY_MODE)] = F("all"); - doc[FPSTR(HA_ENABLED_BY_DEFAULT)] = enabledByDefault; - doc[FPSTR(HA_UNIQUE_ID)] = this->getUniqueIdWithPrefix(F("reset_diagnostic")); - doc[FPSTR(HA_DEFAULT_ENTITY_ID)] = this->getEntityIdWithPrefix(FPSTR(HA_ENTITY_BUTTON), F("reset_diagnostic")); - doc[FPSTR(HA_ENTITY_CATEGORY)] = FPSTR(HA_ENTITY_CATEGORY_CONFIG); - doc[FPSTR(HA_DEVICE_CLASS)] = FPSTR(S_RESTART); - doc[FPSTR(HA_NAME)] = F("Reset diagnostic"); - doc[FPSTR(HA_COMMAND_TOPIC)] = this->setStateTopic.c_str(); - doc[FPSTR(HA_COMMAND_TEMPLATE)] = F("{\"actions\": {\"resetDiagnostic\": true}}"); - doc[FPSTR(HA_EXPIRE_AFTER)] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_BUTTON), F("reset_diagnostic")).c_str(), doc); - } - - - template - bool deleteEntities(CT category) { - return this->publish(this->makeConfigTopic(category).c_str()); - } - - bool deleteSwitchDhw() { - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_SWITCH), F("dhw")).c_str()); - } - - bool deleteInputDhwMinTemp() { - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_NUMBER), F("dhw_min_temp")).c_str()); - } - - bool deleteInputDhwMaxTemp() { - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_NUMBER), F("dhw_max_temp")).c_str()); - } - - bool deleteDhwState() { - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_BINARY_SENSOR), F("dhw")).c_str()); - } - - bool deleteInputDhwTarget() { - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_NUMBER), F("dhw_target")).c_str()); - } - - bool deleteClimateDhw() { - return this->publish(this->makeConfigTopic(FPSTR(HA_ENTITY_CLIMATE), F("dhw"), '_').c_str()); - } - - protected: - unsigned short expireAfter = 300u; - String statusTopic, stateTopic, setStateTopic, settingsTopic, setSettingsTopic; -}; - -const char HaHelper::AVAILABILITY_OT_CONN[] = "{{ iif(value_json.slave.connected, 'online', 'offline') }}"; -const char HaHelper::AVAILABILITY_SENSOR_CONN[] = "{{ iif(value_json.connected, 'online', 'offline') }}"; \ No newline at end of file diff --git a/src/MainTask.h b/src/MainTask.h deleted file mode 100644 index 44fde67..0000000 --- a/src/MainTask.h +++ /dev/null @@ -1,729 +0,0 @@ -#include - -using namespace NetworkUtils; - -extern NetworkMgr* network; -extern MqttTask* tMqtt; -extern OpenThermTask* tOt; -extern FileData fsNetworkSettings, fsSettings, fsSensorsSettings; -extern ESPTelnetStream* telnetStream; - - -class MainTask : public Task { -public: - MainTask(bool _enabled = false, unsigned long _interval = 0) : Task(_enabled, _interval) { - this->blinker = new Blinker(); - - network->setDelayCallback([this](unsigned int time) { - this->delay(time); - })->setYieldCallback([this]() { - this->yield(); - }); - } - - ~MainTask() { - delete this->blinker; - } - -protected: - enum class PumpStartReason {NONE, HEATING, ANTISTUCK}; - - Blinker* blinker = nullptr; - unsigned long miscRunned = 0; - unsigned long lastHeapInfo = 0; - unsigned int minFreeHeap = 0; - unsigned int minMaxFreeBlockHeap = 0; - bool restartSignalReceived = false; - unsigned long restartSignalReceivedTime = 0; - bool heatingEnabled = false; - unsigned long heatingDisabledTime = 0; - PumpStartReason extPumpStartReason = PumpStartReason::NONE; - unsigned long externalPumpStartTime = 0; - bool ntpStarted = false; - bool telnetStarted = false; - bool emergencyDetected = false; - unsigned long emergencyFlipTime = 0; - - #if defined(ARDUINO_ARCH_ESP32) - const char* getTaskName() override { - return "Main"; - } - - /*BaseType_t getTaskCore() override { - return 1; - }*/ - - int getTaskPriority() override { - return 3; - } - #endif - - void setup() {} - - void loop() { - network->loop(); - - if (fsNetworkSettings.tick() == FD_WRITE) { - Log.sinfoln(FPSTR(L_NETWORK_SETTINGS), F("Updated")); - } - - if (fsSettings.tick() == FD_WRITE) { - Log.sinfoln(FPSTR(L_SETTINGS), F("Updated")); - } - - if (fsSensorsSettings.tick() == FD_WRITE) { - Log.sinfoln(FPSTR(L_SENSORS_SETTINGS), F("Updated")); - } - - if (vars.actions.restart) { - this->restartSignalReceivedTime = millis(); - this->restartSignalReceived = true; - vars.actions.restart = false; - - Log.sinfoln(FPSTR(L_MAIN), F("Received restart signal")); - } - - if (!vars.states.restarting && this->restartSignalReceived && millis() - this->restartSignalReceivedTime > 5000) { - vars.states.restarting = true; - - // save settings - fsSettings.updateNow(); - - // save sensors settings - fsSensorsSettings.updateNow(); - - // force save network settings - if (fsNetworkSettings.updateNow() == FD_FILE_ERR && LittleFS.begin()) { - fsNetworkSettings.write(); - } - - Log.sinfoln(FPSTR(L_MAIN), F("Restart scheduled in 10 sec.")); - } - - vars.mqtt.connected = tMqtt->isConnected(); - vars.network.connected = network->isConnected(); - vars.network.rssi = network->getRssi(); - vars.network.connectionType = network->getUplink(); - - if (settings.system.logLevel >= TinyLogger::Level::SILENT && settings.system.logLevel <= TinyLogger::Level::VERBOSE) { - if (Log.getLevel() != settings.system.logLevel) { - Log.setLevel(static_cast(settings.system.logLevel)); - } - } - - if (network->isConnected()) { - if (!this->ntpStarted) { - if (strlen(settings.system.ntp.server)) { - configTime(0, 0, settings.system.ntp.server); - setenv("TZ", settings.system.ntp.timezone, 1); - tzset(); - - this->ntpStarted = true; - } - } - - if (!this->telnetStarted && telnetStream != nullptr) { - telnetStream->begin(23, false); - this->telnetStarted = true; - } - - if (settings.mqtt.enabled && !tMqtt->isEnabled()) { - tMqtt->enable(); - - } else if (!settings.mqtt.enabled && tMqtt->isEnabled()) { - tMqtt->disable(); - } - - } else { - if (this->ntpStarted) { - this->ntpStarted = false; - } - - if (this->telnetStarted) { - telnetStream->stop(); - this->telnetStarted = false; - } - - if (tMqtt->isEnabled()) { - tMqtt->disable(); - } - - Sensors::setConnectionStatusByType(Sensors::Type::MANUAL, false, false); - } - - this->yield(); - if (this->misc()) { - this->yield(); - } - this->ledStatus(); - - // telnet - if (this->telnetStarted) { - this->yield(); - telnetStream->loop(); - this->yield(); - } - - - // anti memory leak - for (Stream* stream : Log.getStreams()) { - while (stream->available() > 0) { - stream->read(); - - #ifdef ARDUINO_ARCH_ESP8266 - ::optimistic_yield(1000); - #endif - } - } - - // heap info - this->heap(); - } - - bool misc() { - if (millis() - this->miscRunned < 1000) { - return false; - } - - // restart if required - if (this->restartSignalReceived && millis() - this->restartSignalReceivedTime > 15000) { - this->restartSignalReceived = false; - - ESP.restart(); - } - - this->heating(); - this->emergency(); - this->cascadeControl(); - this->externalPump(); - this->miscRunned = millis(); - - return true; - } - - void heap() { - unsigned int freeHeap = getFreeHeap(); - unsigned int maxFreeBlockHeap = getMaxFreeBlockHeap(); - - // critical heap - if (!vars.states.restarting && (freeHeap < 2048 || maxFreeBlockHeap < 2048)) { - this->restartSignalReceivedTime = millis(); - this->restartSignalReceived = true; - vars.states.restarting = true; - } - - if (settings.system.logLevel < TinyLogger::Level::VERBOSE) { - return; - } - - size_t minFreeHeap = getFreeHeap(true); - size_t minFreeHeapDiff = 0; - if (minFreeHeap < this->minFreeHeap || this->minFreeHeap == 0) { - minFreeHeapDiff = this->minFreeHeap - minFreeHeap; - this->minFreeHeap = minFreeHeap; - } - - size_t minMaxFreeBlockHeap = getMaxFreeBlockHeap(true); - size_t minMaxFreeBlockHeapDiff = 0; - if (minMaxFreeBlockHeap < this->minMaxFreeBlockHeap || this->minMaxFreeBlockHeap == 0) { - minMaxFreeBlockHeapDiff = this->minMaxFreeBlockHeap - minMaxFreeBlockHeap; - this->minMaxFreeBlockHeap = minMaxFreeBlockHeap; - } - - if (millis() - this->lastHeapInfo > 20000 || minFreeHeapDiff > 0 || minMaxFreeBlockHeapDiff > 0) { - Log.sverboseln( - FPSTR(L_MAIN), - F("Free heap size: %u of %u bytes (min: %u, diff: %u), max free block: %u (min: %u, diff: %u, frag: %hhu%%)"), - freeHeap, getTotalHeap(), this->minFreeHeap, minFreeHeapDiff, maxFreeBlockHeap, this->minMaxFreeBlockHeap, minMaxFreeBlockHeapDiff, getHeapFrag() - ); - this->lastHeapInfo = millis(); - } - } - - void heating() { - // freeze protection - { - float lowTemp = 255.0f; - uint8_t availableSensors = 0; - - if (Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::INDOOR_TEMP)) { - auto value = Sensors::getMeanValueByPurpose(Sensors::Purpose::INDOOR_TEMP, Sensors::ValueType::PRIMARY); - if (value < lowTemp) { - lowTemp = value; - } - - availableSensors++; - } - - if (Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::HEATING_TEMP)) { - auto value = Sensors::getMeanValueByPurpose(Sensors::Purpose::HEATING_TEMP, Sensors::ValueType::PRIMARY); - if (value < lowTemp) { - lowTemp = value; - } - - availableSensors++; - } - - if (Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::HEATING_RETURN_TEMP)) { - auto value = Sensors::getMeanValueByPurpose(Sensors::Purpose::HEATING_RETURN_TEMP, Sensors::ValueType::PRIMARY); - if (value < lowTemp) { - lowTemp = value; - } - - availableSensors++; - } - - if (availableSensors) { - if (vars.master.heating.freezing) { - if (lowTemp - (float) settings.heating.freezeProtection.highTemp + 0.0001f >= 0.0f) { - vars.master.heating.freezing = false; - - Log.sinfoln( - FPSTR(L_MAIN), - F("No freezing detected. Current low temp: %.2f, threshold (high): %hhu"), - lowTemp, settings.heating.freezeProtection.highTemp - ); - } - - } else { - if ((float) settings.heating.freezeProtection.lowTemp - lowTemp + 0.0001f >= 0.0f) { - vars.master.heating.freezing = true; - - if (!settings.heating.enabled) { - settings.heating.enabled = true; - fsSettings.update(); - } - - Log.sinfoln( - FPSTR(L_MAIN), - F("Freezing detected! Current low temp: %.2f, threshold (low): %hhu"), - lowTemp, settings.heating.freezeProtection.lowTemp - ); - } - } - - } else if (vars.master.heating.freezing) { - vars.master.heating.freezing = false; - - Log.sinfoln(FPSTR(L_MAIN), F("No sensors available, freeze protection unavailable!")); - } - } - } - - void emergency() { - // flags - uint8_t emergencyFlags = 0b00000000; - - // set outdoor sensor flag - if (settings.equitherm.enabled) { - if (!Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::OUTDOOR_TEMP)) { - emergencyFlags |= 0b00000001; - } - } - - // set indoor sensor flags - if (!Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::INDOOR_TEMP)) { - if (!settings.equitherm.enabled && settings.pid.enabled) { - emergencyFlags |= 0b00000010; - } - - if (settings.opentherm.options.nativeOTC) { - emergencyFlags |= 0b00000100; - } - } - - // if any flags is true - if ((emergencyFlags & 0b00001111) != 0) { - if (!this->emergencyDetected) { - // flip flag - this->emergencyDetected = true; - this->emergencyFlipTime = millis(); - - } else if (this->emergencyDetected && !vars.emergency.state) { - // enable emergency - if (millis() - this->emergencyFlipTime > (settings.emergency.tresholdTime * 1000)) { - vars.emergency.state = true; - Log.sinfoln(FPSTR(L_MAIN), F("Emergency mode enabled (%hhu)"), emergencyFlags); - } - } - - } else { - if (this->emergencyDetected) { - // flip flag - this->emergencyDetected = false; - this->emergencyFlipTime = millis(); - - } else if (!this->emergencyDetected && vars.emergency.state) { - // disable emergency - if (millis() - this->emergencyFlipTime > (settings.emergency.tresholdTime * 1000)) { - vars.emergency.state = false; - Log.sinfoln(FPSTR(L_MAIN), F("Emergency mode disabled")); - } - } - } - } - - void ledStatus() { - uint8_t errors[4]; - uint8_t errCount = 0; - static uint8_t errPos = 0; - static unsigned long endBlinkTime = 0; - static bool ledOn = false; - static uint8_t configuredGpio = GPIO_IS_NOT_CONFIGURED; - - if (settings.system.statusLedGpio != configuredGpio) { - if (configuredGpio != GPIO_IS_NOT_CONFIGURED) { - digitalWrite(configuredGpio, LOW); - } - - if (GPIO_IS_VALID(settings.system.statusLedGpio)) { - configuredGpio = settings.system.statusLedGpio; - pinMode(configuredGpio, OUTPUT); - digitalWrite(configuredGpio, LOW); - this->blinker->init(configuredGpio); - - } else if (configuredGpio != GPIO_IS_NOT_CONFIGURED) { - configuredGpio = GPIO_IS_NOT_CONFIGURED; - } - } - - if (configuredGpio == GPIO_IS_NOT_CONFIGURED) { - return; - } - - if (!network->isConnected()) { - errors[errCount++] = 2; - } - - if (!vars.slave.connected) { - errors[errCount++] = 3; - } - - if (vars.slave.fault.active) { - errors[errCount++] = 4; - } - - if (vars.emergency.state) { - errors[errCount++] = 5; - } - - - if (this->blinker->ready()) { - endBlinkTime = millis(); - } - - if (!this->blinker->running() && millis() - endBlinkTime >= 5000) { - if (errCount == 0) { - if (!ledOn) { - digitalWrite(configuredGpio, HIGH); - ledOn = true; - } - - return; - - } else if (ledOn) { - digitalWrite(configuredGpio, LOW); - ledOn = false; - endBlinkTime = millis(); - return; - } - - if (errPos >= errCount) { - errPos = 0; - - // end of error list - this->blinker->blink(10, 50, 50); - - } else { - this->blinker->blink(errors[errPos++], 300, 300); - } - } - - this->blinker->tick(); - } - - void cascadeControl() { - static uint8_t configuredInputGpio = GPIO_IS_NOT_CONFIGURED; - static uint8_t configuredOutputGpio = GPIO_IS_NOT_CONFIGURED; - static bool inputTempValue = false; - static unsigned long inputChangedTs = 0; - static bool outputTempValue = false; - static unsigned long outputChangedTs = 0; - - // input - if (settings.cascadeControl.input.enabled) { - if (settings.cascadeControl.input.gpio != configuredInputGpio) { - if (configuredInputGpio != GPIO_IS_NOT_CONFIGURED) { - pinMode(configuredInputGpio, OUTPUT); - digitalWrite(configuredInputGpio, LOW); - - Log.sinfoln(FPSTR(L_CASCADE_INPUT), F("Deinitialized on GPIO %hhu"), configuredInputGpio); - } - - if (GPIO_IS_VALID(settings.cascadeControl.input.gpio)) { - configuredInputGpio = settings.cascadeControl.input.gpio; - pinMode(configuredInputGpio, INPUT); - - Log.sinfoln(FPSTR(L_CASCADE_INPUT), F("Initialized on GPIO %hhu"), configuredInputGpio); - - } else if (configuredInputGpio != GPIO_IS_NOT_CONFIGURED) { - configuredInputGpio = GPIO_IS_NOT_CONFIGURED; - - Log.swarningln(FPSTR(L_CASCADE_INPUT), F("Failed initialize: GPIO %hhu is not valid!"), configuredInputGpio); - } - } - - if (configuredInputGpio != GPIO_IS_NOT_CONFIGURED) { - bool value; - if (digitalRead(configuredInputGpio) == HIGH) { - value = true ^ settings.cascadeControl.input.invertState; - } else { - value = false ^ settings.cascadeControl.input.invertState; - } - - if (value != vars.cascadeControl.input) { - if (value != inputTempValue) { - inputTempValue = value; - inputChangedTs = millis(); - - } else if (millis() - inputChangedTs >= settings.cascadeControl.input.thresholdTime * 1000u) { - vars.cascadeControl.input = value; - - Log.sinfoln( - FPSTR(L_CASCADE_INPUT), - F("State changed to %s"), - value ? F("TRUE") : F("FALSE") - ); - } - - } else if (value != inputTempValue) { - inputTempValue = value; - } - } - } - - if (!settings.cascadeControl.input.enabled || configuredInputGpio == GPIO_IS_NOT_CONFIGURED) { - if (!vars.cascadeControl.input) { - vars.cascadeControl.input = true; - - Log.sinfoln( - FPSTR(L_CASCADE_INPUT), - F("Disabled, state changed to %s"), - vars.cascadeControl.input ? F("TRUE") : F("FALSE") - ); - } - } - - - // output - if (settings.cascadeControl.output.enabled) { - if (settings.cascadeControl.output.gpio != configuredOutputGpio) { - if (configuredOutputGpio != GPIO_IS_NOT_CONFIGURED) { - pinMode(configuredOutputGpio, OUTPUT); - digitalWrite(configuredOutputGpio, LOW); - - Log.sinfoln(FPSTR(L_CASCADE_OUTPUT), F("Deinitialized on GPIO %hhu"), configuredOutputGpio); - } - - if (GPIO_IS_VALID(settings.cascadeControl.output.gpio)) { - configuredOutputGpio = settings.cascadeControl.output.gpio; - pinMode(configuredOutputGpio, OUTPUT); - digitalWrite( - configuredOutputGpio, - settings.cascadeControl.output.invertState - ? HIGH - : LOW - ); - - Log.sinfoln(FPSTR(L_CASCADE_OUTPUT), F("Initialized on GPIO %hhu"), configuredOutputGpio); - - } else if (configuredOutputGpio != GPIO_IS_NOT_CONFIGURED) { - configuredOutputGpio = GPIO_IS_NOT_CONFIGURED; - - Log.swarningln(FPSTR(L_CASCADE_OUTPUT), F("Failed initialize: GPIO %hhu is not valid!"), configuredOutputGpio); - } - } - - if (configuredOutputGpio != GPIO_IS_NOT_CONFIGURED) { - bool value = false; - if (settings.cascadeControl.output.onFault && vars.slave.fault.active) { - value = true; - - } else if (settings.cascadeControl.output.onLossConnection && !vars.slave.connected) { - value = true; - - } else if (settings.cascadeControl.output.onEnabledHeating && settings.heating.enabled && vars.cascadeControl.input) { - value = true; - } - - if (value != vars.cascadeControl.output) { - if (value != outputTempValue) { - outputTempValue = value; - outputChangedTs = millis(); - - } else if (millis() - outputChangedTs >= settings.cascadeControl.output.thresholdTime * 1000u) { - vars.cascadeControl.output = value; - - digitalWrite( - configuredOutputGpio, - vars.cascadeControl.output ^ settings.cascadeControl.output.invertState - ? HIGH - : LOW - ); - - Log.sinfoln( - FPSTR(L_CASCADE_OUTPUT), - F("State changed to %s"), - value ? F("TRUE") : F("FALSE") - ); - } - - } else if (value != outputTempValue) { - outputTempValue = value; - } - } - } - - if (!settings.cascadeControl.output.enabled || configuredOutputGpio == GPIO_IS_NOT_CONFIGURED) { - if (vars.cascadeControl.output) { - vars.cascadeControl.output = false; - - if (configuredOutputGpio != GPIO_IS_NOT_CONFIGURED) { - digitalWrite( - configuredOutputGpio, - vars.cascadeControl.output ^ settings.cascadeControl.output.invertState - ? HIGH - : LOW - ); - } - - Log.sinfoln( - FPSTR(L_CASCADE_OUTPUT), - F("Disabled, state changed to %s"), - vars.cascadeControl.output ? F("TRUE") : F("FALSE") - ); - } - } - } - - void externalPump() { - static uint8_t configuredGpio = GPIO_IS_NOT_CONFIGURED; - - if (settings.externalPump.gpio != configuredGpio) { - if (configuredGpio != GPIO_IS_NOT_CONFIGURED) { - digitalWrite(configuredGpio, LOW); - } - - if (GPIO_IS_VALID(settings.externalPump.gpio)) { - configuredGpio = settings.externalPump.gpio; - pinMode(configuredGpio, OUTPUT); - digitalWrite( - configuredGpio, - settings.externalPump.invertState - ? HIGH - : LOW - ); - - } else if (configuredGpio != GPIO_IS_NOT_CONFIGURED) { - configuredGpio = GPIO_IS_NOT_CONFIGURED; - } - } - - if (configuredGpio == GPIO_IS_NOT_CONFIGURED) { - if (vars.externalPump.state) { - vars.externalPump.state = false; - vars.externalPump.lastEnabledTime = millis(); - - Log.sinfoln(FPSTR(L_EXTPUMP), F("Disabled: use = off")); - } - - return; - } - - if (!vars.master.heating.enabled && this->heatingEnabled) { - this->heatingEnabled = false; - this->heatingDisabledTime = millis(); - - } else if (vars.master.heating.enabled && !this->heatingEnabled) { - this->heatingEnabled = true; - } - - if (!settings.externalPump.use) { - if (vars.externalPump.state) { - digitalWrite( - configuredGpio, - settings.externalPump.invertState - ? HIGH - : LOW - ); - - vars.externalPump.state = false; - vars.externalPump.lastEnabledTime = millis(); - - Log.sinfoln(FPSTR(L_EXTPUMP), F("Disabled: use = off")); - } - - return; - } - - if (vars.externalPump.state && !this->heatingEnabled) { - if (this->extPumpStartReason == MainTask::PumpStartReason::HEATING && millis() - this->heatingDisabledTime > (settings.externalPump.postCirculationTime * 1000u)) { - digitalWrite( - configuredGpio, - settings.externalPump.invertState - ? HIGH - : LOW - ); - - vars.externalPump.state = false; - vars.externalPump.lastEnabledTime = millis(); - - Log.sinfoln(FPSTR(L_EXTPUMP), F("Disabled: expired post circulation time")); - - } else if (this->extPumpStartReason == MainTask::PumpStartReason::ANTISTUCK && millis() - this->externalPumpStartTime >= (settings.externalPump.antiStuckTime * 1000u)) { - digitalWrite( - configuredGpio, - settings.externalPump.invertState - ? HIGH - : LOW - ); - - vars.externalPump.state = false; - vars.externalPump.lastEnabledTime = millis(); - - Log.sinfoln(FPSTR(L_EXTPUMP), F("Disabled: expired anti stuck time")); - } - - } else if (vars.externalPump.state && this->heatingEnabled && this->extPumpStartReason == MainTask::PumpStartReason::ANTISTUCK) { - this->extPumpStartReason = MainTask::PumpStartReason::HEATING; - - } else if (!vars.externalPump.state && this->heatingEnabled) { - vars.externalPump.state = true; - this->externalPumpStartTime = millis(); - this->extPumpStartReason = MainTask::PumpStartReason::HEATING; - - digitalWrite( - configuredGpio, - settings.externalPump.invertState - ? LOW - : HIGH - ); - - Log.sinfoln(FPSTR(L_EXTPUMP), F("Enabled: heating on")); - - } else if (!vars.externalPump.state && (vars.externalPump.lastEnabledTime == 0 || millis() - vars.externalPump.lastEnabledTime >= (settings.externalPump.antiStuckInterval * 1000lu))) { - vars.externalPump.state = true; - this->externalPumpStartTime = millis(); - this->extPumpStartReason = MainTask::PumpStartReason::ANTISTUCK; - - digitalWrite( - configuredGpio, - settings.externalPump.invertState - ? LOW - : HIGH - ); - - Log.sinfoln(FPSTR(L_EXTPUMP), F("Enabled: anti stuck")); - } - } -}; \ No newline at end of file diff --git a/src/MqttTask.h b/src/MqttTask.h deleted file mode 100644 index b9f6132..0000000 --- a/src/MqttTask.h +++ /dev/null @@ -1,651 +0,0 @@ -#include -#include -#include -#include -#include "HaHelper.h" - -extern FileData fsSettings; - -class MqttTask : public Task { -public: - MqttTask(bool _enabled = false, unsigned long _interval = 0) : Task(_enabled, _interval) { - this->wifiClient = new MqttWiFiClient(); - this->client = new MqttClient(this->wifiClient); - this->writer = new MqttWriter(this->client, 256); - this->haHelper = new HaHelper(); - } - - ~MqttTask() { - delete this->haHelper; - - if (this->client != nullptr) { - if (this->client->connected()) { - this->client->stop(); - - if (this->connected) { - this->onDisconnect(); - this->connected = false; - } - } - - delete this->client; - } - - delete this->writer; - delete this->wifiClient; - } - - void disable() { - this->client->stop(); - - if (this->connected) { - this->onDisconnect(); - this->connected = false; - } - - Task::disable(); - - Log.sinfoln(FPSTR(L_MQTT), F("Disabled")); - } - - void enable() { - Task::enable(); - - Log.sinfoln(FPSTR(L_MQTT), F("Enabled")); - } - - inline bool isConnected() { - return this->connected; - } - - inline void resetPublishedSettingsTime() { - this->prevPubSettingsTime = 0; - } - - inline void resetPublishedSensorTime(uint8_t sensorId) { - this->prevPubSensorTime[sensorId] = 0; - } - - inline void resetPublishedVarsTime() { - this->prevPubVarsTime = 0; - } - - inline void reconfigureSensor(uint8_t sensorId, Sensors::Settings& prevSettings) { - this->queueReconfigureSensors[sensorId] = prevSettings; - } - -protected: - MqttWiFiClient* wifiClient = nullptr; - MqttClient* client = nullptr; - HaHelper* haHelper = nullptr; - MqttWriter* writer = nullptr; - UnitSystem currentUnitSystem = UnitSystem::METRIC; - bool currentHomeAssistantDiscovery = false; - std::unordered_map queueReconfigureSensors; - unsigned short readyForSendTime = 30000; - unsigned long lastReconnectTime = 0; - unsigned long connectedTime = 0; - unsigned long disconnectedTime = 0; - unsigned long prevPubVarsTime = 0; - unsigned long prevPubSettingsTime = 0; - std::unordered_map prevPubSensorTime; - bool connected = false; - bool newConnection = false; - - #if defined(ARDUINO_ARCH_ESP32) - const char* getTaskName() override { - return "Mqtt"; - } - - /*BaseType_t getTaskCore() override { - return 1; - }*/ - - int getTaskPriority() override { - return 2; - } - #endif - - inline bool isReadyForSend() { - return millis() - this->connectedTime > this->readyForSendTime; - } - - void setup() { - Log.sinfoln(FPSTR(L_MQTT), F("Started")); - - // wificlient settings - #ifdef ARDUINO_ARCH_ESP8266 - this->wifiClient->setSync(true); - this->wifiClient->setNoDelay(true); - #endif - - // client settings - this->client->setTxPayloadSize(256); - #ifdef ARDUINO_ARCH_ESP8266 - this->client->setConnectionTimeout(1000); - #else - this->client->setConnectionTimeout(3000); - #endif - - this->client->onMessage([this] (void*, size_t length) { - const String& topic = this->client->messageTopic(); - if (!length || length > 2048 || !topic.length()) { - return; - } - - uint8_t payload[length]; - for (size_t i = 0; i < length && this->client->available(); i++) { - payload[i] = this->client->read(); - } - - this->onMessage(topic, payload, length); - }); - - // writer settings - #ifdef ARDUINO_ARCH_ESP32 - this->writer->setYieldCallback([this] { - this->delay(10); - }); - #endif - - this->writer->setPublishEventCallback([this] (const char* topic, size_t written, size_t length, bool result) { - Log.straceln(FPSTR(L_MQTT), F("%s publish %u of %u bytes to topic: %s"), result ? F("Successfully") : F("Failed"), written, length, topic); - - #ifdef ARDUINO_ARCH_ESP8266 - ::optimistic_yield(1000); - #endif - - //this->client->poll(); - this->delay(250); - }); - - #ifdef ARDUINO_ARCH_ESP8266 - this->writer->setFlushEventCallback([this] (size_t, size_t) { - ::optimistic_yield(1000); - - if (this->wifiClient->connected()) { - this->wifiClient->flush(); - } - - ::optimistic_yield(1000); - }); - #endif - - // ha helper settings - this->haHelper->setDevicePrefix(settings.mqtt.prefix); - this->haHelper->setDeviceVersion(BUILD_VERSION); - this->haHelper->setDeviceModel(PROJECT_NAME); - this->haHelper->setDeviceName(PROJECT_NAME); - this->haHelper->setWriter(this->writer); - - sprintf(buffer, CONFIG_URL, WiFi.localIP().toString().c_str()); - this->haHelper->setDeviceConfigUrl(buffer); - } - - void loop() { - if (vars.states.restarting || vars.states.upgrading) { - return; - } - - if (this->connected && !this->client->connected()) { - this->connected = false; - this->onDisconnect(); - - } else if (!this->connected && millis() - this->lastReconnectTime >= MQTT_RECONNECT_INTERVAL) { - Log.sinfoln(FPSTR(L_MQTT), F("Connecting to %s:%u..."), settings.mqtt.server, settings.mqtt.port); - - this->haHelper->setDevicePrefix(settings.mqtt.prefix); - this->haHelper->updateCachedTopics(); - - this->client->stop(); - this->client->setKeepAliveInterval(settings.mqtt.interval * 10000); - this->client->setId(networkSettings.hostname); - this->client->setUsernamePassword(settings.mqtt.user, settings.mqtt.password); - this->client->beginWill(this->haHelper->getDeviceTopic(F("status")).c_str(), 7, true, 1); - this->client->print(F("offline")); - this->client->endWill(); - this->client->connect(settings.mqtt.server, settings.mqtt.port); - this->lastReconnectTime = millis(); - this->yield(); - - } else if (!this->connected && this->client->connected()) { - this->connected = true; - this->onConnect(); - } - - if (!this->connected) { - return; - } - - this->client->poll(); - - // delay for publish data - if (!this->isReadyForSend()) { - return; - } - - #ifdef ARDUINO_ARCH_ESP8266 - ::optimistic_yield(1000); - #endif - - // publish variables and status - if (this->newConnection || millis() - this->prevPubVarsTime > (settings.mqtt.interval * 1000u)) { - this->writer->publish(this->haHelper->getDeviceTopic(F("status")).c_str(), "online", false); - this->publishVariables(this->haHelper->getDeviceTopic(F("state")).c_str()); - this->prevPubVarsTime = millis(); - } - - // publish settings - if (this->newConnection || millis() - this->prevPubSettingsTime > (settings.mqtt.interval * 10000u)) { - this->publishSettings(this->haHelper->getDeviceTopic(F("settings")).c_str()); - this->prevPubSettingsTime = millis(); - } - - // publish sensors - for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { - if (!Sensors::hasEnabledAndValid(sensorId)) { - continue; - } - - auto& rSensor = Sensors::results[sensorId]; - bool needUpdate = false; - if (millis() - this->prevPubSensorTime[sensorId] > ((this->haHelper->getExpireAfter() - 10) * 1000u)) { - needUpdate = true; - - } else if (rSensor.activityTime >= this->prevPubSensorTime[sensorId]) { - auto estimated = rSensor.activityTime - this->prevPubSensorTime[sensorId]; - needUpdate = estimated > 1000u; - } - - if (this->newConnection || needUpdate) { - this->publishSensor(sensorId); - this->prevPubSensorTime[sensorId] = millis(); - } - } - - // publish ha entities if not published - if (settings.mqtt.homeAssistantDiscovery) { - if (this->newConnection || !this->currentHomeAssistantDiscovery || this->currentUnitSystem != settings.system.unitSystem) { - this->publishHaEntities(); - this->publishNonStaticHaEntities(true); - this->currentHomeAssistantDiscovery = true; - this->currentUnitSystem = settings.system.unitSystem; - - } else { - // publish non static ha entities - this->publishNonStaticHaEntities(); - } - - // rebuilding ha configs - for (auto& [sensorId, prevSettings] : this->queueReconfigureSensors) { - Log.sinfoln(FPSTR(L_MQTT_HA), F("Rebuilding config for sensor #%hhu '%s'"), sensorId, prevSettings.name); - - // delete old config - if (strlen(prevSettings.name) && prevSettings.enabled) { - switch (prevSettings.type) { - case Sensors::Type::BLUETOOTH: - this->haHelper->deleteConnectionDynamicSensor(prevSettings); - this->haHelper->deleteSignalQualityDynamicSensor(prevSettings); - this->haHelper->deleteDynamicSensor(prevSettings, Sensors::ValueType::TEMPERATURE); - this->haHelper->deleteDynamicSensor(prevSettings, Sensors::ValueType::HUMIDITY); - this->haHelper->deleteDynamicSensor(prevSettings, Sensors::ValueType::BATTERY); - this->haHelper->deleteDynamicSensor(prevSettings, Sensors::ValueType::RSSI); - break; - - case Sensors::Type::DALLAS_TEMP: - this->haHelper->deleteConnectionDynamicSensor(prevSettings); - this->haHelper->deleteSignalQualityDynamicSensor(prevSettings); - this->haHelper->deleteDynamicSensor(prevSettings, Sensors::ValueType::TEMPERATURE); - break; - - default: - this->haHelper->deleteDynamicSensor(prevSettings, Sensors::ValueType::PRIMARY); - } - } - - if (!Sensors::hasEnabledAndValid(sensorId)) { - continue; - } - - // make new config - auto& sSettings = Sensors::settings[sensorId]; - switch (sSettings.type) { - case Sensors::Type::BLUETOOTH: - this->haHelper->publishConnectionDynamicSensor(sSettings); - this->haHelper->publishSignalQualityDynamicSensor(sSettings, false); - this->haHelper->publishDynamicSensor(sSettings, Sensors::ValueType::TEMPERATURE, settings.system.unitSystem); - this->haHelper->publishDynamicSensor(sSettings, Sensors::ValueType::HUMIDITY, settings.system.unitSystem); - this->haHelper->publishDynamicSensor(sSettings, Sensors::ValueType::BATTERY, settings.system.unitSystem); - this->haHelper->publishDynamicSensor(sSettings, Sensors::ValueType::RSSI, settings.system.unitSystem, false); - break; - - case Sensors::Type::DALLAS_TEMP: - this->haHelper->publishConnectionDynamicSensor(sSettings); - this->haHelper->publishSignalQualityDynamicSensor(sSettings, false); - this->haHelper->publishDynamicSensor(sSettings, Sensors::ValueType::TEMPERATURE, settings.system.unitSystem); - break; - - default: - this->haHelper->publishDynamicSensor(sSettings, Sensors::ValueType::PRIMARY, settings.system.unitSystem); - } - } - - } else if (this->currentHomeAssistantDiscovery) { - this->currentHomeAssistantDiscovery = false; - } - - // reconfigure manual sensors - for (auto& [sensorId, prevSettings] : this->queueReconfigureSensors) { - // unsubscribe from old topic - if (strlen(prevSettings.name) && prevSettings.enabled) { - if (prevSettings.type == Sensors::Type::MANUAL) { - this->client->unsubscribe( - this->haHelper->getDeviceTopic( - F("sensors"), - Sensors::makeObjectId(prevSettings.name).c_str(), - F("set") - ).c_str() - ); - } - } - - if (!Sensors::hasEnabledAndValid(sensorId)) { - continue; - } - - // subscribe to new topic - auto& sSettings = Sensors::settings[sensorId]; - if (sSettings.type == Sensors::Type::MANUAL) { - this->client->subscribe( - this->haHelper->getDeviceTopic( - F("sensors"), - Sensors::makeObjectId(sSettings.name).c_str(), - F("set") - ).c_str() - ); - } - } - - // clear queue - this->queueReconfigureSensors.clear(); - - if (this->newConnection) { - this->newConnection = false; - } - } - - void onConnect() { - this->connectedTime = millis(); - this->newConnection = true; - unsigned long downtime = (millis() - this->disconnectedTime) / 1000; - Log.sinfoln(FPSTR(L_MQTT), F("Connected (downtime: %u s.)"), downtime); - - this->client->subscribe(this->haHelper->getDeviceTopic(F("settings/set")).c_str()); - this->client->subscribe(this->haHelper->getDeviceTopic(F("state/set")).c_str()); - - // subscribe to manual sensors - for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { - if (!Sensors::hasEnabledAndValid(sensorId)) { - continue; - } - - auto& sSettings = Sensors::settings[sensorId]; - if (sSettings.type != Sensors::Type::MANUAL) { - continue; - } - - this->client->subscribe( - this->haHelper->getDeviceTopic( - F("sensors"), - Sensors::makeObjectId(sSettings.name).c_str(), - F("set") - ).c_str() - ); - } - } - - void onDisconnect() { - this->disconnectedTime = millis(); - - unsigned long uptime = (millis() - this->connectedTime) / 1000; - Log.swarningln(FPSTR(L_MQTT), F("Disconnected (reason: %d uptime: %lu s.)"), this->client->connectError(), uptime); - } - - void onMessage(const String& topic, uint8_t* payload, size_t length) { - if (!length) { - return; - } - - if (settings.system.logLevel >= TinyLogger::Level::TRACE) { - Log.strace(FPSTR(L_MQTT_MSG), F("Topic: %s\r\n> "), topic.c_str()); - if (Log.lock()) { - for (size_t i = 0; i < length; i++) { - if (payload[i] == 0) { - break; - } else if (payload[i] == 13) { - continue; - } else if (payload[i] == 10) { - Log.print(F("\r\n> ")); - } else { - Log.print((char) payload[i]); - } - } - Log.print(F("\r\n\n")); - Log.flush(); - Log.unlock(); - } - } - - JsonDocument doc; - DeserializationError dErr = deserializeJson(doc, payload, length); - if (dErr != DeserializationError::Ok) { - Log.swarningln(FPSTR(L_MQTT_MSG), F("Error on deserialization: %s"), dErr.f_str()); - return; - - } else if (doc.isNull() || !doc.size()) { - Log.swarningln(FPSTR(L_MQTT_MSG), F("Not valid json")); - return; - } - doc.shrinkToFit(); - - // delete topic - this->writer->publish(topic.c_str(), nullptr, 0, true); - - if (this->haHelper->getDeviceTopic(F("state/set")).equals(topic)) { - if (jsonToVars(doc, vars)) { - this->resetPublishedVarsTime(); - } - - } else if (this->haHelper->getDeviceTopic(F("settings/set")).equals(topic)) { - if (safeJsonToSettings(doc, settings)) { - this->resetPublishedSettingsTime(); - fsSettings.update(); - } - - } else { - const String& sensorsTopic = this->haHelper->getDeviceTopic(F("sensors/")); - auto stLength = sensorsTopic.length(); - - if (topic.startsWith(sensorsTopic) && topic.endsWith(F("/set"))) { - if (topic.length() > stLength + 4) { - const String& name = topic.substring(stLength, topic.indexOf('/', stLength)); - int16_t id = Sensors::getIdByObjectId(name.c_str()); - - if (id == -1) { - return; - } - - if (jsonToSensorResult(id, doc)) { - this->resetPublishedSensorTime(id); - } - } - } - } - } - - void publishHaEntities() { - // heating - this->haHelper->publishSwitchHeatingTurbo(false); - this->haHelper->publishSwitchHeatingHysteresis(); - this->haHelper->publishInputHeatingHysteresis(settings.system.unitSystem); - this->haHelper->publishInputHeatingTurboFactor(false); - this->haHelper->publishInputHeatingMinTemp(settings.system.unitSystem); - this->haHelper->publishInputHeatingMaxTemp(settings.system.unitSystem); - - // pid - this->haHelper->publishSwitchPid(); - this->haHelper->publishInputPidFactorP(false); - this->haHelper->publishInputPidFactorI(false); - this->haHelper->publishInputPidFactorD(false); - this->haHelper->publishInputPidDt(false); - this->haHelper->publishInputPidMinTemp(settings.system.unitSystem, false); - this->haHelper->publishInputPidMaxTemp(settings.system.unitSystem, false); - - // equitherm - this->haHelper->publishSwitchEquitherm(); - this->haHelper->publishInputEquithermSlope(false); - this->haHelper->publishInputEquithermExponent(false); - this->haHelper->publishInputEquithermShift(false); - this->haHelper->publishInputEquithermTargetDiffFactor(false); - - // states - this->haHelper->publishStatusState(); - this->haHelper->publishEmergencyState(); - this->haHelper->publishOpenthermConnectedState(); - this->haHelper->publishHeatingState(); - this->haHelper->publishFlameState(); - this->haHelper->publishFaultState(); - this->haHelper->publishDiagState(); - this->haHelper->publishExternalPumpState(false); - - // sensors - this->haHelper->publishFaultCode(); - this->haHelper->publishDiagCode(); - this->haHelper->publishNetworkRssi(false); - this->haHelper->publishUptime(false); - - // buttons - this->haHelper->publishRestartButton(false); - this->haHelper->publishResetFaultButton(); - this->haHelper->publishResetDiagButton(); - - // dynamic sensors - for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { - if (!Sensors::hasEnabledAndValid(sensorId)) { - continue; - } - - auto& sSettings = Sensors::settings[sensorId]; - switch (sSettings.type) { - case Sensors::Type::BLUETOOTH: - this->haHelper->publishConnectionDynamicSensor(sSettings); - this->haHelper->publishSignalQualityDynamicSensor(sSettings, false); - this->haHelper->publishDynamicSensor(sSettings, Sensors::ValueType::TEMPERATURE, settings.system.unitSystem); - this->haHelper->publishDynamicSensor(sSettings, Sensors::ValueType::HUMIDITY, settings.system.unitSystem); - this->haHelper->publishDynamicSensor(sSettings, Sensors::ValueType::BATTERY, settings.system.unitSystem); - this->haHelper->publishDynamicSensor(sSettings, Sensors::ValueType::RSSI, settings.system.unitSystem, false); - break; - - case Sensors::Type::DALLAS_TEMP: - this->haHelper->publishConnectionDynamicSensor(sSettings); - this->haHelper->publishSignalQualityDynamicSensor(sSettings, false); - this->haHelper->publishDynamicSensor(sSettings, Sensors::ValueType::TEMPERATURE, settings.system.unitSystem); - break; - - default: - this->haHelper->publishDynamicSensor(sSettings, Sensors::ValueType::PRIMARY, settings.system.unitSystem); - } - } - } - - bool publishNonStaticHaEntities(bool force = false) { - static uint8_t _heatingMinTemp, _heatingMaxTemp, _dhwMinTemp, _dhwMaxTemp = 0; - static bool _indoorTempControl, _dhwSupport = false; - - bool published = false; - if (force || _dhwSupport != settings.opentherm.options.dhwSupport) { - _dhwSupport = settings.opentherm.options.dhwSupport; - - if (_dhwSupport) { - this->haHelper->publishInputDhwMinTemp(settings.system.unitSystem); - this->haHelper->publishInputDhwMaxTemp(settings.system.unitSystem); - this->haHelper->publishDhwState(); - - } else { - this->haHelper->deleteSwitchDhw(); - this->haHelper->deleteInputDhwMinTemp(); - this->haHelper->deleteInputDhwMaxTemp(); - this->haHelper->deleteDhwState(); - this->haHelper->deleteInputDhwTarget(); - this->haHelper->deleteClimateDhw(); - } - - published = true; - } - - if (force || _indoorTempControl != vars.master.heating.indoorTempControl || _heatingMinTemp != vars.master.heating.minTemp || _heatingMaxTemp != vars.master.heating.maxTemp) { - _heatingMinTemp = vars.master.heating.minTemp; - _heatingMaxTemp = vars.master.heating.maxTemp; - _indoorTempControl = vars.master.heating.indoorTempControl; - - this->haHelper->publishClimateHeating( - settings.system.unitSystem, - vars.master.heating.minTemp, - vars.master.heating.maxTemp - ); - - published = true; - } - - if (_dhwSupport && (force || _dhwMinTemp != settings.dhw.minTemp || _dhwMaxTemp != settings.dhw.maxTemp)) { - _dhwMinTemp = settings.dhw.minTemp; - _dhwMaxTemp = settings.dhw.maxTemp; - - this->haHelper->publishClimateDhw(settings.system.unitSystem, settings.dhw.minTemp, settings.dhw.maxTemp); - - published = true; - } - - return published; - } - - bool publishSettings(const char* topic) { - JsonDocument doc; - safeSettingsToJson(settings, doc); - doc.shrinkToFit(); - - return this->writer->publish(topic, doc, true); - } - - bool publishSensor(uint8_t sensorId) { - auto& sSettings = Sensors::settings[sensorId]; - - if (!Sensors::isValidSensorId(sensorId)) { - return false; - - } else if (!strlen(sSettings.name)) { - return false; - } - - JsonDocument doc; - sensorResultToJson(sensorId, doc); - doc.shrinkToFit(); - - return this->writer->publish( - this->haHelper->getDeviceTopic( - F("sensors"), - Sensors::makeObjectId(sSettings.name).c_str() - ).c_str(), - doc, - true - ); - } - - bool publishVariables(const char* topic) { - JsonDocument doc; - varsToJson(vars, doc); - doc.shrinkToFit(); - - return this->writer->publish(topic, doc, true); - } -}; \ No newline at end of file diff --git a/src/OpenThermTask.h b/src/OpenThermTask.h deleted file mode 100644 index ff5aacd..0000000 --- a/src/OpenThermTask.h +++ /dev/null @@ -1,2622 +0,0 @@ -#include -extern FileData fsSettings; - -class OpenThermTask : public Task { -public: - OpenThermTask(bool _enabled = false, unsigned long _interval = 0) : Task(_enabled, _interval) {} - - ~OpenThermTask() { - delete this->instance; - } - -protected: - const unsigned short readyTime = 60000u; - const unsigned int resetBusInterval = 120000u; - const unsigned short heatingSetTempInterval = 60000u; - const unsigned short dhwSetTempInterval = 60000u; - const unsigned short ch2SetTempInterval = 60000u; - const unsigned int initializingInterval = 3600000u; - - CustomOpenTherm* instance = nullptr; - unsigned long instanceCreatedTime = 0; - uint8_t instanceInGpio = 0; - uint8_t instanceOutGpio = 0; - bool initialized = false; - unsigned long connectedTime = 0; - unsigned long disconnectedTime = 0; - unsigned long resetBusTime = 0; - unsigned long initializedTime = 0; - unsigned long lastSuccessResponse = 0; - unsigned long prevUpdateNonEssentialVars = 0; - unsigned long heatingSetTempTime = 0; - unsigned long dhwSetTempTime = 0; - unsigned long ch2SetTempTime = 0; - uint8_t configuredRxLedGpio = GPIO_IS_NOT_CONFIGURED; - - #if defined(ARDUINO_ARCH_ESP32) - const char* getTaskName() override { - return "OpenTherm"; - } - - BaseType_t getTaskCore() override { - return 1; - } - - int getTaskPriority() override { - return 5; - } - #endif - - void setup() { - // Convert defaults at start - if (settings.system.unitSystem != UnitSystem::METRIC) { - vars.slave.heating.minTemp = convertTemp(vars.slave.heating.minTemp, UnitSystem::METRIC, settings.system.unitSystem); - vars.slave.heating.maxTemp = convertTemp(vars.slave.heating.maxTemp, UnitSystem::METRIC, settings.system.unitSystem); - vars.slave.dhw.minTemp = convertTemp(vars.slave.dhw.minTemp, UnitSystem::METRIC, settings.system.unitSystem); - vars.slave.dhw.maxTemp = convertTemp(vars.slave.dhw.maxTemp, UnitSystem::METRIC, settings.system.unitSystem); - } - - // delete instance - if (this->instance != nullptr) { - delete this->instance; - this->instance = nullptr; - Log.sinfoln(FPSTR(L_OT), F("Stopped")); - } - - if (!GPIO_IS_VALID(settings.opentherm.inGpio) || !GPIO_IS_VALID(settings.opentherm.outGpio)) { - Log.swarningln( - FPSTR(L_OT), - F("Not started. GPIO IN: %hhu or GPIO OUT: %hhu is not valid"), - settings.opentherm.inGpio, - settings.opentherm.outGpio - ); - return; - } - - #ifdef OT_BYPASS_RELAY_GPIO - pinMode(OT_BYPASS_RELAY_GPIO, OUTPUT); - digitalWrite(OT_BYPASS_RELAY_GPIO, true); - #endif - - // create instance - this->instance = new CustomOpenTherm(settings.opentherm.inGpio, settings.opentherm.outGpio); - - // flags - this->instanceCreatedTime = millis(); - this->instanceInGpio = settings.opentherm.inGpio; - this->instanceOutGpio = settings.opentherm.outGpio; - this->resetBusTime = millis(); - this->initialized = false; - - Log.sinfoln(FPSTR(L_OT), F("Started. GPIO IN: %hhu, GPIO OUT: %hhu"), settings.opentherm.inGpio, settings.opentherm.outGpio); - - this->instance->setAfterSendRequestCallback([this](unsigned long request, unsigned long response, OpenThermResponseStatus status, uint8_t attempt) { - Log.sverboseln( - FPSTR(L_OT), - F("ID: %4d Request: %8lx Response: %8lx Msg type: %s Attempt: %2d Status: %s"), - CustomOpenTherm::getDataID(request), - request, - response, - CustomOpenTherm::getResponseMessageTypeString(response), - attempt, - CustomOpenTherm::statusToString(status) - ); - - if (status == OpenThermResponseStatus::SUCCESS) { - this->lastSuccessResponse = millis(); - - if (this->configuredRxLedGpio != GPIO_IS_NOT_CONFIGURED) { - digitalWrite(this->configuredRxLedGpio, HIGH); - delayMicroseconds(2000); - digitalWrite(this->configuredRxLedGpio, LOW); - } - } - }); - - this->instance->setDelayCallback([this](unsigned int time) { - this->delay(time); - }); - } - - void loop() { - if (vars.states.restarting || vars.states.upgrading) { - return; - } - - if (this->instanceInGpio != settings.opentherm.inGpio || this->instanceOutGpio != settings.opentherm.outGpio) { - this->setup(); - - } else if (vars.master.memberId != settings.opentherm.memberId || vars.master.flags != settings.opentherm.flags) { - this->initialized = false; - vars.master.memberId = settings.opentherm.memberId; - vars.master.flags = settings.opentherm.flags; - vars.master.protocolVersion = 2.2f; - vars.master.appVersion = 0x3F; - vars.master.type = 0x01; - - } else if (millis() - this->initializedTime > this->initializingInterval) { - this->initialized = false; - } - - if (this->instance == nullptr) { - this->delay(5000); - return; - - } else if (this->instance->status == OpenThermStatus::NOT_INITIALIZED) { - if (!this->instance->begin()) { - Log.swarningln(FPSTR(L_OT), F("Failed begin")); - - this->delay(5000); - return; - } - } - - // RX LED GPIO setup - if (settings.opentherm.rxLedGpio != this->configuredRxLedGpio) { - if (this->configuredRxLedGpio != GPIO_IS_NOT_CONFIGURED) { - digitalWrite(this->configuredRxLedGpio, LOW); - } - - if (GPIO_IS_VALID(settings.opentherm.rxLedGpio)) { - this->configuredRxLedGpio = settings.opentherm.rxLedGpio; - pinMode(this->configuredRxLedGpio, OUTPUT); - digitalWrite(this->configuredRxLedGpio, LOW); - - } else if (this->configuredRxLedGpio != GPIO_IS_NOT_CONFIGURED) { - this->configuredRxLedGpio = GPIO_IS_NOT_CONFIGURED; - } - } - - // Heating settings - vars.master.heating.enabled = this->isReady() - && settings.heating.enabled - && (vars.master.heating.freezing || (vars.cascadeControl.input && !vars.master.heating.blocking)) - && !vars.master.heating.overheat; - - // DHW settings - vars.master.dhw.enabled = settings.opentherm.options.dhwSupport - && settings.dhw.enabled - && !vars.master.dhw.overheat; - vars.master.dhw.targetTemp = settings.dhw.target; - - // CH2 settings - vars.master.ch2.enabled = settings.opentherm.options.ch2AlwaysEnabled - || (settings.opentherm.options.heatingToCh2 && vars.master.heating.enabled) - || (settings.opentherm.options.dhwToCh2 && settings.opentherm.options.dhwSupport && settings.dhw.enabled); - - if (settings.opentherm.options.heatingToCh2) { - vars.master.ch2.targetTemp = !settings.opentherm.options.nativeOTC - ? vars.master.heating.setpointTemp - : vars.master.heating.targetTemp; - - } else if (settings.opentherm.options.dhwToCh2) { - vars.master.ch2.targetTemp = vars.master.dhw.targetTemp; - } - - // Set boiler status LB - // Some boilers require this, although this is against protocol - uint8_t statusLb = 0; - - // Immergas fix - // https://arduino.ru/forum/programmirovanie/termostat-opentherm-na-esp8266?page=15#comment-649392 - if (settings.opentherm.options.immergasFix) { - statusLb = 0xCA; - } - - // Summer/winter mode - bool summerWinterMode = settings.opentherm.options.summerWinterMode; - if (settings.opentherm.options.heatingStateToSummerWinterMode) { - summerWinterMode = vars.master.heating.enabled == summerWinterMode; - } - - // DHW blocking - bool dhwBlocking = settings.opentherm.options.dhwBlocking; - if (settings.opentherm.options.dhwStateAsDhwBlocking) { - dhwBlocking = vars.master.dhw.enabled == dhwBlocking; - } - - unsigned long response = this->instance->setBoilerStatus( - vars.master.heating.enabled, - vars.master.dhw.enabled, - settings.opentherm.options.coolingSupport, - settings.opentherm.options.nativeOTC, - vars.master.ch2.enabled, - summerWinterMode, - dhwBlocking, - statusLb - ); - - if (!CustomOpenTherm::isValidResponse(response) || !CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::Status)) { - Log.swarningln( - FPSTR(L_OT), - F("Failed receive boiler status: %s"), - CustomOpenTherm::statusToString(this->instance->getLastResponseStatus()) - ); - - } else { - vars.slave.heating.active = CustomOpenTherm::isCentralHeatingActive(response); - vars.slave.dhw.active = settings.opentherm.options.dhwSupport ? CustomOpenTherm::isHotWaterActive(response) : false; - vars.slave.flame = CustomOpenTherm::isFlameOn(response); - vars.slave.cooling.active = CustomOpenTherm::isCoolingActive(response); - vars.slave.ch2.active = CustomOpenTherm::isCh2Active(response); - vars.slave.fault.active = CustomOpenTherm::isFault(response); - - if (!settings.opentherm.options.ignoreDiagState) { - vars.slave.diag.active = CustomOpenTherm::isDiagnostic(response); - - } else if (vars.slave.diag.active) { - vars.slave.diag.active = false; - } - - Log.snoticeln( - FPSTR(L_OT), F("Received boiler status. Heating: %hhu; DHW: %hhu; flame: %hhu; cooling: %hhu; channel 2: %hhu; fault: %hhu; diag: %hhu"), - vars.slave.heating.active, vars.slave.dhw.active, - vars.slave.flame, vars.slave.cooling.active, vars.slave.ch2.active, vars.slave.fault.active, vars.slave.diag.active - ); - } - - // 5 request retries - // 1000ms maximum response waiting time - // 100ms delay between requests - // +15% - // 5 * (1000 + 100) * 1.15 = 6325 ms - if (!vars.slave.connected && millis() - this->lastSuccessResponse < 6325) { - Log.sinfoln( - FPSTR(L_OT), - F("Connected, downtime: %lu s."), - (millis() - this->disconnectedTime) / 1000 - ); - - this->connectedTime = millis(); - vars.slave.connected = true; - - } else if (vars.slave.connected && millis() - this->lastSuccessResponse > 6325) { - Log.swarningln( - FPSTR(L_OT), - F("Disconnected, uptime: %lu s."), - (millis() - this->connectedTime) / 1000 - ); - - // Mark sensors as disconnected - Sensors::setConnectionStatusByType(Sensors::Type::OT_OUTDOOR_TEMP, false); - Sensors::setConnectionStatusByType(Sensors::Type::OT_HEATING_TEMP, false); - Sensors::setConnectionStatusByType(Sensors::Type::OT_HEATING_RETURN_TEMP, false); - Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_TEMP, false); - Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_TEMP2, false); - Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_FLOW_RATE, false); - Sensors::setConnectionStatusByType(Sensors::Type::OT_CH2_TEMP, false); - Sensors::setConnectionStatusByType(Sensors::Type::OT_EXHAUST_TEMP, false); - Sensors::setConnectionStatusByType(Sensors::Type::OT_HEAT_EXCHANGER_TEMP, false); - Sensors::setConnectionStatusByType(Sensors::Type::OT_PRESSURE, false); - Sensors::setConnectionStatusByType(Sensors::Type::OT_MODULATION_LEVEL, false); - Sensors::setConnectionStatusByType(Sensors::Type::OT_CURRENT_POWER, false); - Sensors::setConnectionStatusByType(Sensors::Type::OT_EXHAUST_CO2, false); - Sensors::setConnectionStatusByType(Sensors::Type::OT_EXHAUST_FAN_SPEED, false); - Sensors::setConnectionStatusByType(Sensors::Type::OT_SUPPLY_FAN_SPEED, false); - Sensors::setConnectionStatusByType(Sensors::Type::OT_SOLAR_STORAGE_TEMP, false); - Sensors::setConnectionStatusByType(Sensors::Type::OT_SOLAR_COLLECTOR_TEMP, false); - Sensors::setConnectionStatusByType(Sensors::Type::OT_FAN_SPEED_SETPOINT, false); - Sensors::setConnectionStatusByType(Sensors::Type::OT_FAN_SPEED_CURRENT, false); - - Sensors::setConnectionStatusByType(Sensors::Type::OT_BURNER_STARTS, false); - Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_BURNER_STARTS, false); - Sensors::setConnectionStatusByType(Sensors::Type::OT_HEATING_PUMP_STARTS, false); - Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_PUMP_STARTS, false); - Sensors::setConnectionStatusByType(Sensors::Type::OT_BURNER_HOURS, false); - Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_BURNER_HOURS, false); - Sensors::setConnectionStatusByType(Sensors::Type::OT_HEATING_PUMP_HOURS, false); - Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_PUMP_HOURS, false); - Sensors::setConnectionStatusByType(Sensors::Type::OT_COOLING_HOURS, false); - - this->initialized = false; - this->disconnectedTime = millis(); - vars.slave.connected = false; - } - - // If boiler is disconnected, no need try setting other OT stuff - if (!vars.slave.connected) { - vars.slave.heating.enabled = false; - vars.slave.heating.active = false; - vars.slave.dhw.enabled = false; - vars.slave.dhw.active = false; - vars.slave.flame = false; - vars.slave.cooling.active = false; - vars.slave.cooling.setpoint = 0; - vars.slave.fault.active = false; - vars.slave.fault.code = 0; - vars.slave.diag.active = false; - vars.slave.diag.code = 0; - - // reset bus - if (millis() - this->disconnectedTime > this->resetBusInterval) { - if (millis() - this->resetBusTime > this->resetBusInterval) { - Log.sinfoln(FPSTR(L_OT), F("Reset bus...")); - - this->instance->end(); - this->instance->status = OpenThermStatus::NOT_INITIALIZED; - - digitalWrite(this->instanceOutGpio, LOW); - this->resetBusTime = millis(); - this->delay(5000); - } - } - - return; - } - - if (!this->initialized) { - Log.sinfoln(FPSTR(L_OT), F("Initializing...")); - this->initialized = true; - this->initializedTime = millis(); - this->initialize(); - } - - if (vars.master.heating.enabled != vars.slave.heating.enabled) { - this->prevUpdateNonEssentialVars = 0; - vars.slave.heating.enabled = vars.master.heating.enabled; - Log.sinfoln(FPSTR(L_OT_HEATING), vars.master.heating.enabled ? F("Enabled") : F("Disabled")); - } - - if (vars.master.dhw.enabled != vars.slave.dhw.enabled) { - this->prevUpdateNonEssentialVars = 0; - vars.slave.dhw.enabled = vars.master.dhw.enabled; - Log.sinfoln(FPSTR(L_OT_DHW), vars.master.dhw.enabled ? F("Enabled") : F("Disabled")); - } - - // These parameters will be updated every minute - if (millis() - this->prevUpdateNonEssentialVars > 60000) { - // Set date & time - if (settings.opentherm.options.setDateAndTime) { - struct tm ti; - - if (getLocalTime(&ti)) { - if (this->setYear(&ti)) { - Log.sinfoln(FPSTR(L_OT), F("Year of date set successfully")); - - } else { - Log.sinfoln(FPSTR(L_OT), F("Failed set year of date")); - } - - if (this->setDayAndMonth(&ti)) { - Log.sinfoln(FPSTR(L_OT), F("Day and month of date set successfully")); - - } else { - Log.sinfoln(FPSTR(L_OT), F("Failed set day and month of date")); - } - - if (this->setTime(&ti)) { - Log.sinfoln(FPSTR(L_OT), F("Time set successfully")); - - } else { - Log.sinfoln(FPSTR(L_OT), F("Failed set time")); - } - } - } - - // Get min modulation level & max power - if (this->updateMinModulationLevel()) { - Log.snoticeln( - FPSTR(L_OT), F("Received min modulation: %hhu%%, max power: %.2f kW"), - vars.slave.modulation.min, vars.slave.power.max - ); - - if (settings.heating.maxModulation < vars.slave.modulation.min) { - settings.heating.maxModulation = vars.slave.modulation.min; - fsSettings.update(); - - Log.swarningln( - FPSTR(L_SETTINGS_HEATING), F("Updated min modulation: %hhu%%"), - settings.heating.maxModulation - ); - } - - if (settings.dhw.maxModulation < vars.slave.modulation.min) { - settings.dhw.maxModulation = vars.slave.modulation.min; - fsSettings.update(); - - Log.swarningln( - FPSTR(L_SETTINGS_DHW), F("Updated min modulation: %hhu%%"), - settings.dhw.maxModulation - ); - } - - if (fabsf(settings.opentherm.maxPower) < 0.1f && vars.slave.power.max > 0.1f) { - settings.opentherm.maxPower = vars.slave.power.max; - settings.opentherm.minPower = vars.slave.power.min; - - fsSettings.update(); - Log.swarningln( - FPSTR(L_SETTINGS_OT), F("Updated power, min: %.2f kW, max: %.2f kW"), - settings.opentherm.minPower, settings.opentherm.maxPower - ); - } - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed receive min modulation and max power")); - } - - - // Get DHW min/max temp (if necessary) - if (settings.opentherm.options.dhwSupport && settings.opentherm.options.getMinMaxTemp) { - if (this->updateMinMaxDhwTemp()) { - uint8_t convertedMinTemp = convertTemp( - vars.slave.dhw.minTemp, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - uint8_t convertedMaxTemp = convertTemp( - vars.slave.dhw.maxTemp, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - FPSTR(L_OT_DHW), F("Received min temp: %hhu (converted: %hhu), max temp: %hhu (converted: %hhu)"), - vars.slave.dhw.minTemp, convertedMinTemp, vars.slave.dhw.maxTemp, convertedMaxTemp - ); - - if (settings.dhw.minTemp < convertedMinTemp) { - settings.dhw.minTemp = convertedMinTemp; - fsSettings.update(); - - Log.swarningln(FPSTR(L_SETTINGS_DHW), F("Updated min temp: %hhu"), settings.dhw.minTemp); - } - - if (settings.dhw.maxTemp > convertedMaxTemp) { - settings.dhw.maxTemp = convertedMaxTemp; - fsSettings.update(); - - Log.swarningln(FPSTR(L_SETTINGS_DHW), F("Updated max temp: %hhu"), settings.dhw.maxTemp); - } - - } else { - Log.swarningln(FPSTR(L_OT_DHW), F("Failed receive min/max temp")); - } - } - - if (settings.dhw.minTemp >= settings.dhw.maxTemp) { - settings.dhw.minTemp = convertTemp(DEFAULT_DHW_MIN_TEMP, UnitSystem::METRIC, settings.system.unitSystem); - settings.dhw.maxTemp = convertTemp(DEFAULT_DHW_MAX_TEMP, UnitSystem::METRIC, settings.system.unitSystem); - fsSettings.update(); - } - - - // Get heating min/max temp - if (settings.opentherm.options.getMinMaxTemp) { - if (this->updateMinMaxHeatingTemp()) { - uint8_t convertedMinTemp = convertTemp( - vars.slave.heating.minTemp, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - uint8_t convertedMaxTemp = convertTemp( - vars.slave.heating.maxTemp, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - FPSTR(L_OT_HEATING), F("Received min temp: %hhu (converted: %hhu), max temp: %hhu (converted: %hhu)"), - vars.slave.heating.minTemp, convertedMinTemp, vars.slave.heating.maxTemp, convertedMaxTemp - ); - - if (settings.heating.minTemp < convertedMinTemp) { - settings.heating.minTemp = convertedMinTemp; - fsSettings.update(); - - Log.swarningln(FPSTR(L_SETTINGS_HEATING), F("Updated min temp: %hhu"), settings.heating.minTemp); - } - - if (settings.heating.maxTemp > convertedMaxTemp) { - settings.heating.maxTemp = convertedMaxTemp; - fsSettings.update(); - - Log.swarningln(FPSTR(L_SETTINGS_HEATING), F("Updated max temp: %hhu"), settings.heating.maxTemp); - } - - } else { - Log.swarningln(FPSTR(L_OT_HEATING), F("Failed receive min/max temp")); - } - } - - if (settings.heating.minTemp >= settings.heating.maxTemp) { - settings.heating.minTemp = convertTemp(DEFAULT_HEATING_MIN_TEMP, UnitSystem::METRIC, settings.system.unitSystem);; - settings.heating.maxTemp = convertTemp(DEFAULT_HEATING_MAX_TEMP, UnitSystem::METRIC, settings.system.unitSystem);; - fsSettings.update(); - } - - // Get fault code (if necessary) - if (vars.slave.fault.active) { - if (this->updateFaultCode()) { - Log.snoticeln( - FPSTR(L_OT), F("Received fault code: %hhu (0x%02X)"), - vars.slave.fault.code, vars.slave.fault.code - ); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed receive fault code")); - } - - } else if (vars.slave.fault.code != 0) { - vars.slave.fault.code = 0; - } - - // Get diagnostic code (if necessary) - if (vars.slave.fault.active || vars.slave.diag.active) { - if (this->updateDiagCode()) { - Log.snoticeln( - FPSTR(L_OT), F("Received diag code: %hu (0x%02X)"), - vars.slave.diag.code, vars.slave.diag.code - ); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed receive diag code")); - } - - } else if (vars.slave.diag.code != 0) { - vars.slave.diag.code = 0; - } - - // Update burner starts - if (Sensors::getAmountByType(Sensors::Type::OT_BURNER_STARTS, true)) { - if (this->updateBurnerStarts()) { - Log.snoticeln(FPSTR(L_OT), F("Received burner starts: %hu"), vars.slave.stats.burnerStarts); - - Sensors::setValueByType( - Sensors::Type::OT_BURNER_STARTS, vars.slave.stats.burnerStarts, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed receive burner starts")); - } - } - - // Update DHW burner starts - if (Sensors::getAmountByType(Sensors::Type::OT_DHW_BURNER_STARTS, true)) { - if (this->updateDhwBurnerStarts()) { - Log.snoticeln(FPSTR(L_OT), F("Received DHW burner starts: %hu"), vars.slave.stats.dhwBurnerStarts); - - Sensors::setValueByType( - Sensors::Type::OT_DHW_BURNER_STARTS, vars.slave.stats.dhwBurnerStarts, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed receive DHW burner starts")); - } - } - - // Update heating pump starts - if (Sensors::getAmountByType(Sensors::Type::OT_HEATING_PUMP_STARTS, true)) { - if (this->updateHeatingPumpStarts()) { - Log.snoticeln(FPSTR(L_OT), F("Received heating pump starts: %hu"), vars.slave.stats.heatingPumpStarts); - - Sensors::setValueByType( - Sensors::Type::OT_HEATING_PUMP_STARTS, vars.slave.stats.heatingPumpStarts, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed receive heating pump starts")); - } - } - - // Update DHW pump starts - if (Sensors::getAmountByType(Sensors::Type::OT_DHW_PUMP_STARTS, true)) { - if (this->updateDhwPumpStarts()) { - Log.snoticeln(FPSTR(L_OT), F("Received DHW pump starts: %hu"), vars.slave.stats.dhwPumpStarts); - - Sensors::setValueByType( - Sensors::Type::OT_DHW_PUMP_STARTS, vars.slave.stats.dhwPumpStarts, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed receive DHW pump starts")); - } - } - - // Update burner hours - if (Sensors::getAmountByType(Sensors::Type::OT_BURNER_HOURS, true)) { - if (this->updateBurnerHours()) { - Log.snoticeln(FPSTR(L_OT), F("Received burner hours: %hu"), vars.slave.stats.burnerHours); - - Sensors::setValueByType( - Sensors::Type::OT_BURNER_HOURS, vars.slave.stats.burnerHours, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed receive burner hours")); - } - } - - // Update DHW burner hours - if (Sensors::getAmountByType(Sensors::Type::OT_DHW_BURNER_HOURS, true)) { - if (this->updateDhwBurnerHours()) { - Log.snoticeln(FPSTR(L_OT), F("Received DHW burner hours: %hu"), vars.slave.stats.dhwBurnerHours); - - Sensors::setValueByType( - Sensors::Type::OT_DHW_BURNER_HOURS, vars.slave.stats.dhwBurnerHours, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed receive DHW burner hours")); - } - } - - // Update heating pump hours - if (Sensors::getAmountByType(Sensors::Type::OT_HEATING_PUMP_HOURS, true)) { - if (this->updateHeatingPumpHours()) { - Log.snoticeln(FPSTR(L_OT), F("Received heating pump hours: %hu"), vars.slave.stats.heatingPumpHours); - - Sensors::setValueByType( - Sensors::Type::OT_HEATING_PUMP_HOURS, vars.slave.stats.heatingPumpHours, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed receive heating pump hours")); - } - } - - // Update DHW pump hours - if (Sensors::getAmountByType(Sensors::Type::OT_DHW_PUMP_HOURS, true)) { - if (this->updateDhwPumpHours()) { - Log.snoticeln(FPSTR(L_OT), F("Received DHW pump hours: %hu"), vars.slave.stats.dhwPumpHours); - - Sensors::setValueByType( - Sensors::Type::OT_DHW_PUMP_HOURS, vars.slave.stats.dhwPumpHours, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed receive DHW pump hours")); - } - } - - // Update cooling hours - if (Sensors::getAmountByType(Sensors::Type::OT_COOLING_HOURS, true)) { - if (this->updateCoolingHours()) { - Log.snoticeln(FPSTR(L_OT), F("Received cooling hours: %hu"), vars.slave.stats.coolingHours); - - Sensors::setValueByType( - Sensors::Type::OT_COOLING_HOURS, vars.slave.stats.coolingHours, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed receive cooling hours")); - } - } - - // Auto fault reset - if (settings.opentherm.options.autoFaultReset && vars.slave.fault.active && !vars.actions.resetFault) { - vars.actions.resetFault = true; - } - - // Auto diag reset - if (settings.opentherm.options.autoDiagReset && vars.slave.diag.active && !vars.actions.resetDiagnostic) { - vars.actions.resetDiagnostic = true; - } - - this->prevUpdateNonEssentialVars = millis(); - } - - // Set cooling setpoint = heating max modulation - if (settings.opentherm.options.coolingSupport) { - if (this->setCoolingSetpoint(settings.heating.maxModulation)) { - Log.snoticeln( - FPSTR(L_OT), F("Set cooling setpoint: %hhu%% (response: %hhu%%)"), - settings.heating.maxModulation, vars.slave.cooling.setpoint - ); - - } else { - Log.swarningln( - FPSTR(L_OT), F("Failed set cooling setpoint: %hhu%% (response: %hhu%%)"), - settings.heating.maxModulation, vars.slave.cooling.setpoint - ); - } - } - - // Set max modulation level - uint8_t targetMaxModulation = vars.slave.modulation.max; - if (vars.slave.heating.active) { - targetMaxModulation = settings.heating.maxModulation; - - } else if (vars.slave.dhw.active) { - targetMaxModulation = settings.dhw.maxModulation; - } - - if (this->setMaxModulationLevel(targetMaxModulation)) { - Log.snoticeln( - FPSTR(L_OT), F("Set max modulation: %hhu%% (response: %hhu%%)"), - targetMaxModulation, vars.slave.modulation.max - ); - - } else { - Log.swarningln( - FPSTR(L_OT), F("Failed set max modulation: %hhu%% (response: %hhu%%)"), - targetMaxModulation, vars.slave.modulation.max - ); - } - - // Update modulation level - if ( - Sensors::getAmountByType(Sensors::Type::OT_MODULATION_LEVEL, true) || - Sensors::getAmountByType(Sensors::Type::OT_CURRENT_POWER, true) - ) { - if (vars.slave.flame) { - if (this->updateModulationLevel()) { - float power = 0.0f; - if (settings.opentherm.maxPower > 0.1f) { - power += settings.opentherm.minPower; - - if (vars.slave.modulation.current > 0) { - power += ( - settings.opentherm.maxPower - settings.opentherm.minPower - ) / 100.0f * vars.slave.modulation.current; - } - } - vars.slave.power.current = power; - - Log.snoticeln( - FPSTR(L_OT), F("Received modulation level: %hhu%%, power: %.2f of %.2f kW (min: %.2f kW)"), - vars.slave.modulation.current, vars.slave.power.current, - settings.opentherm.maxPower, settings.opentherm.minPower - ); - - // Modulation level sensors - Sensors::setValueByType( - Sensors::Type::OT_MODULATION_LEVEL, vars.slave.modulation.current, - Sensors::ValueType::PRIMARY, true, true - ); - - // Power sensors - Sensors::setValueByType( - Sensors::Type::OT_CURRENT_POWER, vars.slave.power.current, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed receive modulation level")); - } - - } else { - vars.slave.modulation.current = 0; - vars.slave.power.current = 0.0f; - - // Modulation level sensors - Sensors::setValueByType( - Sensors::Type::OT_MODULATION_LEVEL, vars.slave.modulation.current, - Sensors::ValueType::PRIMARY, true, true - ); - - // Power sensors - Sensors::setValueByType( - Sensors::Type::OT_CURRENT_POWER, vars.slave.power.current, - Sensors::ValueType::PRIMARY, true, true - ); - } - } - - // Update DHW temp - if (settings.opentherm.options.dhwSupport && Sensors::getAmountByType(Sensors::Type::OT_DHW_TEMP, true)) { - bool result = this->updateDhwTemp(); - - if (result) { - const float convertedDhwTemp = convertTemp( - vars.slave.dhw.currentTemp, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - FPSTR(L_OT_DHW), F("Received temp: %.2f (converted: %.2f)"), - vars.slave.dhw.currentTemp, convertedDhwTemp - ); - - Sensors::setValueByType( - Sensors::Type::OT_DHW_TEMP, convertedDhwTemp, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(FPSTR(L_OT_DHW), F("Failed receive temp")); - } - } - - // Update DHW temp 2 - if (settings.opentherm.options.dhwSupport && Sensors::getAmountByType(Sensors::Type::OT_DHW_TEMP2, true)) { - if (this->updateDhwTemp2()) { - const float convertedDhwTemp2 = convertTemp( - vars.slave.dhw.currentTemp2, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - FPSTR(L_OT_DHW), F("Received temp 2: %.2f (converted: %.2f)"), - vars.slave.dhw.currentTemp2, convertedDhwTemp2 - ); - - Sensors::setValueByType( - Sensors::Type::OT_DHW_TEMP2, convertedDhwTemp2, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(FPSTR(L_OT_DHW), F("Failed receive temp 2")); - } - } - - // Update DHW flow rate - if (settings.opentherm.options.dhwSupport && Sensors::getAmountByType(Sensors::Type::OT_DHW_FLOW_RATE, true)) { - if (this->updateDhwFlowRate()) { - const float convertedDhwFlowRate = convertVolume( - vars.slave.dhw.flowRate, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - FPSTR(L_OT_DHW), F("Received flow rate: %.2f (converted: %.2f)"), - vars.slave.dhw.flowRate, convertedDhwFlowRate - ); - - Sensors::setValueByType( - Sensors::Type::OT_DHW_FLOW_RATE, convertedDhwFlowRate, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(FPSTR(L_OT_DHW), F("Failed receive flow rate")); - } - } - - // Update heating temp - if (Sensors::getAmountByType(Sensors::Type::OT_HEATING_TEMP, true)) { - if (this->updateHeatingTemp()) { - const float convertedHeatingTemp = convertTemp( - vars.slave.heating.currentTemp, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - FPSTR(L_OT_HEATING), F("Received temp: %.2f"), - vars.slave.heating.currentTemp, convertedHeatingTemp - ); - - Sensors::setValueByType( - Sensors::Type::OT_HEATING_TEMP, convertedHeatingTemp, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(FPSTR(L_OT_HEATING), F("Failed receive temp")); - } - } - - // Update heating return temp - if (Sensors::getAmountByType(Sensors::Type::OT_HEATING_RETURN_TEMP, true)) { - if (this->updateHeatingReturnTemp()) { - const float convertedHeatingReturnTemp = convertTemp( - vars.slave.heating.returnTemp, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - FPSTR(L_OT_HEATING), F("Received return temp: %.2f (converted: %.2f)"), - vars.slave.heating.returnTemp, convertedHeatingReturnTemp - ); - - Sensors::setValueByType( - Sensors::Type::OT_HEATING_RETURN_TEMP, convertedHeatingReturnTemp, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(FPSTR(L_OT_HEATING), F("Failed receive return temp")); - } - } - - // Update CH2 temp - if (Sensors::getAmountByType(Sensors::Type::OT_CH2_TEMP, true)) { - if (vars.master.ch2.enabled && !settings.opentherm.options.nativeOTC) { - if (this->updateCh2Temp()) { - const float convertedCh2Temp = convertTemp( - vars.slave.ch2.currentTemp, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - FPSTR(L_OT_CH2), F("Received temp: %.2f (converted: %.2f)"), - vars.slave.ch2.currentTemp, convertedCh2Temp - ); - - Sensors::setValueByType( - Sensors::Type::OT_CH2_TEMP, convertedCh2Temp, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(FPSTR(L_OT_CH2), F("Failed receive temp")); - } - } - } - - // Update exhaust temp - if (Sensors::getAmountByType(Sensors::Type::OT_EXHAUST_TEMP, true)) { - if (this->updateExhaustTemp()) { - const float convertedExhaustTemp = convertTemp( - vars.slave.exhaust.temp, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - FPSTR(L_OT), F("Received exhaust temp: %.2f (converted: %.2f)"), - vars.slave.exhaust.temp, convertedExhaustTemp - ); - - Sensors::setValueByType( - Sensors::Type::OT_EXHAUST_TEMP, convertedExhaustTemp, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed receive exhaust temp")); - } - } - - // Update heat exchanger temp - if (Sensors::getAmountByType(Sensors::Type::OT_HEAT_EXCHANGER_TEMP, true)) { - if (this->updateHeatExchangerTemp()) { - const float convertedHeatExchTemp = convertTemp( - vars.slave.heatExchangerTemp, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - FPSTR(L_OT), F("Received heat exchanger temp: %.2f (converted: %.2f)"), - vars.slave.heatExchangerTemp, convertedHeatExchTemp - ); - - Sensors::setValueByType( - Sensors::Type::OT_HEAT_EXCHANGER_TEMP, convertedHeatExchTemp, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed receive heat exchanger temp")); - } - } - - // Update outdoor temp - if (Sensors::getAmountByType(Sensors::Type::OT_OUTDOOR_TEMP, true)) { - if (this->updateOutdoorTemp()) { - const float convertedOutdoorTemp = convertTemp( - vars.slave.heating.outdoorTemp, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - FPSTR(L_OT), F("Received outdoor temp: %.2f (converted: %.2f)"), - vars.slave.heating.outdoorTemp, convertedOutdoorTemp - ); - - Sensors::setValueByType( - Sensors::Type::OT_OUTDOOR_TEMP, convertedOutdoorTemp, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed receive outdoor temp")); - } - } - - // Update solar storage temp - if (Sensors::getAmountByType(Sensors::Type::OT_SOLAR_STORAGE_TEMP, true)) { - if (this->updateSolarStorageTemp()) { - const float convertedSolarStorageTemp = convertTemp( - vars.slave.solar.storage, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - FPSTR(L_OT), F("Received solar storage temp: %.2f (converted: %.2f)"), - vars.slave.solar.storage, convertedSolarStorageTemp - ); - - Sensors::setValueByType( - Sensors::Type::OT_SOLAR_STORAGE_TEMP, convertedSolarStorageTemp, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed receive solar storage temp")); - } - } - - // Update solar collector temp - if (Sensors::getAmountByType(Sensors::Type::OT_SOLAR_COLLECTOR_TEMP, true)) { - if (this->updateSolarCollectorTemp()) { - const float convertedSolarCollectorTemp = convertTemp( - vars.slave.solar.collector, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - FPSTR(L_OT), F("Received solar collector temp: %.2f (converted: %.2f)"), - vars.slave.solar.collector, convertedSolarCollectorTemp - ); - - Sensors::setValueByType( - Sensors::Type::OT_SOLAR_COLLECTOR_TEMP, convertedSolarCollectorTemp, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed receive solar collector temp")); - } - } - - // Update fan speed - if ( - Sensors::getAmountByType(Sensors::Type::OT_FAN_SPEED_SETPOINT, true) || - Sensors::getAmountByType(Sensors::Type::OT_FAN_SPEED_CURRENT, true) - ) { - if (this->updateFanSpeed()) { - Log.snoticeln( - FPSTR(L_OT), F("Received fan speed, setpoint: %hhu%%, current: %hhu%%"), - vars.slave.fanSpeed.setpoint, vars.slave.fanSpeed.current - ); - - Sensors::setValueByType( - Sensors::Type::OT_FAN_SPEED_SETPOINT, vars.slave.fanSpeed.setpoint, - Sensors::ValueType::PRIMARY, true, true - ); - Sensors::setValueByType( - Sensors::Type::OT_FAN_SPEED_CURRENT, vars.slave.fanSpeed.current, - Sensors::ValueType::PRIMARY, true, true - ); - } - } - - // Update pressure - if (Sensors::getAmountByType(Sensors::Type::OT_PRESSURE, true)) { - if (this->updatePressure()) { - const float convertedPressure = convertPressure( - vars.slave.pressure, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - FPSTR(L_OT), F("Received pressure: %.2f (converted: %.2f)"), - vars.slave.pressure, convertedPressure - ); - - Sensors::setValueByType( - Sensors::Type::OT_PRESSURE, convertedPressure, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed receive pressure")); - } - } - - // Update exhaust CO2 - if (Sensors::getAmountByType(Sensors::Type::OT_EXHAUST_CO2, true)) { - if (this->updateExhaustCo2()) { - Log.snoticeln( - FPSTR(L_OT), F("Received exhaust CO2: %hu ppm"), - vars.slave.exhaust.co2 - ); - - Sensors::setValueByType( - Sensors::Type::OT_EXHAUST_CO2, vars.slave.exhaust.co2, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed receive exhaust CO2")); - } - } - - // Update exhaust fan speed - if (Sensors::getAmountByType(Sensors::Type::OT_EXHAUST_FAN_SPEED, true)) { - if (this->updateExhaustFanSpeed()) { - Log.snoticeln( - FPSTR(L_OT), F("Received exhaust fan speed: %hu rpm"), - vars.slave.exhaust.fanSpeed - ); - - Sensors::setValueByType( - Sensors::Type::OT_EXHAUST_FAN_SPEED, vars.slave.exhaust.fanSpeed, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed receive exhaust fan speed")); - } - } - - // Update supply fan speed - if (Sensors::getAmountByType(Sensors::Type::OT_SUPPLY_FAN_SPEED, true)) { - if (this->updateSupplyFanSpeed()) { - Log.snoticeln( - FPSTR(L_OT), F("Received supply fan speed: %hu rpm"), - vars.slave.fanSpeed.supply - ); - - Sensors::setValueByType( - Sensors::Type::OT_SUPPLY_FAN_SPEED, vars.slave.fanSpeed.supply, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed receive supply fan speed")); - } - } - - // Fault reset action - if (vars.actions.resetFault) { - if (vars.slave.fault.active) { - if (this->instance->sendBoilerReset()) { - Log.sinfoln(FPSTR(L_OT), F("Boiler fault reset successfully")); - - } else { - Log.serrorln(FPSTR(L_OT), F("Boiler fault reset failed")); - } - } - - vars.actions.resetFault = false; - } - - // Diag reset action - if (vars.actions.resetDiagnostic) { - if (vars.slave.diag.active) { - if (this->instance->sendServiceReset()) { - Log.sinfoln(FPSTR(L_OT), F("Boiler diagnostic reset successfully")); - - } else { - Log.serrorln(FPSTR(L_OT), F("Boiler diagnostic reset failed")); - } - } - - vars.actions.resetDiagnostic = false; - } - - - // Update DHW temp - if (vars.master.dhw.enabled) { - // Target dhw temp - const float& targetTemp = vars.master.dhw.targetTemp; - - // Converted target dhw temp - const float convertedTemp = convertTemp( - targetTemp, - settings.system.unitSystem, - settings.opentherm.unitSystem - ); - - // Set DHW temp - if (this->needSetDhwTemp(convertedTemp)) { - if (this->setDhwTemp(convertedTemp)) { - this->dhwSetTempTime = millis(); - - Log.sinfoln( - FPSTR(L_OT_DHW), F("Set temp: %.2f (converted: %.2f, response: %.2f)"), - targetTemp, convertedTemp, vars.slave.dhw.targetTemp - ); - - } else { - Log.swarningln(FPSTR(L_OT_DHW), F("Failed set temp")); - } - } - } - - // Send indoor temp if AlwaysSendIndoorTemp option is enabled. - if (settings.opentherm.options.nativeOTC || settings.opentherm.options.alwaysSendIndoorTemp) { - // Current indoor temp - const float& indoorTemp = vars.master.heating.indoorTemp; - - // Converted current indoor temp - const float convertedTemp = convertTemp(indoorTemp, settings.system.unitSystem, settings.opentherm.unitSystem); - - // Set current indoor temp - if (this->setRoomTemp(convertedTemp)) { - Log.sinfoln( - FPSTR(L_OT_HEATING), F("Set current indoor temp: %.2f (converted: %.2f, response: %.2f)"), - indoorTemp, convertedTemp, vars.slave.heating.indoorTemp - ); - - } else { - Log.swarningln(FPSTR(L_OT_HEATING), F("Failed set current indoor temp")); - } - - // Set current CH2 indoor temp - if (settings.opentherm.options.heatingToCh2) { - if (this->setRoomTempCh2(convertedTemp)) { - Log.sinfoln( - FPSTR(L_OT_HEATING), F("Set current CH2 indoor temp: %.2f (converted: %.2f, response: %.2f)"), - indoorTemp, convertedTemp, vars.slave.ch2.indoorTemp - ); - - } else { - Log.swarningln(FPSTR(L_OT_HEATING), F("Failed set current CH2 indoor temp")); - } - } - } - - // NativeOTC - if (settings.opentherm.options.nativeOTC) { - // Target indoor temp - const float& targetTemp = vars.master.heating.targetTemp; - - // Converted target indoor temp - const float convertedTemp = convertTemp( - targetTemp, - settings.system.unitSystem, - settings.opentherm.unitSystem - ); - - // Set target indoor temp - if (this->needSetHeatingTemp(convertedTemp)) { - if (this->setRoomSetpoint(convertedTemp)) { - this->heatingSetTempTime = millis(); - - Log.sinfoln( - FPSTR(L_OT_HEATING), F("Set target indoor temp: %.2f (converted: %.2f, response: %.2f)"), - targetTemp, convertedTemp, vars.slave.heating.targetTemp - ); - - } else { - Log.swarningln(FPSTR(L_OT_HEATING), F("Failed set target indoor temp")); - } - } - - // Set target CH2 temp - if (settings.opentherm.options.heatingToCh2 && this->needSetCh2Temp(convertedTemp)) { - if (this->setRoomSetpointCh2(convertedTemp)) { - this->ch2SetTempTime = millis(); - - Log.sinfoln( - FPSTR(L_OT_HEATING), F("Set target CH2 indoor temp: %.2f (converted: %.2f, response: %.2f)"), - targetTemp, convertedTemp, vars.slave.ch2.targetTemp - ); - - } else { - Log.swarningln(FPSTR(L_OT_HEATING), F("Failed set target CH2 indoor temp")); - } - } - } - - // Set heating temp - { - // Target heating temp - float targetTemp = 0.0f; - if (vars.master.heating.enabled) { - targetTemp = !settings.opentherm.options.nativeOTC - ? vars.master.heating.setpointTemp - : vars.master.heating.targetTemp; - } - - // Converted target heating temp - const float convertedTemp = convertTemp( - targetTemp, - settings.system.unitSystem, - settings.opentherm.unitSystem - ); - - if (this->needSetHeatingTemp(convertedTemp)) { - // Set max heating temp - if (settings.opentherm.options.maxTempSyncWithTargetTemp) { - if (this->setMaxHeatingTemp(convertedTemp)) { - Log.sinfoln( - FPSTR(L_OT_HEATING), F("Set max heating temp: %.2f (converted: %.2f)"), - targetTemp, convertedTemp - ); - - } else { - Log.swarningln( - FPSTR(L_OT_HEATING), F("Failed set max heating temp: %.2f (converted: %.2f)"), - targetTemp, convertedTemp - ); - } - } - - // Set target heating temp - if (this->setHeatingTemp(convertedTemp)) { - this->heatingSetTempTime = millis(); - - Log.sinfoln( - FPSTR(L_OT_HEATING), F("Set target temp: %.2f (converted: %.2f, response: %.2f)"), - targetTemp, convertedTemp, vars.slave.heating.targetTemp - ); - - } else { - Log.swarningln(FPSTR(L_OT_HEATING), F("Failed set target temp")); - } - } - } - - // Set CH2 temp - if (settings.opentherm.options.heatingToCh2 || settings.opentherm.options.dhwToCh2) { - // Target CH2 heating temp - const float targetTemp = vars.master.ch2.enabled - ? vars.master.ch2.targetTemp - : 0.0f; - - // Converted target CH2 temp - const float convertedTemp = convertTemp( - targetTemp, - settings.system.unitSystem, - settings.opentherm.unitSystem - ); - - if (this->needSetCh2Temp(convertedTemp)) { - if (this->setCh2Temp(convertedTemp)) { - this->ch2SetTempTime = millis(); - - Log.sinfoln( - FPSTR(L_OT_CH2), F("Set temp: %.2f (converted: %.2f, response: %.2f)"), - targetTemp, convertedTemp, vars.slave.ch2.targetTemp - ); - - } else { - Log.swarningln(FPSTR(L_OT_CH2), F("Failed set temp")); - } - } - } - - - // Heating overheat control - if (settings.heating.overheatProtection.highTemp > 0 && settings.heating.overheatProtection.lowTemp > 0) { - const float highTemp = convertTemp( - max({ - vars.slave.heating.currentTemp, - vars.slave.heating.returnTemp, - vars.slave.heatExchangerTemp - }), - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - if (vars.master.heating.overheat) { - if ((float) settings.heating.overheatProtection.lowTemp - highTemp + 0.0001f >= 0.0f) { - vars.master.heating.overheat = false; - - Log.sinfoln( - FPSTR(L_OT_HEATING), F("Overheating not detected. Current high temp: %.2f, threshold (low): %hhu"), - highTemp, settings.heating.overheatProtection.lowTemp - ); - } - - } else if (vars.slave.heating.active) { - if (highTemp - (float) settings.heating.overheatProtection.highTemp + 0.0001f >= 0.0f) { - vars.master.heating.overheat = true; - - Log.swarningln( - FPSTR(L_OT_HEATING), F("Overheating detected! Current high temp: %.2f, threshold (high): %hhu"), - highTemp, settings.heating.overheatProtection.highTemp - ); - } - } - - } else if (vars.master.heating.overheat) { - vars.master.heating.overheat = false; - } - - // DHW overheat control - if (settings.dhw.overheatProtection.highTemp > 0 && settings.dhw.overheatProtection.lowTemp > 0) { - const float highTemp = convertTemp( - max({ - vars.slave.heating.currentTemp, - vars.slave.heating.returnTemp, - vars.slave.heatExchangerTemp, - vars.slave.dhw.currentTemp, - vars.slave.dhw.currentTemp2, - vars.slave.dhw.returnTemp - }), - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - if (vars.master.dhw.overheat) { - if ((float) settings.dhw.overheatProtection.lowTemp - highTemp + 0.0001f >= 0.0f) { - vars.master.dhw.overheat = false; - - Log.sinfoln( - FPSTR(L_OT_DHW), F("Overheating not detected. Current high temp: %.2f, threshold (low): %hhu"), - highTemp, settings.dhw.overheatProtection.lowTemp - ); - } - - } else if (vars.slave.dhw.active) { - if (highTemp - (float) settings.dhw.overheatProtection.highTemp + 0.0001f >= 0.0f) { - vars.master.dhw.overheat = true; - - Log.swarningln( - FPSTR(L_OT_DHW), F("Overheating detected! Current high temp: %.2f, threshold (high): %hhu"), - highTemp, settings.dhw.overheatProtection.highTemp - ); - } - } - - } else if (vars.master.dhw.overheat) { - vars.master.dhw.overheat = false; - } - } - - void initialize() { - // Not all boilers support these, only try once when the boiler becomes connected - if (this->updateSlaveVersion()) { - Log.snoticeln( - FPSTR(L_OT), F("Received slave app version: %u, type: %u"), - vars.slave.appVersion, vars.slave.type - ); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed receive slave version")); - } - - if (this->setMasterVersion(vars.master.appVersion, vars.master.type)) { - Log.snoticeln( - FPSTR(L_OT), F("Set master version: %u, type: %u"), - vars.master.appVersion, vars.master.type - ); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed set master version")); - } - - if (this->updateSlaveOtVersion()) { - Log.snoticeln(FPSTR(L_OT), F("Received slave OT version: %f"), vars.slave.protocolVersion); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed receive slave OT version")); - } - - if (this->setMasterOtVersion(vars.master.protocolVersion)) { - Log.snoticeln(FPSTR(L_OT), F("Set master OT version: %f"), vars.master.protocolVersion); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed set master OT version")); - } - - if (this->updateSlaveConfig()) { - Log.snoticeln( - FPSTR(L_OT), F("Received slave member id: %u, flags: %u"), - vars.slave.memberId, vars.slave.flags - ); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed receive slave config")); - } - - if (this->setMasterConfig(vars.master.memberId, vars.master.flags)) { - Log.snoticeln( - FPSTR(L_OT), F("Set master member id: %u, flags: %u"), - vars.master.memberId, vars.master.flags - ); - - } else { - Log.swarningln(FPSTR(L_OT), F("Failed set master config")); - } - - /*char buf[100]; - if (this->instance->getStr(OpenThermMessageID::Brand, buf, sizeof(buf) - 1)) { - Log.snoticeln(FPSTR(L_OT), F("Slave brand: %s"), buf); - } - - if (this->instance->getStr(OpenThermMessageID::BrandVersion, buf, sizeof(buf) - 1)) { - Log.snoticeln(FPSTR(L_OT), F("Slave brand version: %s"), buf); - } - - if (this->instance->getStr(OpenThermMessageID::BrandSerialNumber, buf, sizeof(buf) - 1)) { - Log.snoticeln(FPSTR(L_OT), F("Slave brand s/n: %s"), buf); - }*/ - } - - bool isReady() { - return millis() - this->instanceCreatedTime > this->readyTime; - } - - bool needSetDhwTemp(const float target) { - return millis() - this->dhwSetTempTime > this->dhwSetTempInterval - || fabsf(target - vars.slave.dhw.targetTemp) > 0.05f; - } - - bool needSetHeatingTemp(const float target) { - return millis() - this->heatingSetTempTime > this->heatingSetTempInterval - || fabsf(target - vars.slave.heating.targetTemp) > 0.05f; - } - - bool needSetCh2Temp(const float target) { - return millis() - this->ch2SetTempTime > this->ch2SetTempInterval - || fabsf(target - vars.slave.ch2.targetTemp) > 0.05f; - } - - bool updateSlaveConfig() { - unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::SConfigSMemberIDcode, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::SConfigSMemberIDcode)) { - return false; - } - - vars.slave.memberId = response & 0xFF; - vars.slave.flags = (response & 0xFFFF) >> 8; - - /*uint8_t flags = (response & 0xFFFF) >> 8; - Log.straceln( - "OT", - F("MasterMemberIdCode:\r\n DHW present: %u\r\n Control type: %u\r\n Cooling configuration: %u\r\n DHW configuration: %u\r\n Pump control: %u\r\n CH2 present: %u\r\n Remote water filling function: %u\r\n Heat/cool mode control: %u\r\n Slave MemberID Code: %u\r\n Raw: %u"), - (bool) (flags & 0x01), - (bool) (flags & 0x02), - (bool) (flags & 0x04), - (bool) (flags & 0x08), - (bool) (flags & 0x10), - (bool) (flags & 0x20), - (bool) (flags & 0x40), - (bool) (flags & 0x80), - response & 0xFF, - response - );*/ - - return true; - } - - bool setYear(const struct tm *ptm) { - const unsigned int request = (ptm->tm_year + 1900) & 0xFFFF; - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::WRITE_DATA, - OpenThermMessageID::Year, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::Year)) { - return false; - } - - return CustomOpenTherm::getUInt(response) == request; - } - - bool setDayAndMonth(const struct tm *ptm) { - const uint8_t month = (ptm->tm_mon + 1) & 0xFF; - const unsigned int request = (month << 8) | (ptm->tm_mday & 0xFF); - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::WRITE_DATA, - OpenThermMessageID::Date, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::Date)) { - return false; - } - - return CustomOpenTherm::getUInt(response) == request; - } - - bool setTime(const struct tm *ptm) { - const uint8_t dayOfWeek = ptm->tm_wday == 0 ? 6 : ptm->tm_wday - 1; - const unsigned int request = ((dayOfWeek & 0x07) << 13) - | ((ptm->tm_hour & 0x1F) << 8) - | (ptm->tm_min & 0x3F); - - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::WRITE_DATA, - OpenThermMessageID::DayTime, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::DayTime)) { - return false; - } - - return CustomOpenTherm::getUInt(response) == request; - } - - bool setCoolingSetpoint(const uint8_t value) { - const unsigned int request = CustomOpenTherm::toFloat(value); - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::WRITE_DATA, - OpenThermMessageID::CoolingControl, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::CoolingControl)) { - return false; - } - - vars.slave.cooling.setpoint = CustomOpenTherm::getFloat(response); - - return CustomOpenTherm::getUInt(response) == request; - } - - bool setMaxModulationLevel(const uint8_t value) { - const unsigned int request = CustomOpenTherm::toFloat(value); - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::WRITE_DATA, - OpenThermMessageID::MaxRelModLevelSetting, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::MaxRelModLevelSetting)) { - return false; - } - - vars.slave.modulation.max = CustomOpenTherm::getFloat(response); - - return CustomOpenTherm::getUInt(response) == request; - } - - bool setDhwTemp(const float temperature) { - const unsigned int request = CustomOpenTherm::temperatureToData(temperature); - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::WRITE_DATA, - OpenThermMessageID::TdhwSet, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::TdhwSet)) { - return false; - } - - vars.slave.dhw.targetTemp = CustomOpenTherm::getFloat(response); - - return CustomOpenTherm::getUInt(response) == request; - } - - - bool setRoomTemp(const float temperature) { - const unsigned int request = CustomOpenTherm::temperatureToData(temperature); - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::WRITE_DATA, - OpenThermMessageID::Tr, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::Tr)) { - return false; - } - - vars.slave.heating.indoorTemp = CustomOpenTherm::getFloat(response); - - return CustomOpenTherm::getUInt(response) == request; - } - - bool setRoomTempCh2(const float temperature) { - const unsigned int request = CustomOpenTherm::temperatureToData(temperature); - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::WRITE_DATA, - OpenThermMessageID::TrCH2, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::TrCH2)) { - return false; - } - - vars.slave.ch2.indoorTemp = CustomOpenTherm::getFloat(response); - - return CustomOpenTherm::getUInt(response) == request; - } - - bool setRoomSetpoint(const float temperature) { - const unsigned int request = CustomOpenTherm::temperatureToData(temperature); - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::WRITE_DATA, - OpenThermMessageID::TrSet, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::TrSet)) { - return false; - } - - vars.slave.heating.targetTemp = CustomOpenTherm::getFloat(response); - - return CustomOpenTherm::getUInt(response) == request; - } - - bool setRoomSetpointCh2(const float temperature) { - const unsigned int request = CustomOpenTherm::temperatureToData(temperature); - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::WRITE_DATA, - OpenThermMessageID::TrSetCH2, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::TrSetCH2)) { - return false; - } - - vars.slave.ch2.targetTemp = CustomOpenTherm::getFloat(response); - - return CustomOpenTherm::getUInt(response) == request; - } - - bool setMaxHeatingTemp(const float temperature) { - const unsigned int request = CustomOpenTherm::temperatureToData(temperature); - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::WRITE_DATA, - OpenThermMessageID::MaxTSet, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::MaxTSet)) { - return false; - } - - return CustomOpenTherm::getUInt(response) == request; - } - - bool setHeatingTemp(const float temperature) { - const unsigned int request = CustomOpenTherm::temperatureToData(temperature); - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::WRITE_DATA, - OpenThermMessageID::TSet, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::TSet)) { - return false; - } - - vars.slave.heating.targetTemp = CustomOpenTherm::getFloat(response); - - return CustomOpenTherm::getUInt(response) == request; - } - - bool setCh2Temp(const float temperature) { - const unsigned int request = CustomOpenTherm::temperatureToData(temperature); - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::WRITE_DATA, - OpenThermMessageID::TsetCH2, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::TsetCH2)) { - return false; - } - - vars.slave.ch2.targetTemp = CustomOpenTherm::getFloat(response); - - return CustomOpenTherm::getUInt(response) == request; - } - - bool setMasterVersion(const uint8_t version, const uint8_t type) { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::WRITE_DATA, - OpenThermMessageID::MasterVersion, - (unsigned int) version | (unsigned int) type << 8 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::MasterVersion)) { - return false; - } - - uint8_t rVersion = response & 0xFF; - uint8_t rType = (response & 0xFFFF) >> 8; - - return rVersion == version && rType == type; - } - - bool setMasterOtVersion(const float version) { - const unsigned int request = CustomOpenTherm::toFloat(version); - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::WRITE_DATA, - OpenThermMessageID::OpenThermVersionMaster, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::OpenThermVersionMaster)) { - return false; - } - - return CustomOpenTherm::getUInt(response) == request; - } - - /** - * @brief Set the Master Config - * From slave member id code: - * id: slave.memberIdCode & 0xFF, - * flags: (slave.memberIdCode & 0xFFFF) >> 8 - * @param id - * @param flags - * @param force - * @return true - * @return false - */ - bool setMasterConfig(const uint8_t id, const uint8_t flags, const bool force = false) { - const uint8_t rMemberId = (force || id > 0) ? id : vars.slave.memberId; - const uint8_t rFlags = (force || flags > 0) ? flags : vars.slave.flags; - const unsigned int request = (unsigned int) rMemberId | (unsigned int) rFlags << 8; - - // if empty request - if (!request) { - return true; - } - - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::WRITE_DATA, - OpenThermMessageID::MConfigMMemberIDcode, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::MConfigMMemberIDcode)) { - return false; - } - - //uint8_t rMemberId = response & 0xFF; - //uint8_t rFlags = (response & 0xFFFF) >> 8; - - return CustomOpenTherm::getUInt(response) == request; - } - - bool updateSlaveOtVersion() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::OpenThermVersionSlave, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::OpenThermVersionSlave)) { - return false; - } - - vars.slave.protocolVersion = CustomOpenTherm::getFloat(response); - - return true; - } - - bool updateSlaveVersion() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::SlaveVersion, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::SlaveVersion)) { - return false; - } - - vars.slave.appVersion = response & 0xFF; - vars.slave.type = (response & 0xFFFF) >> 8; - - return true; - } - - bool updateMinModulationLevel() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::MaxCapacityMinModLevel, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::MaxCapacityMinModLevel)) { - return false; - } - - vars.slave.modulation.min = response & 0xFF; - vars.slave.power.max = (response & 0xFFFF) >> 8; - vars.slave.power.min = vars.slave.modulation.min > 0 && vars.slave.power.max > 0.1f - ? (vars.slave.modulation.min * 0.01f) * vars.slave.power.max - : 0.0f; - - return true; - } - - bool updateMinMaxDhwTemp() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::TdhwSetUBTdhwSetLB, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::TdhwSetUBTdhwSetLB)) { - return false; - } - - uint8_t minTemp = response & 0xFF; - uint8_t maxTemp = (response & 0xFFFF) >> 8; - - if (minTemp >= 0 && maxTemp > 0 && maxTemp > minTemp) { - vars.slave.dhw.minTemp = minTemp; - vars.slave.dhw.maxTemp = maxTemp; - - return true; - } - - return false; - } - - bool updateMinMaxHeatingTemp() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::MaxTSetUBMaxTSetLB, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::MaxTSetUBMaxTSetLB)) { - return false; - } - - uint8_t minTemp = response & 0xFF; - uint8_t maxTemp = (response & 0xFFFF) >> 8; - - if (minTemp >= 0 && maxTemp > 0 && maxTemp > minTemp) { - vars.slave.heating.minTemp = minTemp; - vars.slave.heating.maxTemp = maxTemp; - - return true; - } - - return false; - } - - bool updateFaultCode() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::ASFflags, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::ASFflags)) { - return false; - } - - vars.slave.fault.code = response & 0xFF; - - return true; - } - - bool updateDiagCode() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::OEMDiagnosticCode, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::OEMDiagnosticCode)) { - return false; - } - - vars.slave.diag.code = CustomOpenTherm::getUInt(response); - - return true; - } - - bool updateBurnerStarts() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::SuccessfulBurnerStarts, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::SuccessfulBurnerStarts)) { - return false; - } - - vars.slave.stats.burnerStarts = CustomOpenTherm::getUInt(response); - - return true; - } - - bool updateDhwBurnerStarts() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::DHWBurnerStarts, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::DHWBurnerStarts)) { - return false; - } - - vars.slave.stats.dhwBurnerStarts = CustomOpenTherm::getUInt(response); - - return true; - } - - bool updateHeatingPumpStarts() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::CHPumpStarts, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::CHPumpStarts)) { - return false; - } - - vars.slave.stats.heatingPumpStarts = CustomOpenTherm::getUInt(response); - - return true; - } - - bool updateDhwPumpStarts() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::DHWPumpValveStarts, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::DHWPumpValveStarts)) { - return false; - } - - vars.slave.stats.dhwPumpStarts = CustomOpenTherm::getUInt(response); - - return true; - } - - bool updateBurnerHours() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::BurnerOperationHours, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::BurnerOperationHours)) { - return false; - } - - vars.slave.stats.burnerHours = CustomOpenTherm::getUInt(response); - - return true; - } - - bool updateDhwBurnerHours() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::DHWBurnerOperationHours, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::DHWBurnerOperationHours)) { - return false; - } - - vars.slave.stats.dhwBurnerHours = CustomOpenTherm::getUInt(response); - - return true; - } - - bool updateHeatingPumpHours() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::CHPumpOperationHours, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::CHPumpOperationHours)) { - return false; - } - - vars.slave.stats.heatingPumpHours = CustomOpenTherm::getUInt(response); - - return true; - } - - bool updateDhwPumpHours() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::DHWPumpValveOperationHours, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::DHWPumpValveOperationHours)) { - return false; - } - - vars.slave.stats.dhwPumpHours = CustomOpenTherm::getUInt(response); - - return true; - } - - bool updateCoolingHours() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::CoolingOperationHours, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::CoolingOperationHours)) { - return false; - } - - vars.slave.stats.coolingHours = CustomOpenTherm::getUInt(response); - - return true; - } - - bool updateModulationLevel() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::RelModLevel, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::RelModLevel)) { - return false; - } - - const float value = CustomOpenTherm::getFloat(response); - if (value < 0) { - return false; - } - - vars.slave.modulation.current = value; - - return true; - } - - bool updateDhwTemp() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::READ_DATA, - OpenThermMessageID::Tdhw, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::Tdhw)) { - return false; - } - - const float value = CustomOpenTherm::getFloat(response); - if (value <= 0) { - return false; - } - - vars.slave.dhw.currentTemp = value; - - return true; - } - - bool updateDhwTemp2() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::READ_DATA, - OpenThermMessageID::Tdhw2, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::Tdhw2)) { - return false; - } - - const float value = CustomOpenTherm::getFloat(response); - if (value <= 0) { - return false; - } - - vars.slave.dhw.currentTemp2 = value; - - return true; - } - - bool updateDhwFlowRate() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::READ_DATA, - OpenThermMessageID::DHWFlowRate, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::DHWFlowRate)) { - return false; - } - - float value = CustomOpenTherm::getFloat(response); - if (value < 0) { - return false; - } - - // no minuscule values - // some boilers send a response of 0.06 when there is no flow - if (value < 0.1f) { - value = 0.0f; - } - - vars.slave.dhw.flowRate = value; - - return true; - } - - bool updateHeatingTemp() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::READ_DATA, - OpenThermMessageID::Tboiler, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::Tboiler)) { - return false; - } - - const float value = CustomOpenTherm::getFloat(response); - if (value <= 0) { - return false; - } - - vars.slave.heating.currentTemp = value; - - return true; - } - - bool updateHeatingReturnTemp() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::READ_DATA, - OpenThermMessageID::Tret, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::Tret)) { - return false; - } - - vars.slave.heating.returnTemp = CustomOpenTherm::getFloat(response); - - return true; - } - - bool updateCh2Temp() { - unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::TflowCH2, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::TflowCH2)) { - return false; - } - - vars.slave.ch2.currentTemp = CustomOpenTherm::getFloat(response); - - return true; - } - - - - bool updateExhaustTemp() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::Texhaust, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::Texhaust)) { - return false; - } - - const float value = (float) CustomOpenTherm::getInt(response); - if (!isValidTemp(value, settings.opentherm.unitSystem, -40, 500)) { - return false; - } - - vars.slave.exhaust.temp = value; - - return true; - } - - bool updateHeatExchangerTemp() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::TboilerHeatExchanger, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::TboilerHeatExchanger)) { - return false; - } - - const float value = (float) CustomOpenTherm::getInt(response); - if (value <= 0) { - return false; - } - - vars.slave.heatExchangerTemp = value; - - return true; - } - - bool updateOutdoorTemp() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::Toutside, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::Toutside)) { - return false; - } - - vars.slave.heating.outdoorTemp = CustomOpenTherm::getFloat(response); - - return true; - } - - bool updateSolarStorageTemp() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::READ_DATA, - OpenThermMessageID::Tstorage, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::Tstorage)) { - return false; - } - - vars.slave.solar.storage = CustomOpenTherm::getFloat(response); - - return true; - } - - bool updateSolarCollectorTemp() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::READ_DATA, - OpenThermMessageID::Tcollector, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::Tcollector)) { - return false; - } - - vars.slave.solar.collector = CustomOpenTherm::getFloat(response); - - return true; - } - - bool updateFanSpeed() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::BoilerFanSpeedSetpointAndActual, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::BoilerFanSpeedSetpointAndActual)) { - return false; - } - - vars.slave.fanSpeed.setpoint = (response & 0xFFFF) >> 8; - vars.slave.fanSpeed.current = response & 0xFF; - - return true; - } - - bool updatePressure() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::CHPressure, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::CHPressure)) { - return false; - } - - const float value = CustomOpenTherm::getFloat(response); - if (value < 0) { - return false; - } - - vars.slave.pressure = value; - - return true; - } - - bool updateExhaustCo2() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::CO2exhaust, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::CO2exhaust)) { - return false; - } - - vars.slave.exhaust.co2 = CustomOpenTherm::getUInt(response); - - return true; - } - - bool updateExhaustFanSpeed() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::RPMexhaust, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::RPMexhaust)) { - return false; - } - - vars.slave.exhaust.fanSpeed = CustomOpenTherm::getUInt(response); - - return true; - } - - bool updateSupplyFanSpeed() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::RPMsupply, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::RPMsupply)) { - return false; - } - - vars.slave.fanSpeed.supply = CustomOpenTherm::getUInt(response); - - return true; - } -}; diff --git a/src/PortalTask.h b/src/PortalTask.h deleted file mode 100644 index 6142d54..0000000 --- a/src/PortalTask.h +++ /dev/null @@ -1,1194 +0,0 @@ -//#define PORTAL_CACHE "max-age=86400" -#define PORTAL_CACHE nullptr -#ifdef ARDUINO_ARCH_ESP8266 -#include -#include -#include -using WebServer = ESP8266WebServer; -#else -#include -#include -#include -#endif -#include -#include -#include -#include -#include - -using namespace NetworkUtils; - -extern NetworkMgr* network; -extern FileData fsNetworkSettings, fsSettings, fsSensorsSettings; -extern MqttTask* tMqtt; - - -class PortalTask : public LeanTask { -public: - PortalTask(bool _enabled = false, unsigned long _interval = 0) : LeanTask(_enabled, _interval) { - this->webServer = new WebServer(80); - this->bufferedWebServer = new BufferedWebServer(this->webServer, 32u); - this->dnsServer = new DNSServer(); - this->mDnsRetryTime = millis() - this->mDnsRetryInterval; - } - - ~PortalTask() { - delete this->bufferedWebServer; - - if (this->webServer != nullptr) { - this->stopWebServer(); - delete this->webServer; - } - - if (this->dnsServer != nullptr) { - this->stopDnsServer(); - delete this->dnsServer; - } - } - -protected: - const unsigned int changeStateInterval = 5000; - - WebServer* webServer = nullptr; - BufferedWebServer* bufferedWebServer = nullptr; - DNSServer* dnsServer = nullptr; - - bool webServerEnabled = false; - bool dnsServerEnabled = false; - unsigned long webServerChangeState = 0; - bool mDnsState = false; - #if USE_ETHERNET - NetworkMgr::Uplink mdnsConnectionType = NetworkMgr::Uplink::None; - #endif - unsigned long mDnsRetryTime = 0; - const unsigned long mDnsRetryInterval = 5000; - - #if defined(ARDUINO_ARCH_ESP32) - const char* getTaskName() override { - return "Portal"; - } - - /*BaseType_t getTaskCore() override { - return 1; - }*/ - - int getTaskPriority() override { - return 1; - } - #endif - - void setup() { - this->dnsServer->setTTL(0); - this->dnsServer->setErrorReplyCode(DNSReplyCode::NoError); - this->webServer->enableETag(true, [](FS &fs, const String &fName) -> const String { - char buf[32]; - { - MD5Builder md5; - md5.begin(); - md5.add(fName); - md5.add(" " BUILD_ENV " " BUILD_VERSION " " __DATE__ " " __TIME__); - md5.calculate(); - md5.getChars(buf); - } - - String etag; - etag.reserve(34); - etag += '\"'; - etag.concat(buf, 32); - etag += '\"'; - return etag; - }); - - // index page - /*auto indexPage = (new DynamicPage("/", &LittleFS, "/pages/index.html")) - ->setTemplateCallback([](const char* var) -> String { - String result; - - if (strcmp(var, "ver") == 0) { - result = BUILD_VERSION; - } - - return result; - }); - this->webServer->addHandler(indexPage);*/ - this->webServer->addHandler(new StaticPage("/", &LittleFS, F("/pages/index.html"), PORTAL_CACHE)); - - // dashboard page - auto dashboardPage = (new StaticPage("/dashboard.html", &LittleFS, F("/pages/dashboard.html"), PORTAL_CACHE)) - ->setBeforeSendCallback([this]() { - if (this->isAuthRequired() && !this->isValidCredentials()) { - this->webServer->requestAuthentication(BASIC_AUTH); - return false; - } - - return true; - }); - this->webServer->addHandler(dashboardPage); - - // restart - this->webServer->on(F("/restart.html"), HTTP_GET, [this]() { - if (this->isAuthRequired() && !this->isValidCredentials()) { - this->webServer->requestAuthentication(BASIC_AUTH); - return; - } - - vars.actions.restart = true; - this->webServer->sendHeader(F("Location"), "/"); - this->webServer->send(302); - }); - - // network settings page - auto networkPage = (new StaticPage("/network.html", &LittleFS, F("/pages/network.html"), PORTAL_CACHE)) - ->setBeforeSendCallback([this]() { - if (this->isAuthRequired() && !this->isValidCredentials()) { - this->webServer->requestAuthentication(BASIC_AUTH); - return false; - } - - return true; - }); - this->webServer->addHandler(networkPage); - - // settings page - auto settingsPage = (new StaticPage("/settings.html", &LittleFS, F("/pages/settings.html"), PORTAL_CACHE)) - ->setBeforeSendCallback([this]() { - if (this->isAuthRequired() && !this->isValidCredentials()) { - this->webServer->requestAuthentication(BASIC_AUTH); - return false; - } - - return true; - }); - this->webServer->addHandler(settingsPage); - - // sensors page - auto sensorsPage = (new StaticPage("/sensors.html", &LittleFS, F("/pages/sensors.html"), PORTAL_CACHE)) - ->setBeforeSendCallback([this]() { - if (this->isAuthRequired() && !this->isValidCredentials()) { - this->webServer->requestAuthentication(BASIC_AUTH); - return false; - } - - return true; - }); - this->webServer->addHandler(sensorsPage); - - // upgrade page - auto upgradePage = (new StaticPage("/upgrade.html", &LittleFS, F("/pages/upgrade.html"), PORTAL_CACHE)) - ->setBeforeSendCallback([this]() { - if (this->isAuthRequired() && !this->isValidCredentials()) { - this->webServer->requestAuthentication(BASIC_AUTH); - return false; - } - - return true; - }); - this->webServer->addHandler(upgradePage); - - // OTA - auto upgradeHandler = (new UpgradeHandler("/api/upgrade"))->setCanUploadCallback([this](const String& uri) { - if (this->isAuthRequired() && !this->isValidCredentials()) { - this->webServer->sendHeader(F("Connection"), F("close")); - this->webServer->send(401); - return false; - } - - return true; - })->setBeforeUpgradeCallback([](UpgradeHandler::UpgradeType type) -> bool { - if (vars.states.restarting) { - return false; - } - - vars.states.upgrading = true; - return true; - })->setAfterUpgradeCallback([this](const UpgradeHandler::UpgradeResult& fwResult, const UpgradeHandler::UpgradeResult& fsResult) { - unsigned short status = 200; - if (fwResult.status == UpgradeHandler::UpgradeStatus::SUCCESS || fsResult.status == UpgradeHandler::UpgradeStatus::SUCCESS) { - vars.actions.restart = true; - - } else { - status = 400; - } - - String response = F("{\"firmware\": {\"status\": "); - response.concat((short int) fwResult.status); - response.concat(F(", \"error\": \"")); - response.concat(fwResult.error); - response.concat(F("\"}, \"filesystem\": {\"status\": ")); - response.concat((short int) fsResult.status); - response.concat(F(", \"error\": \"")); - response.concat(fsResult.error); - response.concat(F("\"}}")); - this->webServer->send(status, F("application/json"), response); - - vars.states.upgrading = false; - }); - this->webServer->addHandler(upgradeHandler); - - - // backup - this->webServer->on(F("/api/backup/save"), HTTP_GET, [this]() { - if (this->isAuthRequired() && !this->isValidCredentials()) { - return this->webServer->send(401); - } - - JsonDocument doc; - - auto networkDoc = doc[FPSTR(S_NETWORK)].to(); - networkSettingsToJson(networkSettings, networkDoc); - - auto settingsDoc = doc[FPSTR(S_SETTINGS)].to(); - settingsToJson(settings, settingsDoc); - - for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { - auto sensorsettingsDoc = doc[FPSTR(S_SENSORS)][sensorId].to(); - sensorSettingsToJson(sensorId, Sensors::settings[sensorId], sensorsettingsDoc); - } - - doc.shrinkToFit(); - - char filename[64]; - getFilename(filename, sizeof(filename), "backup"); - - char contentDispositionHeaderValue[128]; - snprintf_P( - contentDispositionHeaderValue, - sizeof(contentDispositionHeaderValue), - PSTR("attachment; filename=\"%s\""), - filename - ); - this->webServer->sendHeader(F("Content-Disposition"), contentDispositionHeaderValue); - this->bufferedWebServer->send(200, F("application/json"), doc); - }); - - this->webServer->on(F("/api/backup/restore"), HTTP_POST, [this]() { - if (this->isAuthRequired() && !this->isValidCredentials()) { - return this->webServer->send(401); - } - - if (vars.states.restarting) { - return this->webServer->send(503); - } - - const String& plain = this->webServer->arg(0); - Log.straceln(FPSTR(L_PORTAL_WEBSERVER), F("Request /api/backup/restore %d bytes: %s"), plain.length(), plain.c_str()); - - if (plain.length() < 5) { - this->webServer->send(406); - return; - - } else if (plain.length() > 2536) { - this->webServer->send(413); - return; - } - - JsonDocument doc; - DeserializationError dErr = deserializeJson(doc, plain); - - if (dErr != DeserializationError::Ok || doc.isNull() || !doc.size()) { - this->webServer->send(400); - return; - } - - bool changed = false; - if (!doc[FPSTR(S_NETWORK)].isNull() && jsonToNetworkSettings(doc[FPSTR(S_NETWORK)], networkSettings)) { - fsNetworkSettings.update(); - network->setHostname(networkSettings.hostname) - ->setStaCredentials(networkSettings.sta.ssid, networkSettings.sta.password, networkSettings.sta.channel) - ->setApCredentials(networkSettings.ap.ssid, networkSettings.ap.password, networkSettings.ap.channel) - ->setUseDhcp(networkSettings.useDhcp) - ->setStaticConfig( - networkSettings.staticConfig.ip, - networkSettings.staticConfig.gateway, - networkSettings.staticConfig.subnet, - networkSettings.staticConfig.dns - ) - ->setEthernet(networkSettings.ethernet.enabled); - changed = true; - } - - if (!doc[FPSTR(S_SETTINGS)].isNull() && jsonToSettings(doc[FPSTR(S_SETTINGS)], settings)) { - fsSettings.update(); - applyEthernetSettings(); - changed = true; - } - - if (!doc[FPSTR(S_SENSORS)].isNull()) { - for (auto sensor : doc[FPSTR(S_SENSORS)].as()) { - if (!isDigit(sensor.key().c_str())) { - continue; - } - - int sensorId = atoi(sensor.key().c_str()); - if (sensorId < 0 || sensorId > 255 || !Sensors::isValidSensorId(sensorId)) { - continue; - } - - if (jsonToSensorSettings(sensorId, sensor.value(), Sensors::settings[sensorId])) { - fsSensorsSettings.update(); - changed = true; - } - } - } - - doc.clear(); - doc.shrinkToFit(); - - if (changed) { - vars.actions.restart = true; - } - - this->webServer->send(changed ? 201 : 200); - }); - - // network - this->webServer->on(F("/api/network/settings"), HTTP_GET, [this]() { - if (this->isAuthRequired() && !this->isValidCredentials()) { - return this->webServer->send(401); - } - - JsonDocument doc; - networkSettingsToJson(networkSettings, doc); - this->ethernetToJson(doc); - doc.shrinkToFit(); - - this->bufferedWebServer->send(200, F("application/json"), doc); - }); - - this->webServer->on(F("/api/network/settings"), HTTP_POST, [this]() { - if (this->isAuthRequired() && !this->isValidCredentials()) { - return this->webServer->send(401); - } - - if (vars.states.restarting) { - return this->webServer->send(503); - } - - const String& plain = this->webServer->arg(0); - Log.straceln(FPSTR(L_PORTAL_WEBSERVER), F("Request /api/network/settings %d bytes: %s"), plain.length(), plain.c_str()); - - if (plain.length() < 5) { - this->webServer->send(406); - return; - - } else if (plain.length() > 512) { - this->webServer->send(413); - return; - } - - JsonDocument doc; - DeserializationError dErr = deserializeJson(doc, plain); - - if (dErr != DeserializationError::Ok || doc.isNull() || !doc.size()) { - this->webServer->send(400); - return; - } - - bool changed = jsonToNetworkSettings(doc, networkSettings); - - // ethernet is only usable with a complete W5500 pin set - if (!this->isEthernetConfigured() && networkSettings.ethernet.enabled) { - networkSettings.ethernet.enabled = false; - changed = true; - } - - doc.clear(); - doc.shrinkToFit(); - - networkSettingsToJson(networkSettings, doc); - this->ethernetToJson(doc); - doc.shrinkToFit(); - - this->bufferedWebServer->send(changed ? 201 : 200, F("application/json"), doc); - - if (changed) { - doc.clear(); - doc.shrinkToFit(); - - fsNetworkSettings.update(); - network->setHostname(networkSettings.hostname) - ->setStaCredentials(networkSettings.sta.ssid, networkSettings.sta.password, networkSettings.sta.channel) - ->setApCredentials(networkSettings.ap.ssid, networkSettings.ap.password, networkSettings.ap.channel) - ->setUseDhcp(networkSettings.useDhcp) - ->setStaticConfig( - networkSettings.staticConfig.ip, - networkSettings.staticConfig.gateway, - networkSettings.staticConfig.subnet, - networkSettings.staticConfig.dns - ) - ->setEthernet(networkSettings.ethernet.enabled) - ->reconnect(); - - this->applyEthernetSettings(); - } - }); - - this->webServer->on(F("/api/network/scan"), HTTP_GET, [this]() { - if (this->isAuthRequired() && !this->isValidCredentials()) { - return this->webServer->send(401); - } - - // scanning needs WiFi, which is not the uplink while ethernet carries the traffic - if (network->getUplink() == NetworkMgr::Uplink::Ethernet) { - this->webServer->send(409); - return; - } - - auto apCount = WiFi.scanComplete(); - if (apCount <= 0) { - if (apCount != WIFI_SCAN_RUNNING) { - #ifdef ARDUINO_ARCH_ESP8266 - WiFi.scanNetworks(true, true); - #else - WiFi.scanNetworks(true, true, true); - #endif - } - - this->webServer->send(404); - return; - } - - JsonDocument doc; - for (short int i = 0; i < apCount; i++) { - const String& ssid = WiFi.SSID(i); - doc[i][FPSTR(S_SSID)] = ssid; - doc[i][FPSTR(S_BSSID)] = WiFi.BSSIDstr(i); - doc[i][FPSTR(S_SIGNAL_QUALITY)] = NetworkMgr::rssiToSignalQuality(WiFi.RSSI(i)); - doc[i][FPSTR(S_CHANNEL)] = WiFi.channel(i); - doc[i][FPSTR(S_HIDDEN)] = !ssid.length(); - #ifdef ARDUINO_ARCH_ESP8266 - const bss_info* info = WiFi.getScanInfoByIndex(i); - doc[i][FPSTR(S_AUTH)] = info->authmode; - #else - doc[i][FPSTR(S_AUTH)] = WiFi.encryptionType(i); - #endif - } - doc.shrinkToFit(); - - this->bufferedWebServer->send(200, F("application/json"), doc); - - WiFi.scanDelete(); - }); - - - // settings - this->webServer->on(F("/api/settings"), HTTP_GET, [this]() { - if (this->isAuthRequired() && !this->isValidCredentials()) { - return this->webServer->send(401); - } - - JsonDocument doc; - settingsToJson(settings, doc); - doc.shrinkToFit(); - - this->bufferedWebServer->send(200, F("application/json"), doc); - }); - - this->webServer->on(F("/api/settings"), HTTP_POST, [this]() { - if (this->isAuthRequired() && !this->isValidCredentials()) { - return this->webServer->send(401); - } - - if (vars.states.restarting) { - return this->webServer->send(503); - } - - const String& plain = this->webServer->arg(0); - Log.straceln(FPSTR(L_PORTAL_WEBSERVER), F("Request /api/settings %d bytes: %s"), plain.length(), plain.c_str()); - - if (plain.length() < 5) { - this->webServer->send(406); - return; - - } else if (plain.length() > 2536) { - this->webServer->send(413); - return; - } - - JsonDocument doc; - DeserializationError dErr = deserializeJson(doc, plain); - - if (dErr != DeserializationError::Ok || doc.isNull() || !doc.size()) { - this->webServer->send(400); - return; - } - - bool changed = jsonToSettings(doc, settings); - doc.clear(); - doc.shrinkToFit(); - - settingsToJson(settings, doc); - doc.shrinkToFit(); - - this->bufferedWebServer->send(changed ? 201 : 200, F("application/json"), doc); - - if (changed) { - doc.clear(); - doc.shrinkToFit(); - - fsSettings.update(); - applyEthernetSettings(); - tMqtt->resetPublishedSettingsTime(); - } - }); - - - // sensors list - this->webServer->on(F("/api/sensors"), HTTP_GET, [this]() { - if (this->isAuthRequired() && !this->isValidCredentials()) { - return this->webServer->send(401); - } - - bool detailed = false; - if (this->webServer->hasArg(F("detailed"))) { - detailed = this->webServer->arg(F("detailed")).toInt() > 0; - } - - JsonDocument doc; - for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { - if (detailed) { - auto& sSensor = Sensors::settings[sensorId]; - doc[sensorId][FPSTR(S_ENABLED)] = sSensor.enabled; - doc[sensorId][FPSTR(S_NAME)] = sSensor.name; - doc[sensorId][FPSTR(S_PURPOSE)] = static_cast(sSensor.purpose); - sensorResultToJson(sensorId, doc[sensorId]); - - } else { - doc[sensorId] = Sensors::settings[sensorId].name; - } - } - - doc.shrinkToFit(); - this->bufferedWebServer->send(200, F("application/json"), doc); - }); - - // sensor settings - this->webServer->on(F("/api/sensor"), HTTP_GET, [this]() { - if (this->isAuthRequired() && !this->isValidCredentials()) { - return this->webServer->send(401); - } - - if (!this->webServer->hasArg(F("id"))) { - return this->webServer->send(400); - } - - auto id = this->webServer->arg(F("id")); - if (!isDigit(id.c_str())) { - return this->webServer->send(400); - } - - uint8_t sensorId = id.toInt(); - id.clear(); - if (!Sensors::isValidSensorId(sensorId)) { - return this->webServer->send(404); - } - - JsonDocument doc; - sensorSettingsToJson(sensorId, Sensors::settings[sensorId], doc); - doc.shrinkToFit(); - this->bufferedWebServer->send(200, F("application/json"), doc); - }); - - this->webServer->on(F("/api/sensor"), HTTP_POST, [this]() { - if (this->isAuthRequired() && !this->isValidCredentials()) { - return this->webServer->send(401); - } - - if (vars.states.restarting) { - return this->webServer->send(503); - } - - #ifdef ARDUINO_ARCH_ESP8266 - if (!this->webServer->hasArg(F("id")) || this->webServer->args() != 1) { - return this->webServer->send(400); - } - #else - if (!this->webServer->hasArg(F("id")) || this->webServer->args() != 2) { - return this->webServer->send(400); - } - #endif - - auto id = this->webServer->arg(F("id")); - if (!isDigit(id.c_str())) { - return this->webServer->send(400); - } - - uint8_t sensorId = id.toInt(); - id.clear(); - if (!Sensors::isValidSensorId(sensorId)) { - return this->webServer->send(404); - } - - auto plain = this->webServer->arg(1); - Log.straceln(FPSTR(L_PORTAL_WEBSERVER), F("Request /api/sensor/?id=%hhu %d bytes: %s"), sensorId, plain.length(), plain.c_str()); - - if (plain.length() < 5) { - return this->webServer->send(406); - - } else if (plain.length() > 1024) { - return this->webServer->send(413); - } - - bool changed = false; - auto prevSettings = Sensors::settings[sensorId]; - { - JsonDocument doc; - DeserializationError dErr = deserializeJson(doc, plain); - plain.clear(); - - if (dErr != DeserializationError::Ok || doc.isNull() || !doc.size()) { - return this->webServer->send(400); - } - - if (jsonToSensorSettings(sensorId, doc, Sensors::settings[sensorId])) { - changed = true; - } - } - - { - JsonDocument doc; - auto& sSettings = Sensors::settings[sensorId]; - sensorSettingsToJson(sensorId, sSettings, doc); - doc.shrinkToFit(); - - this->bufferedWebServer->send(changed ? 201 : 200, F("application/json"), doc); - } - - if (changed) { - tMqtt->reconfigureSensor(sensorId, prevSettings); - fsSensorsSettings.update(); - } - }); - - - // vars - this->webServer->on(F("/api/vars"), HTTP_GET, [this]() { - JsonDocument doc; - varsToJson(vars, doc); - doc.shrinkToFit(); - - this->bufferedWebServer->send(200, F("application/json"), doc); - }); - - this->webServer->on(F("/api/vars"), HTTP_POST, [this]() { - if (this->isAuthRequired() && !this->isValidCredentials()) { - return this->webServer->send(401); - } - - const String& plain = this->webServer->arg(0); - Log.straceln(FPSTR(L_PORTAL_WEBSERVER), F("Request /api/vars %d bytes: %s"), plain.length(), plain.c_str()); - - if (plain.length() < 5) { - this->webServer->send(406); - return; - - } else if (plain.length() > 1536) { - this->webServer->send(413); - return; - } - - JsonDocument doc; - DeserializationError dErr = deserializeJson(doc, plain); - - if (dErr != DeserializationError::Ok || doc.isNull() || !doc.size()) { - this->webServer->send(400); - return; - } - - bool changed = jsonToVars(doc, vars); - doc.clear(); - doc.shrinkToFit(); - - varsToJson(vars, doc); - doc.shrinkToFit(); - - this->bufferedWebServer->send(changed ? 201 : 200, F("application/json"), doc); - - if (changed) { - doc.clear(); - doc.shrinkToFit(); - - tMqtt->resetPublishedVarsTime(); - } - }); - - this->webServer->on(F("/api/info"), HTTP_GET, [this]() { - bool isConnected = network->isConnected(); - - JsonDocument doc; - - // capabilities: only the flags this build actually has; the UI shows features on an explicit true - auto docFeatures = doc[FPSTR(S_FEATURES)].to(); - #if USE_ETHERNET - docFeatures[FPSTR(S_ETHERNET)] = true; - #endif - - #if USE_BLE - docFeatures[FPSTR(S_BLE)] = true; - #endif - - auto docSystem = doc[FPSTR(S_SYSTEM)].to(); - docSystem[FPSTR(S_RESET_REASON)] = getResetReason(); - docSystem[FPSTR(S_UPTIME)] = millis() / 1000; - - auto docNetwork = doc[FPSTR(S_NETWORK)].to(); - docNetwork[FPSTR(S_HOSTNAME)] = networkSettings.hostname; - docNetwork[FPSTR(S_MAC)] = network->getStaMac(); - docNetwork[FPSTR(S_CONNECTED)] = isConnected; - docNetwork[FPSTR(S_CONNECTION_TYPE)] = network->getConnectionType(); - // SSID, signal and channel describe the WiFi uplink only: with ethernet up the radio is - // parked and those readings are stale, so report them as not applicable rather than 0 dBm - const bool wifiUplink = network->getUplink() == NetworkMgr::Uplink::Wifi; - const char* staSsid = network->getStaSsid(); - - docNetwork[FPSTR(S_SSID)] = (wifiUplink && staSsid) ? staSsid : ""; - docNetwork[FPSTR(S_SIGNAL_QUALITY)] = network->getSignalQuality(); - docNetwork[FPSTR(S_CHANNEL)] = wifiUplink ? network->getStaChannel() : 0; - docNetwork[FPSTR(S_IP)] = isConnected ? network->getStaIp().toString() : ""; - docNetwork[FPSTR(S_SUBNET)] = isConnected ? network->getStaSubnet().toString() : ""; - docNetwork[FPSTR(S_GATEWAY)] = isConnected ? network->getStaGateway().toString() : ""; - docNetwork[FPSTR(S_DNS)] = isConnected ? network->getStaDns().toString() : ""; - - auto docBuild = doc[FPSTR(S_BUILD)].to(); - docBuild[FPSTR(S_VERSION)] = BUILD_VERSION; - docBuild[FPSTR(S_DATE)] = __DATE__ " " __TIME__; - docBuild[FPSTR(S_ENV)] = BUILD_ENV; - #ifdef ARDUINO_ARCH_ESP8266 - docBuild[FPSTR(S_CORE)] = ESP.getCoreVersion(); - docBuild[FPSTR(S_SDK)] = ESP.getSdkVersion(); - #elif ARDUINO_ARCH_ESP32 - docBuild[FPSTR(S_CORE)] = ESP.getCoreVersion(); - docBuild[FPSTR(S_SDK)] = ESP.getSdkVersion(); - #else - docBuild[FPSTR(S_CORE)] = 0; - docBuild[FPSTR(S_SDK)] = 0; - #endif - - auto docHeap = doc[FPSTR(S_HEAP)].to(); - docHeap[FPSTR(S_TOTAL)] = getTotalHeap(); - docHeap[FPSTR(S_FREE)] = getFreeHeap(); - docHeap[FPSTR(S_MIN_FREE)] = getFreeHeap(true); - docHeap[FPSTR(S_MAX_FREE_BLOCK)] = getMaxFreeBlockHeap(); - docHeap[FPSTR(S_MIN_MAX_FREE_BLOCK)] = getMaxFreeBlockHeap(true); - - auto docChip = doc[FPSTR(S_CHIP)].to(); - #ifdef ARDUINO_ARCH_ESP8266 - docChip[FPSTR(S_MODEL)] = esp_is_8285() ? F("ESP8285") : F("ESP8266"); - docChip[FPSTR(S_REV)] = 0; - docChip[FPSTR(S_CORES)] = 1; - docChip[FPSTR(S_FREQ)] = ESP.getCpuFreqMHz(); - #elif ARDUINO_ARCH_ESP32 - docChip[FPSTR(S_MODEL)] = ESP.getChipModel(); - docChip[FPSTR(S_REV)] = ESP.getChipRevision(); - docChip[FPSTR(S_CORES)] = ESP.getChipCores(); - docChip[FPSTR(S_FREQ)] = ESP.getCpuFreqMHz(); - #else - docChip[FPSTR(S_MODEL)] = 0; - docChip[FPSTR(S_REV)] = 0; - docChip[FPSTR(S_CORES)] = 0; - docChip[FPSTR(S_FREQ)] = 0; - #endif - - auto docFlash = doc[FPSTR(S_FLASH)].to(); - #ifdef ARDUINO_ARCH_ESP8266 - docFlash[FPSTR(S_SIZE)] = ESP.getFlashChipSize(); - docFlash[FPSTR(S_REAL_SIZE)] = ESP.getFlashChipRealSize(); - #elif ARDUINO_ARCH_ESP32 - docFlash[FPSTR(S_SIZE)] = ESP.getFlashChipSize(); - docFlash[FPSTR(S_REAL_SIZE)] = docFlash[FPSTR(S_SIZE)]; - #else - docFlash[FPSTR(S_SIZE)] = 0; - docFlash[FPSTR(S_REAL_SIZE)] = 0; - #endif - - doc.shrinkToFit(); - - this->bufferedWebServer->send(200, F("application/json"), doc); - }); - - this->webServer->on(F("/api/debug"), HTTP_GET, [this]() { - JsonDocument doc; - - auto docNetwork = doc[FPSTR(S_NETWORK)].to(); - docNetwork[FPSTR(S_CONNECTION_TYPE)] = network->getConnectionType(); - - auto docBuild = doc[FPSTR(S_BUILD)].to(); - docBuild[FPSTR(S_VERSION)] = BUILD_VERSION; - docBuild[FPSTR(S_DATE)] = __DATE__ " " __TIME__; - docBuild[FPSTR(S_ENV)] = BUILD_ENV; - #ifdef ARDUINO_ARCH_ESP8266 - docBuild[FPSTR(S_CORE)] = ESP.getCoreVersion(); - docBuild[FPSTR(S_SDK)] = ESP.getSdkVersion(); - #elif ARDUINO_ARCH_ESP32 - docBuild[FPSTR(S_CORE)] = ESP.getCoreVersion(); - docBuild[FPSTR(S_SDK)] = ESP.getSdkVersion(); - #else - docBuild[FPSTR(S_CORE)] = 0; - docBuild[FPSTR(S_SDK)] = 0; - #endif - - auto docHeap = doc[FPSTR(S_HEAP)].to(); - docHeap[FPSTR(S_TOTAL)] = getTotalHeap(); - docHeap[FPSTR(S_FREE)] = getFreeHeap(); - docHeap[FPSTR(S_MIN_FREE)] = getFreeHeap(true); - docHeap[FPSTR(S_MAX_FREE_BLOCK)] = getMaxFreeBlockHeap(); - docHeap[FPSTR(S_MIN_MAX_FREE_BLOCK)] = getMaxFreeBlockHeap(true); - - auto docChip = doc[FPSTR(S_CHIP)].to(); - #ifdef ARDUINO_ARCH_ESP8266 - docChip[FPSTR(S_MODEL)] = esp_is_8285() ? F("ESP8285") : F("ESP8266"); - docChip[FPSTR(S_REV)] = 0; - docChip[FPSTR(S_CORES)] = 1; - docChip[FPSTR(S_FREQ)] = ESP.getCpuFreqMHz(); - #elif ARDUINO_ARCH_ESP32 - docChip[FPSTR(S_MODEL)] = ESP.getChipModel(); - docChip[FPSTR(S_REV)] = ESP.getChipRevision(); - docChip[FPSTR(S_CORES)] = ESP.getChipCores(); - docChip[FPSTR(S_FREQ)] = ESP.getCpuFreqMHz(); - #else - docChip[FPSTR(S_MODEL)] = 0; - docChip[FPSTR(S_REV)] = 0; - docChip[FPSTR(S_CORES)] = 0; - docChip[FPSTR(S_FREQ)] = 0; - #endif - - auto docFlash = doc[FPSTR(S_FLASH)].to(); - #ifdef ARDUINO_ARCH_ESP8266 - docFlash[FPSTR(S_SIZE)] = ESP.getFlashChipSize(); - docFlash[FPSTR(S_REAL_SIZE)] = ESP.getFlashChipRealSize(); - #elif ARDUINO_ARCH_ESP32 - docFlash[FPSTR(S_SIZE)] = ESP.getFlashChipSize(); - docFlash[FPSTR(S_REAL_SIZE)] = docFlash[FPSTR(S_SIZE)]; - #else - docFlash[FPSTR(S_SIZE)] = 0; - docFlash[FPSTR(S_REAL_SIZE)] = 0; - #endif - - #if defined(ARDUINO_ARCH_ESP32) - auto reason = esp_reset_reason(); - if (reason != ESP_RST_UNKNOWN && reason != ESP_RST_POWERON && reason != ESP_RST_SW) { - #elif defined(ARDUINO_ARCH_ESP8266) - auto reason = ESP.getResetInfoPtr()->reason; - if (reason != REASON_DEFAULT_RST && reason != REASON_SOFT_RESTART && reason != REASON_EXT_SYS_RST) { - #else - if (false) { - #endif - auto docCrash = doc[FPSTR(S_CRASH)].to(); - docCrash[FPSTR(S_REASON)] = getResetReason(); - docCrash[FPSTR(S_CORE)] = CrashRecorder::ext.core; - docCrash[FPSTR(S_HEAP)] = CrashRecorder::ext.heap; - docCrash[FPSTR(S_UPTIME)] = CrashRecorder::ext.uptime; - - if (CrashRecorder::backtrace.length > 0 && CrashRecorder::backtrace.length <= CrashRecorder::backtraceMaxLength) { - String backtraceStr; - arr2str(backtraceStr, CrashRecorder::backtrace.data, CrashRecorder::backtrace.length); - docCrash[FPSTR(S_BACKTRACE)][FPSTR(S_DATA)] = backtraceStr; - docCrash[FPSTR(S_BACKTRACE)][FPSTR(S_CONTINUES)] = CrashRecorder::backtrace.continues; - } - - if (CrashRecorder::epc.length > 0 && CrashRecorder::epc.length <= CrashRecorder::epcMaxLength) { - String epcStr; - arr2str(epcStr, CrashRecorder::epc.data, CrashRecorder::epc.length); - docCrash[FPSTR(S_EPC)] = epcStr; - } - } - - doc.shrinkToFit(); - - char filename[64]; - getFilename(filename, sizeof(filename), "debug"); - - char contentDispositionHeaderValue[128]; - snprintf_P( - contentDispositionHeaderValue, - sizeof(contentDispositionHeaderValue), - PSTR("attachment; filename=\"%s\""), - filename - ); - - this->webServer->sendHeader(F("Content-Disposition"), contentDispositionHeaderValue); - this->bufferedWebServer->send(200, F("application/json"), doc, true); - }); - - - // not found - this->webServer->onNotFound([this]() { - Log.straceln(FPSTR(L_PORTAL_WEBSERVER), F("Page not found, uri: %s"), this->webServer->uri().c_str()); - - const String& uri = this->webServer->uri(); - if (uri.equals(F("/"))) { - this->webServer->send(200, F("text/plain"), F("The file system is not flashed!")); - - } else if (network->isApEnabled()) { - this->onCaptivePortal(); - - } else { - this->webServer->send(404, F("text/plain"), F("Page not found")); - } - }); - - this->webServer->serveStatic("/robots.txt", LittleFS, "/static/robots.txt", PORTAL_CACHE); - this->webServer->serveStatic("/favicon.ico", LittleFS, "/static/images/favicon.ico", PORTAL_CACHE); - this->webServer->serveStatic("/static", LittleFS, "/static", PORTAL_CACHE); - } - - void loop() { - // web server - if (!this->stateWebServer() && (network->isApEnabled() || network->isConnected()) && millis() - this->webServerChangeState >= this->changeStateInterval) { - #ifdef ARDUINO_ARCH_ESP32 - this->delay(250); - #endif - - this->startWebServer(); - Log.straceln(FPSTR(L_PORTAL_WEBSERVER), F("Started: AP up or network connected")); - - #ifdef ARDUINO_ARCH_ESP8266 - ::optimistic_yield(1000); - #endif - - } else if (this->stateWebServer() && !network->isApEnabled() && !network->isConnected()) { - this->stopWebServer(); - Log.straceln(FPSTR(L_PORTAL_WEBSERVER), F("Stopped: no network")); - - #ifdef ARDUINO_ARCH_ESP8266 - ::optimistic_yield(1000); - #endif - } - - // mDNS - this->loopMdns(); - - // dns server - if (!this->stateDnsServer() && !network->isConnected() && network->isApEnabled() && this->stateWebServer()) { - this->startDnsServer(); - Log.straceln(FPSTR(L_PORTAL_DNSSERVER), F("Started: AP up")); - - #ifdef ARDUINO_ARCH_ESP8266 - ::optimistic_yield(1000); - #endif - - } else if (this->stateDnsServer() && (network->isConnected() || !network->isApEnabled() || !this->stateWebServer())) { - this->stopDnsServer(); - Log.straceln(FPSTR(L_PORTAL_DNSSERVER), F("Stopped: AP down/STA connected")); - - #ifdef ARDUINO_ARCH_ESP8266 - ::optimistic_yield(1000); - #endif - } - - if (this->stateDnsServer()) { - this->dnsServer->processNextRequest(); - - #ifdef ARDUINO_ARCH_ESP8266 - ::optimistic_yield(1000); - #endif - } - - if (this->stateWebServer()) { - #ifdef ARDUINO_ARCH_ESP32 - // Fix ERR_CONNECTION_RESET for Chrome based browsers - auto& client = this->webServer->client(); - if (!client.getNoDelay()) { - client.setNoDelay(true); - } - #endif - - this->webServer->handleClient(); - } - - if (!this->stateDnsServer() && !this->stateWebServer()) { - this->delay(250); - } - } - - bool isAuthRequired() { - return !network->isApEnabled() && settings.portal.auth && strlen(settings.portal.password); - } - - /** - * @brief Keep mDNS in sync with the active uplink - * @details The responder binds its records to the interface that is up when it starts, so when - * switching between interfaces, mDNS must be restarted - */ - void loopMdns() { - #if USE_ETHERNET - const NetworkMgr::Uplink connectionType = network->getUplink(); - - if (connectionType != this->mdnsConnectionType) { - this->mdnsConnectionType = connectionType; - - if (this->mDnsState) { - MDNS.end(); - this->mDnsState = false; - - Log.straceln(FPSTR(L_PORTAL_WEBSERVER), F("mDNS restarting: connection is now %s"), NetworkMgr::uplinkName(connectionType)); - } - } - #endif - - if (!settings.portal.mdns || !this->stateWebServer()) { - if (this->mDnsState) { - MDNS.end(); - this->mDnsState = false; - - Log.straceln(FPSTR(L_PORTAL_WEBSERVER), F("mDNS disabled")); - } - - return; - } - - if (this->mDnsState || millis() - this->mDnsRetryTime < this->mDnsRetryInterval) { - return; - } - - this->mDnsRetryTime = millis(); - - if (MDNS.begin(networkSettings.hostname)) { - MDNS.addService("http", "tcp", 80); - this->mDnsState = true; - - Log.straceln(FPSTR(L_PORTAL_WEBSERVER), F("mDNS enabled and service added")); - } - } - - /** - * @brief Add the computed W5500 state to a network settings document - * @details The key is absent entirely on builds without ethernet, rather than an empty object: - * presence of the section is what tells a client the target can do it. The stored fields - * (enabled flag, pinout) come from networkSettingsToJson, this adds only what is derived. - */ - void ethernetToJson(JsonDocument& dst) { - #if USE_ETHERNET - dst[FPSTR(S_ETHERNET)][FPSTR(S_CONFIGURED)] = this->isEthernetConfigured(); - #endif - } - - /** - * @brief Ethernet can only be used when all six W5500 pins are configured - */ - bool isEthernetConfigured() { - #if USE_ETHERNET - return networkSettings.ethernet.w5500.clk != GPIO_IS_NOT_CONFIGURED - && networkSettings.ethernet.w5500.mosi != GPIO_IS_NOT_CONFIGURED - && networkSettings.ethernet.w5500.miso != GPIO_IS_NOT_CONFIGURED - && networkSettings.ethernet.w5500.cs != GPIO_IS_NOT_CONFIGURED - && networkSettings.ethernet.w5500.irq != GPIO_IS_NOT_CONFIGURED - && networkSettings.ethernet.w5500.rst != GPIO_IS_NOT_CONFIGURED; - #else - // nothing to configure: the W5500 driver is not compiled into this target - return false; - #endif - } - - /** - * @brief Push the W5500 wiring from the settings into the network manager - */ - void applyEthernetSettings() { - #if USE_ETHERNET - network - ->setEthernet(networkSettings.ethernet.enabled) - ->setEthernetPins( - networkSettings.ethernet.w5500.clk, - networkSettings.ethernet.w5500.mosi, - networkSettings.ethernet.w5500.miso, - networkSettings.ethernet.w5500.cs, - networkSettings.ethernet.w5500.irq, - networkSettings.ethernet.w5500.rst - ); - #endif - } - - bool isValidCredentials() { - return this->webServer->authenticate(settings.portal.login, settings.portal.password); - } - - void onCaptivePortal() { - const String& uri = this->webServer->uri(); - - if (uri.equals(F("/connecttest.txt"))) { - this->webServer->sendHeader(F("Location"), F("http://logout.net")); - this->webServer->send(302); - - Log.straceln(FPSTR(L_PORTAL_CAPTIVE), F("Redirect to http://logout.net with 302 code")); - - } else if (uri.equals(F("/wpad.dat"))) { - this->webServer->send(404); - - Log.straceln(FPSTR(L_PORTAL_CAPTIVE), F("Send empty page with 404 code")); - - } else if (uri.equals(F("/success.txt"))) { - this->webServer->send(200); - - Log.straceln(FPSTR(L_PORTAL_CAPTIVE), F("Send empty page with 200 code")); - - } else { - String portalUrl = F("http://"); - portalUrl += network->getApIp().toString().c_str(); - portalUrl += '/'; - - this->webServer->sendHeader(F("Location"), portalUrl); - this->webServer->send(302); - - Log.straceln(FPSTR(L_PORTAL_CAPTIVE), F("Redirect to portal page with 302 code")); - } - } - - bool stateWebServer() { - return this->webServerEnabled; - } - - void startWebServer() { - if (this->stateWebServer()) { - return; - } - - this->webServer->begin(); - #ifdef ARDUINO_ARCH_ESP8266 - this->webServer->getServer().setNoDelay(true); - #endif - this->webServerEnabled = true; - this->webServerChangeState = millis(); - } - - void stopWebServer() { - if (!this->stateWebServer()) { - return; - } - - //this->webServer->handleClient(); - this->webServer->stop(); - this->webServerEnabled = false; - this->webServerChangeState = millis(); - } - - bool stateDnsServer() { - return this->dnsServerEnabled; - } - - void startDnsServer() { - if (this->stateDnsServer()) { - return; - } - - this->dnsServer->start(53, "*", network->getApIp()); - this->dnsServerEnabled = true; - } - - void stopDnsServer() { - if (!this->stateDnsServer()) { - return; - } - - //this->dnsServer->processNextRequest(); - this->dnsServer->stop(); - this->dnsServerEnabled = false; - } - - static void getFilename(char* filename, size_t maxSizeFilename, const char* type) { - const time_t now = time(nullptr); - const tm* localNow = localtime(&now); - char localNowValue[20]; - strftime(localNowValue, sizeof(localNowValue), PSTR("%Y-%m-%d-%H-%M-%S"), localNow); - snprintf_P(filename, maxSizeFilename, PSTR("%s_%s_%s.json"), networkSettings.hostname, localNowValue, type); - } -}; diff --git a/src/RegulatorTask.h b/src/RegulatorTask.h deleted file mode 100644 index cc170d0..0000000 --- a/src/RegulatorTask.h +++ /dev/null @@ -1,250 +0,0 @@ -#include - -GyverPID pidRegulator(0, 0, 0); - - -class RegulatorTask : public LeanTask { -public: - RegulatorTask(bool _enabled = false, unsigned long _interval = 0) : LeanTask(_enabled, _interval) {} - -protected: - float prevHeatingTarget = 0.0f; - float prevEtResult = 0.0f; - float prevPidResult = 0.0f; - - bool indoorSensorsConnected = false; - //bool outdoorSensorsConnected = false; - - #if defined(ARDUINO_ARCH_ESP32) - const char* getTaskName() override { - return "Regulator"; - } - - /*BaseType_t getTaskCore() override { - return 1; - }*/ - - int getTaskPriority() override { - return 4; - } - #endif - - void loop() { - if (vars.states.restarting || vars.states.upgrading) { - return; - } - - this->indoorSensorsConnected = Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::INDOOR_TEMP); - //this->outdoorSensorsConnected = Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::OUTDOOR_TEMP); - - if (settings.equitherm.enabled || settings.pid.enabled || settings.opentherm.options.nativeOTC) { - vars.master.heating.indoorTempControl = true; - vars.master.heating.minTemp = THERMOSTAT_INDOOR_MIN_TEMP; - vars.master.heating.maxTemp = THERMOSTAT_INDOOR_MAX_TEMP; - - } else { - vars.master.heating.indoorTempControl = false; - vars.master.heating.minTemp = settings.heating.minTemp; - vars.master.heating.maxTemp = settings.heating.maxTemp; - } - - if (!settings.pid.enabled && fabsf(pidRegulator.integral) > 0.01f) { - pidRegulator.integral = 0.0f; - - Log.sinfoln(FPSTR(L_REGULATOR_PID), F("Integral sum has been reset")); - } - - this->turbo(); - this->hysteresis(); - - vars.master.heating.targetTemp = settings.heating.target; - vars.master.heating.setpointTemp = roundf(constrain( - this->getHeatingSetpointTemp(), - this->getHeatingMinSetpointTemp(), - this->getHeatingMaxSetpointTemp() - ), 0); - - Sensors::setValueByType( - Sensors::Type::HEATING_SETPOINT_TEMP, vars.master.heating.setpointTemp, - Sensors::ValueType::PRIMARY, true, true - ); - } - - void turbo() { - if (settings.heating.turbo) { - if (!settings.heating.enabled || vars.emergency.state || !this->indoorSensorsConnected) { - settings.heating.turbo = false; - - } else if (!settings.pid.enabled && !settings.equitherm.enabled) { - settings.heating.turbo = false; - - } else if (fabsf(settings.heating.target - vars.master.heating.indoorTemp) <= 1.0f) { - settings.heating.turbo = false; - } - - if (!settings.heating.turbo) { - Log.sinfoln(FPSTR(L_REGULATOR), F("Turbo mode auto disabled")); - } - } - } - - void hysteresis() { - bool useHyst = false; - if (settings.heating.hysteresis.enabled && this->indoorSensorsConnected) { - useHyst = settings.equitherm.enabled || settings.pid.enabled || settings.opentherm.options.nativeOTC; - } - - if (useHyst) { - if (!vars.master.heating.blocking && vars.master.heating.indoorTemp - settings.heating.target + 0.0001f >= settings.heating.hysteresis.value) { - vars.master.heating.blocking = true; - - } else if (vars.master.heating.blocking && vars.master.heating.indoorTemp - settings.heating.target - 0.0001f <= -(settings.heating.hysteresis.value)) { - vars.master.heating.blocking = false; - } - - } else if (vars.master.heating.blocking) { - vars.master.heating.blocking = false; - } - } - - inline float getHeatingMinSetpointTemp() { - return settings.opentherm.options.nativeOTC - ? vars.master.heating.minTemp - : settings.heating.minTemp; - } - - inline float getHeatingMaxSetpointTemp() { - return settings.opentherm.options.nativeOTC - ? vars.master.heating.maxTemp - : settings.heating.maxTemp; - } - - float getHeatingSetpointTemp() { - float newTemp = 0; - - if (fabsf(prevHeatingTarget - settings.heating.target) > 0.0001f) { - prevHeatingTarget = settings.heating.target; - Log.sinfoln(FPSTR(L_REGULATOR), F("New target: %.2f"), settings.heating.target); - - /*if (settings.pid.enabled) { - pidRegulator.integral = 0.0f; - Log.sinfoln(FPSTR(L_REGULATOR_PID), F("Integral sum has been reset")); - }*/ - } - - if (vars.emergency.state) { - return settings.emergency.target; - - } else if (settings.opentherm.options.nativeOTC) { - return settings.heating.target; - - } else if (!settings.equitherm.enabled && !settings.pid.enabled) { - return settings.heating.target; - } - - // if use equitherm - if (settings.equitherm.enabled) { - float tempDelta = settings.heating.target - vars.master.heating.outdoorTemp; - float maxPoint = settings.heating.target - ( - settings.heating.maxTemp - settings.heating.target - ) / settings.equitherm.slope; - - float sf = (settings.heating.maxTemp - settings.heating.target) / pow( - settings.heating.target - maxPoint, - 1.0f / settings.equitherm.exponent - ); - float etResult = settings.heating.target + settings.equitherm.shift + sf * ( - tempDelta >= 0 - ? pow(tempDelta, 1.0f / settings.equitherm.exponent) - : -(pow(-(tempDelta), 1.0f / settings.equitherm.exponent)) - ); - - // add diff - if (this->indoorSensorsConnected && !settings.pid.enabled && !settings.heating.turbo) { - etResult += constrain( - settings.heating.target - vars.master.heating.indoorTemp, - -3.0f, - 3.0f - ) * settings.equitherm.targetDiffFactor; - } - - // limit - etResult = constrain(etResult, settings.heating.minTemp, settings.heating.maxTemp); - - if (fabsf(prevEtResult - etResult) > 0.09f) { - prevEtResult = etResult; - newTemp += etResult; - - Log.sinfoln(FPSTR(L_REGULATOR_EQUITHERM), F("New result: %.2f"), etResult); - - } else { - newTemp += prevEtResult; - } - } - - // if use pid - if (settings.pid.enabled) { - //if (vars.parameters.heatingEnabled) { - if (settings.heating.enabled && this->indoorSensorsConnected) { - pidRegulator.Kp = settings.heating.turbo ? 0.0f : settings.pid.p_factor; - pidRegulator.Ki = settings.pid.i_factor; - pidRegulator.Kd = settings.pid.d_factor; - - pidRegulator.setLimits(settings.pid.minTemp, settings.pid.maxTemp); - pidRegulator.setDt(settings.pid.dt * 1000u); - pidRegulator.input = vars.master.heating.indoorTemp; - pidRegulator.setpoint = settings.heating.target; - - /*if (fabsf(pidRegulator.Ki - settings.pid.i_factor) >= 0.0001f) { - pidRegulator.Ki = settings.pid.i_factor; - pidRegulator.integral = 0.0f; - pidRegulator.getResultNow(); - - Log.sinfoln(FPSTR(L_REGULATOR_PID), F("Integral sum has been reset")); - }*/ - - float error = pidRegulator.setpoint - pidRegulator.input; - bool hasDeadband = settings.pid.deadband.enabled - && (error > -(settings.pid.deadband.thresholdHigh)) - && (error < settings.pid.deadband.thresholdLow); - - if (hasDeadband) { - pidRegulator.Kp *= settings.pid.deadband.p_multiplier; - pidRegulator.Ki *= settings.pid.deadband.i_multiplier; - pidRegulator.Kd *= settings.pid.deadband.d_multiplier; - } - - float pidResult = pidRegulator.getResultTimer(); - if (fabsf(prevPidResult - pidResult) > 0.09f) { - prevPidResult = pidResult; - newTemp += pidResult; - - Log.sinfoln(FPSTR(L_REGULATOR_PID), F("New result: %.2f"), pidResult); - Log.straceln(FPSTR(L_REGULATOR_PID), F("Integral: %.2f"), pidRegulator.integral); - - } else { - newTemp += prevPidResult; - } - - } else { - newTemp += prevPidResult; - } - } - - // Turbo mode - if (settings.heating.turbo && (settings.equitherm.enabled || settings.pid.enabled)) { - newTemp += constrain( - settings.heating.target - vars.master.heating.indoorTemp, - -3.0f, - 3.0f - ) * settings.heating.turboFactor; - } - - // If freezing, set temperature to no lower than low temp provided by freeze protection - if (vars.master.heating.freezing && fabsf(settings.heating.freezeProtection.lowTemp - newTemp) < 0.0001f) { - newTemp = settings.heating.freezeProtection.lowTemp; - } - - return newTemp; - } -}; diff --git a/src/Sensors.h b/src/Sensors.h deleted file mode 100644 index 71b9ac3..0000000 --- a/src/Sensors.h +++ /dev/null @@ -1,475 +0,0 @@ -#pragma once - -class Sensors { -protected: - static uint8_t maxSensors; - -public: - enum class Type : uint8_t { - OT_OUTDOOR_TEMP = 0, - OT_HEATING_TEMP = 1, - OT_HEATING_RETURN_TEMP = 2, - OT_DHW_TEMP = 3, - OT_DHW_TEMP2 = 4, - OT_DHW_FLOW_RATE = 5, - OT_CH2_TEMP = 6, - OT_EXHAUST_TEMP = 7, - OT_HEAT_EXCHANGER_TEMP = 8, - OT_PRESSURE = 9, - OT_MODULATION_LEVEL = 10, - OT_CURRENT_POWER = 11, - OT_EXHAUST_CO2 = 12, - OT_EXHAUST_FAN_SPEED = 13, - OT_SUPPLY_FAN_SPEED = 14, - OT_SOLAR_STORAGE_TEMP = 15, - OT_SOLAR_COLLECTOR_TEMP = 16, - OT_FAN_SPEED_SETPOINT = 17, - OT_FAN_SPEED_CURRENT = 18, - - OT_BURNER_STARTS = 19, - OT_DHW_BURNER_STARTS = 20, - OT_HEATING_PUMP_STARTS = 21, - OT_DHW_PUMP_STARTS = 22, - OT_BURNER_HOURS = 23, - OT_DHW_BURNER_HOURS = 24, - OT_HEATING_PUMP_HOURS = 25, - OT_DHW_PUMP_HOURS = 26, - OT_COOLING_HOURS = 27, - - NTC_10K_TEMP = 50, - DALLAS_TEMP = 51, - BLUETOOTH = 52, - - HEATING_SETPOINT_TEMP = 253, - MANUAL = 254, - NOT_CONFIGURED = 255 - }; - - enum class Purpose : uint8_t { - OUTDOOR_TEMP = 0, - INDOOR_TEMP = 1, - HEATING_TEMP = 2, - HEATING_RETURN_TEMP = 3, - DHW_TEMP = 4, - DHW_RETURN_TEMP = 5, - DHW_FLOW_RATE = 6, - EXHAUST_TEMP = 7, - MODULATION_LEVEL = 8, - - NUMBER = 247, - POWER_FACTOR = 248, - POWER = 249, - FAN_SPEED = 250, - CO2 = 251, - PRESSURE = 252, - HUMIDITY = 253, - TEMPERATURE = 254, - NOT_CONFIGURED = 255 - }; - - enum class ValueType : uint8_t { - PRIMARY = 0, - TEMPERATURE = 0, - HUMIDITY = 1, - BATTERY = 2, - RSSI = 3 - }; - - typedef struct { - bool enabled = false; - char name[33]; - Purpose purpose = Purpose::NOT_CONFIGURED; - Type type = Type::NOT_CONFIGURED; - uint8_t gpio = GPIO_IS_NOT_CONFIGURED; - uint8_t address[8] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; - float offset = 0.0f; - float factor = 1.0f; - bool filtering = false; - float filteringFactor = 0.15f; - } Settings; - - typedef struct { - bool connected = false; - unsigned long activityTime = 0; - uint8_t signalQuality = 100; - //float raw[4] = {0.0f, 0.0f, 0.0f, 0.0f}; - float values[4] = {0.0f, 0.0f, 0.0f, 0.0f}; - } Result; - - - static Settings* settings; - static Result* results; - - static inline void setMaxSensors(uint8_t value) { - maxSensors = value; - } - - static inline uint8_t getMaxSensors() { - return maxSensors; - } - - static uint8_t getMaxSensorId() { - uint8_t maxSensors = getMaxSensors(); - return maxSensors > 1 ? (maxSensors - 1) : 0; - } - - static inline bool isValidSensorId(const uint8_t id) { - return id >= 0 && id <= getMaxSensorId(); - } - - static inline bool isValidValueId(const uint8_t id) { - return id >= (uint8_t) ValueType::TEMPERATURE && id <= (uint8_t) ValueType::RSSI; - } - - static bool hasEnabledAndValid(const uint8_t id) { - if (!isValidSensorId(id) || !settings[id].enabled) { - return false; - } - - if (settings[id].type == Type::NOT_CONFIGURED || settings[id].purpose == Purpose::NOT_CONFIGURED) { - return false; - } - - return true; - } - - static uint8_t getAmountByType(Type type, bool onlyEnabled = false) { - if (settings == nullptr) { - return 0; - } - - uint8_t amount = 0; - for (uint8_t id = 0; id <= getMaxSensorId(); id++) { - if (settings[id].type == type && (!onlyEnabled || settings[id].enabled)) { - amount++; - } - } - - return amount; - } - - static int16_t getIdByName(const char* name) { - if (settings == nullptr) { - return -1; - } - - for (uint8_t id = 0; id <= getMaxSensorId(); id++) { - if (strcmp(settings[id].name, name) == 0) { - return id; - } - } - - return -1; - } - - static int16_t getIdByObjectId(const char* objectId) { - if (settings == nullptr) { - return -1; - } - - String refObjectId; - for (uint8_t id = 0; id <= getMaxSensorId(); id++) { - Sensors::makeObjectId(refObjectId, settings[id].name); - if (refObjectId.equals(objectId)) { - return id; - } - } - - return -1; - } - - static bool setValueById(const uint8_t sensorId, float value, const ValueType valueType, const bool updateActivityTime = false, const bool markConnected = false) { - if (settings == nullptr || results == nullptr) { - return false; - } - - uint8_t valueId = (uint8_t) valueType; - if (!isValidSensorId(sensorId) || !isValidValueId(valueId)) { - return false; - } - - auto& sSensor = settings[sensorId]; - auto& rSensor = results[sensorId]; - - float compensatedValue = value; - if (sSensor.type == Type::HEATING_SETPOINT_TEMP || sSensor.type == Type::MANUAL) { - rSensor.values[valueId] = compensatedValue; - - } else { - if (valueType == ValueType::PRIMARY) { - if (fabsf(sSensor.factor) > 0.001f) { - compensatedValue *= sSensor.factor; - } - - if (fabsf(sSensor.offset) > 0.001f) { - compensatedValue += sSensor.offset; - } - - } else if (valueType == ValueType::RSSI) { - if (sSensor.type == Type::BLUETOOTH) { - rSensor.signalQuality = Sensors::bluetoothRssiToQuality(value); - } - } - - if (sSensor.filtering && fabsf(rSensor.values[valueId]) >= 0.1f) { - rSensor.values[valueId] += (compensatedValue - rSensor.values[valueId]) * sSensor.filteringFactor; - - } else { - rSensor.values[valueId] = compensatedValue; - } - } - - if (updateActivityTime) { - rSensor.activityTime = millis(); - } - - if (markConnected && !rSensor.connected) { - rSensor.connected = true; - - Log.snoticeln( - FPSTR(L_SENSORS), F("#%hhu '%s' new status: CONNECTED"), - sensorId, sSensor.name - ); - } - - Log.snoticeln( - FPSTR(L_SENSORS), F("#%hhu '%s' new value %hhu: %.2f, compensated: %.2f, raw: %.2f"), - sensorId, sSensor.name, valueId, rSensor.values[valueId], compensatedValue, value - ); - - return true; - } - - static uint8_t setValueByType(Type type, float value, const ValueType valueType, const bool updateActivityTime = false, const bool markConnected = false) { - if (settings == nullptr) { - return 0; - } - - uint8_t updated = 0; - - // read sensors data for current instance - for (uint8_t sensorId = 0; sensorId <= getMaxSensorId(); sensorId++) { - auto& sSensor = settings[sensorId]; - - // only target & valid sensors - if (!sSensor.enabled || sSensor.type != type) { - continue; - } - - if (setValueById(sensorId, value, valueType, updateActivityTime, markConnected)) { - updated++; - } - } - - return updated; - } - - static bool getConnectionStatusById(const uint8_t sensorId) { - if (settings == nullptr || results == nullptr) { - return false; - } - - if (!isValidSensorId(sensorId)) { - return false; - } - - return results[sensorId].connected; - } - - static bool setConnectionStatusById(const uint8_t sensorId, const bool status, const bool updateActivityTime = true) { - if (settings == nullptr || results == nullptr) { - return false; - } - - if (!isValidSensorId(sensorId)) { - return false; - } - - auto& sSensor = settings[sensorId]; - auto& rSensor = results[sensorId]; - - if (rSensor.connected != status) { - Log.snoticeln( - FPSTR(L_SENSORS), F("#%hhu '%s' new status: %s"), - sensorId, sSensor.name, status ? F("CONNECTED") : F("DISCONNECTED") - ); - - rSensor.connected = status; - } - - if (updateActivityTime) { - rSensor.activityTime = millis(); - } - - return true; - } - - static uint8_t setConnectionStatusByType(Type type, const bool status, const bool updateActivityTime = true) { - if (settings == nullptr) { - return 0; - } - - uint8_t updated = 0; - - // read sensors data for current instance - for (uint8_t sensorId = 0; sensorId <= getMaxSensorId(); sensorId++) { - auto& sSensor = settings[sensorId]; - - // only target & valid sensors - if (!sSensor.enabled || sSensor.type != type) { - continue; - } - - if (setConnectionStatusById(sensorId, status, updateActivityTime)) { - updated++; - } - } - - return updated; - } - - static float getMeanValueByPurpose(Purpose purpose, const ValueType valueType, bool onlyConnected = true) { - if (settings == nullptr || results == nullptr) { - return 0.0f; - } - - uint8_t valueId = (uint8_t) valueType; - if (!isValidValueId(valueId)) { - return 0.0f; - } - - float value = 0.0f; - uint8_t amount = 0; - - for (uint8_t id = 0; id <= getMaxSensorId(); id++) { - auto& sSensor = settings[id]; - auto& rSensor = results[id]; - - if (sSensor.purpose == purpose && (!onlyConnected || rSensor.connected)) { - value += rSensor.values[valueId]; - amount++; - } - } - - if (!amount) { - return 0.0f; - - } else if (amount == 1) { - return value; - - } else { - return value / amount; - } - } - - static bool existsConnectedSensorsByPurpose(Purpose purpose) { - if (settings == nullptr || results == nullptr) { - return false; - } - - for (uint8_t id = 0; id <= getMaxSensorId(); id++) { - if (settings[id].purpose == purpose && results[id].connected) { - return true; - } - } - - return false; - } - - static String& cleanName(String& value, char space = ' ') { - // only valid symbols - for (uint8_t pos = 0; pos < value.length(); pos++) { - char symbol = value.charAt(pos); - - // 0..9 - if (symbol >= 48 && symbol <= 57) { - continue; - } - - // A..Z - if (symbol >= 65 && symbol <= 90) { - continue; - } - - // a..z - if (symbol >= 97 && symbol <= 122) { - continue; - } - - // _- - if (symbol == 95 || symbol == 45 || symbol == space) { - continue; - } - - value.setCharAt(pos, space); - } - - value.trim(); - - return value; - } - - template - static String cleanName(T value, char space = ' ') { - String res = value; - return cleanName(res, space); - } - - template - static String& makeObjectId(String& res, T value, char separator = '_') { - res = value; - cleanName(res); - res.toLowerCase(); - res.replace(' ', separator); - - return res; - } - - template - static String makeObjectId(T value, char separator = '_') { - String res; - makeObjectId(res, value, separator); - - return res; - } - - template - static String& makeObjectIdWithSuffix(String& res, TV value, TS suffix, char separator = '_') { - res.clear(); - makeObjectId(res, value, separator); - res += separator; - res += suffix; - - return res; - } - - template - static String makeObjectIdWithSuffix(TV value, TS suffix, char separator = '_') { - String res; - makeObjectIdWithSuffix(res, value, suffix, separator); - return res; - } - - template - static String& makeObjectIdWithPrefix(String& res, TV value, TP prefix, char separator = '_') { - res = prefix; - res += separator; - res += makeObjectId(value, separator).c_str(); - - return res; - } - - template - static String makeObjectIdWithPrefix(TV value, TP prefix, char separator = '_') { - String res; - return makeObjectIdWithPrefix(res, value, prefix, separator); - } - - static uint8_t bluetoothRssiToQuality(int rssi) { - return constrain(map(rssi, -110, -50, 0, 100), 0, 100);; - } -}; - -uint8_t Sensors::maxSensors = 0; -Sensors::Settings* Sensors::settings = nullptr; -Sensors::Result* Sensors::results = nullptr; \ No newline at end of file diff --git a/src/SensorsTask.h b/src/SensorsTask.h deleted file mode 100644 index 156842b..0000000 --- a/src/SensorsTask.h +++ /dev/null @@ -1,1047 +0,0 @@ -#include -#include -#include - -#if USE_BLE - #include -#endif - -extern FileData fsSensorsSettings; - -#if USE_BLE -class BluetoothClientCallbacks : public NimBLEClientCallbacks { -public: - BluetoothClientCallbacks(uint8_t sensorId) : sensorId(sensorId) {} - - void onConnect(NimBLEClient* pClient) { - auto& sSensor = Sensors::settings[this->sensorId]; - - Log.sinfoln( - FPSTR(L_SENSORS_BLE), F("Sensor #%hhu '%s': connected to %s"), - sensorId, sSensor.name, pClient->getPeerAddress().toString().c_str() - ); - } - - void onDisconnect(NimBLEClient* pClient, int reason) { - auto& sSensor = Sensors::settings[this->sensorId]; - - Log.sinfoln( - FPSTR(L_SENSORS_BLE), F("Sensor #%hhu '%s': disconnected, reason %i"), - sensorId, sSensor.name, reason - ); - } - - void onConnectFail(NimBLEClient* pClient, int reason) { - auto& sSensor = Sensors::settings[this->sensorId]; - - Log.sinfoln( - FPSTR(L_SENSORS_BLE), F("Sensor #%hhu '%s': failed to connect, reason %i"), - sensorId, sSensor.name, reason - ); - - pClient->cancelConnect(); - } - -protected: - uint8_t sensorId; -}; -#endif - -class SensorsTask : public LeanTask { -public: - SensorsTask(bool _enabled = false, unsigned long _interval = 0) : LeanTask(_enabled, _interval) { - this->owInstances.reserve(2); - this->dallasInstances.reserve(2); - this->dallasSearchTime.reserve(2); - this->dallasPolling.reserve(2); - this->dallasLastPollingTime.reserve(2); - } - - ~SensorsTask() { - this->dallasInstances.clear(); - this->owInstances.clear(); - this->dallasSearchTime.clear(); - this->dallasPolling.clear(); - this->dallasLastPollingTime.clear(); - } - -protected: - const unsigned int wiredDisconnectTimeout = 180000u; - const unsigned int wirelessDisconnectTimeout = 600000u; - const unsigned short dallasSearchInterval = 60000; - const unsigned short dallasPollingInterval = 10000; - const unsigned short globalPollingInterval = 15000; - #if USE_BLE - const unsigned int bleSetDtInterval = 7200000; - #endif - - std::unordered_map owInstances; - std::unordered_map dallasInstances; - std::unordered_map dallasSearchTime; - std::unordered_map dallasPolling; - std::unordered_map dallasLastPollingTime; - #if USE_BLE - std::unordered_map bleClients; - std::unordered_map bleSubscribed; - std::unordered_map bleLastSetDtTime; - #endif - unsigned long globalLastPollingTime = 0; - - #if defined(ARDUINO_ARCH_ESP32) - const char* getTaskName() override { - return "Sensors"; - } - - BaseType_t getTaskCore() override { - // https://github.com/h2zero/NimBLE-Arduino/issues/676 - #if USE_BLE && defined(CONFIG_BT_NIMBLE_PINNED_TO_CORE) - return CONFIG_BT_NIMBLE_PINNED_TO_CORE; - #else - return tskNO_AFFINITY; - #endif - } - - int getTaskPriority() override { - return 4; - } - #endif - - void loop() { - if (vars.states.restarting || vars.states.upgrading) { - return; - } - - if (isPollingDallasSensors()) { - pollingDallasSensors(false); - this->yield(); - } - - if (millis() - this->globalLastPollingTime > this->globalPollingInterval) { - cleanDallasInstances(); - makeDallasInstances(); - this->yield(); - - searchDallasSensors(); - fillingAddressesDallasSensors(); - this->yield(); - - pollingDallasSensors(); - this->yield(); - - pollingNtcSensors(); - this->yield(); - - #if USE_BLE - cleanBleInstances(); - pollingBleSensors(); - this->yield(); - #endif - - this->globalLastPollingTime = millis(); - } - - updateConnectionStatus(); - updateMasterValues(); - } - - void updateMasterValues() { - vars.master.heating.outdoorTemp = Sensors::getMeanValueByPurpose(Sensors::Purpose::OUTDOOR_TEMP, Sensors::ValueType::PRIMARY); - vars.master.heating.indoorTemp = Sensors::getMeanValueByPurpose(Sensors::Purpose::INDOOR_TEMP, Sensors::ValueType::PRIMARY); - - vars.master.heating.currentTemp = Sensors::getMeanValueByPurpose(Sensors::Purpose::HEATING_TEMP, Sensors::ValueType::PRIMARY); - vars.master.heating.returnTemp = Sensors::getMeanValueByPurpose(Sensors::Purpose::HEATING_RETURN_TEMP, Sensors::ValueType::PRIMARY); - - vars.master.dhw.currentTemp = Sensors::getMeanValueByPurpose(Sensors::Purpose::DHW_TEMP, Sensors::ValueType::PRIMARY); - vars.master.dhw.returnTemp = Sensors::getMeanValueByPurpose(Sensors::Purpose::DHW_RETURN_TEMP, Sensors::ValueType::PRIMARY); - } - - void makeDallasInstances() { - for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { - auto& sSensor = Sensors::settings[sensorId]; - - if (!sSensor.enabled || sSensor.type != Sensors::Type::DALLAS_TEMP || sSensor.purpose == Sensors::Purpose::NOT_CONFIGURED) { - continue; - - } else if (this->dallasInstances.count(sSensor.gpio)) { - // no need to make instances - continue; - } - - auto& owInstance = this->owInstances[sSensor.gpio]; - owInstance.begin(sSensor.gpio); - owInstance.reset(); - - this->dallasSearchTime[sSensor.gpio] = 0; - this->dallasPolling[sSensor.gpio] = false; - this->dallasLastPollingTime[sSensor.gpio] = 0; - - auto& instance = this->dallasInstances[sSensor.gpio]; - instance.setOneWire(&owInstance); - instance.setWaitForConversion(false); - - Log.sinfoln(FPSTR(L_SENSORS_DALLAS), F("Started on GPIO %hhu"), sSensor.gpio); - } - } - - void cleanDallasInstances() { - // for (auto& [gpio, instance] : this->dallasInstances) { - auto it = this->dallasInstances.begin(); - while (it != this->dallasInstances.end()) { - auto gpio = it->first; - bool instanceUsed = false; - - for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { - auto& sSensor = Sensors::settings[sensorId]; - - if (!sSensor.enabled || sSensor.type != Sensors::Type::DALLAS_TEMP || sSensor.purpose == Sensors::Purpose::NOT_CONFIGURED) { - continue; - } - - if (Sensors::settings[sensorId].gpio == gpio) { - instanceUsed = true; - break; - } - } - - if (!instanceUsed) { - it = this->dallasInstances.erase(it); - this->owInstances.erase(gpio); - this->dallasSearchTime.erase(gpio); - this->dallasPolling.erase(gpio); - this->dallasLastPollingTime.erase(gpio); - - Log.sinfoln(FPSTR(L_SENSORS_DALLAS), F("Stopped on GPIO %hhu"), gpio); - continue; - } - - it++; - } - } - - void searchDallasSensors() { - // search sensors on bus - for (auto& [gpio, instance] : this->dallasInstances) { - // do not search if polling! - if (this->dallasPolling[gpio]) { - continue; - } - - if (millis() - this->dallasSearchTime[gpio] < this->dallasSearchInterval) { - continue; - } - - this->dallasSearchTime[gpio] = millis(); - this->owInstances[gpio].reset(); - instance.begin(); - - Log.straceln( - FPSTR(L_SENSORS_DALLAS), - F("GPIO %hhu, devices on bus: %hhu, DS18* devices: %hhu"), - gpio, instance.getDeviceCount(), instance.getDS18Count() - ); - } - } - - void fillingAddressesDallasSensors() { - // check & filling sensors address - for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { - auto& sSensor = Sensors::settings[sensorId]; - - if (!sSensor.enabled || sSensor.type != Sensors::Type::DALLAS_TEMP || sSensor.purpose == Sensors::Purpose::NOT_CONFIGURED) { - continue; - - } else if (!this->dallasInstances.count(sSensor.gpio)) { - continue; - } - - // do nothing if address not empty - if (!isEmptyAddress(sSensor.address)) { - continue; - } - - // do nothing if polling - if (this->dallasPolling[sSensor.gpio]) { - continue; - } - - auto& instance = this->dallasInstances[sSensor.gpio]; - DeviceAddress devAddr; - for (uint8_t devId = 0; devId < instance.getDeviceCount(); devId++) { - if (!instance.getAddress(devAddr, devId)) { - continue; - } - - bool freeAddress = true; - - // checking address usage - for (uint8_t checkingSensorId = 0; checkingSensorId <= Sensors::getMaxSensorId(); checkingSensorId++) { - auto& sCheckingSensor = Sensors::settings[checkingSensorId]; - if (sCheckingSensor.type != Sensors::Type::DALLAS_TEMP || checkingSensorId == sensorId) { - continue; - } - - if (sCheckingSensor.gpio != sSensor.gpio || isEmptyAddress(sCheckingSensor.address)) { - continue; - } - - if (isEqualAddress(sCheckingSensor.address, devAddr)) { - freeAddress = false; - break; - } - } - - // address already in use - if (!freeAddress) { - continue; - } - - // set address - for (uint8_t i = 0; i < 8; i++) { - sSensor.address[i] = devAddr[i]; - } - - fsSensorsSettings.update(); - Log.straceln( - FPSTR(L_SENSORS_DALLAS), F("GPIO %hhu, sensor #%hhu '%s', set address: %hhX:%hhX:%hhX:%hhX:%hhX:%hhX:%hhX:%hhX"), - sSensor.gpio, sensorId, sSensor.name, - sSensor.address[0], sSensor.address[1], sSensor.address[2], sSensor.address[3], - sSensor.address[4], sSensor.address[5], sSensor.address[6], sSensor.address[7] - ); - - break; - } - } - } - - bool isPollingDallasSensors() { - for (auto& [gpio, instance] : this->dallasInstances) { - if (this->dallasPolling.count(gpio) && this->dallasPolling[gpio]) { - return true; - } - } - - return false; - } - - void pollingDallasSensors(bool newPolling = true) { - for (auto& [gpio, instance] : this->dallasInstances) { - unsigned long ts = millis(); - - if (this->dallasPolling[gpio]) { - unsigned long minPollingTime = instance.millisToWaitForConversion(12) * 2; - unsigned long estimatePollingTime = ts - this->dallasLastPollingTime[gpio]; - - // check conversion time - // isConversionComplete does not work with chinese clones! - if (estimatePollingTime < minPollingTime) { - continue; - } - - // read sensors data for current instance - for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { - auto& sSensor = Sensors::settings[sensorId]; - - // only target & valid sensors - if (!sSensor.enabled || sSensor.type != Sensors::Type::DALLAS_TEMP || sSensor.purpose == Sensors::Purpose::NOT_CONFIGURED) { - continue; - - } else if (sSensor.gpio != gpio || isEmptyAddress(sSensor.address)) { - continue; - } - - auto& rSensor = Sensors::results[sensorId]; - float value = instance.getTempC(sSensor.address); - if (value == DEVICE_DISCONNECTED_C) { - Log.swarningln( - FPSTR(L_SENSORS_DALLAS), F("GPIO %hhu, sensor #%hhu '%s': failed receiving data"), - sSensor.gpio, sensorId, sSensor.name - ); - - if (rSensor.signalQuality > 0) { - rSensor.signalQuality--; - } - - continue; - } - - Log.straceln( - FPSTR(L_SENSORS_DALLAS), F("GPIO %hhu, sensor #%hhu '%s', received data: %.2f"), - sSensor.gpio, sensorId, sSensor.name, value - ); - - if (rSensor.signalQuality < 100) { - rSensor.signalQuality++; - } - - // set sensor value - Sensors::setValueById(sensorId, value, Sensors::ValueType::TEMPERATURE, true, true); - } - - // reset polling flag - this->dallasPolling[gpio] = false; - - } else if (newPolling) { - auto estimateLastPollingTime = ts - this->dallasLastPollingTime[gpio]; - - // check last polling time - if (estimateLastPollingTime < this->dallasPollingInterval) { - continue; - } - - // start polling - instance.setResolution(12); - instance.requestTemperatures(); - this->dallasPolling[gpio] = true; - this->dallasLastPollingTime[gpio] = ts; - - Log.straceln(FPSTR(L_SENSORS_DALLAS), F("GPIO %hhu, polling..."), gpio); - } - } - } - - void pollingNtcSensors() { - for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { - auto& sSensor = Sensors::settings[sensorId]; - - if (!sSensor.enabled || sSensor.type != Sensors::Type::NTC_10K_TEMP || sSensor.purpose == Sensors::Purpose::NOT_CONFIGURED) { - continue; - } - - #ifdef ARDUINO_ARCH_ESP32 - const auto value = analogReadMilliVolts(sSensor.gpio); - #else - const auto value = analogRead(sSensor.gpio) / 1023 * DEFAULT_NTC_VREF; - #endif - - if (value < DEFAULT_NTC_VLOW_TRESHOLD || value > DEFAULT_NTC_VHIGH_TRESHOLD) { - if (Sensors::getConnectionStatusById(sensorId)) { - Sensors::setConnectionStatusById(sensorId, false, false); - } - - Log.swarningln( - FPSTR(L_SENSORS_NTC), F("GPIO %hhu, sensor #%hhu '%s', voltage is out of threshold: %.3f"), - sSensor.gpio, sensorId, sSensor.name, (value / 1000.0f) - ); - - continue; - } - - const float sensorResistance = value > 1 - ? DEFAULT_NTC_REF_RESISTANCE / (DEFAULT_NTC_VREF / (float) value - 1.0f) - : 0.0f; - const float rawTemp = 1.0f / ( - 1.0f / (DEFAULT_NTC_NOMINAL_TEMP + 273.15f) + - log(sensorResistance / DEFAULT_NTC_NOMINAL_RESISTANCE) / DEFAULT_NTC_BETA_FACTOR - ) - 273.15f; - - Log.straceln( - FPSTR(L_SENSORS_NTC), F("GPIO %hhu, sensor #%hhu '%s', raw temp: %.2f, raw voltage: %.3f, raw resistance: %.2f"), - sSensor.gpio, sensorId, sSensor.name, rawTemp, (value / 1000.0f), sensorResistance - ); - - // set temp - Sensors::setValueById(sensorId, rawTemp, Sensors::ValueType::TEMPERATURE, true, true); - } - } - - #if USE_BLE - void cleanBleInstances() { - if (!NimBLEDevice::isInitialized()) { - return; - } - - for (auto& [sensorId, pClient]: this->bleClients) { - if (pClient == nullptr) { - continue; - } - - auto& sSensor = Sensors::settings[sensorId]; - const auto sAddress = NimBLEAddress(sSensor.address, 0); - - if (sAddress.isNull() || !sSensor.enabled || sSensor.type != Sensors::Type::BLUETOOTH || sSensor.purpose == Sensors::Purpose::NOT_CONFIGURED) { - Log.sinfoln( - FPSTR(L_SENSORS_BLE), F("Sensor #%hhu '%s', deleted unused client"), - sensorId, sSensor.name - ); - - NimBLEDevice::deleteClient(pClient); - pClient = nullptr; - } - } - } - - void pollingBleSensors() { - if (!Sensors::getAmountByType(Sensors::Type::BLUETOOTH, true)) { - return; - } - - if (!NimBLEDevice::isInitialized() && millis() > 5000) { - Log.sinfoln(FPSTR(L_SENSORS_BLE), F("Initialized")); - BLEDevice::init(""); - NimBLEDevice::setPower(9); - } - - for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { - auto& sSensor = Sensors::settings[sensorId]; - auto& rSensor = Sensors::results[sensorId]; - - if (!sSensor.enabled || sSensor.type != Sensors::Type::BLUETOOTH || sSensor.purpose == Sensors::Purpose::NOT_CONFIGURED) { - continue; - } - - const auto address = NimBLEAddress(sSensor.address, 0); - if (address.isNull()) { - continue; - } - - auto pClient = this->getBleClient(sensorId); - if (pClient == nullptr) { - continue; - } - - if (pClient->getPeerAddress() != address) { - if (pClient->isConnected()) { - if (!pClient->disconnect()) { - continue; - } - } - - pClient->setPeerAddress(address); - } - - if (!pClient->isConnected()) { - this->bleSubscribed[sensorId] = false; - this->bleLastSetDtTime[sensorId] = 0; - - if (pClient->connect(false, true, true)) { - Log.sinfoln( - FPSTR(L_SENSORS_BLE), F("Sensor #%hhu '%s': trying connecting to %s..."), - sensorId, sSensor.name, pClient->getPeerAddress().toString().c_str() - ); - } - - continue; - } - - if (!this->bleSubscribed[sensorId]) { - if (this->subscribeToBleDevice(sensorId, pClient)) { - this->bleSubscribed[sensorId] = true; - - } else { - this->bleSubscribed[sensorId] = false; - pClient->disconnect(); - continue; - } - } - - // Mark connected - Sensors::setConnectionStatusById(sensorId, true, true); - - if (!this->bleLastSetDtTime[sensorId] || millis() - this->bleLastSetDtTime[sensorId] > this->bleSetDtInterval) { - struct tm ti; - - if (getLocalTime(&ti)) { - if (this->setDateOnBleSensor(pClient, &ti)) { - Log.sinfoln( - FPSTR(L_SENSORS_BLE), F("Sensor #%hhu '%s', successfully set date: %02d.%02d.%04d %02d:%02d:%02d"), - sensorId, sSensor.name, - ti.tm_mday, ti.tm_mon + 1, ti.tm_year + 1900, ti.tm_hour, ti.tm_min, ti.tm_sec - ); - - } else { - Log.swarningln( - FPSTR(L_SENSORS_BLE), F("Sensor #%hhu '%s', failed set date: %02d.%02d.%04d %02d:%02d:%02d"), - sensorId, sSensor.name, - ti.tm_mday, ti.tm_mon + 1, ti.tm_year + 1900, ti.tm_hour, ti.tm_min, ti.tm_sec - ); - } - - this->bleLastSetDtTime[sensorId] = millis(); - } - } - } - } - - NimBLEClient* getBleClient(const uint8_t sensorId) { - if (!NimBLEDevice::isInitialized()) { - return nullptr; - } - - auto& sSensor = Sensors::settings[sensorId]; - auto& rSensor = Sensors::results[sensorId]; - - if (!sSensor.enabled || sSensor.type != Sensors::Type::BLUETOOTH || sSensor.purpose == Sensors::Purpose::NOT_CONFIGURED) { - return nullptr; - } - - if (this->bleClients[sensorId] && this->bleClients[sensorId] != nullptr) { - return this->bleClients[sensorId]; - } - - auto pClient = NimBLEDevice::createClient(); - if (pClient == nullptr) { - return nullptr; - } - - //pClient->setConnectionParams(BLE_GAP_CONN_ITVL_MS(10), BLE_GAP_CONN_ITVL_MS(100), 10, 150); - pClient->setConnectTimeout(30000); - pClient->setSelfDelete(false, false); - pClient->setClientCallbacks(new BluetoothClientCallbacks(sensorId), true); - - this->bleClients[sensorId] = pClient; - - return pClient; - } - - bool subscribeToBleDevice(const uint8_t sensorId, NimBLEClient* pClient) { - auto& sSensor = Sensors::settings[sensorId]; - auto pAddress = pClient->getPeerAddress().toString(); - - NimBLERemoteService* pService = nullptr; - NimBLERemoteCharacteristic* pChar = nullptr; - - // ENV Service (0x181A) - NimBLEUUID serviceUuid((uint16_t) 0x181AU); - pService = pClient->getService(serviceUuid); - if (!pService) { - Log.straceln( - FPSTR(L_SENSORS_BLE), F("Sensor #%hhu '%s': failed to find env service (%s) on device %s"), - sensorId, sSensor.name, serviceUuid.toString().c_str(), pAddress.c_str() - ); - - } else { - Log.straceln( - FPSTR(L_SENSORS_BLE), F("Sensor #%hhu '%s': found env service (%s) on device %s"), - sensorId, sSensor.name, serviceUuid.toString().c_str(), pAddress.c_str() - ); - - // 0x2A6E - Notify temperature x0.01C (pvvx) - bool tempNotifyCreated = false; - if (!tempNotifyCreated) { - NimBLEUUID charUuid((uint16_t) 0x2A6E); - pChar = pService->getCharacteristic(charUuid); - - if (pChar && (pChar->canNotify() || pChar->canIndicate())) { - Log.straceln( - FPSTR(L_SENSORS_BLE), F("Sensor #%hhu '%s': found temp char (%s) in env service on device %s"), - sensorId, sSensor.name, charUuid.toString().c_str(), pAddress.c_str() - ); - - pChar->unsubscribe(); - tempNotifyCreated = pChar->subscribe( - pChar->canNotify(), - [sensorId](NimBLERemoteCharacteristic* pChar, uint8_t* pData, size_t length, bool isNotify) { - if (pChar == nullptr) { - return; - } - - const NimBLERemoteService* pService = pChar->getRemoteService(); - if (pService == nullptr) { - return; - } - - NimBLEClient* pClient = pService->getClient(); - if (pClient == nullptr) { - return; - } - - auto& sSensor = Sensors::settings[sensorId]; - - if (length != 2) { - Log.swarningln( - FPSTR(L_SENSORS_BLE), - F("Sensor #%hhu '%s': invalid notification data at temp char (%s) on device %s"), - sensorId, - sSensor.name, - pChar->getUUID().toString().c_str(), - pClient->getPeerAddress().toString().c_str() - ); - - return; - } - - float rawTemp = (pChar->getValue() * 0.01f); - Log.straceln( - FPSTR(L_SENSORS_BLE), - F("Sensor #%hhu '%s': received temp: %.2f"), - sensorId, sSensor.name, rawTemp - ); - - // set temp - Sensors::setValueById(sensorId, rawTemp, Sensors::ValueType::TEMPERATURE, true, true); - - // update rssi - Sensors::setValueById(sensorId, pClient->getRssi(), Sensors::ValueType::RSSI, false, false); - } - ); - - if (tempNotifyCreated) { - Log.straceln( - FPSTR(L_SENSORS_BLE), F("Sensor #%hhu '%s': subscribed to temp char (%s) in env service on device %s"), - sensorId, sSensor.name, - charUuid.toString().c_str(), pAddress.c_str() - ); - - } else { - Log.swarningln( - FPSTR(L_SENSORS_BLE), F("Sensor #%hhu '%s': failed to subscribe to temp char (%s) in env service on device %s"), - sensorId, sSensor.name, - charUuid.toString().c_str(), pAddress.c_str() - ); - } - } - } - - - // 0x2A1F - Notify temperature x0.1C (atc1441/pvvx) - if (!tempNotifyCreated) { - NimBLEUUID charUuid((uint16_t) 0x2A1F); - pChar = pService->getCharacteristic(charUuid); - - if (pChar && (pChar->canNotify() || pChar->canIndicate())) { - Log.straceln( - FPSTR(L_SENSORS_BLE), F("Sensor #%hhu '%s': found temp char (%s) in env service on device %s"), - sensorId, sSensor.name, charUuid.toString().c_str(), pAddress.c_str() - ); - - pChar->unsubscribe(); - tempNotifyCreated = pChar->subscribe( - pChar->canNotify(), - [sensorId](NimBLERemoteCharacteristic* pChar, uint8_t* pData, size_t length, bool isNotify) { - if (pChar == nullptr) { - return; - } - - const NimBLERemoteService* pService = pChar->getRemoteService(); - if (pService == nullptr) { - return; - } - - NimBLEClient* pClient = pService->getClient(); - if (pClient == nullptr) { - return; - } - - auto& sSensor = Sensors::settings[sensorId]; - - if (length != 2) { - Log.swarningln( - FPSTR(L_SENSORS_BLE), - F("Sensor #%hhu '%s': invalid notification data at temp char (%s) on device %s"), - sensorId, - sSensor.name, - pChar->getUUID().toString().c_str(), - pClient->getPeerAddress().toString().c_str() - ); - - return; - } - - float rawTemp = (pChar->getValue() * 0.1f); - Log.straceln( - FPSTR(L_SENSORS_BLE), - F("Sensor #%hhu '%s': received temp: %.2f"), - sensorId, sSensor.name, rawTemp - ); - - // set temp - Sensors::setValueById(sensorId, rawTemp, Sensors::ValueType::TEMPERATURE, true, true); - - // update rssi - Sensors::setValueById(sensorId, pClient->getRssi(), Sensors::ValueType::RSSI, false, false); - } - ); - - if (tempNotifyCreated) { - Log.straceln( - FPSTR(L_SENSORS_BLE), F("Sensor #%hhu '%s': subscribed to temp char (%s) in env service on device %s"), - sensorId, sSensor.name, - charUuid.toString().c_str(), pAddress.c_str() - ); - - } else { - Log.swarningln( - FPSTR(L_SENSORS_BLE), F("Sensor #%hhu '%s': failed to subscribe to temp char (%s) in env service on device %s"), - sensorId, sSensor.name, - charUuid.toString().c_str(), pAddress.c_str() - ); - } - } - } - - if (!tempNotifyCreated) { - Log.swarningln( - FPSTR(L_SENSORS_BLE), F("Sensor #%hhu '%s': not found supported temp chars in env service on device %s"), - sensorId, sSensor.name, pAddress.c_str() - ); - - pClient->disconnect(); - return false; - } - - - // 0x2A6F - Notify about humidity x0.01% (pvvx) - { - bool humidityNotifyCreated = false; - if (!humidityNotifyCreated) { - NimBLEUUID charUuid((uint16_t) 0x2A6F); - pChar = pService->getCharacteristic(charUuid); - - if (pChar && (pChar->canNotify() || pChar->canIndicate())) { - Log.straceln( - FPSTR(L_SENSORS_BLE), F("Sensor #%hhu '%s': found humidity char (%s) in env service on device %s"), - sensorId, sSensor.name, charUuid.toString().c_str(), pAddress.c_str() - ); - - pChar->unsubscribe(); - humidityNotifyCreated = pChar->subscribe( - pChar->canNotify(), - [sensorId](NimBLERemoteCharacteristic* pChar, uint8_t* pData, size_t length, bool isNotify) { - if (pChar == nullptr) { - return; - } - - const NimBLERemoteService* pService = pChar->getRemoteService(); - if (pService == nullptr) { - return; - } - - NimBLEClient* pClient = pService->getClient(); - if (pClient == nullptr) { - return; - } - - auto& sSensor = Sensors::settings[sensorId]; - - if (length != 2) { - Log.swarningln( - FPSTR(L_SENSORS_BLE), - F("Sensor #%hhu '%s': invalid notification data at humidity char (%s) on device %s"), - sensorId, - sSensor.name, - pChar->getUUID().toString().c_str(), - pClient->getPeerAddress().toString().c_str() - ); - - return; - } - - float rawHumidity = (pChar->getValue() * 0.01f); - Log.straceln( - FPSTR(L_SENSORS_BLE), - F("Sensor #%hhu '%s': received humidity: %.2f"), - sensorId, sSensor.name, rawHumidity - ); - - // set humidity - Sensors::setValueById(sensorId, rawHumidity, Sensors::ValueType::HUMIDITY, true, true); - - // update rssi - Sensors::setValueById(sensorId, pClient->getRssi(), Sensors::ValueType::RSSI, false, false); - } - ); - - if (humidityNotifyCreated) { - Log.straceln( - FPSTR(L_SENSORS_BLE), F("Sensor #%hhu '%s': subscribed to humidity char (%s) in env service on device %s"), - sensorId, sSensor.name, - charUuid.toString().c_str(), pAddress.c_str() - ); - - } else { - Log.swarningln( - FPSTR(L_SENSORS_BLE), F("Sensor #%hhu '%s': failed to subscribe to humidity char (%s) in env service on device %s"), - sensorId, sSensor.name, - charUuid.toString().c_str(), pAddress.c_str() - ); - } - } - } - - if (!humidityNotifyCreated) { - Log.swarningln( - FPSTR(L_SENSORS_BLE), F("Sensor #%hhu '%s': not found supported humidity chars in env service on device %s"), - sensorId, sSensor.name, pAddress.c_str() - ); - } - } - } - - - // Battery Service (0x180F) - { - NimBLEUUID serviceUuid((uint16_t) 0x180F); - pService = pClient->getService(serviceUuid); - if (!pService) { - Log.straceln( - FPSTR(L_SENSORS_BLE), F("Sensor #%hhu '%s': failed to find battery service (%s) on device %s"), - sensorId, sSensor.name, serviceUuid.toString().c_str(), pAddress.c_str() - ); - - } else { - Log.straceln( - FPSTR(L_SENSORS_BLE), F("Sensor #%hhu '%s': found battery service (%s) on device %s"), - sensorId, sSensor.name, serviceUuid.toString().c_str(), pAddress.c_str() - ); - - // 0x2A19 - Notify the battery charge level 0..99% (pvvx) - bool batteryNotifyCreated = false; - if (!batteryNotifyCreated) { - NimBLEUUID charUuid((uint16_t) 0x2A19); - pChar = pService->getCharacteristic(charUuid); - - if (pChar && (pChar->canNotify() || pChar->canIndicate())) { - Log.straceln( - FPSTR(L_SENSORS_BLE), F("Sensor #%hhu '%s': found battery char (%s) in battery service on device %s"), - sensorId, sSensor.name, charUuid.toString().c_str(), pAddress.c_str() - ); - - pChar->unsubscribe(); - batteryNotifyCreated = pChar->subscribe( - pChar->canNotify(), - [sensorId](NimBLERemoteCharacteristic* pChar, uint8_t* pData, size_t length, bool isNotify) { - if (pChar == nullptr) { - return; - } - - const NimBLERemoteService* pService = pChar->getRemoteService(); - if (pService == nullptr) { - return; - } - - NimBLEClient* pClient = pService->getClient(); - if (pClient == nullptr) { - return; - } - - auto& sSensor = Sensors::settings[sensorId]; - - if (length != 1) { - Log.swarningln( - FPSTR(L_SENSORS_BLE), - F("Sensor #%hhu '%s': invalid notification data at battery char (%s) on device %s"), - sensorId, - sSensor.name, - pChar->getUUID().toString().c_str(), - pClient->getPeerAddress().toString().c_str() - ); - - return; - } - - auto rawBattery = pChar->getValue(); - Log.straceln( - FPSTR(L_SENSORS_BLE), - F("Sensor #%hhu '%s': received battery: %hhu"), - sensorId, sSensor.name, rawBattery - ); - - // set battery - Sensors::setValueById(sensorId, rawBattery, Sensors::ValueType::BATTERY, true, true); - - // update rssi - Sensors::setValueById(sensorId, pClient->getRssi(), Sensors::ValueType::RSSI, false, false); - } - ); - - if (batteryNotifyCreated) { - Log.straceln( - FPSTR(L_SENSORS_BLE), F("Sensor #%hhu '%s': subscribed to battery char (%s) in battery service on device %s"), - sensorId, sSensor.name, - charUuid.toString().c_str(), pAddress.c_str() - ); - - } else { - Log.swarningln( - FPSTR(L_SENSORS_BLE), F("Sensor #%hhu '%s': failed to subscribe to battery char (%s) in battery service on device %s"), - sensorId, sSensor.name, - charUuid.toString().c_str(), pAddress.c_str() - ); - } - } - } - - if (!batteryNotifyCreated) { - Log.swarningln( - FPSTR(L_SENSORS_BLE), F("Sensor #%hhu '%s': not found supported battery chars in battery service on device %s"), - sensorId, sSensor.name, pAddress.c_str() - ); - } - } - } - - return true; - } - - bool setDateOnBleSensor(NimBLEClient* pClient, const struct tm *ptm) { - auto ts = mkgmtime(ptm); - - uint8_t data[5] = {}; - data[0] = 0x23; - data[1] = ts & 0xff; - data[2] = (ts >> 8) & 0xff; - data[3] = (ts >> 16) & 0xff; - data[4] = (ts >> 24) & 0xff; - - return pClient->setValue( - NimBLEUUID((uint16_t) 0x1f10), - NimBLEUUID((uint16_t) 0x1f1f), - NimBLEAttValue(data, sizeof(data)) - ); - } - #endif - - void updateConnectionStatus() { - for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { - auto& sSensor = Sensors::settings[sensorId]; - auto& rSensor = Sensors::results[sensorId]; - - if (rSensor.connected && !sSensor.enabled) { - Sensors::setConnectionStatusById(sensorId, false, false); - - } else if (rSensor.connected && sSensor.type == Sensors::Type::NOT_CONFIGURED) { - Sensors::setConnectionStatusById(sensorId, false, false); - - } else if (rSensor.connected && sSensor.purpose == Sensors::Purpose::NOT_CONFIGURED) { - Sensors::setConnectionStatusById(sensorId, false, false); - - } else if (rSensor.connected) { - if (sSensor.type == Sensors::Type::MANUAL || sSensor.type == Sensors::Type::BLUETOOTH) { - if ((millis() - rSensor.activityTime) > this->wirelessDisconnectTimeout) { - Sensors::setConnectionStatusById(sensorId, false, false); - } - - } else if ((millis() - rSensor.activityTime) > this->wiredDisconnectTimeout) { - Sensors::setConnectionStatusById(sensorId, false, false); - } - } - } - } - - static bool isEqualAddress(const uint8_t *addr1, const uint8_t *addr2, const uint8_t length = 8) { - return memcmp(addr1, addr2, length) == 0; - /*bool result = true; - - for (uint8_t i = 0; i < length; i++) { - if (addr1[i] != addr2[i]) { - result = false; - break; - } - } - - return result;*/ - } - - static bool isEmptyAddress(const uint8_t *addr, const uint8_t length = 8) { - bool result = true; - - for (uint8_t i = 0; i < length; i++) { - if (addr[i] != 0) { - result = false; - break; - } - } - - return result; - } -}; \ No newline at end of file diff --git a/src/Settings.h b/src/Settings.h deleted file mode 100644 index c75ded3..0000000 --- a/src/Settings.h +++ /dev/null @@ -1,462 +0,0 @@ -// NetworkSettings struct is append-only. The file is persisted across updates, -// and removing/modifying existing keys will lead to file corruption. -struct NetworkSettings { - char hostname[25] = DEFAULT_HOSTNAME; - bool useDhcp = true; - - struct { - char ip[16] = "192.168.0.100"; - char gateway[16] = "192.168.0.1"; - char subnet[16] = "255.255.255.0"; - char dns[16] = "192.168.0.1"; - } staticConfig; - - struct { - char ssid[33] = DEFAULT_AP_SSID; - char password[65] = DEFAULT_AP_PASSWORD; - uint8_t channel = 6; - } ap; - - struct { - char ssid[33] = DEFAULT_STA_SSID; - char password[65] = DEFAULT_STA_PASSWORD; - uint8_t channel = 0; - } sta; - - struct { - bool enabled = DEFAULT_ETHERNET_ENABLED; - - // nothing reads this yet: the W5500 is the only implementation the firmware can drive - EthernetImplementation implementation = EthernetImplementation::W5500; - - struct { - uint8_t clk = DEFAULT_ETH_CLK_GPIO; - uint8_t mosi = DEFAULT_ETH_MOSI_GPIO; - uint8_t miso = DEFAULT_ETH_MISO_GPIO; - uint8_t cs = DEFAULT_ETH_CS_GPIO; - uint8_t irq = DEFAULT_ETH_IRQ_GPIO; - uint8_t rst = DEFAULT_ETH_RST_GPIO; - } w5500; - } ethernet; -} networkSettings; - -struct Settings { - struct { - uint8_t logLevel = DEFAULT_LOG_LEVEL; - - struct { - bool enabled = DEFAULT_SERIAL_ENABLED; - unsigned int baudrate = DEFAULT_SERIAL_BAUD; - } serial; - - struct { - bool enabled = DEFAULT_TELNET_ENABLED; - unsigned short port = DEFAULT_TELNET_PORT; - } telnet; - - struct { - char server[49] = "pool.ntp.org"; - char timezone[49] = "UTC0"; - } ntp; - - UnitSystem unitSystem = UnitSystem::METRIC; - uint8_t statusLedGpio = DEFAULT_STATUS_LED_GPIO; - } system; - - struct { - bool auth = false; - char login[13] = DEFAULT_PORTAL_LOGIN; - char password[33] = DEFAULT_PORTAL_PASSWORD; - bool mdns = true; - } portal; - - struct { - UnitSystem unitSystem = UnitSystem::METRIC; - uint8_t inGpio = DEFAULT_OT_IN_GPIO; - uint8_t outGpio = DEFAULT_OT_OUT_GPIO; - uint8_t rxLedGpio = DEFAULT_OT_RX_LED_GPIO; - uint8_t memberId = 0; - uint8_t flags = 0; - float minPower = 0.0f; - float maxPower = 0.0f; - - struct { - bool dhwSupport = true; - bool coolingSupport = false; - bool summerWinterMode = false; - bool heatingStateToSummerWinterMode = false; - bool ch2AlwaysEnabled = true; - bool heatingToCh2 = false; - bool dhwToCh2 = false; - bool dhwBlocking = false; - bool dhwStateAsDhwBlocking = false; - bool maxTempSyncWithTargetTemp = true; - bool getMinMaxTemp = true; - bool ignoreDiagState = false; - bool autoFaultReset = false; - bool autoDiagReset = false; - bool setDateAndTime = false; - bool alwaysSendIndoorTemp = true; - bool nativeOTC = false; - bool immergasFix = false; - } options; - } opentherm; - - struct { - bool enabled = DEFAULT_MQTT_ENABLED; - char server[81] = DEFAULT_MQTT_SERVER; - unsigned short port = DEFAULT_MQTT_PORT; - char user[33] = DEFAULT_MQTT_USER; - char password[33] = DEFAULT_MQTT_PASSWORD; - char prefix[33] = DEFAULT_MQTT_PREFIX; - unsigned short interval = 5; - bool homeAssistantDiscovery = true; - } mqtt; - - struct { - float target = DEFAULT_HEATING_TARGET_TEMP; - unsigned short tresholdTime = 120; - } emergency; - - struct { - bool enabled = true; - bool turbo = false; - float target = DEFAULT_HEATING_TARGET_TEMP; - float turboFactor = 7.5f; - uint8_t minTemp = DEFAULT_HEATING_MIN_TEMP; - uint8_t maxTemp = DEFAULT_HEATING_MAX_TEMP; - uint8_t maxModulation = 100; - - struct { - bool enabled = true; - float value = 0.5f; - HysteresisAction action = HysteresisAction::DISABLE_HEATING; - } hysteresis; - - struct { - uint8_t highTemp = 95; - uint8_t lowTemp = 90; - } overheatProtection; - - struct { - uint8_t highTemp = 15; - uint8_t lowTemp = 10; - } freezeProtection; - } heating; - - struct { - bool enabled = true; - float target = DEFAULT_DHW_TARGET_TEMP; - uint8_t minTemp = DEFAULT_DHW_MIN_TEMP; - uint8_t maxTemp = DEFAULT_DHW_MAX_TEMP; - uint8_t maxModulation = 100; - - struct { - uint8_t highTemp = 95; - uint8_t lowTemp = 90; - } overheatProtection; - } dhw; - - struct { - bool enabled = false; - float p_factor = 2.0f; - float i_factor = 0.002f; - float d_factor = 0.0f; - unsigned short dt = 300; - short minTemp = 0; - short maxTemp = DEFAULT_HEATING_MAX_TEMP; - - struct { - bool enabled = true; - float p_multiplier = 1.0f; - float i_multiplier = 0.05f; - float d_multiplier = 1.0f; - float thresholdHigh = 0.5f; - float thresholdLow = 1.0f; - } deadband; - } pid; - - struct { - bool enabled = false; - float slope = 0.7f; - float exponent = 1.3f; - float shift = 0.0f; - float targetDiffFactor = 2.0f; - } equitherm; - - struct { - bool use = false; - uint8_t gpio = DEFAULT_EXT_PUMP_GPIO; - bool invertState = false; - unsigned short postCirculationTime = 600; - unsigned int antiStuckInterval = 2592000; - unsigned short antiStuckTime = 300; - } externalPump; - - struct { - struct { - bool enabled = false; - uint8_t gpio = GPIO_IS_NOT_CONFIGURED; - bool invertState = false; - unsigned short thresholdTime = 60; - } input; - - struct { - bool enabled = false; - uint8_t gpio = GPIO_IS_NOT_CONFIGURED; - bool invertState = false; - unsigned short thresholdTime = 60; - bool onFault = true; - bool onLossConnection = true; - bool onEnabledHeating = false; - } output; - } cascadeControl; - - char validationValue[8] = SETTINGS_VALID_VALUE; -} settings; - -Sensors::Settings sensorsSettings[SENSORS_AMOUNT] = { - { - false, - "Outdoor temp", - Sensors::Purpose::OUTDOOR_TEMP, - Sensors::Type::OT_OUTDOOR_TEMP, - DEFAULT_SENSOR_OUTDOOR_GPIO - }, - { - false, - "Indoor temp", - Sensors::Purpose::INDOOR_TEMP, - Sensors::Type::DALLAS_TEMP, - DEFAULT_SENSOR_INDOOR_GPIO - }, - { - true, - "Heating temp", - Sensors::Purpose::HEATING_TEMP, - Sensors::Type::OT_HEATING_TEMP, - }, - { - true, - "Heating return temp", - Sensors::Purpose::HEATING_RETURN_TEMP, - Sensors::Type::OT_HEATING_RETURN_TEMP, - }, - { - true, - "Heating setpoint temp", - Sensors::Purpose::TEMPERATURE, - Sensors::Type::HEATING_SETPOINT_TEMP, - }, - { - true, - "DHW temp", - Sensors::Purpose::DHW_TEMP, - Sensors::Type::OT_DHW_TEMP, - }, - { - true, - "DHW flow rate", - Sensors::Purpose::DHW_FLOW_RATE, - Sensors::Type::OT_DHW_FLOW_RATE, - }, - { - true, - "Exhaust temp", - Sensors::Purpose::EXHAUST_TEMP, - Sensors::Type::OT_EXHAUST_TEMP, - }, - { - true, - "Pressure", - Sensors::Purpose::PRESSURE, - Sensors::Type::OT_PRESSURE, - }, - { - true, - "Modulation level", - Sensors::Purpose::MODULATION_LEVEL, - Sensors::Type::OT_MODULATION_LEVEL, - }, - { - true, - "Power", - Sensors::Purpose::POWER, - Sensors::Type::OT_CURRENT_POWER, - } -}; - -struct Variables { - struct { - bool connected = false; - int8_t rssi = 0; - NetworkUtils::NetworkMgr::Uplink connectionType = NetworkUtils::NetworkMgr::Uplink::None; - } network; - - struct { - bool connected = false; - } mqtt; - - struct { - bool state = false; - } emergency; - - struct { - bool state = false; - unsigned long lastEnabledTime = 0; - } externalPump; - - struct { - bool input = false; - bool output = false; - } cascadeControl; - - struct { - uint8_t memberId = 0; - uint8_t flags = 0; - uint8_t type = 0; - uint8_t appVersion = 0; - float protocolVersion = 0.0f; - - struct { - bool blocking = false; - bool enabled = false; - bool indoorTempControl = false; - bool overheat = false; - bool freezing = false; - float setpointTemp = 0.0f; - float targetTemp = 0.0f; - float currentTemp = 0.0f; - float returnTemp = 0.0f; - float indoorTemp = 0.0f; - float outdoorTemp = 0.0f; - float minTemp = 0.0f; - float maxTemp = 0.0f; - } heating; - - struct { - bool enabled = false; - bool overheat = false; - float targetTemp = 0.0f; - float currentTemp = 0.0f; - float returnTemp = 0.0f; - } dhw; - - struct { - bool enabled = false; - float targetTemp = 0.0f; - } ch2; - } master; - - struct { - uint8_t memberId = 0; - uint8_t flags = 0; - uint8_t type = 0; - uint8_t appVersion = 0; - float protocolVersion = 0.0f; - - bool connected = false; - bool flame = false; - float pressure = 0.0f; - float heatExchangerTemp = 0.0f; - - struct { - bool active = false; - uint8_t setpoint = 0; - } cooling; - - struct { - bool active = false; - uint8_t code = 0; - } fault; - - struct { - bool active = false; - uint16_t code = 0; - } diag; - - struct { - uint8_t current = 0; - uint8_t min = 0; - uint8_t max = 100; - } modulation; - - struct { - float current = 0.0f; - float min = 0.0f; - float max = 0.0f; - } power; - - struct { - float temp = 0.0f; - uint16_t co2 = 0; - uint16_t fanSpeed = 0; - } exhaust; - - struct { - float storage = 0.0f; - float collector = 0.0f; - } solar; - - struct { - uint8_t setpoint = 0; - uint8_t current = 0; - uint16_t supply = 0; - } fanSpeed; - - struct { - uint16_t burnerStarts = 0; - uint16_t dhwBurnerStarts = 0; - uint16_t heatingPumpStarts = 0; - uint16_t dhwPumpStarts = 0; - uint16_t coolingHours = 0; - uint16_t burnerHours = 0; - uint16_t dhwBurnerHours = 0; - uint16_t heatingPumpHours = 0; - uint16_t dhwPumpHours = 0; - } stats; - - struct { - bool active = false; - bool enabled = false; - float targetTemp = 0.0f; - float currentTemp = 0.0f; - float returnTemp = 0.0f; - float indoorTemp = 0.0f; - float outdoorTemp = 0.0f; - uint8_t minTemp = DEFAULT_HEATING_MIN_TEMP; - uint8_t maxTemp = DEFAULT_HEATING_MAX_TEMP; - } heating; - - struct { - bool active = false; - bool enabled = false; - float targetTemp = 0.0f; - float currentTemp = 0.0f; - float currentTemp2 = 0.0f; - float returnTemp = 0.0f; - float flowRate = 0.0f; - uint8_t minTemp = DEFAULT_DHW_MIN_TEMP; - uint8_t maxTemp = DEFAULT_DHW_MAX_TEMP; - } dhw; - - struct { - bool active = false; - bool enabled = false; - float targetTemp = 0.0f; - float currentTemp = 0.0f; - float indoorTemp = 0.0f; - } ch2; - } slave; - - struct { - bool restart = false; - bool resetFault = false; - bool resetDiagnostic = false; - } actions; - - struct { - bool restarting = false; - bool upgrading = false; - } states; -} vars; diff --git a/src/bluetooth.hpp b/src/bluetooth.hpp new file mode 100644 index 0000000..81114c2 --- /dev/null +++ b/src/bluetooth.hpp @@ -0,0 +1,320 @@ +#pragma once + +#include +#include +#include +#include + +#include "Sensors.h" +#include "strings_shared.h" + +class BluetoothScanCallbacks : public NimBLEScanCallbacks { +public: + void onDiscovered(const NimBLEAdvertisedDevice* device) override { + auto& deviceAddress = device->getAddress(); + + bool found = false; + uint8_t sensorId; + std::optional sSensor; + for (sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { + sSensor = Sensors::getSettings(sensorId); + if (!sSensor) { + continue; + } + if (!sSensor->enabled || sSensor->type != Sensors::Type::BLUETOOTH || sSensor->purpose == Sensors::Purpose::NOT_CONFIGURED) { + continue; + } + + const auto sensorAddress = NimBLEAddress(sSensor->address, deviceAddress.getType()); + if (sensorAddress.isNull() || sensorAddress != deviceAddress) { + continue; + } + + found = true; + break; + } + + if (!found) { + return; + } + + auto deviceName = device->getName(); + auto deviceRssi = device->getRSSI(); + + ESP_LOGI( + L_SENSORS_BLE, "Sensor #%hhu '%s': discovered device %s, name: %s, RSSI: %hhd", + sensorId, sSensor->name, + deviceAddress.toString().c_str(), deviceName.c_str(), deviceRssi + ); + + if (!device->haveServiceData()) { + ESP_LOGW( + L_SENSORS_BLE, "Sensor #%hhu '%s': not found service data!", + sensorId, sSensor->name + ); + return; + } + + auto serviceDataCount = device->getServiceDataCount(); + ESP_LOGD( + L_SENSORS_BLE, "Sensor #%hhu '%s': found %hhu service data", + sensorId, sSensor->name, serviceDataCount + ); + + if (parseAtcData(device, sensorId) || parsePvvxData(device, sensorId) || parseBTHomeData(device, sensorId)) { + // update rssi + Sensors::setValueById(sensorId, deviceRssi, Sensors::ValueType::RSSI, false, false); + + } else { + ESP_LOGW( + L_SENSORS_BLE, "Sensor #%hhu '%s': unsupported data format!", + sensorId, sSensor->name + ); + } + } + + static bool parseAtcData(const NimBLEAdvertisedDevice* device, uint8_t sensorId) { + NimBLEUUID serviceUuid(static_cast(0x181A)); + + auto serviceData = device->getServiceData(serviceUuid); + if (!serviceData.size()) { + ESP_LOGD( + L_SENSORS_BLE, "Sensor #%hhu, service %s: not found ATC1441 data", + sensorId, serviceUuid.toString().c_str() + ); + return false; + + } else if (serviceData.size() != 13) { + ESP_LOGD( + L_SENSORS_BLE, "Sensor #%hhu, service %s: not in ATC1441 format", + sensorId, serviceUuid.toString().c_str() + ); + return false; + } + + ESP_LOGI( + L_SENSORS_BLE, "Sensor #%hhu, service %s: found ATC1441 format", + sensorId, serviceUuid.toString().c_str() + ); + + // Temperature (2 bytes, signed, big-endian) + float temperature = static_cast( + (static_cast(serviceData[6]) << 8) | + static_cast(serviceData[7]) + ) * 0.1f; + Sensors::setValueById( + sensorId, temperature, + Sensors::ValueType::TEMPERATURE, true, true + ); + + // Humidity (1 byte) + float humidity = static_cast(serviceData[8]); + Sensors::setValueById(sensorId, humidity, Sensors::ValueType::HUMIDITY, true, true); + + // Battery level (1 byte) + uint8_t batteryLevel = static_cast(serviceData[9]); + Sensors::setValueById(sensorId, batteryLevel, Sensors::ValueType::BATTERY, true, true); + + // Battery mV (2 bytes, big-endian) + uint16_t batteryMv = (static_cast(serviceData[10]) << 8) | static_cast(serviceData[11]); + + // Log + ESP_LOGI( + L_SENSORS_BLE, + "Sensor #%hhu, received temp: %.2f; humidity: %.2f, battery voltage: %hu, battery level: %hhu", + sensorId, temperature, humidity, batteryMv, batteryLevel + ); + + return true; + } + + static bool parsePvvxData(const NimBLEAdvertisedDevice* device, uint8_t sensorId) { + NimBLEUUID serviceUuid(static_cast(0x181A)); + + auto serviceData = device->getServiceData(serviceUuid); + if (!serviceData.size()) { + ESP_LOGD( + L_SENSORS_BLE, "Sensor #%hhu, service %s: not found PVVX data", + sensorId, serviceUuid.toString().c_str() + ); + return false; + + } else if (serviceData.size() != 14 && serviceData.size() != 15) { + ESP_LOGD( + L_SENSORS_BLE, "Sensor #%hhu, service %s: not in PVVX format", + sensorId, serviceUuid.toString().c_str() + ); + return false; + } + + ESP_LOGI( + L_SENSORS_BLE, "Sensor #%hhu, service %s: found PVVX format", + sensorId, serviceUuid.toString().c_str() + ); + + // Temperature (2 bytes, signed, little-endian) + float temperature = static_cast( + (static_cast(serviceData[7]) << 8) | + static_cast(serviceData[6]) + ) * 0.01f; + Sensors::setValueById( + sensorId, temperature, + Sensors::ValueType::TEMPERATURE, true, true + ); + + // Humidity (2 bytes, little-endian) + float humidity = ( + (static_cast(serviceData[9]) << 8) | static_cast(serviceData[8]) + ) * 0.01f; + Sensors::setValueById(sensorId, humidity, Sensors::ValueType::HUMIDITY, true, true); + + // Battery level (1 byte) + uint8_t batteryLevel = static_cast(serviceData[12]); + Sensors::setValueById(sensorId, batteryLevel, Sensors::ValueType::BATTERY, true, true); + + // Battery mV (2 bytes, little-endian) + uint16_t batteryMv = (static_cast(serviceData[11]) << 8) | static_cast(serviceData[10]); + + // Log + ESP_LOGI( + L_SENSORS_BLE, + "Sensor #%hhu, received temp: %.2f; humidity: %.2f, battery voltage: %hu, battery level: %hhu", + sensorId, temperature, humidity, batteryMv, batteryLevel + ); + + return true; + } + + static bool parseBTHomeData(const NimBLEAdvertisedDevice* device, uint8_t sensorId) { + NimBLEUUID serviceUuid(static_cast(0xFCD2)); + + auto serviceData = device->getServiceData(serviceUuid); + if (!serviceData.size()) { + ESP_LOGD( + L_SENSORS_BLE, "Sensor #%hhu, service %s: not found BTHome data", + sensorId, serviceUuid.toString().c_str() + ); + return false; + + } else if ((serviceData[0] & 0xE0) != 0x40) { + ESP_LOGD( + L_SENSORS_BLE, "Sensor #%hhu, service %s: unsupported BTHome version", + sensorId, serviceUuid.toString().c_str() + ); + return false; + + } else if ((serviceData[0] & 0x01) != 0) { + ESP_LOGD( + L_SENSORS_BLE, "Sensor #%hhu, service %s: unsupported BTHome encrypted data", + sensorId, serviceUuid.toString().c_str() + ); + return false; + } + + ESP_LOGI( + L_SENSORS_BLE, "Sensor #%hhu, service %s: found BTHome format", + sensorId, serviceUuid.toString().c_str() + ); + + bool foundData = false; + size_t serviceDataPos = 1; + while (serviceDataPos < serviceData.size()) { + uint8_t objectId = serviceData[serviceDataPos++]; + + switch (objectId) { + // Packet ID (1 byte) + case 0x00: + if (serviceDataPos + 1 > serviceData.size()) { + return foundData; + } + + serviceDataPos += 1; + break; + + // Battery (1 byte) + case 0x01: { + if (serviceDataPos + 1 > serviceData.size()) { + return foundData; + } + + uint8_t batteryLevel = static_cast(serviceData[serviceDataPos]); + Sensors::setValueById(sensorId, batteryLevel, Sensors::ValueType::BATTERY, true, true); + serviceDataPos += 1; + foundData = true; + + ESP_LOGI( + L_SENSORS_BLE, "Sensor #%hhu, received battery level: %hhu", + sensorId, batteryLevel + ); + break; + } + + // Temperature (2 bytes, signed, little-endian) + case 0x02: { + if (serviceDataPos + 2 > serviceData.size()) { + return foundData; + } + + int16_t rawTemperature = (static_cast(serviceData[serviceDataPos + 1]) << 8) + | static_cast(serviceData[serviceDataPos]); + float temperature = static_cast(rawTemperature) * 0.01f; + Sensors::setValueById( + sensorId, temperature, + Sensors::ValueType::TEMPERATURE, true, true + ); + serviceDataPos += 2; + foundData = true; + + ESP_LOGI( + L_SENSORS_BLE, "Sensor #%hhu, received temp: %.2f", + sensorId, temperature + ); + break; + } + + // Humidity (2 bytes, little-endian) + case 0x03: { + if (serviceDataPos + 2 > serviceData.size()) { + return foundData; + } + + uint16_t rawHumidity = (static_cast(serviceData[serviceDataPos + 1]) << 8) + | static_cast(serviceData[serviceDataPos]); + float humidity = static_cast(rawHumidity) * 0.01f; + Sensors::setValueById(sensorId, humidity, Sensors::ValueType::HUMIDITY, true, true); + serviceDataPos += 2; + foundData = true; + + ESP_LOGI( + L_SENSORS_BLE, "Sensor #%hhu, received humidity: %.2f", + sensorId, humidity + ); + break; + } + + // Voltage (2 bytes, little-endian) + case 0x0C: { + if (serviceDataPos + 2 > serviceData.size()) { + return foundData; + } + + uint16_t batteryMv = (static_cast(serviceData[serviceDataPos + 1]) << 8) + | static_cast(serviceData[serviceDataPos]); + serviceDataPos += 2; + foundData = true; + + ESP_LOGI( + L_SENSORS_BLE, "Sensor #%hhu, received battery voltage: %hu", + sensorId, batteryMv + ); + break; + } + + default: + return foundData; + } + } + + return foundData; + } +}; diff --git a/src/config.cpp b/src/config.cpp new file mode 100644 index 0000000..e17c73b --- /dev/null +++ b/src/config.cpp @@ -0,0 +1,3661 @@ +#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE + +#include + +#include +#include +#include +#include +#include +#include + +NetworkSettings networkSettings; +Settings settings; + +Sensors::Settings sensorsSettings[SENSORS_AMOUNT] = { + { + false, + "Outdoor temp", + "outdoor_temp", + Sensors::Purpose::OUTDOOR_TEMP, + Sensors::Type::OT_OUTDOOR_TEMP, + DEFAULT_SENSOR_OUTDOOR_GPIO + }, + { + false, + "Indoor temp", + "indoor_temp", + Sensors::Purpose::INDOOR_TEMP, + DEFAULT_SENSOR_INDOOR_TYPE, + DEFAULT_SENSOR_INDOOR_GPIO + }, + { + true, + "Heating temp", + "heating_temp", + Sensors::Purpose::HEATING_TEMP, + Sensors::Type::OT_HEATING_TEMP, + }, + { + true, + "Heating return temp", + "heating_return_temp", + Sensors::Purpose::HEATING_RETURN_TEMP, + Sensors::Type::OT_HEATING_RETURN_TEMP, + }, + { + true, + "Heating setpoint temp", + "heating_setpoint_temp", + Sensors::Purpose::TEMPERATURE, + Sensors::Type::HEATING_SETPOINT_TEMP, + }, + { + true, + "DHW temp", + "dhw_temp", + Sensors::Purpose::DHW_TEMP, + Sensors::Type::OT_DHW_TEMP, + }, + { + true, + "DHW flow rate", + "dhw_flow_rate", + Sensors::Purpose::DHW_FLOW_RATE, + Sensors::Type::OT_DHW_FLOW_RATE, + }, + { + true, + "Exhaust temp", + "exhaust_temp", + Sensors::Purpose::EXHAUST_TEMP, + Sensors::Type::OT_EXHAUST_TEMP, + }, + { + true, + "Pressure", + "pressure", + Sensors::Purpose::PRESSURE, + Sensors::Type::OT_PRESSURE, + }, + { + true, + "Modulation level", + "modulation_level", + Sensors::Purpose::MODULATION_LEVEL, + Sensors::Type::OT_MODULATION_LEVEL, + }, + { + true, + "Power", + "power", + Sensors::Purpose::POWER, + Sensors::Type::OT_CURRENT_POWER, + } +}; + +static FileData fsNetworkSettings(&LittleFS, "/network.conf", 'n', &networkSettings, sizeof(networkSettings), 1000); +static FileData fsSettings(&LittleFS, "/settings.conf", 's', &settings, sizeof(settings), 60000); +static FileData fsSensorsSettings(&LittleFS, "/sensors.conf", 'e', &sensorsSettings, sizeof(sensorsSettings), 60000); + +// FileData requests can arrive while the save task is running. +static std::mutex settingsSaveMutex; + +void requestSaveNetworkSettings() { + std::lock_guard lock(settingsSaveMutex); + fsNetworkSettings.update(); +} + +void requestSaveSettings() { + std::lock_guard lock(settingsSaveMutex); + fsSettings.update(); +} + +void requestSaveSensorsSettings() { + std::lock_guard lock(Sensors::mutex); + fsSensorsSettings.update(); +} + +static Task settingsSaveTask("Settings save", [](void*) { + FDstat_t status; + { + std::lock_guard lock(settingsSaveMutex); + status = fsNetworkSettings.tick(); + } + if (status == FD_WRITE) { + ESP_LOGI(L_NETWORK_SETTINGS, "Updated"); + } + + { + std::lock_guard lock(settingsSaveMutex); + status = fsSettings.tick(); + } + if (status == FD_WRITE) { + ESP_LOGI(L_SETTINGS, "Updated"); + } + + { + std::lock_guard lock(Sensors::mutex); + status = fsSensorsSettings.tick(); + } + if (status == FD_WRITE) { + ESP_LOGI(L_SENSORS_SETTINGS, "Updated"); + } +}); + +void saveSettingsNow() { + { + std::lock_guard lock(settingsSaveMutex); + fsSettings.updateNow(); + } + + { + std::lock_guard lock(Sensors::mutex); + fsSensorsSettings.updateNow(); + } + + // Always preserve the network configuration + { + std::lock_guard lock(settingsSaveMutex); + if (fsNetworkSettings.updateNow() == FD_FILE_ERR && LittleFS.begin()) { + fsNetworkSettings.write(); + } + } +} + +// Initialization +static bool loadNetworkSettings() { + bool loaded = false; + fsNetworkSettings.addWithoutWipe(true); + + switch (fsNetworkSettings.read()) { + case FD_FS_ERR: + ESP_LOGW(L_NETWORK_SETTINGS, "Filesystem error, load default"); + break; + + case FD_FILE_ERR: + ESP_LOGW(L_NETWORK_SETTINGS, "Bad data, load default"); + break; + + case FD_WRITE: + ESP_LOGI(L_NETWORK_SETTINGS, "Not found, load default"); + break; + + case FD_ADD: + case FD_READ: + ESP_LOGI(L_NETWORK_SETTINGS, "Loaded"); + loaded = true; + break; + + default: + break; + } + + if (!networkSettings.hostname[0]) { + strcpy(networkSettings.hostname, getChipId("otgateway-").c_str()); + requestSaveNetworkSettings(); + } + + return loaded; +} + +static bool loadSettings() { + bool loaded = false; + + switch (fsSettings.read()) { + case FD_FS_ERR: + ESP_LOGW(L_SETTINGS, "Filesystem error, load default"); + break; + + case FD_FILE_ERR: + ESP_LOGW(L_SETTINGS, "Bad data, load default"); + break; + + case FD_WRITE: + ESP_LOGI(L_SETTINGS, "Not found, load default"); + break; + + case FD_ADD: + case FD_READ: + if (memcmp(settings.validationValue, SETTINGS_VALID_VALUE, sizeof(settings.validationValue)) == 0) { + ESP_LOGI(L_SETTINGS, "Loaded"); + loaded = true; + + } else { + ESP_LOGW(L_SETTINGS, "Loaded, but not valid, reset to default"); + settings = Settings{}; + fsSettings.reset(); + } + break; + + default: + break; + } + + if (settings.system.logLevel < ESP_LOG_NONE || settings.system.logLevel > ESP_LOG_VERBOSE) { + settings.system.logLevel = static_cast(DEFAULT_LOG_LEVEL); + requestSaveSettings(); + } + + // generate mqtt prefix if it is empty + if (!strlen(settings.mqtt.prefix)) { + strcpy(settings.mqtt.prefix, getChipId("otgateway_").c_str()); + requestSaveSettings(); + } + + return loaded; +} + +static bool loadSensorsSettings() { + bool loaded = false; + + switch (fsSensorsSettings.read()) { + case FD_FS_ERR: + ESP_LOGW(L_SENSORS, "Filesystem error, load default"); + break; + + case FD_FILE_ERR: + ESP_LOGW(L_SENSORS, "Bad data, load default"); + break; + + case FD_WRITE: + ESP_LOGI(L_SENSORS, "Not found, load default"); + break; + + case FD_ADD: + case FD_READ: + ESP_LOGI(L_SENSORS, "Loaded"); + loaded = true; + break; + + default: + break; + } + + return loaded; +} + +void initConfig() { + loadNetworkSettings(); + loadSettings(); + loadSensorsSettings(); + configureLoggingTask.forceRun(); + + appTaskManager.addTask(settingsSaveTask.setInterval(100)); +} + +// JSON API + +// Shared validation + +static bool isSettingInteger(float value, float minValue, float maxValue) { + return std::isfinite(value) && value >= minValue && value <= maxValue && std::trunc(value) == value; +} + +// Network settings + +static bool isHostnameValid(const char* value) { + if (value == nullptr) { + return false; + } + + size_t len = strlen(value); + if (len == 0 || len > 24 || value[0] == '-' || value[len - 1] == '-') { + return false; + } + + for (size_t i = 0; i < len; i++) { + const char symbol = value[i]; + + // Lowercase ASCII letters. + if (symbol >= 'a' && symbol <= 'z') { + continue; + } + + // Uppercase ASCII letters. + if (symbol >= 'A' && symbol <= 'Z') { + continue; + } + + // Decimal digits. + if (symbol >= '0' && symbol <= '9') { + continue; + } + + // Hyphens are allowed inside the hostname. + if (symbol == '-') { + continue; + } + + // All other characters are invalid. + return false; + } + + return true; +} + +JsonVariant toJson(const NetworkSettings& src, JsonVariant dst) { + dst[S_HOSTNAME] = src.hostname; + + dst[S_USE_DHCP] = src.useDhcp; + dst[S_STATIC_CONFIG][S_IP] = src.staticConfig.ip; + dst[S_STATIC_CONFIG][S_GATEWAY] = src.staticConfig.gateway; + dst[S_STATIC_CONFIG][S_SUBNET] = src.staticConfig.subnet; + dst[S_STATIC_CONFIG][S_DNS] = src.staticConfig.dns; + + auto wifi = dst[S_WIFI].to(); + wifi[S_AP][S_SSID] = src.wifi.ap.ssid; + wifi[S_AP][S_PASSWORD] = src.wifi.ap.password; + wifi[S_AP][S_CHANNEL] = src.wifi.ap.channel; + + wifi[S_STA][S_SSID] = src.wifi.sta.ssid; + wifi[S_STA][S_PASSWORD] = src.wifi.sta.password; + wifi[S_STA][S_CHANNEL] = src.wifi.sta.channel; + + #if USE_ETHERNET + auto gpio = dst[S_ETHERNET][S_GPIO].to(); + gpio[S_CLK] = src.ethernet.w5500.clk; + gpio[S_MOSI] = src.ethernet.w5500.mosi; + gpio[S_MISO] = src.ethernet.w5500.miso; + gpio[S_CS] = src.ethernet.w5500.cs; + gpio[S_IRQ] = src.ethernet.w5500.irq; + gpio[S_RST] = src.ethernet.w5500.rst; + #endif + + dst[S_TYPE] = static_cast(src.type); + + return dst; +} + +SettingResult fromJson(JsonVariantConst src, NetworkSettings& dst) { + SettingResult result; + + // hostname + if (src[S_HOSTNAME].is()) { + const JsonString value = src[S_HOSTNAME].as(); + + if (strlen(value.c_str()) == value.size()) { + if (value.size() < sizeof(dst.hostname) && isHostnameValid(value.c_str())) { + result.accepted = true; + if (strcmp(value.c_str(), dst.hostname) != 0) { + strcpy(dst.hostname, value.c_str()); + result.changed = true; + } + } + } + } + + // use dhcp + if (src[S_USE_DHCP].is()) { + const auto value = src[S_USE_DHCP].as(); + result.accepted = true; + + if (value != dst.useDhcp) { + dst.useDhcp = value; + result.changed = true; + } + } + + + // static config + if (src[S_STATIC_CONFIG][S_IP].is()) { + const JsonString value = src[S_STATIC_CONFIG][S_IP].as(); + + if (strlen(value.c_str()) == value.size()) { + if (value.size() < sizeof(dst.staticConfig.ip)) { + result.accepted = true; + if (strcmp(value.c_str(), dst.staticConfig.ip) != 0) { + strcpy(dst.staticConfig.ip, value.c_str()); + result.changed = true; + } + } + } + } + + if (src[S_STATIC_CONFIG][S_GATEWAY].is()) { + const JsonString value = src[S_STATIC_CONFIG][S_GATEWAY].as(); + + if (strlen(value.c_str()) == value.size()) { + if (value.size() < sizeof(dst.staticConfig.gateway)) { + result.accepted = true; + if (strcmp(value.c_str(), dst.staticConfig.gateway) != 0) { + strcpy(dst.staticConfig.gateway, value.c_str()); + result.changed = true; + } + } + } + } + + if (src[S_STATIC_CONFIG][S_SUBNET].is()) { + const JsonString value = src[S_STATIC_CONFIG][S_SUBNET].as(); + + if (strlen(value.c_str()) == value.size()) { + if (value.size() < sizeof(dst.staticConfig.subnet)) { + result.accepted = true; + if (strcmp(value.c_str(), dst.staticConfig.subnet) != 0) { + strcpy(dst.staticConfig.subnet, value.c_str()); + result.changed = true; + } + } + } + } + + if (src[S_STATIC_CONFIG][S_DNS].is()) { + const JsonString value = src[S_STATIC_CONFIG][S_DNS].as(); + + if (strlen(value.c_str()) == value.size()) { + if (value.size() < sizeof(dst.staticConfig.dns)) { + result.accepted = true; + if (strcmp(value.c_str(), dst.staticConfig.dns) != 0) { + strcpy(dst.staticConfig.dns, value.c_str()); + result.changed = true; + } + } + } + } + + + const auto wifi = src[S_WIFI]; + const auto ap = wifi[S_AP]; + const auto sta = wifi[S_STA]; + + // ap + if (ap[S_SSID].is()) { + const JsonString value = ap[S_SSID].as(); + + if (strlen(value.c_str()) == value.size()) { + if (value.size() && value.size() < sizeof(dst.wifi.ap.ssid)) { + result.accepted = true; + if (strcmp(value.c_str(), dst.wifi.ap.ssid) != 0) { + strcpy(dst.wifi.ap.ssid, value.c_str()); + result.changed = true; + } + } + } + } + + if (ap[S_PASSWORD].is()) { + const JsonString value = ap[S_PASSWORD].as(); + + if (strlen(value.c_str()) == value.size()) { + if (value.size() && value.size() < sizeof(dst.wifi.ap.password)) { + result.accepted = true; + if (strcmp(value.c_str(), dst.wifi.ap.password) != 0) { + strcpy(dst.wifi.ap.password, value.c_str()); + result.changed = true; + } + } + } + } + + if (ap[S_CHANNEL].is()) { + const auto value = ap[S_CHANNEL].as(); + + if (value < 12) { + result.accepted = true; + + if (value != dst.wifi.ap.channel) { + dst.wifi.ap.channel = value; + result.changed = true; + } + } + } + + + // sta + if (sta[S_SSID].is()) { + const JsonString value = sta[S_SSID].as(); + + if (strlen(value.c_str()) == value.size()) { + if (value.size() && value.size() < sizeof(dst.wifi.sta.ssid)) { + result.accepted = true; + if (strcmp(value.c_str(), dst.wifi.sta.ssid) != 0) { + strcpy(dst.wifi.sta.ssid, value.c_str()); + result.changed = true; + } + } + } + } + + if (sta[S_PASSWORD].is()) { + const JsonString value = sta[S_PASSWORD].as(); + + if (strlen(value.c_str()) == value.size()) { + if (value.size() < sizeof(dst.wifi.sta.password)) { + result.accepted = true; + if (strcmp(value.c_str(), dst.wifi.sta.password) != 0) { + strcpy(dst.wifi.sta.password, value.c_str()); + result.changed = true; + } + } + } + } + + if (sta[S_CHANNEL].is()) { + const auto value = sta[S_CHANNEL].as(); + + if (value < 12) { + result.accepted = true; + + if (value != dst.wifi.sta.channel) { + dst.wifi.sta.channel = value; + result.changed = true; + } + } + } + + #if USE_ETHERNET + // Ethernet GPIOs use the same strict numeric contract as the other GPIO settings. + const auto ethernet = src[S_ETHERNET]; + const auto parseGpio = [&result](JsonVariantConst gpio, uint8_t& target, bool output) { + uint8_t value; + if (gpio.is() && gpio.as().size() == 0) { + value = GPIO_IS_NOT_CONFIGURED; + + } else if (gpio.is()) { + value = gpio.as(); + + } else { + return; + } + + if (value != GPIO_IS_NOT_CONFIGURED && !(output ? GPIO_IS_VALID_OUTPUT(value) : GPIO_IS_VALID_INPUT(value))) { + return; + } + + result.accepted = true; + if (value != target) { + target = value; + result.changed = true; + } + }; + + const auto gpio = ethernet[S_GPIO]; + parseGpio(gpio[S_CLK], dst.ethernet.w5500.clk, true); + parseGpio(gpio[S_MOSI], dst.ethernet.w5500.mosi, true); + parseGpio(gpio[S_MISO], dst.ethernet.w5500.miso, false); + parseGpio(gpio[S_CS], dst.ethernet.w5500.cs, true); + parseGpio(gpio[S_IRQ], dst.ethernet.w5500.irq, false); + parseGpio(gpio[S_RST], dst.ethernet.w5500.rst, true); + #endif + + if (src[S_TYPE].is()) { + const auto value = static_cast(src[S_TYPE].as()); + if (value == NetworkMode::STA + #if USE_ETHERNET + || value == NetworkMode::ETH + #endif + ) { + result.accepted = true; + if (value != dst.type) { + dst.type = value; + result.changed = true; + } + } + } + + return result; +} + +// System settings + +JsonVariant toJson(const SystemSettings& src, JsonVariant dst) { + auto system = dst.to(); + system[S_LOG_LEVEL] = static_cast(src.logLevel); + + auto serial = system[S_SERIAL].to(); + serial[S_ENABLED] = src.serial.enabled; + serial[S_BAUDRATE] = src.serial.baudrate; + + auto webSerial = system[S_WEBSERIAL].to(); + webSerial[S_ENABLED] = src.webSerial.enabled; + + auto ntp = system[S_NTP].to(); + ntp[S_SERVER] = src.ntp.server; + ntp[S_TIMEZONE] = src.ntp.timezone; + + system[S_UNIT_SYSTEM] = static_cast(src.unitSystem); + system[S_STATUS_LED_GPIO] = src.statusLedGpio; + + return dst; +} + +SettingResult fromJson(JsonVariantConst src, SystemSettings& dst) { + SettingResult result; + + if (src[S_LOG_LEVEL].is()) { + const auto value = src[S_LOG_LEVEL].as(); + + if (value >= ESP_LOG_NONE && value <= ESP_LOG_VERBOSE) { + result.accepted = true; + if (value != dst.logLevel) { + dst.logLevel = static_cast(value); + result.changed = true; + } + } + } + + if (src[S_SERIAL][S_ENABLED].is()) { + const auto value = src[S_SERIAL][S_ENABLED].as(); + + result.accepted = true; + if (value != dst.serial.enabled) { + dst.serial.enabled = value; + result.changed = true; + } + } + + if (src[S_SERIAL][S_BAUDRATE].is()) { + const auto value = src[S_SERIAL][S_BAUDRATE].as(); + + if (value == 9600 || value == 19200 || value == 38400 || value == 57600 || value == 74880 || value == 115200) { + result.accepted = true; + if (value != dst.serial.baudrate) { + dst.serial.baudrate = value; + result.changed = true; + } + } + } + + if (src[S_WEBSERIAL][S_ENABLED].is()) { + const auto value = src[S_WEBSERIAL][S_ENABLED].as(); + + result.accepted = true; + if (value != dst.webSerial.enabled) { + dst.webSerial.enabled = value; + result.changed = true; + } + } + + if (src[S_NTP][S_SERVER].is()) { + const JsonString value = src[S_NTP][S_SERVER].as(); + + if (strlen(value.c_str()) == value.size()) { + if (value.size() < sizeof(dst.ntp.server)) { + result.accepted = true; + if (strcmp(value.c_str(), dst.ntp.server) != 0) { + strcpy(dst.ntp.server, value.c_str()); + result.changed = true; + } + } + } + } + + if (src[S_NTP][S_TIMEZONE].is()) { + const JsonString value = src[S_NTP][S_TIMEZONE].as(); + + if (strlen(value.c_str()) == value.size()) { + if (value.size() < sizeof(dst.ntp.timezone)) { + result.accepted = true; + if (strcmp(value.c_str(), dst.ntp.timezone) != 0) { + strcpy(dst.ntp.timezone, value.c_str()); + result.changed = true; + } + } + } + } + + if (src[S_UNIT_SYSTEM].is()) { + const auto value = src[S_UNIT_SYSTEM].as(); + + switch (value) { + case static_cast(UnitSystem::METRIC): + result.accepted = true; + if (dst.unitSystem != UnitSystem::METRIC) { + dst.unitSystem = UnitSystem::METRIC; + result.changed = true; + } + break; + + case static_cast(UnitSystem::IMPERIAL): + result.accepted = true; + if (dst.unitSystem != UnitSystem::IMPERIAL) { + dst.unitSystem = UnitSystem::IMPERIAL; + result.changed = true; + } + break; + + default: + break; + } + + } + + if (!src[S_STATUS_LED_GPIO].isNull()) { + if (src[S_STATUS_LED_GPIO].is() && src[S_STATUS_LED_GPIO].as().size() == 0) { + result.accepted = true; + if (dst.statusLedGpio != GPIO_IS_NOT_CONFIGURED) { + dst.statusLedGpio = GPIO_IS_NOT_CONFIGURED; + result.changed = true; + } + + } else if (src[S_STATUS_LED_GPIO].is()) { + const auto value = src[S_STATUS_LED_GPIO].as(); + + if (value == GPIO_IS_NOT_CONFIGURED || GPIO_IS_VALID_OUTPUT(value)) { + result.accepted = true; + if (value != dst.statusLedGpio) { + dst.statusLedGpio = value; + result.changed = true; + } + } + } + } + + return result; +} + +// Portal settings + +JsonVariant toJson(const PortalSettings& src, JsonVariant dst) { + auto portal = dst.to(); + portal[S_AUTH] = src.auth; + portal[S_LOGIN] = src.login; + portal[S_PASSWORD] = src.password; + portal[S_MDNS] = src.mdns; + + return dst; +} + +SettingResult fromJson(JsonVariantConst src, PortalSettings& dst) { + SettingResult result; + + if (src[S_AUTH].is()) { + const auto value = src[S_AUTH].as(); + + result.accepted = true; + if (value != dst.auth) { + dst.auth = value; + result.changed = true; + } + } + + if (src[S_LOGIN].is()) { + const JsonString value = src[S_LOGIN].as(); + + if (strlen(value.c_str()) == value.size()) { + if (value.size() && value.size() < sizeof(dst.login)) { + result.accepted = true; + if (strcmp(value.c_str(), dst.login) != 0) { + strcpy(dst.login, value.c_str()); + result.changed = true; + } + } + } + } + + if (src[S_PASSWORD].is()) { + const JsonString value = src[S_PASSWORD].as(); + + if (strlen(value.c_str()) == value.size()) { + if (value.size() && value.size() < sizeof(dst.password)) { + result.accepted = true; + if (strcmp(value.c_str(), dst.password) != 0) { + strcpy(dst.password, value.c_str()); + result.changed = true; + } + } + } + } + + if (dst.auth && (!strlen(dst.login) || !strlen(dst.password))) { + dst.auth = false; + result.changed = true; + } + + if (src[S_MDNS].is()) { + const auto value = src[S_MDNS].as(); + + result.accepted = true; + if (value != dst.mdns) { + dst.mdns = value; + result.changed = true; + } + } + + return result; +} + +// OpenTherm settings + +static SettingResult jsonToChannelDisablingAction(const JsonVariantConst src, ChannelDisablingAction& dst) { + if (!src.is()) { + return {}; + } + + const uint8_t value = src.as(); + switch (value) { + case static_cast(ChannelDisablingAction::OFF): + case static_cast(ChannelDisablingAction::ZERO_SETPOINT): + case static_cast(ChannelDisablingAction::OFF_AND_ZERO_SETPOINT): + if (static_cast(dst) != value) { + dst = static_cast(value); + return {.changed = true, .accepted = true}; + } + return {.accepted = true}; + + default: + break; + } + + return {}; +} + +JsonVariant toJson(const OpenThermSettings& src, JsonVariant dst) { + auto opentherm = dst.to(); + opentherm[S_IN_GPIO] = src.inGpio; + opentherm[S_OUT_GPIO] = src.outGpio; + opentherm[S_RX_LED_GPIO] = src.rxLedGpio; + opentherm[S_MEMBER_ID] = src.memberId; + opentherm[S_FLAGS] = src.flags; + opentherm[S_HEATING_DISABLING_ACTION] = static_cast(src.heatingDisablingAction); + opentherm[S_DHW_DISABLING_ACTION] = static_cast(src.dhwDisablingAction); + opentherm[S_CH2_DISABLING_ACTION] = static_cast(src.ch2DisablingAction); + opentherm[S_MIN_POWER] = roundf(src.minPower, 2); + opentherm[S_MAX_POWER] = roundf(src.maxPower, 2); + + auto otOptions = opentherm[S_OPTIONS].to(); + otOptions[S_DHW_SUPPORT] = src.options.dhwSupport; + otOptions[S_COOLING_SUPPORT] = src.options.coolingSupport; + otOptions[S_SUMMER_WINTER_MODE] = src.options.summerWinterMode; + otOptions[S_HEATING_STATE_TO_SUMMER_WINTER_MODE] = src.options.heatingStateToSummerWinterMode; + otOptions[S_CH2_ALWAYS_ENABLED] = src.options.ch2AlwaysEnabled; + otOptions[S_HEATING_TO_CH2] = src.options.heatingToCh2; + otOptions[S_DHW_TO_CH2] = src.options.dhwToCh2; + otOptions[S_DHW_BLOCKING] = src.options.dhwBlocking; + otOptions[S_DHW_STATE_AS_DHW_BLOCKING] = src.options.dhwStateAsDhwBlocking; + otOptions[S_MAX_TEMP_SYNC_WITH_TARGET_TEMP] = src.options.maxTempSyncWithTargetTemp; + otOptions[S_GET_MIN_MAX_TEMP] = src.options.getMinMaxTemp; + otOptions[S_IGNORE_DIAG_STATE] = src.options.ignoreDiagState; + otOptions[S_AUTO_FAULT_RESET] = src.options.autoFaultReset; + otOptions[S_AUTO_DIAG_RESET] = src.options.autoDiagReset; + otOptions[S_SET_DATE_AND_TIME] = src.options.setDateAndTime; + otOptions[S_ALWAYS_SEND_INDOOR_TEMP] = src.options.alwaysSendIndoorTemp; + otOptions[S_NATIVE_OTC] = src.options.nativeOTC; + otOptions[S_IMMERGAS_FIX] = src.options.immergasFix; + + return dst; +} + +SettingResult fromJson(JsonVariantConst src, OpenThermSettings& dst) { + SettingResult result; + + if (!src[S_IN_GPIO].isNull()) { + if (src[S_IN_GPIO].is() && src[S_IN_GPIO].as().size() == 0) { + result.accepted = true; + if (dst.inGpio != GPIO_IS_NOT_CONFIGURED) { + dst.inGpio = GPIO_IS_NOT_CONFIGURED; + result.changed = true; + } + + } else if (src[S_IN_GPIO].is()) { + const auto value = src[S_IN_GPIO].as(); + + if (value == GPIO_IS_NOT_CONFIGURED || GPIO_IS_VALID_INPUT(value)) { + result.accepted = true; + if (value != dst.inGpio) { + dst.inGpio = value; + result.changed = true; + } + } + } + } + + if (!src[S_OUT_GPIO].isNull()) { + if (src[S_OUT_GPIO].is() && src[S_OUT_GPIO].as().size() == 0) { + result.accepted = true; + if (dst.outGpio != GPIO_IS_NOT_CONFIGURED) { + dst.outGpio = GPIO_IS_NOT_CONFIGURED; + result.changed = true; + } + + } else if (src[S_OUT_GPIO].is()) { + const auto value = src[S_OUT_GPIO].as(); + + if (value == GPIO_IS_NOT_CONFIGURED || GPIO_IS_VALID_OUTPUT(value)) { + result.accepted = true; + if (value != dst.outGpio) { + dst.outGpio = value; + result.changed = true; + } + } + } + } + + if (!src[S_RX_LED_GPIO].isNull()) { + if (src[S_RX_LED_GPIO].is() && src[S_RX_LED_GPIO].as().size() == 0) { + result.accepted = true; + if (dst.rxLedGpio != GPIO_IS_NOT_CONFIGURED) { + dst.rxLedGpio = GPIO_IS_NOT_CONFIGURED; + result.changed = true; + } + + } else if (src[S_RX_LED_GPIO].is()) { + const auto value = src[S_RX_LED_GPIO].as(); + + if (value == GPIO_IS_NOT_CONFIGURED || GPIO_IS_VALID_OUTPUT(value)) { + result.accepted = true; + if (value != dst.rxLedGpio) { + dst.rxLedGpio = value; + result.changed = true; + } + } + } + } + + if (src[S_MEMBER_ID].is()) { + const auto value = src[S_MEMBER_ID].as(); + + result.accepted = true; + if (value != dst.memberId) { + dst.memberId = value; + result.changed = true; + } + } + + if (src[S_FLAGS].is()) { + const auto value = src[S_FLAGS].as(); + + result.accepted = true; + if (value != dst.flags) { + dst.flags = value; + result.changed = true; + } + } + + const auto heatingDisablingActionResult = jsonToChannelDisablingAction(src[S_HEATING_DISABLING_ACTION], dst.heatingDisablingAction); + result.changed = heatingDisablingActionResult.changed || result.changed; + result.accepted = heatingDisablingActionResult.accepted || result.accepted; + + const auto dhwDisablingActionResult = jsonToChannelDisablingAction(src[S_DHW_DISABLING_ACTION], dst.dhwDisablingAction); + result.changed = dhwDisablingActionResult.changed || result.changed; + result.accepted = dhwDisablingActionResult.accepted || result.accepted; + + const auto ch2DisablingActionResult = jsonToChannelDisablingAction(src[S_CH2_DISABLING_ACTION], dst.ch2DisablingAction); + result.changed = ch2DisablingActionResult.changed || result.changed; + result.accepted = ch2DisablingActionResult.accepted || result.accepted; + + if (src[S_MIN_POWER].is()) { + const auto value = roundf(src[S_MIN_POWER].as(), 2); + + if (value >= 0 && value <= 1000) { + result.accepted = true; + if (isFloatDifferent(value, dst.minPower, 0.0001f)) { + dst.minPower = value; + result.changed = true; + } + } + } + + if (src[S_MAX_POWER].is()) { + const auto value = roundf(src[S_MAX_POWER].as(), 2); + + if (value >= 0 && value <= 1000) { + result.accepted = true; + if (isFloatDifferent(value, dst.maxPower, 0.0001f)) { + dst.maxPower = value; + result.changed = true; + } + } + } + + if (src[S_OPTIONS][S_DHW_SUPPORT].is()) { + const auto value = src[S_OPTIONS][S_DHW_SUPPORT].as(); + + result.accepted = true; + if (value != dst.options.dhwSupport) { + dst.options.dhwSupport = value; + result.changed = true; + } + } + + if (src[S_OPTIONS][S_COOLING_SUPPORT].is()) { + const auto value = src[S_OPTIONS][S_COOLING_SUPPORT].as(); + + result.accepted = true; + if (value != dst.options.coolingSupport) { + dst.options.coolingSupport = value; + result.changed = true; + } + } + + if (src[S_OPTIONS][S_SUMMER_WINTER_MODE].is()) { + const auto value = src[S_OPTIONS][S_SUMMER_WINTER_MODE].as(); + + result.accepted = true; + if (value != dst.options.summerWinterMode) { + dst.options.summerWinterMode = value; + result.changed = true; + } + } + + if (src[S_OPTIONS][S_HEATING_STATE_TO_SUMMER_WINTER_MODE].is()) { + const auto value = src[S_OPTIONS][S_HEATING_STATE_TO_SUMMER_WINTER_MODE].as(); + + result.accepted = true; + if (value != dst.options.heatingStateToSummerWinterMode) { + dst.options.heatingStateToSummerWinterMode = value; + result.changed = true; + } + } + + if (src[S_OPTIONS][S_CH2_ALWAYS_ENABLED].is()) { + const auto value = src[S_OPTIONS][S_CH2_ALWAYS_ENABLED].as(); + + result.accepted = true; + if (value != dst.options.ch2AlwaysEnabled) { + dst.options.ch2AlwaysEnabled = value; + + if (dst.options.ch2AlwaysEnabled) { + dst.options.heatingToCh2 = false; + dst.options.dhwToCh2 = false; + } + + result.changed = true; + } + } + + if (src[S_OPTIONS][S_HEATING_TO_CH2].is()) { + const auto value = src[S_OPTIONS][S_HEATING_TO_CH2].as(); + + result.accepted = true; + if (value != dst.options.heatingToCh2) { + dst.options.heatingToCh2 = value; + + if (dst.options.heatingToCh2) { + dst.options.ch2AlwaysEnabled = false; + dst.options.dhwToCh2 = false; + } + + result.changed = true; + } + } + + if (src[S_OPTIONS][S_DHW_TO_CH2].is()) { + const auto value = src[S_OPTIONS][S_DHW_TO_CH2].as(); + + result.accepted = true; + if (value != dst.options.dhwToCh2) { + dst.options.dhwToCh2 = value; + + if (dst.options.dhwToCh2) { + dst.options.ch2AlwaysEnabled = false; + dst.options.heatingToCh2 = false; + } + + result.changed = true; + } + } + + if (src[S_OPTIONS][S_DHW_BLOCKING].is()) { + const auto value = src[S_OPTIONS][S_DHW_BLOCKING].as(); + + result.accepted = true; + if (value != dst.options.dhwBlocking) { + dst.options.dhwBlocking = value; + result.changed = true; + } + } + + if (src[S_OPTIONS][S_DHW_STATE_AS_DHW_BLOCKING].is()) { + const auto value = src[S_OPTIONS][S_DHW_STATE_AS_DHW_BLOCKING].as(); + + result.accepted = true; + if (value != dst.options.dhwStateAsDhwBlocking) { + dst.options.dhwStateAsDhwBlocking = value; + result.changed = true; + } + } + + if (src[S_OPTIONS][S_MAX_TEMP_SYNC_WITH_TARGET_TEMP].is()) { + const auto value = src[S_OPTIONS][S_MAX_TEMP_SYNC_WITH_TARGET_TEMP].as(); + + result.accepted = true; + if (value != dst.options.maxTempSyncWithTargetTemp) { + dst.options.maxTempSyncWithTargetTemp = value; + result.changed = true; + } + } + + if (src[S_OPTIONS][S_GET_MIN_MAX_TEMP].is()) { + const auto value = src[S_OPTIONS][S_GET_MIN_MAX_TEMP].as(); + + result.accepted = true; + if (value != dst.options.getMinMaxTemp) { + dst.options.getMinMaxTemp = value; + result.changed = true; + } + } + + if (src[S_OPTIONS][S_IGNORE_DIAG_STATE].is()) { + const auto value = src[S_OPTIONS][S_IGNORE_DIAG_STATE].as(); + + result.accepted = true; + if (value != dst.options.ignoreDiagState) { + dst.options.ignoreDiagState = value; + result.changed = true; + } + } + + if (src[S_OPTIONS][S_AUTO_FAULT_RESET].is()) { + const auto value = src[S_OPTIONS][S_AUTO_FAULT_RESET].as(); + + result.accepted = true; + if (value != dst.options.autoFaultReset) { + dst.options.autoFaultReset = value; + result.changed = true; + } + } + + if (src[S_OPTIONS][S_AUTO_DIAG_RESET].is()) { + const auto value = src[S_OPTIONS][S_AUTO_DIAG_RESET].as(); + + result.accepted = true; + if (value != dst.options.autoDiagReset) { + dst.options.autoDiagReset = value; + result.changed = true; + } + } + + if (src[S_OPTIONS][S_SET_DATE_AND_TIME].is()) { + const auto value = src[S_OPTIONS][S_SET_DATE_AND_TIME].as(); + + result.accepted = true; + if (value != dst.options.setDateAndTime) { + dst.options.setDateAndTime = value; + result.changed = true; + } + } + + if (src[S_OPTIONS][S_ALWAYS_SEND_INDOOR_TEMP].is()) { + const auto value = src[S_OPTIONS][S_ALWAYS_SEND_INDOOR_TEMP].as(); + + result.accepted = true; + if (value != dst.options.alwaysSendIndoorTemp) { + dst.options.alwaysSendIndoorTemp = value; + result.changed = true; + } + } + + if (src[S_OPTIONS][S_NATIVE_OTC].is()) { + const auto value = src[S_OPTIONS][S_NATIVE_OTC].as(); + + result.accepted = true; + if (value != dst.options.nativeOTC) { + dst.options.nativeOTC = value; + + result.changed = true; + } + } + + if (src[S_OPTIONS][S_IMMERGAS_FIX].is()) { + const auto value = src[S_OPTIONS][S_IMMERGAS_FIX].as(); + + result.accepted = true; + if (value != dst.options.immergasFix) { + dst.options.immergasFix = value; + result.changed = true; + } + } + + return result; +} + +// MQTT settings + +JsonVariant toJson(const MqttSettings& src, JsonVariant dst) { + auto mqtt = dst.to(); + mqtt[S_ENABLED] = src.enabled; + mqtt[S_SERVER] = src.server; + mqtt[S_PORT] = src.port; + mqtt[S_USER] = src.user; + mqtt[S_PASSWORD] = src.password; + mqtt[S_PREFIX] = src.prefix; + mqtt[S_INTERVAL] = src.interval; + mqtt[S_HOME_ASSISTANT_DISCOVERY] = src.homeAssistantDiscovery; + mqtt[S_HOME_ASSISTANT_DISCOVERY_PREFIX] = src.homeAssistantDiscoveryPrefix; + + return dst; +} + +SettingResult fromJson(JsonVariantConst src, MqttSettings& dst) { + SettingResult result; + + if (src[S_ENABLED].is()) { + const auto value = src[S_ENABLED].as(); + + result.accepted = true; + if (value != dst.enabled) { + dst.enabled = value; + result.changed = true; + } + } + + if (src[S_SERVER].is()) { + const JsonString value = src[S_SERVER].as(); + + if (strlen(value.c_str()) == value.size()) { + if (value.size() && value.size() < sizeof(dst.server)) { + result.accepted = true; + if (strcmp(value.c_str(), dst.server) != 0) { + strcpy(dst.server, value.c_str()); + result.changed = true; + } + } + } + } + + if (src[S_PORT].is()) { + const auto value = src[S_PORT].as(); + + if (value > 0 && value <= 65535) { + result.accepted = true; + if (value != dst.port) { + dst.port = value; + result.changed = true; + } + } + } + + if (src[S_USER].is()) { + const JsonString value = src[S_USER].as(); + + if (strlen(value.c_str()) == value.size()) { + if (value.size() < sizeof(dst.user)) { + result.accepted = true; + if (strcmp(value.c_str(), dst.user) != 0) { + strcpy(dst.user, value.c_str()); + result.changed = true; + } + } + } + } + + if (src[S_PASSWORD].is()) { + const JsonString value = src[S_PASSWORD].as(); + + if (strlen(value.c_str()) == value.size()) { + if (value.size() < sizeof(dst.password)) { + result.accepted = true; + if (strcmp(value.c_str(), dst.password) != 0) { + strcpy(dst.password, value.c_str()); + result.changed = true; + } + } + } + } + + if (src[S_PREFIX].is()) { + const JsonString value = src[S_PREFIX].as(); + + if (strlen(value.c_str()) == value.size()) { + if (value.size() && value.size() < sizeof(dst.prefix) && strpbrk(value.c_str(), "+#") == nullptr) { + result.accepted = true; + if (strcmp(value.c_str(), dst.prefix) != 0) { + strcpy(dst.prefix, value.c_str()); + result.changed = true; + } + } + } + } + + if (src[S_INTERVAL].is()) { + const auto value = src[S_INTERVAL].as(); + + if (value >= 15 && value <= 3600) { + result.accepted = true; + if (value != dst.interval) { + dst.interval = value; + result.changed = true; + } + } + } + + if (src[S_HOME_ASSISTANT_DISCOVERY].is()) { + const auto value = src[S_HOME_ASSISTANT_DISCOVERY].as(); + + result.accepted = true; + if (value != dst.homeAssistantDiscovery) { + dst.homeAssistantDiscovery = value; + result.changed = true; + } + } + + if (src[S_HOME_ASSISTANT_DISCOVERY_PREFIX].is()) { + const JsonString value = src[S_HOME_ASSISTANT_DISCOVERY_PREFIX].as(); + + if (strlen(value.c_str()) == value.size()) { + if (value.size() && value.size() < sizeof(dst.homeAssistantDiscoveryPrefix) && strpbrk(value.c_str(), "+#") == nullptr) { + result.accepted = true; + if (strcmp(value.c_str(), dst.homeAssistantDiscoveryPrefix) != 0) { + strcpy(dst.homeAssistantDiscoveryPrefix, value.c_str()); + result.changed = true; + } + } + } + } + + return result; +} + +// Emergency settings + +static SettingResult setEmergencyTarget(EmergencySettings& dst, float value) { + bool changed = false; + + bool noRegulators = !settings.opentherm.options.nativeOTC; + float minTemp = noRegulators + ? settings.heating.minTemp + : THERMOSTAT_INDOOR_MIN_TEMP; + float maxTemp = noRegulators + ? settings.heating.maxTemp + : THERMOSTAT_INDOOR_MAX_TEMP; + + bool valid = std::isfinite(value); + if (valid) { + value = roundf(value, 2); + valid = isValidTemp( + value, + UnitSystem::METRIC, + minTemp, + maxTemp, + UnitSystem::METRIC + ); + } + + if (!valid) { + value = noRegulators ? DEFAULT_HEATING_TARGET_TEMP : THERMOSTAT_INDOOR_DEFAULT_TEMP; + } + + value = constrain(value, minTemp, maxTemp); + if (isFloatDifferent(dst.target, value, 0.0001f)) { + dst.target = value; + changed = true; + } + + return {.changed = changed, .accepted = valid}; +} + +static SettingResult applySetting(EmergencySettings& dst, std::string_view path, float input) { + if (path == S_TARGET) { + return setEmergencyTarget(dst, input); + } + + return {}; +} + +JsonVariant toJson(const EmergencySettings& src, JsonVariant dst) { + auto emergency = dst.to(); + emergency[S_TARGET] = roundf(convertTemp(src.target, UnitSystem::METRIC, settings.system.unitSystem), 2); + emergency[S_THRESHOLD_TIME] = src.thresholdTime; + + return dst; +} + +SettingResult fromJson(JsonVariantConst src, EmergencySettings& dst) { + SettingResult result; + + if (src[S_THRESHOLD_TIME].is()) { + const auto value = src[S_THRESHOLD_TIME].as(); + + if (value >= 60 && value <= 1800) { + result.accepted = true; + if (value != dst.thresholdTime) { + dst.thresholdTime = value; + result.changed = true; + } + } + } + + float value = src[S_TARGET].is() + ? convertTemp(src[S_TARGET].as(), settings.system.unitSystem, UnitSystem::METRIC) + : dst.target; + const auto fieldResult = applySetting(dst, S_TARGET, value); + result.changed = fieldResult.changed || result.changed; + if (src[S_TARGET].is()) { + result.accepted = fieldResult.accepted || result.accepted; + } + + return result; +} + +// Heating settings + +static bool normalizeHeatingBounds(HeatingSettings& dst) { + bool changed = false; + + if (dst.maxTemp < dst.minTemp) { + dst.maxTemp = dst.minTemp; + changed = true; + } + + return changed; +} + +static bool normalizeHeatingOverheatBounds(HeatingSettings& dst) { + bool changed = false; + + if (dst.overheatProtection.highTemp < dst.overheatProtection.lowTemp) { + dst.overheatProtection.highTemp = dst.overheatProtection.lowTemp; + changed = true; + } + + return changed; +} + +static bool normalizeHeatingFreezeBounds(HeatingSettings& dst) { + bool changed = false; + + if (dst.freezeProtection.highTemp <= dst.freezeProtection.lowTemp) { + dst.freezeProtection.highTemp = dst.freezeProtection.lowTemp + 1; + changed = true; + } + + return changed; +} + +static SettingResult setHeatingTarget(HeatingSettings& dst, float value) { + bool changed = false; + + bool smartControl = settings.equitherm.enabled || settings.pid.enabled || settings.opentherm.options.nativeOTC; + float minTemp = smartControl + ? THERMOSTAT_INDOOR_MIN_TEMP + : dst.minTemp; + float maxTemp = smartControl + ? THERMOSTAT_INDOOR_MAX_TEMP + : dst.maxTemp; + + bool valid = std::isfinite(value); + if (valid) { + value = roundf(value, 2); + valid = isValidTemp( + value, + UnitSystem::METRIC, + minTemp, + maxTemp, + UnitSystem::METRIC + ); + } + + if (!valid) { + value = smartControl ? THERMOSTAT_INDOOR_DEFAULT_TEMP : DEFAULT_HEATING_TARGET_TEMP; + } + + value = constrain(value, minTemp, maxTemp); + if (isFloatDifferent(dst.target, value, 0.0001f)) { + dst.target = value; + changed = true; + } + + return {.changed = changed, .accepted = valid}; +} + +static SettingResult applySetting(HeatingSettings& dst, std::string_view path, bool value) { + bool changed = false; + + if (path == S_ENABLED) { + if (value != dst.enabled) { + dst.enabled = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_TURBO) { + if (value && (settings.opentherm.options.nativeOTC || (!settings.equitherm.enabled && !settings.pid.enabled))) { + return {}; + } + + if (value != dst.turbo) { + dst.turbo = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == "hysteresis/enabled") { + if (value != dst.hysteresis.enabled) { + dst.hysteresis.enabled = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + return {}; +} + +static SettingResult applySetting(HeatingSettings& dst, std::string_view path, float input) { + bool changed = false; + + if (path == "hysteresis/value") { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + value = roundf(value, 2); + if (value < 0.05f || value > 15.0f) { + return {}; + } + + if (isFloatDifferent(value, dst.hysteresis.value, 0.0001f)) { + dst.hysteresis.value = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_TURBO_FACTOR) { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + value = roundf(value, 3); + if (value < 1.5f || value > 10.0f) { + return {}; + } + + if (isFloatDifferent(value, dst.turboFactor, 0.0001f)) { + dst.turboFactor = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_MIN_TEMP) { + input = std::round(input); + + if (!isSettingInteger(input, 0, 255)) { + return {}; + } + + unsigned char value = static_cast(input); + + if (value < vars.slave.heating.minTemp || value >= vars.slave.heating.maxTemp || value == dst.maxTemp) { + return {}; + } + + if (value != dst.minTemp) { + dst.minTemp = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_MAX_TEMP) { + input = std::round(input); + + if (!isSettingInteger(input, 0, 255)) { + return {}; + } + + unsigned char value = static_cast(input); + + if (value <= vars.slave.heating.minTemp || value > vars.slave.heating.maxTemp || value == dst.minTemp) { + return {}; + } + + if (value != dst.maxTemp) { + dst.maxTemp = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_MAX_MODULATION) { + if (!isSettingInteger(input, 0, 255)) { + return {}; + } + + unsigned char value = static_cast(input); + + if (value <= 0 || value > 100) { + return {}; + } + + if (value != dst.maxModulation) { + dst.maxModulation = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_INDOOR_TEMP_AVG_TYPE) { + if (!isSettingInteger(input, 0, 255)) { + return {}; + } + + uint8_t value = static_cast(input); + + switch (value) { + case static_cast(Sensors::AverageType::MEAN): + case static_cast(Sensors::AverageType::MINIMUM): + case static_cast(Sensors::AverageType::MAXIMUM): + if (static_cast(dst.indoorTempAvgType) != value) { + dst.indoorTempAvgType = static_cast(value); + changed = true; + } + break; + + default: + return {}; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_OUTDOOR_TEMP_AVG_TYPE) { + if (!isSettingInteger(input, 0, 255)) { + return {}; + } + + uint8_t value = static_cast(input); + + switch (value) { + case static_cast(Sensors::AverageType::MEAN): + case static_cast(Sensors::AverageType::MINIMUM): + case static_cast(Sensors::AverageType::MAXIMUM): + if (static_cast(dst.outdoorTempAvgType) != value) { + dst.outdoorTempAvgType = static_cast(value); + changed = true; + } + break; + + default: + return {}; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == "overheat_protection/high_temp") { + input = std::round(input); + + if (!isSettingInteger(input, 0, 255)) { + return {}; + } + + unsigned char value = static_cast(input); + + if (value != 0 && !isValidTemp(value, UnitSystem::METRIC, 0.0f, 100.0f)) { + return {}; + } + + if (value != dst.overheatProtection.highTemp) { + dst.overheatProtection.highTemp = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == "overheat_protection/low_temp") { + input = std::round(input); + + if (!isSettingInteger(input, 0, 255)) { + return {}; + } + + unsigned char value = static_cast(input); + + if (value != 0 && !isValidTemp(value, UnitSystem::METRIC, 0.0f, 99.0f)) { + return {}; + } + + if (value != dst.overheatProtection.lowTemp) { + dst.overheatProtection.lowTemp = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == "freeze_protection/high_temp") { + input = std::round(input); + + if (!isSettingInteger(input, 0, 65535)) { + return {}; + } + + unsigned short value = static_cast(input); + + if (!isValidTemp(value, UnitSystem::METRIC, 1, 50)) { + return {}; + } + + if (value != dst.freezeProtection.highTemp) { + dst.freezeProtection.highTemp = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == "freeze_protection/low_temp") { + input = std::round(input); + + if (!isSettingInteger(input, 0, 65535)) { + return {}; + } + + unsigned short value = static_cast(input); + + if (!isValidTemp(value, UnitSystem::METRIC, 1, 30)) { + return {}; + } + + if (value != dst.freezeProtection.lowTemp) { + dst.freezeProtection.lowTemp = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_TARGET) { + return setHeatingTarget(dst, input); + } + + return {}; +} + +JsonVariant toJson(const HeatingSettings& src, JsonVariant dst) { + auto heating = dst.to(); + heating[S_ENABLED] = src.enabled; + heating[S_TURBO] = src.turbo; + heating[S_TARGET] = roundf(convertTemp(src.target, UnitSystem::METRIC, settings.system.unitSystem), 2); + heating[S_HYSTERESIS][S_ENABLED] = src.hysteresis.enabled; + heating[S_HYSTERESIS][S_VALUE] = roundf(src.hysteresis.value, 3); + heating[S_TURBO_FACTOR] = roundf(src.turboFactor, 3); + heating[S_MIN_TEMP] = convertTemp(src.minTemp, UnitSystem::METRIC, settings.system.unitSystem); + heating[S_MAX_TEMP] = convertTemp(src.maxTemp, UnitSystem::METRIC, settings.system.unitSystem); + heating[S_MAX_MODULATION] = src.maxModulation; + heating[S_INDOOR_TEMP_AVG_TYPE] = static_cast(src.indoorTempAvgType); + heating[S_OUTDOOR_TEMP_AVG_TYPE] = static_cast(src.outdoorTempAvgType); + + auto heatingOverheatProtection = heating[S_OVERHEAT_PROTECTION].to(); + heatingOverheatProtection[S_HIGH_TEMP] = src.overheatProtection.highTemp == 0 + ? 0 + : convertTemp(src.overheatProtection.highTemp, UnitSystem::METRIC, settings.system.unitSystem); + heatingOverheatProtection[S_LOW_TEMP] = src.overheatProtection.lowTemp == 0 + ? 0 + : convertTemp(src.overheatProtection.lowTemp, UnitSystem::METRIC, settings.system.unitSystem); + + auto freezeProtection = heating[S_FREEZE_PROTECTION].to(); + freezeProtection[S_HIGH_TEMP] = convertTemp(src.freezeProtection.highTemp, UnitSystem::METRIC, settings.system.unitSystem); + freezeProtection[S_LOW_TEMP] = convertTemp(src.freezeProtection.lowTemp, UnitSystem::METRIC, settings.system.unitSystem); + + return dst; +} + +SettingResult fromJson(JsonVariantConst src, HeatingSettings& dst) { + SettingResult result; + + if (src[S_ENABLED].is()) { + const auto value = src[S_ENABLED].as(); + const auto fieldResult = applySetting(dst, S_ENABLED, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_TURBO].is()) { + const auto value = src[S_TURBO].as(); + const auto fieldResult = applySetting(dst, S_TURBO, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_HYSTERESIS][S_ENABLED].is()) { + const auto value = src[S_HYSTERESIS][S_ENABLED].as(); + const auto fieldResult = applySetting(dst, "hysteresis/enabled", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_HYSTERESIS][S_VALUE].is()) { + const auto value = src[S_HYSTERESIS][S_VALUE].as(); + const auto fieldResult = applySetting(dst, "hysteresis/value", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_TURBO_FACTOR].is()) { + const auto value = src[S_TURBO_FACTOR].as(); + const auto fieldResult = applySetting(dst, S_TURBO_FACTOR, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_MIN_TEMP].is()) { + float value = convertTemp(src[S_MIN_TEMP].as(), settings.system.unitSystem, UnitSystem::METRIC); + const auto fieldResult = applySetting(dst, S_MIN_TEMP, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_MAX_TEMP].is()) { + float value = convertTemp(src[S_MAX_TEMP].as(), settings.system.unitSystem, UnitSystem::METRIC); + const auto fieldResult = applySetting(dst, S_MAX_TEMP, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + result.changed = normalizeHeatingBounds(dst) || result.changed; + + + if (src[S_MAX_MODULATION].is()) { + const auto value = src[S_MAX_MODULATION].as(); + const auto fieldResult = applySetting(dst, S_MAX_MODULATION, static_cast(value)); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_INDOOR_TEMP_AVG_TYPE].is()) { + const auto value = src[S_INDOOR_TEMP_AVG_TYPE].as(); + const auto fieldResult = applySetting(dst, S_INDOOR_TEMP_AVG_TYPE, static_cast(value)); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_OUTDOOR_TEMP_AVG_TYPE].is()) { + const auto value = src[S_OUTDOOR_TEMP_AVG_TYPE].as(); + const auto fieldResult = applySetting(dst, S_OUTDOOR_TEMP_AVG_TYPE, static_cast(value)); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_OVERHEAT_PROTECTION][S_HIGH_TEMP].is()) { + float value = src[S_OVERHEAT_PROTECTION][S_HIGH_TEMP].as(); + if (value != 0) { + value = convertTemp(value, settings.system.unitSystem, UnitSystem::METRIC); + } + + const auto fieldResult = applySetting(dst, "overheat_protection/high_temp", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_OVERHEAT_PROTECTION][S_LOW_TEMP].is()) { + float value = src[S_OVERHEAT_PROTECTION][S_LOW_TEMP].as(); + if (value != 0) { + value = convertTemp(value, settings.system.unitSystem, UnitSystem::METRIC); + } + + const auto fieldResult = applySetting(dst, "overheat_protection/low_temp", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + result.changed = normalizeHeatingOverheatBounds(dst) || result.changed; + + if (src[S_FREEZE_PROTECTION][S_HIGH_TEMP].is()) { + float value = convertTemp(src[S_FREEZE_PROTECTION][S_HIGH_TEMP].as(), settings.system.unitSystem, UnitSystem::METRIC); + const auto fieldResult = applySetting(dst, "freeze_protection/high_temp", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_FREEZE_PROTECTION][S_LOW_TEMP].is()) { + float value = convertTemp(src[S_FREEZE_PROTECTION][S_LOW_TEMP].as(), settings.system.unitSystem, UnitSystem::METRIC); + const auto fieldResult = applySetting(dst, "freeze_protection/low_temp", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + result.changed = normalizeHeatingFreezeBounds(dst) || result.changed; + + float value = src[S_TARGET].is() + ? convertTemp(src[S_TARGET].as(), settings.system.unitSystem, UnitSystem::METRIC) + : dst.target; + const auto fieldResult = applySetting(dst, S_TARGET, value); + result.changed = fieldResult.changed || result.changed; + if (src[S_TARGET].is()) { + result.accepted = fieldResult.accepted || result.accepted; + } + + return result; +} + +// DHW settings + +static bool normalizeDhwBounds(DhwSettings& dst) { + bool changed = false; + + if (dst.maxTemp < dst.minTemp) { + dst.maxTemp = dst.minTemp; + changed = true; + } + + return changed; +} + +static bool normalizeDhwOverheatBounds(DhwSettings& dst) { + bool changed = false; + + if (dst.overheatProtection.highTemp < dst.overheatProtection.lowTemp) { + dst.overheatProtection.highTemp = dst.overheatProtection.lowTemp; + changed = true; + } + + return changed; +} + +static SettingResult setDhwTarget(DhwSettings& dst, float value) { + bool changed = false; + + bool valid = std::isfinite(value) && isValidTemp( + value, + UnitSystem::METRIC, + dst.minTemp, + dst.maxTemp, + UnitSystem::METRIC + ); + + if (!valid) { + value = DEFAULT_DHW_TARGET_TEMP; + } + + value = constrain(value, dst.minTemp, dst.maxTemp); + if (isFloatDifferent(dst.target, value, 0.0001f)) { + dst.target = value; + changed = true; + } + + return {.changed = changed, .accepted = valid}; +} + +static SettingResult applySetting(DhwSettings& dst, std::string_view path, bool value) { + bool changed = false; + + if (path == S_ENABLED) { + if (value != dst.enabled) { + dst.enabled = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + return {}; +} + +static SettingResult applySetting(DhwSettings& dst, std::string_view path, float input) { + bool changed = false; + + if (path == S_MIN_TEMP) { + input = std::round(input); + + if (!isSettingInteger(input, 0, 255)) { + return {}; + } + + unsigned char value = static_cast(input); + + if (value < vars.slave.dhw.minTemp || value >= vars.slave.dhw.maxTemp) { + return {}; + } + + if (value != dst.minTemp) { + dst.minTemp = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_MAX_TEMP) { + input = std::round(input); + + if (!isSettingInteger(input, 0, 255)) { + return {}; + } + + unsigned char value = static_cast(input); + + if (value <= vars.slave.dhw.minTemp || value > vars.slave.dhw.maxTemp) { + return {}; + } + + if (value != dst.maxTemp) { + dst.maxTemp = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_MAX_MODULATION) { + if (!isSettingInteger(input, 0, 255)) { + return {}; + } + + unsigned char value = static_cast(input); + + if (value <= 0 || value > 100) { + return {}; + } + + if (value != dst.maxModulation) { + dst.maxModulation = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == "overheat_protection/high_temp") { + input = std::round(input); + + if (!isSettingInteger(input, 0, 255)) { + return {}; + } + + unsigned char value = static_cast(input); + + if (value != 0 && !isValidTemp(value, UnitSystem::METRIC, 0.0f, 100.0f)) { + return {}; + } + + if (value != dst.overheatProtection.highTemp) { + dst.overheatProtection.highTemp = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == "overheat_protection/low_temp") { + input = std::round(input); + + if (!isSettingInteger(input, 0, 255)) { + return {}; + } + + unsigned char value = static_cast(input); + + if (value != 0 && !isValidTemp(value, UnitSystem::METRIC, 0.0f, 99.0f)) { + return {}; + } + + if (value != dst.overheatProtection.lowTemp) { + dst.overheatProtection.lowTemp = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_TARGET) { + return setDhwTarget(dst, input); + } + + return {}; +} + +JsonVariant toJson(const DhwSettings& src, JsonVariant dst) { + auto dhw = dst.to(); + dhw[S_ENABLED] = src.enabled; + dhw[S_TARGET] = roundf(convertTemp(src.target, UnitSystem::METRIC, settings.system.unitSystem), 1); + dhw[S_MIN_TEMP] = convertTemp(src.minTemp, UnitSystem::METRIC, settings.system.unitSystem); + dhw[S_MAX_TEMP] = convertTemp(src.maxTemp, UnitSystem::METRIC, settings.system.unitSystem); + dhw[S_MAX_MODULATION] = src.maxModulation; + + auto dhwOverheatProtection = dhw[S_OVERHEAT_PROTECTION].to(); + dhwOverheatProtection[S_HIGH_TEMP] = src.overheatProtection.highTemp == 0 + ? 0 + : convertTemp(src.overheatProtection.highTemp, UnitSystem::METRIC, settings.system.unitSystem); + dhwOverheatProtection[S_LOW_TEMP] = src.overheatProtection.lowTemp == 0 + ? 0 + : convertTemp(src.overheatProtection.lowTemp, UnitSystem::METRIC, settings.system.unitSystem); + + return dst; +} + +SettingResult fromJson(JsonVariantConst src, DhwSettings& dst) { + SettingResult result; + + if (src[S_ENABLED].is()) { + const auto value = src[S_ENABLED].as(); + const auto fieldResult = applySetting(dst, S_ENABLED, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_MIN_TEMP].is()) { + float value = convertTemp(src[S_MIN_TEMP].as(), settings.system.unitSystem, UnitSystem::METRIC); + const auto fieldResult = applySetting(dst, S_MIN_TEMP, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_MAX_TEMP].is()) { + float value = convertTemp(src[S_MAX_TEMP].as(), settings.system.unitSystem, UnitSystem::METRIC); + const auto fieldResult = applySetting(dst, S_MAX_TEMP, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + result.changed = normalizeDhwBounds(dst) || result.changed; + + if (src[S_MAX_MODULATION].is()) { + const auto value = src[S_MAX_MODULATION].as(); + const auto fieldResult = applySetting(dst, S_MAX_MODULATION, static_cast(value)); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_OVERHEAT_PROTECTION][S_HIGH_TEMP].is()) { + float value = src[S_OVERHEAT_PROTECTION][S_HIGH_TEMP].as(); + if (value != 0) { + value = convertTemp(value, settings.system.unitSystem, UnitSystem::METRIC); + } + + const auto fieldResult = applySetting(dst, "overheat_protection/high_temp", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_OVERHEAT_PROTECTION][S_LOW_TEMP].is()) { + float value = src[S_OVERHEAT_PROTECTION][S_LOW_TEMP].as(); + if (value != 0) { + value = convertTemp(value, settings.system.unitSystem, UnitSystem::METRIC); + } + + const auto fieldResult = applySetting(dst, "overheat_protection/low_temp", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + result.changed = normalizeDhwOverheatBounds(dst) || result.changed; + + float value = src[S_TARGET].is() + ? convertTemp(src[S_TARGET].as(), settings.system.unitSystem, UnitSystem::METRIC) + : dst.target; + const auto fieldResult = applySetting(dst, S_TARGET, value); + result.changed = fieldResult.changed || result.changed; + if (src[S_TARGET].is()) { + result.accepted = fieldResult.accepted || result.accepted; + } + + return result; +} + +// PID settings + +static bool normalizePidBounds(PidSettings& dst) { + bool changed = false; + + if (dst.maxTemp < dst.minTemp) { + dst.maxTemp = dst.minTemp; + changed = true; + } + + return changed; +} + +static SettingResult applySetting(PidSettings& dst, std::string_view path, bool value) { + bool changed = false; + + if (path == S_ENABLED) { + if (!settings.opentherm.options.nativeOTC) { + if (value != dst.enabled) { + dst.enabled = value; + changed = true; + } + + } else if (dst.enabled) { + dst.enabled = false; + changed = true; + } + + return {.changed = changed, .accepted = !value || !settings.opentherm.options.nativeOTC}; + } + + if (path == "deadband/enabled") { + if (value != dst.deadband.enabled) { + dst.deadband.enabled = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + return {}; +} + +static SettingResult applySetting(PidSettings& dst, std::string_view path, float input) { + bool changed = false; + + if (path == S_P_FACTOR) { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + value = roundf(value, 3); + if (value < 0.0f || value > 1000.0f) { + return {}; + } + + if (isFloatDifferent(value, dst.p_factor, 0.0001f)) { + dst.p_factor = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_I_FACTOR) { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + value = roundf(value, 4); + if (value < 0.0f || value > 100.0f) { + return {}; + } + + if (isFloatDifferent(value, dst.i_factor, 0.00005f)) { + dst.i_factor = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_D_FACTOR) { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + value = roundf(value, 1); + if (value < 0.0f || value > 100000.0f) { + return {}; + } + + if (isFloatDifferent(value, dst.d_factor, 0.0001f)) { + dst.d_factor = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_DT) { + if (!isSettingInteger(input, 0, 65535)) { + return {}; + } + + unsigned short value = static_cast(input); + + if (value < 30 || value > 1800) { + return {}; + } + + if (value != dst.dt) { + dst.dt = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_MIN_TEMP) { + if (!settings.equitherm.enabled) { + input = std::round(input); + } + + if (!isSettingInteger(input, -32768, 32767)) { + return {}; + } + + short value = static_cast(input); + + if (settings.equitherm.enabled) { + if (value < -99.9f || value > 99.9f) { + return {}; + } + + } else if (!isValidTemp(value, UnitSystem::METRIC, 0.0f)) { + return {}; + } + + if (value != dst.minTemp) { + dst.minTemp = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_MAX_TEMP) { + if (!settings.equitherm.enabled) { + input = std::round(input); + } + + if (!isSettingInteger(input, -32768, 32767)) { + return {}; + } + + short value = static_cast(input); + + if (settings.equitherm.enabled) { + if (value < 0.1f || value > 99.9f) { + return {}; + } + + } else if (!isValidTemp(value, UnitSystem::METRIC)) { + return {}; + } + + if (value != dst.maxTemp) { + dst.maxTemp = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == "deadband/p_multiplier") { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + value = roundf(value, 3); + if (value < 0.0f || value > 1.0f) { + return {}; + } + + if (isFloatDifferent(value, dst.deadband.p_multiplier, 0.0001f)) { + dst.deadband.p_multiplier = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == "deadband/i_multiplier") { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + value = roundf(value, 3); + if (value < 0.0f || value > 1.0f) { + return {}; + } + + if (isFloatDifferent(value, dst.deadband.i_multiplier, 0.0001f)) { + dst.deadband.i_multiplier = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == "deadband/d_multiplier") { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + value = roundf(value, 3); + if (value < 0.0f || value > 1.0f) { + return {}; + } + + if (isFloatDifferent(value, dst.deadband.d_multiplier, 0.0001f)) { + dst.deadband.d_multiplier = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == "deadband/threshold_high") { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + value = roundf(value, 2); + if (value < 0.0f || value > 5.0f) { + return {}; + } + + if (isFloatDifferent(value, dst.deadband.thresholdHigh, 0.0001f)) { + dst.deadband.thresholdHigh = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == "deadband/threshold_low") { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + value = roundf(value, 2); + if (value < 0.0f || value > 5.0f) { + return {}; + } + + if (isFloatDifferent(value, dst.deadband.thresholdLow, 0.0001f)) { + dst.deadband.thresholdLow = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + return {}; +} + +JsonVariant toJson(const PidSettings& src, JsonVariant dst) { + auto pid = dst.to(); + pid[S_ENABLED] = src.enabled; + pid[S_P_FACTOR] = roundf(src.p_factor, 3); + pid[S_I_FACTOR] = roundf(src.i_factor, 4); + pid[S_D_FACTOR] = roundf(src.d_factor, 1); + pid[S_DT] = src.dt; + pid[S_MIN_TEMP] = settings.equitherm.enabled + ? src.minTemp + : convertTemp(src.minTemp, UnitSystem::METRIC, settings.system.unitSystem); + pid[S_MAX_TEMP] = settings.equitherm.enabled + ? src.maxTemp + : convertTemp(src.maxTemp, UnitSystem::METRIC, settings.system.unitSystem); + + auto pidDeadband = pid[S_DEADBAND].to(); + pidDeadband[S_ENABLED] = src.deadband.enabled; + pidDeadband[S_P_MULTIPLIER] = src.deadband.p_multiplier; + pidDeadband[S_I_MULTIPLIER] = src.deadband.i_multiplier; + pidDeadband[S_D_MULTIPLIER] = src.deadband.d_multiplier; + pidDeadband[S_THRESHOLD_HIGH] = src.deadband.thresholdHigh; + pidDeadband[S_THRESHOLD_LOW] = src.deadband.thresholdLow; + + return dst; +} + +SettingResult fromJson(JsonVariantConst src, PidSettings& dst) { + SettingResult result; + + if (src[S_ENABLED].is()) { + const auto value = src[S_ENABLED].as(); + const auto fieldResult = applySetting(dst, S_ENABLED, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_P_FACTOR].is()) { + const auto value = src[S_P_FACTOR].as(); + const auto fieldResult = applySetting(dst, S_P_FACTOR, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_I_FACTOR].is()) { + const auto value = src[S_I_FACTOR].as(); + const auto fieldResult = applySetting(dst, S_I_FACTOR, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_D_FACTOR].is()) { + const auto value = src[S_D_FACTOR].as(); + const auto fieldResult = applySetting(dst, S_D_FACTOR, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_DT].is()) { + const auto value = src[S_DT].as(); + const auto fieldResult = applySetting(dst, S_DT, static_cast(value)); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_MIN_TEMP].is()) { + float value = src[S_MIN_TEMP].as(); + if (!settings.equitherm.enabled) { + value = convertTemp(value, settings.system.unitSystem, UnitSystem::METRIC); + } + + const auto fieldResult = applySetting(dst, S_MIN_TEMP, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_MAX_TEMP].is()) { + float value = src[S_MAX_TEMP].as(); + if (!settings.equitherm.enabled) { + value = convertTemp(value, settings.system.unitSystem, UnitSystem::METRIC); + } + + const auto fieldResult = applySetting(dst, S_MAX_TEMP, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + result.changed = normalizePidBounds(dst) || result.changed; + + if (src[S_DEADBAND][S_ENABLED].is()) { + const auto value = src[S_DEADBAND][S_ENABLED].as(); + const auto fieldResult = applySetting(dst, "deadband/enabled", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_DEADBAND][S_P_MULTIPLIER].is()) { + const auto value = src[S_DEADBAND][S_P_MULTIPLIER].as(); + const auto fieldResult = applySetting(dst, "deadband/p_multiplier", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_DEADBAND][S_I_MULTIPLIER].is()) { + const auto value = src[S_DEADBAND][S_I_MULTIPLIER].as(); + const auto fieldResult = applySetting(dst, "deadband/i_multiplier", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_DEADBAND][S_D_MULTIPLIER].is()) { + const auto value = src[S_DEADBAND][S_D_MULTIPLIER].as(); + const auto fieldResult = applySetting(dst, "deadband/d_multiplier", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_DEADBAND][S_THRESHOLD_HIGH].is()) { + const auto value = src[S_DEADBAND][S_THRESHOLD_HIGH].as(); + const auto fieldResult = applySetting(dst, "deadband/threshold_high", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_DEADBAND][S_THRESHOLD_LOW].is()) { + const auto value = src[S_DEADBAND][S_THRESHOLD_LOW].as(); + const auto fieldResult = applySetting(dst, "deadband/threshold_low", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + return result; +} + +// Equitherm settings + +static SettingResult applySetting(EquithermSettings& dst, std::string_view path, bool value) { + bool changed = false; + + if (path == S_ENABLED) { + if (!settings.opentherm.options.nativeOTC) { + if (value != dst.enabled) { + dst.enabled = value; + changed = true; + } + + } else if (dst.enabled) { + dst.enabled = false; + changed = true; + } + + return {.changed = changed, .accepted = !value || !settings.opentherm.options.nativeOTC}; + } + + return {}; +} + +static SettingResult applySetting(EquithermSettings& dst, std::string_view path, float input) { + bool changed = false; + + if (path == S_SLOPE) { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + value = roundf(value, 3); + if (value < 0.001f || value > 10.0f) { + return {}; + } + + if (isFloatDifferent(value, dst.slope, 0.0001f)) { + dst.slope = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_EXPONENT) { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + value = roundf(value, 3); + if (value < 0.2f || value > 2.0f) { + return {}; + } + + if (isFloatDifferent(value, dst.exponent, 0.0001f)) { + dst.exponent = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_SHIFT) { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + value = roundf(value, 2); + if (value < -15.0f || value > 15.0f) { + return {}; + } + + if (isFloatDifferent(value, dst.shift, 0.0001f)) { + dst.shift = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_TARGET_DIFF_FACTOR) { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + value = roundf(value, 3); + if (value < 0.0f || value > 10.0f) { + return {}; + } + + if (isFloatDifferent(value, dst.targetDiffFactor, 0.0001f)) { + dst.targetDiffFactor = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + return {}; +} + +JsonVariant toJson(const EquithermSettings& src, JsonVariant dst) { + auto equitherm = dst.to(); + equitherm[S_ENABLED] = src.enabled; + equitherm[S_SLOPE] = roundf(src.slope, 3); + equitherm[S_EXPONENT] = roundf(src.exponent, 3); + equitherm[S_SHIFT] = roundf(src.shift, 2); + equitherm[S_TARGET_DIFF_FACTOR] = roundf(src.targetDiffFactor, 3); + + return dst; +} + +SettingResult fromJson(JsonVariantConst src, EquithermSettings& dst) { + SettingResult result; + + if (src[S_ENABLED].is()) { + const auto value = src[S_ENABLED].as(); + const auto fieldResult = applySetting(dst, S_ENABLED, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_SLOPE].is()) { + const auto value = src[S_SLOPE].as(); + const auto fieldResult = applySetting(dst, S_SLOPE, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_EXPONENT].is()) { + const auto value = src[S_EXPONENT].as(); + const auto fieldResult = applySetting(dst, S_EXPONENT, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_SHIFT].is()) { + const auto value = src[S_SHIFT].as(); + const auto fieldResult = applySetting(dst, S_SHIFT, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_TARGET_DIFF_FACTOR].is()) { + const auto value = src[S_TARGET_DIFF_FACTOR].as(); + const auto fieldResult = applySetting(dst, S_TARGET_DIFF_FACTOR, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + return result; +} + +// External pump settings + +JsonVariant toJson(const ExternalPumpSettings& src, JsonVariant dst) { + auto externalPump = dst.to(); + externalPump[S_USE] = src.use; + externalPump[S_GPIO] = src.gpio; + externalPump[S_INVERT_STATE] = src.invertState; + externalPump[S_POST_CIRCULATION_TIME] = roundf(src.postCirculationTime / 60, 0); + externalPump[S_ANTI_STUCK_INTERVAL] = roundf(src.antiStuckInterval / 86400, 0); + externalPump[S_ANTI_STUCK_TIME] = roundf(src.antiStuckTime / 60, 0); + + return dst; +} + +SettingResult fromJson(JsonVariantConst src, ExternalPumpSettings& dst) { + SettingResult result; + + if (src[S_USE].is()) { + const auto value = src[S_USE].as(); + + result.accepted = true; + if (value != dst.use) { + dst.use = value; + result.changed = true; + } + } + + if (!src[S_GPIO].isNull()) { + if (src[S_GPIO].is() && src[S_GPIO].as().size() == 0) { + result.accepted = true; + if (dst.gpio != GPIO_IS_NOT_CONFIGURED) { + dst.gpio = GPIO_IS_NOT_CONFIGURED; + result.changed = true; + } + + } else if (src[S_GPIO].is()) { + const auto value = src[S_GPIO].as(); + + if (value == GPIO_IS_NOT_CONFIGURED || GPIO_IS_VALID_OUTPUT(value)) { + result.accepted = true; + if (value != dst.gpio) { + dst.gpio = value; + result.changed = true; + } + } + } + } + + if (src[S_INVERT_STATE].is()) { + const auto value = src[S_INVERT_STATE].as(); + + result.accepted = true; + if (value != dst.invertState) { + dst.invertState = value; + result.changed = true; + } + } + + if (src[S_POST_CIRCULATION_TIME].is()) { + unsigned short value = src[S_POST_CIRCULATION_TIME].as(); + + if (value <= 120) { + value = value * 60; + + result.accepted = true; + if (value != dst.postCirculationTime) { + dst.postCirculationTime = value; + result.changed = true; + } + } + } + + if (src[S_ANTI_STUCK_INTERVAL].is()) { + unsigned int value = src[S_ANTI_STUCK_INTERVAL].as(); + + if (value <= 366) { + value = value * 86400; + + result.accepted = true; + if (value != dst.antiStuckInterval) { + dst.antiStuckInterval = value; + result.changed = true; + } + } + } + + if (src[S_ANTI_STUCK_TIME].is()) { + unsigned short value = src[S_ANTI_STUCK_TIME].as(); + + if (value <= 20) { + value = value * 60; + + result.accepted = true; + if (value != dst.antiStuckTime) { + dst.antiStuckTime = value; + result.changed = true; + } + } + } + + return result; +} + +// Cascade control settings + +JsonVariant toJson(const CascadeControlSettings& src, JsonVariant dst) { + auto cascadeControl = dst.to(); + auto cascadeControlInput = cascadeControl[S_INPUT].to(); + cascadeControlInput[S_ENABLED] = src.input.enabled; + cascadeControlInput[S_GPIO] = src.input.gpio; + cascadeControlInput[S_INVERT_STATE] = src.input.invertState; + cascadeControlInput[S_THRESHOLD_TIME] = src.input.thresholdTime; + + auto cascadeControlOutput = cascadeControl[S_OUTPUT].to(); + cascadeControlOutput[S_ENABLED] = src.output.enabled; + cascadeControlOutput[S_GPIO] = src.output.gpio; + cascadeControlOutput[S_INVERT_STATE] = src.output.invertState; + cascadeControlOutput[S_THRESHOLD_TIME] = src.output.thresholdTime; + cascadeControlOutput[S_ON_FAULT] = src.output.onFault; + cascadeControlOutput[S_ON_LOSS_CONNECTION] = src.output.onLossConnection; + cascadeControlOutput[S_ON_ENABLED_HEATING] = src.output.onEnabledHeating; + + return dst; +} + +SettingResult fromJson(JsonVariantConst src, CascadeControlSettings& dst) { + SettingResult result; + + if (src[S_INPUT][S_ENABLED].is()) { + const auto value = src[S_INPUT][S_ENABLED].as(); + + result.accepted = true; + if (value != dst.input.enabled) { + dst.input.enabled = value; + result.changed = true; + } + } + + if (!src[S_INPUT][S_GPIO].isNull()) { + if (src[S_INPUT][S_GPIO].is() && src[S_INPUT][S_GPIO].as().size() == 0) { + result.accepted = true; + if (dst.input.gpio != GPIO_IS_NOT_CONFIGURED) { + dst.input.gpio = GPIO_IS_NOT_CONFIGURED; + result.changed = true; + } + + } else if (src[S_INPUT][S_GPIO].is()) { + const auto value = src[S_INPUT][S_GPIO].as(); + + if (value == GPIO_IS_NOT_CONFIGURED || GPIO_IS_VALID_INPUT(value)) { + result.accepted = true; + if (value != dst.input.gpio) { + dst.input.gpio = value; + result.changed = true; + } + } + } + } + + if (src[S_INPUT][S_INVERT_STATE].is()) { + const auto value = src[S_INPUT][S_INVERT_STATE].as(); + + result.accepted = true; + if (value != dst.input.invertState) { + dst.input.invertState = value; + result.changed = true; + } + } + + if (src[S_INPUT][S_THRESHOLD_TIME].is()) { + const auto value = src[S_INPUT][S_THRESHOLD_TIME].as(); + + if (value >= 5 && value <= 600) { + result.accepted = true; + if (value != dst.input.thresholdTime) { + dst.input.thresholdTime = value; + result.changed = true; + } + } + } + + if (src[S_OUTPUT][S_ENABLED].is()) { + const auto value = src[S_OUTPUT][S_ENABLED].as(); + + result.accepted = true; + if (value != dst.output.enabled) { + dst.output.enabled = value; + result.changed = true; + } + } + + if (!src[S_OUTPUT][S_GPIO].isNull()) { + if (src[S_OUTPUT][S_GPIO].is() && src[S_OUTPUT][S_GPIO].as().size() == 0) { + result.accepted = true; + if (dst.output.gpio != GPIO_IS_NOT_CONFIGURED) { + dst.output.gpio = GPIO_IS_NOT_CONFIGURED; + result.changed = true; + } + + } else if (src[S_OUTPUT][S_GPIO].is()) { + const auto value = src[S_OUTPUT][S_GPIO].as(); + + if (value == GPIO_IS_NOT_CONFIGURED || GPIO_IS_VALID_OUTPUT(value)) { + result.accepted = true; + if (value != dst.output.gpio) { + dst.output.gpio = value; + result.changed = true; + } + } + } + } + + if (src[S_OUTPUT][S_INVERT_STATE].is()) { + const auto value = src[S_OUTPUT][S_INVERT_STATE].as(); + + result.accepted = true; + if (value != dst.output.invertState) { + dst.output.invertState = value; + result.changed = true; + } + } + + if (src[S_OUTPUT][S_THRESHOLD_TIME].is()) { + const auto value = src[S_OUTPUT][S_THRESHOLD_TIME].as(); + + if (value >= 5 && value <= 600) { + result.accepted = true; + if (value != dst.output.thresholdTime) { + dst.output.thresholdTime = value; + result.changed = true; + } + } + } + + if (src[S_OUTPUT][S_ON_FAULT].is()) { + const auto value = src[S_OUTPUT][S_ON_FAULT].as(); + + result.accepted = true; + if (value != dst.output.onFault) { + dst.output.onFault = value; + result.changed = true; + } + } + + if (src[S_OUTPUT][S_ON_LOSS_CONNECTION].is()) { + const auto value = src[S_OUTPUT][S_ON_LOSS_CONNECTION].as(); + + result.accepted = true; + if (value != dst.output.onLossConnection) { + dst.output.onLossConnection = value; + result.changed = true; + } + } + + if (src[S_OUTPUT][S_ON_ENABLED_HEATING].is()) { + const auto value = src[S_OUTPUT][S_ON_ENABLED_HEATING].as(); + + result.accepted = true; + if (value != dst.output.onEnabledHeating) { + dst.output.onEnabledHeating = value; + result.changed = true; + } + } + + return result; +} + +// MQTT paths and cross-section normalization + +SettingResult applySetting(Settings& dst, std::string_view path, bool value) { + const auto separator = path.find('/'); + if (separator == std::string_view::npos) { + return {}; + } + + const auto section = path.substr(0, separator); + path.remove_prefix(separator + 1); + + if (section == S_EQUITHERM) { + return applySetting(dst.equitherm, path, value); + } + + if (section == S_PID) { + return applySetting(dst.pid, path, value); + } + + if (section == S_HEATING) { + return applySetting(dst.heating, path, value); + } + + if (section == S_DHW) { + return applySetting(dst.dhw, path, value); + } + + return {}; +} + +SettingResult applySetting(Settings& dst, std::string_view path, float input) { + const auto separator = path.find('/'); + if (separator == std::string_view::npos) { + return {}; + } + + const auto section = path.substr(0, separator); + path.remove_prefix(separator + 1); + + if (section == S_EQUITHERM) { + return applySetting(dst.equitherm, path, input); + } + + if (section == S_PID) { + return applySetting(dst.pid, path, input); + } + + if (section == S_HEATING) { + return applySetting(dst.heating, path, input); + } + + if (section == S_DHW) { + return applySetting(dst.dhw, path, input); + } + + if (section == S_EMERGENCY) { + return applySetting(dst.emergency, path, input); + } + + return {}; +} + +static bool normalizeRegulatorModes(Settings& dst) { + bool changed = false; + + if (dst.opentherm.options.nativeOTC) { + if (dst.equitherm.enabled) { + dst.equitherm.enabled = false; + changed = true; + } + if (dst.pid.enabled) { + dst.pid.enabled = false; + changed = true; + } + } + + return changed; +} + +bool normalizeSettings(Settings& dst) { + bool changed = false; + + changed = normalizeRegulatorModes(dst) || changed; + + changed = normalizePidBounds(dst.pid) || changed; + changed = normalizeHeatingBounds(dst.heating) || changed; + changed = normalizeHeatingOverheatBounds(dst.heating) || changed; + changed = normalizeHeatingFreezeBounds(dst.heating) || changed; + changed = normalizeDhwBounds(dst.dhw) || changed; + changed = normalizeDhwOverheatBounds(dst.dhw) || changed; + + changed = setEmergencyTarget(dst.emergency, dst.emergency.target).changed || changed; + changed = setHeatingTarget(dst.heating, dst.heating.target).changed || changed; + changed = setDhwTarget(dst.dhw, dst.dhw.target).changed || changed; + + return changed; +} + +// Sensor settings + +JsonVariant toJson(const uint8_t sensorId, const Sensors::Settings& src, JsonVariant dst) { + dst[S_ID] = sensorId; + dst[S_ENABLED] = src.enabled; + // Snapshot storage is temporary; the pointer adapter copies the name. + dst[S_NAME] = static_cast(src.name); + dst[S_SLUG] = static_cast(src.slug); + dst[S_PURPOSE] = static_cast(src.purpose); + dst[S_TYPE] = static_cast(src.type); + dst[S_GPIO] = src.gpio; + + if (src.type == Sensors::Type::DALLAS_TEMP) { + char addr[24]; + sprintf( + addr, + "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx", + src.address[0], src.address[1], src.address[2], src.address[3], + src.address[4], src.address[5], src.address[6], src.address[7] + ); + dst[S_ADDRESS] = addr; + + } else if (src.type == Sensors::Type::BLUETOOTH) { + char addr[18]; + sprintf( + addr, + "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx", + src.address[0], src.address[1], src.address[2], + src.address[3], src.address[4], src.address[5] + ); + dst[S_ADDRESS] = addr; + + } else { + dst[S_ADDRESS] = ""; + } + + dst[S_OFFSET] = roundf(src.offset, 3); + dst[S_FACTOR] = roundf(src.factor, 3); + dst[S_FILTERING] = src.filtering; + dst[S_FILTERING_FACTOR] = roundf(src.filteringFactor, 3); + return dst; +} + +SettingResult fromJson(const JsonVariantConst src, Sensors::Settings& dst) { + SettingResult result; + + // enabled + if (src[S_ENABLED].is()) { + const auto value = src[S_ENABLED].as(); + result.accepted = true; + + if (value != dst.enabled) { + dst.enabled = value; + result.changed = true; + } + } + + // name + if (src[S_NAME].is()) { + const JsonString raw = src[S_NAME].as(); + + if (strlen(raw.c_str()) == raw.size()) { + const auto value = Sensors::cleanName(std::string_view(raw.c_str(), raw.size())); + + if (value.size() < sizeof(dst.name) && value != dst.name) { + const auto slug = Sensors::makeSlug(value); + bool unique = true; + if (Sensors::settings != nullptr && !slug.empty()) { + // The caller holds Sensors::mutex while checking configured sensor slugs. + for (uint8_t id = 0; id <= Sensors::getMaxSensorId(); id++) { + if (&Sensors::settings[id] != &dst && slug == Sensors::settings[id].slug) { + unique = false; + break; + } + } + } + + if (unique) { + result.accepted = true; + strcpy(dst.name, value.c_str()); + strcpy(dst.slug, slug.c_str()); + result.changed = true; + } + + } else if (value.size() < sizeof(dst.name)) { + result.accepted = true; + } + } + } + + if (dst.enabled && !dst.slug[0]) { + dst.enabled = false; + result.changed = true; + } + + // purpose + if (src[S_PURPOSE].is()) { + const auto value = src[S_PURPOSE].as(); + + switch (value) { + case static_cast(Sensors::Purpose::OUTDOOR_TEMP): + case static_cast(Sensors::Purpose::INDOOR_TEMP): + case static_cast(Sensors::Purpose::HEATING_TEMP): + case static_cast(Sensors::Purpose::HEATING_RETURN_TEMP): + case static_cast(Sensors::Purpose::DHW_TEMP): + case static_cast(Sensors::Purpose::DHW_RETURN_TEMP): + case static_cast(Sensors::Purpose::DHW_FLOW_RATE): + case static_cast(Sensors::Purpose::EXHAUST_TEMP): + case static_cast(Sensors::Purpose::MODULATION_LEVEL): + + case static_cast(Sensors::Purpose::NUMBER): + case static_cast(Sensors::Purpose::POWER_FACTOR): + case static_cast(Sensors::Purpose::POWER): + case static_cast(Sensors::Purpose::FAN_SPEED): + case static_cast(Sensors::Purpose::CO2): + case static_cast(Sensors::Purpose::PRESSURE): + case static_cast(Sensors::Purpose::HUMIDITY): + case static_cast(Sensors::Purpose::TEMPERATURE): + case static_cast(Sensors::Purpose::NOT_CONFIGURED): + result.accepted = true; + if (static_cast(dst.purpose) != value) { + dst.purpose = static_cast(value); + result.changed = true; + } + break; + + default: + break; + } + } + + // type + if (src[S_TYPE].is()) { + const auto value = src[S_TYPE].as(); + + switch (value) { + case static_cast(Sensors::Type::OT_OUTDOOR_TEMP): + case static_cast(Sensors::Type::OT_HEATING_TEMP): + case static_cast(Sensors::Type::OT_HEATING_RETURN_TEMP): + case static_cast(Sensors::Type::OT_DHW_TEMP): + case static_cast(Sensors::Type::OT_DHW_TEMP2): + case static_cast(Sensors::Type::OT_DHW_FLOW_RATE): + case static_cast(Sensors::Type::OT_CH2_TEMP): + case static_cast(Sensors::Type::OT_EXHAUST_TEMP): + case static_cast(Sensors::Type::OT_HEAT_EXCHANGER_TEMP): + case static_cast(Sensors::Type::OT_PRESSURE): + case static_cast(Sensors::Type::OT_MODULATION_LEVEL): + case static_cast(Sensors::Type::OT_CURRENT_POWER): + case static_cast(Sensors::Type::OT_EXHAUST_CO2): + case static_cast(Sensors::Type::OT_EXHAUST_FAN_SPEED): + case static_cast(Sensors::Type::OT_SUPPLY_FAN_SPEED): + case static_cast(Sensors::Type::OT_SOLAR_STORAGE_TEMP): + case static_cast(Sensors::Type::OT_SOLAR_COLLECTOR_TEMP): + case static_cast(Sensors::Type::OT_FAN_SPEED_SETPOINT): + case static_cast(Sensors::Type::OT_FAN_SPEED_CURRENT): + + case static_cast(Sensors::Type::OT_BURNER_STARTS): + case static_cast(Sensors::Type::OT_DHW_BURNER_STARTS): + case static_cast(Sensors::Type::OT_HEATING_PUMP_STARTS): + case static_cast(Sensors::Type::OT_DHW_PUMP_STARTS): + case static_cast(Sensors::Type::OT_BURNER_HOURS): + case static_cast(Sensors::Type::OT_DHW_BURNER_HOURS): + case static_cast(Sensors::Type::OT_HEATING_PUMP_HOURS): + case static_cast(Sensors::Type::OT_DHW_PUMP_HOURS): + case static_cast(Sensors::Type::OT_COOLING_HOURS): + + case static_cast(Sensors::Type::NTC_10K_TEMP): + case static_cast(Sensors::Type::DALLAS_TEMP): + #if USE_BLE + case static_cast(Sensors::Type::BLUETOOTH): + #endif + case static_cast(Sensors::Type::DHT11): + case static_cast(Sensors::Type::DHT22): + case static_cast(Sensors::Type::HEATING_SETPOINT_TEMP): + case static_cast(Sensors::Type::MANUAL): + case static_cast(Sensors::Type::NOT_CONFIGURED): + result.accepted = true; + if (static_cast(dst.type) != value) { + dst.type = static_cast(value); + result.changed = true; + } + break; + + default: + break; + } + } + + // gpio + if (!src[S_GPIO].isNull()) { + if (dst.type != Sensors::Type::DALLAS_TEMP && dst.type != Sensors::Type::NTC_10K_TEMP + && dst.type != Sensors::Type::DHT11 && dst.type != Sensors::Type::DHT22) { + if (dst.gpio != GPIO_IS_NOT_CONFIGURED) { + dst.gpio = GPIO_IS_NOT_CONFIGURED; + result.changed = true; + } + + } else if (src[S_GPIO].is() && src[S_GPIO].as().size() == 0) { + result.accepted = true; + if (dst.gpio != GPIO_IS_NOT_CONFIGURED) { + dst.gpio = GPIO_IS_NOT_CONFIGURED; + result.changed = true; + } + + } else if (src[S_GPIO].is()) { + const auto value = src[S_GPIO].as(); + + bool valid = false; + if (value == GPIO_IS_NOT_CONFIGURED) { + valid = true; + + } else if (dst.type == Sensors::Type::NTC_10K_TEMP) { + valid = GPIO_IS_VALID_INPUT(value); + + } else { + valid = GPIO_IS_VALID_INPUT(value) && GPIO_IS_VALID_OUTPUT(value); + } + + if (valid) { + result.accepted = true; + if (value != dst.gpio) { + dst.gpio = value; + result.changed = true; + } + } + } + } + + // address + if (src[S_ADDRESS].is()) { + const JsonString value = src[S_ADDRESS].as(); + + if (strlen(value.c_str()) == value.size()) { + if (dst.type == Sensors::Type::DALLAS_TEMP) { + uint8_t tmp[8]; + int parsed = sscanf( + value.c_str(), + "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx", + &tmp[0], &tmp[1], &tmp[2], &tmp[3], + &tmp[4], &tmp[5], &tmp[6], &tmp[7] + ); + + if (parsed == 8) { + result.accepted = true; + for (uint8_t i = 0; i < parsed; i++) { + if (dst.address[i] != tmp[i]) { + dst.address[i] = tmp[i]; + result.changed = true; + } + } + + } else { + // reset + for (uint8_t i = 0; i < sizeof(dst.address); i++) { + dst.address[i] = 0x00; + } + + result.changed = true; + } + + } else if (dst.type == Sensors::Type::BLUETOOTH) { + uint8_t tmp[6]; + int parsed = sscanf( + value.c_str(), + "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx", + &tmp[0], &tmp[1], &tmp[2], + &tmp[3], &tmp[4], &tmp[5] + ); + + if (parsed == 6) { + result.accepted = true; + for (uint8_t i = 0; i < parsed; i++) { + if (dst.address[i] != tmp[i]) { + dst.address[i] = tmp[i]; + result.changed = true; + } + } + + } else { + // reset + for (uint8_t i = 0; i < sizeof(dst.address); i++) { + dst.address[i] = 0x00; + } + + result.changed = true; + } + } + } + } + + // offset + if (src[S_OFFSET].is()) { + const auto value = roundf(src[S_OFFSET].as(), 2); + + if (value >= -20.0f && value <= 20.0f) { + result.accepted = true; + if (isFloatDifferent(value, dst.offset, 0.0001f)) { + dst.offset = value; + result.changed = true; + } + } + } + + // factor + if (src[S_FACTOR].is()) { + const auto value = roundf(src[S_FACTOR].as(), 3); + + if (value >= 0.09f && value <= 100.0f) { + result.accepted = true; + if (isFloatDifferent(value, dst.factor, 0.0001f)) { + dst.factor = value; + result.changed = true; + } + } + } + + // filtering + if (src[S_FILTERING].is()) { + const auto value = src[S_FILTERING].as(); + result.accepted = true; + + if (value != dst.filtering) { + dst.filtering = value; + result.changed = true; + } + } + + // filtering factor + if (src[S_FILTERING_FACTOR].is()) { + const auto value = roundf(src[S_FILTERING_FACTOR].as(), 3); + + if (value >= 0.001f && value <= 1.0f) { + result.accepted = true; + if (isFloatDifferent(value, dst.filteringFactor, 0.0001f)) { + dst.filteringFactor = value; + result.changed = true; + } + } + } + + return result; +} + +// Sensor measurements + +JsonVariant toJson(const Sensors::Settings& sSensor, const Sensors::Result& rSensor, JsonVariant dst) { + dst[S_CONNECTED] = rSensor.connected; + dst[S_SIGNAL_QUALITY] = rSensor.signalQuality; + + if (sSensor.type == Sensors::Type::BLUETOOTH) { + dst[S_TEMPERATURE] = roundf(convertTemp(rSensor.values[static_cast(Sensors::ValueType::TEMPERATURE)], UnitSystem::METRIC, settings.system.unitSystem), 3); + dst[S_HUMIDITY] = roundf(rSensor.values[static_cast(Sensors::ValueType::HUMIDITY)], 3); + dst[S_BATTERY] = roundf(rSensor.values[static_cast(Sensors::ValueType::BATTERY)], 1); + dst[S_RSSI] = roundf(rSensor.values[static_cast(Sensors::ValueType::RSSI)], 0); + + } else if (sSensor.type == Sensors::Type::DHT11 || sSensor.type == Sensors::Type::DHT22) { + dst[S_TEMPERATURE] = roundf(convertTemp(rSensor.values[static_cast(Sensors::ValueType::TEMPERATURE)], UnitSystem::METRIC, settings.system.unitSystem), 3); + dst[S_HUMIDITY] = roundf(rSensor.values[static_cast(Sensors::ValueType::HUMIDITY)], 3); + + } else { + dst[S_VALUE] = roundf(Sensors::convertValue(sSensor, Sensors::ValueType::PRIMARY, rSensor.values[static_cast(Sensors::ValueType::PRIMARY)], UnitSystem::METRIC, settings.system.unitSystem), 3); + } + return dst; +} + +JsonVariant toJson(const uint8_t sensorId, JsonVariant dst) { + if (const auto snapshot = Sensors::getSnapshot(sensorId)) { + return toJson(snapshot->settings, snapshot->result, dst); + } + return dst; +} + +// Runtime variables and actions + +JsonVariant toJson(const Variables& src, JsonVariant dst) { + auto slave = dst[S_SLAVE].to(); + slave[S_MEMBER_ID] = src.slave.memberId; + slave[S_FLAGS] = src.slave.flags; + slave[S_TYPE] = src.slave.type; + slave[S_APP_VERSION] = src.slave.appVersion; + slave[S_PROTOCOL_VERSION] = src.slave.protocolVersion; + slave[S_CONNECTED] = src.slave.connected; + slave[S_FLAME] = src.slave.flame; + + auto sCooling = slave[S_COOLING].to(); + sCooling[S_ACTIVE] = src.slave.cooling.active; + sCooling[S_SETPOINT] = src.slave.cooling.setpoint; + + auto sModulation = slave[S_MODULATION].to(); + sModulation[S_MIN] = src.slave.modulation.min; + sModulation[S_MAX] = src.slave.modulation.max; + + auto sPower = slave[S_POWER].to(); + sPower[S_MIN] = roundf(src.slave.power.min, 2); + sPower[S_MAX] = roundf(src.slave.power.max, 2); + + auto sHeating = slave[S_HEATING].to(); + sHeating[S_ACTIVE] = src.slave.heating.active; + sHeating[S_MIN_TEMP] = convertTemp(src.slave.heating.minTemp, UnitSystem::METRIC, settings.system.unitSystem); + sHeating[S_MAX_TEMP] = convertTemp(src.slave.heating.maxTemp, UnitSystem::METRIC, settings.system.unitSystem); + + auto sDhw = slave[S_DHW].to(); + sDhw[S_ACTIVE] = src.slave.dhw.active; + sDhw[S_MIN_TEMP] = convertTemp(src.slave.dhw.minTemp, UnitSystem::METRIC, settings.system.unitSystem); + sDhw[S_MAX_TEMP] = convertTemp(src.slave.dhw.maxTemp, UnitSystem::METRIC, settings.system.unitSystem); + + auto sFault = slave[S_FAULT].to(); + sFault[S_ACTIVE] = src.slave.fault.active; + sFault[S_CODE] = src.slave.fault.code; + + auto sDiag = slave[S_DIAG].to(); + sDiag[S_ACTIVE] = src.slave.diag.active; + sDiag[S_CODE] = src.slave.diag.code; + + + auto master = dst[S_MASTER].to(); + auto mHeating = master[S_HEATING].to(); + mHeating[S_ENABLED] = src.master.heating.enabled; + mHeating[S_BLOCKING] = src.master.heating.blocking; + mHeating[S_SMART_CONTROL] = src.master.heating.smartControl; + mHeating[S_OVERHEAT] = src.master.heating.overheat; + mHeating[S_FREEZING] = src.master.heating.freezing; + mHeating[S_SETPOINT_TEMP] = roundf((src.master.heating.setpointTemp == 0 ? 0 : convertTemp(src.master.heating.setpointTemp, UnitSystem::METRIC, settings.system.unitSystem)), 2); + mHeating[S_TARGET_TEMP] = roundf((src.master.heating.targetTemp == 0 ? 0 : convertTemp(src.master.heating.targetTemp, UnitSystem::METRIC, settings.system.unitSystem)), 2); + mHeating[S_CURRENT_TEMP] = roundf(convertTemp(src.master.heating.currentTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + mHeating[S_RETURN_TEMP] = roundf(convertTemp(src.master.heating.returnTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + mHeating[S_INDOOR_TEMP] = roundf(convertTemp(src.master.heating.indoorTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + mHeating[S_OUTDOOR_TEMP] = roundf(convertTemp(src.master.heating.outdoorTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + mHeating[S_MIN_TEMP] = roundf(convertTemp(src.master.heating.minTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + mHeating[S_MAX_TEMP] = roundf(convertTemp(src.master.heating.maxTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + + auto mDhw = master[S_DHW].to(); + mDhw[S_ENABLED] = src.master.dhw.enabled; + mDhw[S_OVERHEAT] = src.master.dhw.overheat; + mDhw[S_TARGET_TEMP] = roundf((src.master.dhw.targetTemp == 0 ? 0 : convertTemp(src.master.dhw.targetTemp, UnitSystem::METRIC, settings.system.unitSystem)), 2); + mDhw[S_CURRENT_TEMP] = roundf(convertTemp(src.master.dhw.currentTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + mDhw[S_RETURN_TEMP] = roundf(convertTemp(src.master.dhw.returnTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + mDhw[S_MIN_TEMP] = convertTemp(src.master.dhw.minTemp, UnitSystem::METRIC, settings.system.unitSystem); + mDhw[S_MAX_TEMP] = convertTemp(src.master.dhw.maxTemp, UnitSystem::METRIC, settings.system.unitSystem); + + master[S_NETWORK][S_CONNECTED] = isNetworkConnected(); + master[S_NETWORK][S_RSSI] = src.network.rssi; + master[S_NETWORK][S_CONNECTION_TYPE] = getNetworkConnectionType(); + master[S_MQTT][S_CONNECTED] = isMqttConnected(); + master[S_EMERGENCY][S_STATE] = src.emergency.state; + master[S_EXTERNAL_PUMP][S_STATE] = src.externalPump.state; + + auto mCascadeControl = master[S_CASCADE_CONTROL].to(); + mCascadeControl[S_INPUT] = src.cascadeControl.input; + mCascadeControl[S_OUTPUT] = src.cascadeControl.output; + + master[S_UPTIME] = millis() / 1000; + return dst; +} + +static SettingResult applyAction(Variables& dst, std::string_view action, bool value) { + SettingResult result; + if (action == "restart") { + if (value) { + restartTask.resume(15000); + result.changed = true; + } + + result.accepted = true; + return result; + } + + if (action == "reset_fault") { + if (value && !dst.actions.resetFault) { + dst.actions.resetFault = true; + result.changed = true; + } + + result.accepted = true; + return result; + } + + if (action == "reset_diagnostic") { + if (value && !dst.actions.resetDiagnostic) { + dst.actions.resetDiagnostic = true; + result.changed = true; + } + + result.accepted = true; + return result; + } + + return result; +} + +bool applyAction(std::string_view action, bool value) { + if (upgrading || restartTask.scheduled() || restartTask.active()) { + return false; + } + + return applyAction(vars, action, value).accepted; +} + +SettingResult fromJson(const JsonVariantConst src, Variables& dst) { + SettingResult result; + + // Admit the whole request before one of its actions schedules a restart. + if (upgrading || restartTask.scheduled() || restartTask.active()) { + return result; + } + + if (src[S_ACTIONS][S_RESTART].is()) { + const auto actionResult = applyAction(dst, "restart", src[S_ACTIONS][S_RESTART].as()); + result.changed = actionResult.changed || result.changed; + result.accepted = actionResult.accepted || result.accepted; + } + + if (src[S_ACTIONS][S_RESET_FAULT].is()) { + const auto actionResult = applyAction(dst, "reset_fault", src[S_ACTIONS][S_RESET_FAULT].as()); + result.changed = actionResult.changed || result.changed; + result.accepted = actionResult.accepted || result.accepted; + } + + if (src[S_ACTIONS][S_RESET_DIAGNOSTIC].is()) { + const auto actionResult = applyAction(dst, "reset_diagnostic", src[S_ACTIONS][S_RESET_DIAGNOSTIC].as()); + result.changed = actionResult.changed || result.changed; + result.accepted = actionResult.accepted || result.accepted; + } + + return result; +} diff --git a/src/control.cpp b/src/control.cpp new file mode 100644 index 0000000..559e14c --- /dev/null +++ b/src/control.cpp @@ -0,0 +1,446 @@ +#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE + +#include +#include + +#include + +Variables vars; + +static bool heatingEnabled = false; +static unsigned long heatingDisabledTime = 0; +static PumpStartReason extPumpStartReason = PumpStartReason::NONE; +static unsigned long externalPumpStartTime = 0; +static bool emergencyDetected = false; +static unsigned long emergencyFlipTime = 0; + +static Task freezeProtectionTask("Freeze protection", [](void*) { + float lowTemp = 255.0f; + uint8_t availableSensors = 0; + + if (Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::INDOOR_TEMP)) { + auto value = Sensors::getMeanValueByPurpose(Sensors::Purpose::INDOOR_TEMP, Sensors::ValueType::PRIMARY, settings.heating.indoorTempAvgType); + if (value < lowTemp) { + lowTemp = value; + } + + availableSensors++; + } + + if (Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::HEATING_TEMP)) { + auto value = Sensors::getMeanValueByPurpose(Sensors::Purpose::HEATING_TEMP, Sensors::ValueType::PRIMARY); + if (value < lowTemp) { + lowTemp = value; + } + + availableSensors++; + } + + if (Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::HEATING_RETURN_TEMP)) { + auto value = Sensors::getMeanValueByPurpose(Sensors::Purpose::HEATING_RETURN_TEMP, Sensors::ValueType::PRIMARY); + if (value < lowTemp) { + lowTemp = value; + } + + availableSensors++; + } + + if (availableSensors) { + if (vars.master.heating.freezing) { + if (lowTemp - static_cast(settings.heating.freezeProtection.highTemp) + 0.0001f >= 0.0f) { + vars.master.heating.freezing = false; + + ESP_LOGI( + L_MAIN, + "No freezing detected. Current low temp: %.2f, threshold (high): %hhu", + lowTemp, settings.heating.freezeProtection.highTemp + ); + } + + } else { + if (static_cast(settings.heating.freezeProtection.lowTemp) - lowTemp + 0.0001f >= 0.0f) { + vars.master.heating.freezing = true; + + if (!settings.heating.enabled) { + settings.heating.enabled = true; + requestSaveSettings(); + } + + ESP_LOGI( + L_MAIN, + "Freezing detected! Current low temp: %.2f, threshold (low): %hhu", + lowTemp, settings.heating.freezeProtection.lowTemp + ); + } + } + + } else if (vars.master.heating.freezing) { + vars.master.heating.freezing = false; + + ESP_LOGI(L_MAIN, "No sensors available, freeze protection unavailable!"); + } +}); + +static Task emergencyTask("Emergency mode", [](void*) { + // flags + uint8_t emergencyFlags = 0b00000000; + + // set outdoor sensor flag + if (settings.equitherm.enabled) { + if (!Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::OUTDOOR_TEMP)) { + emergencyFlags |= 0b00000001; + } + } + + // set indoor sensor flags + if (!Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::INDOOR_TEMP)) { + if (!settings.equitherm.enabled && settings.pid.enabled) { + emergencyFlags |= 0b00000010; + } + + if (settings.opentherm.options.nativeOTC) { + emergencyFlags |= 0b00000100; + } + } + + // if any flags is true + if ((emergencyFlags & 0b00001111) != 0) { + if (!emergencyDetected) { + // flip flag + emergencyDetected = true; + emergencyFlipTime = millis(); + + } else if (emergencyDetected && !vars.emergency.state) { + // enable emergency + if (millis() - emergencyFlipTime > (settings.emergency.thresholdTime * 1000)) { + vars.emergency.state = true; + ESP_LOGI(L_MAIN, "Emergency mode enabled (%hhu)", emergencyFlags); + } + } + + } else { + if (emergencyDetected) { + // flip flag + emergencyDetected = false; + emergencyFlipTime = millis(); + + } else if (!emergencyDetected && vars.emergency.state) { + // disable emergency + if (millis() - emergencyFlipTime > (settings.emergency.thresholdTime * 1000)) { + vars.emergency.state = false; + ESP_LOGI(L_MAIN, "Emergency mode disabled"); + } + } + } +}); + +static Task overheatProtectionTask("Overheat protection", [](void*) { + // Heating overheat control + if (settings.heating.overheatProtection.highTemp > 0 && settings.heating.overheatProtection.lowTemp > 0) { + const float highTemp = std::max({ + vars.slave.heating.currentTemp, + vars.slave.heating.returnTemp, + vars.slave.heatExchangerTemp + }); + + if (vars.master.heating.overheat) { + if (static_cast(settings.heating.overheatProtection.lowTemp) - highTemp + 0.0001f >= 0.0f) { + vars.master.heating.overheat = false; + + ESP_LOGI( + L_OT_HEATING, "Overheating not detected. Current high temp: %.2f, threshold (low): %hhu", + highTemp, settings.heating.overheatProtection.lowTemp + ); + } + + } else if (vars.slave.heating.active) { + if (highTemp - static_cast(settings.heating.overheatProtection.highTemp) + 0.0001f >= 0.0f) { + vars.master.heating.overheat = true; + + ESP_LOGW( + L_OT_HEATING, "Overheating detected! Current high temp: %.2f, threshold (high): %hhu", + highTemp, settings.heating.overheatProtection.highTemp + ); + } + } + + } else if (vars.master.heating.overheat) { + vars.master.heating.overheat = false; + } + + // DHW overheat control + if (settings.dhw.overheatProtection.highTemp > 0 && settings.dhw.overheatProtection.lowTemp > 0) { + const float highTemp = std::max({ + vars.slave.heating.currentTemp, + vars.slave.heating.returnTemp, + vars.slave.heatExchangerTemp, + vars.slave.dhw.currentTemp, + vars.slave.dhw.currentTemp2, + vars.slave.dhw.returnTemp + }); + + if (vars.master.dhw.overheat) { + if (static_cast(settings.dhw.overheatProtection.lowTemp) - highTemp + 0.0001f >= 0.0f) { + vars.master.dhw.overheat = false; + + ESP_LOGI( + L_OT_DHW, "Overheating not detected. Current high temp: %.2f, threshold (low): %hhu", + highTemp, settings.dhw.overheatProtection.lowTemp + ); + } + + } else if (vars.slave.dhw.active) { + if (highTemp - static_cast(settings.dhw.overheatProtection.highTemp) + 0.0001f >= 0.0f) { + vars.master.dhw.overheat = true; + + ESP_LOGW( + L_OT_DHW, "Overheating detected! Current high temp: %.2f, threshold (high): %hhu", + highTemp, settings.dhw.overheatProtection.highTemp + ); + } + } + + } else if (vars.master.dhw.overheat) { + vars.master.dhw.overheat = false; + } +}); + +static Task cascadeTask("Cascade", [](void*) { + static uint8_t configuredInputGpio = GPIO_IS_NOT_CONFIGURED; + static uint8_t configuredOutputGpio = GPIO_IS_NOT_CONFIGURED; + static bool pendingInputState = false; + static unsigned long inputChangedTime = 0; + static bool pendingOutputState = false; + static unsigned long outputChangedTime = 0; + + // input + if (settings.cascadeControl.input.enabled) { + if (settings.cascadeControl.input.gpio != configuredInputGpio) { + if (configuredInputGpio != GPIO_IS_NOT_CONFIGURED) { + // Keep the old input high-impedance, including input-only GPIOs. + pinMode(configuredInputGpio, INPUT); + + ESP_LOGI(L_CASCADE_INPUT, "Deinitialized on GPIO %hhu", configuredInputGpio); + } + + if (GPIO_IS_VALID_INPUT(settings.cascadeControl.input.gpio)) { + configuredInputGpio = settings.cascadeControl.input.gpio; + pinMode(configuredInputGpio, INPUT); + + ESP_LOGI(L_CASCADE_INPUT, "Initialized on GPIO %hhu", configuredInputGpio); + + } else if (configuredInputGpio != GPIO_IS_NOT_CONFIGURED) { + configuredInputGpio = GPIO_IS_NOT_CONFIGURED; + + ESP_LOGW(L_CASCADE_INPUT, "Failed initialize: GPIO %hhu is not valid!", configuredInputGpio); + } + } + + if (configuredInputGpio != GPIO_IS_NOT_CONFIGURED) { + bool value = (digitalRead(configuredInputGpio) == HIGH) ^ settings.cascadeControl.input.invertState; + + if (value != vars.cascadeControl.input) { + if (value != pendingInputState) { + pendingInputState = value; + inputChangedTime = millis(); + + } else if (millis() - inputChangedTime >= settings.cascadeControl.input.thresholdTime * 1000u) { + vars.cascadeControl.input = value; + + ESP_LOGI( + L_CASCADE_INPUT, + "State changed to %s", + value ? "TRUE" : "FALSE" + ); + } + + } else if (value != pendingInputState) { + pendingInputState = value; + } + } + } + + if (!settings.cascadeControl.input.enabled || configuredInputGpio == GPIO_IS_NOT_CONFIGURED) { + if (!vars.cascadeControl.input) { + vars.cascadeControl.input = true; + + ESP_LOGI( + L_CASCADE_INPUT, + "Disabled, state changed to %s", + vars.cascadeControl.input ? "TRUE" : "FALSE" + ); + } + } + + + // output + if (settings.cascadeControl.output.gpio != configuredOutputGpio) { + if (configuredOutputGpio != GPIO_IS_NOT_CONFIGURED) { + digitalWrite(configuredOutputGpio, LOW); + pinMode(configuredOutputGpio, DISABLED); + + ESP_LOGI(L_CASCADE_OUTPUT, "Deinitialized on GPIO %hhu", configuredOutputGpio); + } + + if (GPIO_IS_VALID_OUTPUT(settings.cascadeControl.output.gpio)) { + configuredOutputGpio = settings.cascadeControl.output.gpio; + pinMode(configuredOutputGpio, OUTPUT); + + ESP_LOGI(L_CASCADE_OUTPUT, "Initialized on GPIO %hhu", configuredOutputGpio); + + } else if (configuredOutputGpio != GPIO_IS_NOT_CONFIGURED) { + configuredOutputGpio = GPIO_IS_NOT_CONFIGURED; + + ESP_LOGW(L_CASCADE_OUTPUT, "Failed initialize: GPIO %hhu is not valid!", configuredOutputGpio); + } + } + + if (settings.cascadeControl.output.enabled) { + if (configuredOutputGpio != GPIO_IS_NOT_CONFIGURED) { + bool value = false; + if (settings.cascadeControl.output.onFault && vars.slave.fault.active) { + value = true; + + } else if (settings.cascadeControl.output.onLossConnection && !vars.slave.connected) { + value = true; + + } else if (settings.cascadeControl.output.onEnabledHeating && settings.heating.enabled && vars.cascadeControl.input) { + value = true; + } + + if (value != vars.cascadeControl.output) { + if (value != pendingOutputState) { + pendingOutputState = value; + outputChangedTime = millis(); + + } else if (millis() - outputChangedTime >= settings.cascadeControl.output.thresholdTime * 1000u) { + vars.cascadeControl.output = value; + + ESP_LOGI( + L_CASCADE_OUTPUT, + "State changed to %s", + value ? "TRUE" : "FALSE" + ); + } + + } else if (value != pendingOutputState) { + pendingOutputState = value; + } + } + } + + if (!settings.cascadeControl.output.enabled || configuredOutputGpio == GPIO_IS_NOT_CONFIGURED) { + if (vars.cascadeControl.output) { + vars.cascadeControl.output = false; + + ESP_LOGI( + L_CASCADE_OUTPUT, + "Disabled, state changed to %s", + vars.cascadeControl.output ? "TRUE" : "FALSE" + ); + } + } + + if (configuredOutputGpio != GPIO_IS_NOT_CONFIGURED) { + digitalWrite( + configuredOutputGpio, + (vars.cascadeControl.output ^ settings.cascadeControl.output.invertState) ? HIGH : LOW + ); + } +}); + +static Task externalPumpTask("External pump", [](void*) { + static uint8_t configuredGpio = GPIO_IS_NOT_CONFIGURED; + const uint32_t now = esp_timer_get_time() / 1000000; + + if (settings.externalPump.gpio != configuredGpio) { + if (configuredGpio != GPIO_IS_NOT_CONFIGURED) { + digitalWrite(configuredGpio, LOW); + pinMode(configuredGpio, DISABLED); + } + + if (GPIO_IS_VALID_OUTPUT(settings.externalPump.gpio)) { + configuredGpio = settings.externalPump.gpio; + pinMode(configuredGpio, OUTPUT); + + } else if (configuredGpio != GPIO_IS_NOT_CONFIGURED) { + configuredGpio = GPIO_IS_NOT_CONFIGURED; + } + } + + if (configuredGpio == GPIO_IS_NOT_CONFIGURED) { + if (vars.externalPump.state) { + vars.externalPump.state = false; + vars.externalPump.lastEnabledTime = now; + + ESP_LOGI(L_EXTPUMP, "Disabled: use = off"); + } + + return; + } + + if (!vars.master.heating.enabled && heatingEnabled) { + heatingEnabled = false; + heatingDisabledTime = millis(); + + } else if (vars.master.heating.enabled && !heatingEnabled) { + heatingEnabled = true; + } + + if (!settings.externalPump.use) { + if (vars.externalPump.state) { + vars.externalPump.state = false; + vars.externalPump.lastEnabledTime = now; + + ESP_LOGI(L_EXTPUMP, "Disabled: use = off"); + } + + } else if (vars.externalPump.state && !heatingEnabled) { + if (extPumpStartReason == PumpStartReason::HEATING && millis() - heatingDisabledTime > (settings.externalPump.postCirculationTime * 1000u)) { + vars.externalPump.state = false; + vars.externalPump.lastEnabledTime = now; + + ESP_LOGI(L_EXTPUMP, "Disabled: expired post circulation time"); + + } else if (extPumpStartReason == PumpStartReason::ANTISTUCK && millis() - externalPumpStartTime >= (settings.externalPump.antiStuckTime * 1000u)) { + vars.externalPump.state = false; + vars.externalPump.lastEnabledTime = now; + + ESP_LOGI(L_EXTPUMP, "Disabled: expired anti stuck time"); + } + + } else if (vars.externalPump.state && heatingEnabled && extPumpStartReason == PumpStartReason::ANTISTUCK) { + extPumpStartReason = PumpStartReason::HEATING; + + } else if (!vars.externalPump.state && heatingEnabled) { + vars.externalPump.state = true; + externalPumpStartTime = millis(); + extPumpStartReason = PumpStartReason::HEATING; + + ESP_LOGI(L_EXTPUMP, "Enabled: heating on"); + + } else if (!vars.externalPump.state && (vars.externalPump.lastEnabledTime == 0 || now - vars.externalPump.lastEnabledTime >= settings.externalPump.antiStuckInterval)) { + vars.externalPump.state = true; + externalPumpStartTime = millis(); + extPumpStartReason = PumpStartReason::ANTISTUCK; + + ESP_LOGI(L_EXTPUMP, "Enabled: anti stuck"); + } + + digitalWrite( + configuredGpio, + (vars.externalPump.state ^ settings.externalPump.invertState) ? HIGH : LOW + ); +}); + +void initControl() { + overheatProtectionTask.setEnabledWhen([] { + return vars.slave.connected; + }); + + appTaskManager.addTask(freezeProtectionTask.setInterval(1000)); + appTaskManager.addTask(emergencyTask.setInterval(1000)); + appTaskManager.addTask(overheatProtectionTask.setInterval(1000)); + appTaskManager.addTask(cascadeTask.setInterval(1000)); + appTaskManager.addTask(externalPumpTask.setInterval(1000)); +} diff --git a/src/ha_discovery.cpp b/src/ha_discovery.cpp new file mode 100644 index 0000000..59aaaf0 --- /dev/null +++ b/src/ha_discovery.cpp @@ -0,0 +1,1187 @@ +#include + +std::unique_ptr haDiscovery; + +bool publishHaEntity(HaEntity entityId, bool remove) { + std::unique_ptr entity; + const UnitSystem unit = settings.system.unitSystem; + const uint32_t stateExpiration = 2u * settings.mqtt.interval; + + switch (entityId) { + case HA_ENTITY_HEATING_TURBO: { + auto toggle = std::make_unique("heating_turbo", "Turbo heating"); + if (!remove) { + toggle->stateTopic = "~/settings/heating/turbo"; + toggle->commandTopic = toggle->stateTopic + "/set"; + toggle->category = HA::Category::CONFIG; + toggle->payloadOn = S_TRUE; + toggle->payloadOff = S_FALSE; + toggle->icon = "mdi:rocket-launch-outline"; + toggle->enabledByDefault = false; + } + entity = std::move(toggle); + break; + } + + case HA_ENTITY_HEATING_HYSTERESIS_ENABLED: { + auto toggle = std::make_unique("heating_hysteresis", "Use heating hysteresis"); + if (!remove) { + toggle->stateTopic = "~/settings/heating/hysteresis/enabled"; + toggle->commandTopic = toggle->stateTopic + "/set"; + toggle->category = HA::Category::CONFIG; + toggle->payloadOn = S_TRUE; + toggle->payloadOff = S_FALSE; + toggle->icon = "mdi:altimeter"; + toggle->enabledByDefault = true; + } + entity = std::move(toggle); + break; + } + + case HA_ENTITY_HEATING_HYSTERESIS_VALUE: { + auto number = std::make_unique("heating_hysteresis", "Heating hysteresis"); + if (!remove) { + number->stateTopic = "~/settings/heating/hysteresis/value"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = 0.05f; + number->max = 15; + number->step = 0.01f; + number->icon = "mdi:altimeter"; + number->enabledByDefault = true; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_HEATING_TURBO_FACTOR: { + auto number = std::make_unique("heating_turbo_factor", "Heating turbo factor"); + if (!remove) { + number->stateTopic = "~/settings/heating/turbo_factor"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = 1.5f; + number->max = 10; + number->step = 0.001f; + number->icon = "mdi:multiplication-box"; + number->enabledByDefault = false; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_HEATING_MIN_TEMP: { + auto number = std::make_unique("heating_min_temp", "Heating min temp"); + if (!remove) { + number->stateTopic = "~/settings/heating/min_temp"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = convertTemp(vars.slave.heating.minTemp, UnitSystem::METRIC, unit); + number->max = convertTemp(vars.slave.heating.maxTemp - 1.0f, UnitSystem::METRIC, unit); + if (unit == UnitSystem::METRIC) { + number->unit = "°C"; + number->step = 1.0f; + + } else if (unit == UnitSystem::IMPERIAL) { + number->unit = "°F"; + number->step = 0.1f; + } + number->icon = "mdi:thermometer-chevron-down"; + number->deviceClass = S_TEMPERATURE; + number->enabledByDefault = true; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_HEATING_MAX_TEMP: { + auto number = std::make_unique("heating_max_temp", "Heating max temp"); + if (!remove) { + number->stateTopic = "~/settings/heating/max_temp"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = convertTemp(vars.slave.heating.minTemp + 1.0f, UnitSystem::METRIC, unit); + number->max = convertTemp(vars.slave.heating.maxTemp, UnitSystem::METRIC, unit); + if (unit == UnitSystem::METRIC) { + number->unit = "°C"; + number->step = 1.0f; + + } else if (unit == UnitSystem::IMPERIAL) { + number->unit = "°F"; + number->step = 0.1f; + } + number->icon = "mdi:thermometer-chevron-up"; + number->deviceClass = S_TEMPERATURE; + number->enabledByDefault = true; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_PID_ENABLED: { + auto toggle = std::make_unique("pid", "PID"); + if (!remove) { + toggle->stateTopic = "~/settings/pid/enabled"; + toggle->commandTopic = toggle->stateTopic + "/set"; + toggle->category = HA::Category::CONFIG; + toggle->payloadOn = S_TRUE; + toggle->payloadOff = S_FALSE; + toggle->icon = "mdi:chart-bar-stacked"; + toggle->enabledByDefault = true; + } + entity = std::move(toggle); + break; + } + + case HA_ENTITY_PID_P_FACTOR: { + auto number = std::make_unique("pid_p_factor", "PID factor P"); + if (!remove) { + number->stateTopic = "~/settings/pid/p_factor"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = 0; + number->max = 1000; + number->step = 0.001f; + number->icon = "mdi:alpha-p-circle-outline"; + number->enabledByDefault = false; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_PID_I_FACTOR: { + auto number = std::make_unique("pid_i_factor", "PID factor I"); + if (!remove) { + number->stateTopic = "~/settings/pid/i_factor"; + number->commandTopic = number->stateTopic + "/set"; + // Home Assistant requires a Number step of at least 0.001. + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = 0; + number->max = 100; + number->step = 0.001f; + number->icon = "mdi:alpha-i-circle-outline"; + number->enabledByDefault = false; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_PID_D_FACTOR: { + auto number = std::make_unique("pid_d_factor", "PID factor D"); + if (!remove) { + number->stateTopic = "~/settings/pid/d_factor"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = 0; + number->max = 100000; + number->step = 0.1f; + number->icon = "mdi:alpha-d-circle-outline"; + number->enabledByDefault = false; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_PID_DT: { + auto number = std::make_unique("pid_dt", "PID DT"); + if (!remove) { + number->stateTopic = "~/settings/pid/dt"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = 30; + number->max = 1800; + number->step = 1; + number->icon = "mdi:timer-cog-outline"; + number->enabledByDefault = false; + number->deviceClass = "duration"; + number->unit = "s"; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_PID_MIN_TEMP: { + auto number = std::make_unique("pid_min_temp", "PID min temp"); + if (!remove) { + number->stateTopic = "~/settings/pid/min_temp"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = settings.equitherm.enabled + ? -99.0f + : convertTemp(0, UnitSystem::METRIC, unit); + number->max = settings.equitherm.enabled + ? 99.0f + : convertTemp(99, UnitSystem::METRIC, unit); + if (unit == UnitSystem::METRIC) { + number->unit = "°C"; + number->step = 1.0f; + + } else if (unit == UnitSystem::IMPERIAL) { + number->unit = "°F"; + number->step = settings.equitherm.enabled ? 1.0f : 0.1f; + } + number->icon = "mdi:thermometer-chevron-down"; + number->enabledByDefault = false; + number->deviceClass = S_TEMPERATURE; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_PID_MAX_TEMP: { + auto number = std::make_unique("pid_max_temp", "PID max temp"); + if (!remove) { + number->stateTopic = "~/settings/pid/max_temp"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = settings.equitherm.enabled + ? 1.0f + : convertTemp(1, UnitSystem::METRIC, unit); + number->max = settings.equitherm.enabled + ? 99.0f + : convertTemp(99, UnitSystem::METRIC, unit); + if (unit == UnitSystem::METRIC) { + number->unit = "°C"; + number->step = 1.0f; + + } else if (unit == UnitSystem::IMPERIAL) { + number->unit = "°F"; + number->step = settings.equitherm.enabled ? 1.0f : 0.1f; + } + number->icon = "mdi:thermometer-chevron-up"; + number->enabledByDefault = false; + number->deviceClass = S_TEMPERATURE; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_EQUITHERM_ENABLED: { + auto toggle = std::make_unique("equitherm", "Equitherm"); + if (!remove) { + toggle->stateTopic = "~/settings/equitherm/enabled"; + toggle->commandTopic = toggle->stateTopic + "/set"; + toggle->category = HA::Category::CONFIG; + toggle->payloadOn = S_TRUE; + toggle->payloadOff = S_FALSE; + toggle->icon = "mdi:sun-snowflake-variant"; + toggle->enabledByDefault = true; + } + entity = std::move(toggle); + break; + } + + case HA_ENTITY_EQUITHERM_SLOPE: { + auto number = std::make_unique("equitherm_slope", "Equitherm slope"); + if (!remove) { + number->stateTopic = "~/settings/equitherm/slope"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = 0.001f; + number->max = 10; + number->step = 0.001f; + number->icon = "mdi:slope-uphill"; + number->enabledByDefault = false; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_EQUITHERM_EXPONENT: { + auto number = std::make_unique("equitherm_exponent", "Equitherm exponent"); + if (!remove) { + number->stateTopic = "~/settings/equitherm/exponent"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = 0.2f; + number->max = 2; + number->step = 0.001f; + number->icon = "mdi:exponent"; + number->enabledByDefault = false; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_EQUITHERM_SHIFT: { + auto number = std::make_unique("equitherm_shift", "Equitherm shift"); + if (!remove) { + number->stateTopic = "~/settings/equitherm/shift"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = -15; + number->max = 15; + number->step = 0.01f; + number->icon = "mdi:chart-areaspline"; + number->enabledByDefault = false; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_EQUITHERM_TARGET_DIFF_FACTOR: { + auto number = std::make_unique("equitherm_target_diff_factor", "Equitherm target diff factor"); + if (!remove) { + number->stateTopic = "~/settings/equitherm/target_diff_factor"; + number->commandTopic = number->stateTopic + "/set"; + number->availabilityTopic = "~/settings/pid/enabled"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = 0; + number->max = 10; + number->step = 0.001f; + number->icon = "mdi:chart-timeline-variant-shimmer"; + number->enabledByDefault = false; + number->payloadAvailable = S_FALSE; + number->payloadNotAvailable = S_TRUE; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_STATUS: { + auto state = std::make_unique("status", "Status"); + if (!remove) { + state->stateTopic = "~/status"; + state->category = HA::Category::DIAGNOSTIC; + state->payloadOn = "ON"; + state->payloadOff = "OFF"; + state->deviceClass = "problem"; + state->icon = "mdi:list-status"; + state->useDeviceAvailability = false; + state->valueTemplate = "{{ iif(value == 'online', 'OFF', 'ON') }}"; + state->expireAfter = stateExpiration; + state->enabledByDefault = true; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_EMERGENCY: { + auto state = std::make_unique("emergency", "Emergency"); + if (!remove) { + state->stateTopic = "~/state/master/emergency/state"; + state->category = HA::Category::DIAGNOSTIC; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->deviceClass = "problem"; + state->icon = "mdi:alert-rhombus-outline"; + state->enabledByDefault = true; + state->expireAfter = stateExpiration; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_OPENTHERM_STATUS: { + auto state = std::make_unique("ot_status", "Opentherm status"); + if (!remove) { + state->stateTopic = "~/state/slave/connected"; + state->category = HA::Category::DIAGNOSTIC; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->deviceClass = "connectivity"; + state->icon = "mdi:list-status"; + state->enabledByDefault = true; + state->expireAfter = stateExpiration; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_HEATING: { + auto state = std::make_unique("heating", "Heating"); + if (!remove) { + state->stateTopic = "~/state/slave/heating/active"; + state->availabilityTopic = "~/state/slave/connected"; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->deviceClass = "running"; + state->icon = "mdi:radiator"; + state->enabledByDefault = true; + state->expireAfter = stateExpiration; + state->payloadAvailable = S_TRUE; + state->payloadNotAvailable = S_FALSE; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_FLAME: { + auto state = std::make_unique("flame", "Flame"); + if (!remove) { + state->stateTopic = "~/state/slave/flame"; + state->availabilityTopic = "~/state/slave/connected"; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->deviceClass = "running"; + state->icon = "mdi:gas-burner"; + state->enabledByDefault = true; + state->expireAfter = stateExpiration; + state->payloadAvailable = S_TRUE; + state->payloadNotAvailable = S_FALSE; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_FAULT: { + auto state = std::make_unique("fault", "Fault"); + if (!remove) { + state->stateTopic = "~/state/slave/fault/active"; + state->availabilityTopic = "~/state/slave/connected"; + state->category = HA::Category::DIAGNOSTIC; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->deviceClass = "problem"; + state->icon = "mdi:alert-remove-outline"; + state->enabledByDefault = true; + state->expireAfter = stateExpiration; + state->payloadAvailable = S_TRUE; + state->payloadNotAvailable = S_FALSE; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_DIAGNOSTIC: { + auto state = std::make_unique("diagnostic", "Diagnostic"); + if (!remove) { + state->stateTopic = "~/state/slave/diag/active"; + state->availabilityTopic = "~/state/slave/connected"; + state->category = HA::Category::DIAGNOSTIC; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->deviceClass = "problem"; + state->icon = "mdi:account-wrench"; + state->enabledByDefault = true; + state->expireAfter = stateExpiration; + state->payloadAvailable = S_TRUE; + state->payloadNotAvailable = S_FALSE; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_EXTERNAL_PUMP: { + auto state = std::make_unique("ext_pump", "External pump"); + if (!remove) { + state->stateTopic = "~/state/master/ext_pump/state"; + state->category = HA::Category::DIAGNOSTIC; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->deviceClass = "running"; + state->icon = "mdi:pump"; + state->enabledByDefault = false; + state->expireAfter = stateExpiration; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_FAULT_CODE: { + auto value = std::make_unique("fault_code", "Fault code"); + if (!remove) { + value->stateTopic = "~/state/slave/fault/code"; + value->availabilityTopic = "~/state/slave/fault/active"; + value->category = HA::Category::DIAGNOSTIC; + value->icon = "mdi:cog-box"; + value->valueTemplate = "{{ '%02d (0x%02X)' | format(value | int, value | int) }}"; + value->enabledByDefault = true; + value->expireAfter = stateExpiration; + value->payloadAvailable = S_TRUE; + value->payloadNotAvailable = S_FALSE; + } + entity = std::move(value); + break; + } + + case HA_ENTITY_DIAGNOSTIC_CODE: { + auto value = std::make_unique("diagnostic_code", "Diagnostic code"); + if (!remove) { + value->stateTopic = "~/state/slave/diag/code"; + value->availabilityTopic = "~/state/slave/diag/active"; + value->category = HA::Category::DIAGNOSTIC; + value->icon = "mdi:information-box"; + value->valueTemplate = "{{ '%02d (0x%02X)' | format(value | int, value | int) }}"; + value->enabledByDefault = true; + value->expireAfter = stateExpiration; + value->payloadAvailable = S_TRUE; + value->payloadNotAvailable = S_FALSE; + } + entity = std::move(value); + break; + } + + case HA_ENTITY_RSSI: { + auto gauge = std::make_unique("rssi", "RSSI"); + if (!remove) { + gauge->stateTopic = "~/state/master/network/rssi"; + gauge->availabilityTopic = gauge->stateTopic; + gauge->availabilityTemplate = "{{ 'online' if value | int(0) < 0 else 'offline' }}"; + gauge->category = HA::Category::DIAGNOSTIC; + gauge->deviceClass = "signal_strength"; + gauge->icon = "mdi:signal"; + gauge->unit = "dBm"; + gauge->enabledByDefault = false; + gauge->expireAfter = stateExpiration; + } + entity = std::move(gauge); + break; + } + + case HA_ENTITY_UPTIME: { + auto counter = std::make_unique("uptime", "Uptime"); + if (!remove) { + counter->stateTopic = "~/state/master/uptime"; + counter->category = HA::Category::DIAGNOSTIC; + counter->deviceClass = "duration"; + counter->icon = "mdi:clock-start"; + counter->unit = "s"; + counter->enabledByDefault = false; + counter->expireAfter = stateExpiration; + } + entity = std::move(counter); + break; + } + + case HA_ENTITY_RESTART: { + auto button = std::make_unique("restart", "Restart"); + if (!remove) { + button->commandTopic = "~/actions/restart/set"; + button->category = HA::Category::CONFIG; + button->deviceClass = "restart"; + button->payloadPress = S_TRUE; + button->enabledByDefault = false; + } + entity = std::move(button); + break; + } + + case HA_ENTITY_RESET_FAULT: { + auto button = std::make_unique("reset_fault", "Reset fault"); + if (!remove) { + button->commandTopic = "~/actions/reset_fault/set"; + button->availabilityTopic = "~/state/slave/fault/active"; + button->category = HA::Category::CONFIG; + button->deviceClass = "restart"; + button->payloadPress = S_TRUE; + button->enabledByDefault = true; + button->payloadAvailable = S_TRUE; + button->payloadNotAvailable = S_FALSE; + } + entity = std::move(button); + break; + } + + case HA_ENTITY_RESET_DIAGNOSTIC: { + auto button = std::make_unique("reset_diagnostic", "Reset diagnostic"); + if (!remove) { + button->commandTopic = "~/actions/reset_diagnostic/set"; + button->availabilityTopic = "~/state/slave/diag/active"; + button->category = HA::Category::CONFIG; + button->deviceClass = "restart"; + button->payloadPress = S_TRUE; + button->enabledByDefault = true; + button->payloadAvailable = S_TRUE; + button->payloadNotAvailable = S_FALSE; + } + entity = std::move(button); + break; + } + + case HA_ENTITY_HEATING_CLIMATE: { + auto climate = std::make_unique("heating", "Heating"); + if (!remove) { + climate->icon = "mdi:radiator"; + climate->enabledByDefault = true; + climate->currentTemperatureTopic = vars.master.heating.smartControl + ? "~/state/master/heating/indoor_temp" + : "~/state/master/heating/current_temp"; + climate->temperatureCommandTopic = "~/settings/heating/target/set"; + climate->temperatureStateTopic = "~/settings/heating/target"; + climate->modeCommandTopic = "~/settings/heating/enabled/set"; + climate->modeCommandTemplate = "{% if value == 'heat' %}true{% elif value == 'off' %}false{% endif %}"; + climate->modeStateTopic = "~/settings/heating/enabled"; + climate->modeStateTemplate = "{{ 'heat' if value == 'true' else 'off' }}"; + climate->modes = {"off", "heat"}; + climate->actionTopic = "~/state/slave/heating/active"; + climate->actionTemplate = "{{ 'heating' if value == 'true' else 'idle' }}"; + climate->presetModeCommandTopic = "~/settings/heating/turbo/set"; + climate->presetModeCommandTemplate = "{% if value == 'boost' %}true{% elif value == 'none' %}false{% endif %}"; + climate->presetModeStateTopic = "~/settings/heating/turbo"; + climate->presetModeValueTemplate = "{{ 'boost' if value == 'true' else 'none' }}"; + // Home Assistant adds the reserved reset preset "none" itself. + climate->presetModes = {"boost"}; + if (unit == UnitSystem::METRIC) { + climate->temperatureUnit = "C"; + + } else if (unit == UnitSystem::IMPERIAL) { + climate->temperatureUnit = "F"; + } + climate->minTemp = convertTemp(vars.master.heating.minTemp, UnitSystem::METRIC, unit); + climate->maxTemp = convertTemp(vars.master.heating.maxTemp, UnitSystem::METRIC, unit); + climate->tempStep = 0.1f; + } + entity = std::move(climate); + break; + } + + case HA_ENTITY_DHW_MIN_TEMP: { + remove = remove || !settings.opentherm.options.dhwSupport; + auto number = std::make_unique("dhw_min_temp", "DHW min temp"); + if (!remove) { + number->stateTopic = "~/settings/dhw/min_temp"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = convertTemp(vars.slave.dhw.minTemp, UnitSystem::METRIC, unit); + number->max = convertTemp(vars.slave.dhw.maxTemp - 1.0f, UnitSystem::METRIC, unit); + if (unit == UnitSystem::METRIC) { + number->unit = "°C"; + number->step = 1.0f; + + } else if (unit == UnitSystem::IMPERIAL) { + number->unit = "°F"; + number->step = 0.1f; + } + number->icon = "mdi:thermometer-chevron-down"; + number->enabledByDefault = true; + number->deviceClass = S_TEMPERATURE; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_DHW_MAX_TEMP: { + remove = remove || !settings.opentherm.options.dhwSupport; + auto number = std::make_unique("dhw_max_temp", "DHW max temp"); + if (!remove) { + number->stateTopic = "~/settings/dhw/max_temp"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = convertTemp(vars.slave.dhw.minTemp + 1.0f, UnitSystem::METRIC, unit); + number->max = convertTemp(vars.slave.dhw.maxTemp, UnitSystem::METRIC, unit); + if (unit == UnitSystem::METRIC) { + number->unit = "°C"; + number->step = 1.0f; + + } else if (unit == UnitSystem::IMPERIAL) { + number->unit = "°F"; + number->step = 0.1f; + } + number->icon = "mdi:thermometer-chevron-up"; + number->enabledByDefault = true; + number->deviceClass = S_TEMPERATURE; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_DHW: { + remove = remove || !settings.opentherm.options.dhwSupport; + auto state = std::make_unique("dhw", "DHW"); + if (!remove) { + state->stateTopic = "~/state/slave/dhw/active"; + state->availabilityTopic = "~/state/slave/connected"; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->deviceClass = "running"; + state->icon = "mdi:faucet"; + state->enabledByDefault = true; + state->expireAfter = stateExpiration; + state->payloadAvailable = S_TRUE; + state->payloadNotAvailable = S_FALSE; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_DHW_CLIMATE: { + remove = remove || !settings.opentherm.options.dhwSupport; + auto climate = std::make_unique("dhw", "DHW"); + if (!remove) { + climate->icon = "mdi:faucet"; + climate->enabledByDefault = true; + climate->currentTemperatureTopic = "~/state/master/dhw/current_temp"; + climate->temperatureCommandTopic = "~/settings/dhw/target/set"; + climate->temperatureStateTopic = "~/settings/dhw/target"; + climate->modeCommandTopic = "~/settings/dhw/enabled/set"; + climate->modeCommandTemplate = "{% if value == 'heat' %}true{% elif value == 'off' %}false{% endif %}"; + climate->modeStateTopic = "~/settings/dhw/enabled"; + climate->modeStateTemplate = "{{ 'heat' if value == 'true' else 'off' }}"; + climate->modes = {"off", "heat"}; + climate->actionTopic = "~/state/slave/dhw/active"; + climate->actionTemplate = "{{ 'heating' if value == 'true' else 'idle' }}"; + if (unit == UnitSystem::METRIC) { + climate->temperatureUnit = "C"; + + } else if (unit == UnitSystem::IMPERIAL) { + climate->temperatureUnit = "F"; + } + climate->minTemp = convertTemp(settings.dhw.minTemp, UnitSystem::METRIC, unit); + climate->maxTemp = convertTemp(settings.dhw.maxTemp, UnitSystem::METRIC, unit); + climate->tempStep = 0.1f; + } + entity = std::move(climate); + break; + } + + case HA_ENTITY_HEATING_BLOCKING: { + auto state = std::make_unique("heating_blocking", "Heating blocking"); + if (!remove) { + state->stateTopic = "~/state/master/heating/blocking"; + state->category = HA::Category::DIAGNOSTIC; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->icon = "mdi:radiator-off"; + state->enabledByDefault = false; + state->expireAfter = stateExpiration; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_HEATING_OVERHEAT: { + auto state = std::make_unique("heating_overheat", "Heating overheat"); + if (!remove) { + state->stateTopic = "~/state/master/heating/overheat"; + state->category = HA::Category::DIAGNOSTIC; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->deviceClass = "problem"; + state->icon = "mdi:thermometer-alert"; + state->enabledByDefault = false; + state->expireAfter = stateExpiration; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_HEATING_FREEZING: { + auto state = std::make_unique("heating_freezing", "Heating freezing"); + if (!remove) { + state->stateTopic = "~/state/master/heating/freezing"; + state->category = HA::Category::DIAGNOSTIC; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->icon = "mdi:snowflake"; + state->enabledByDefault = false; + state->expireAfter = stateExpiration; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_DHW_OVERHEAT: { + remove = remove || !settings.opentherm.options.dhwSupport; + auto state = std::make_unique("dhw_overheat", "DHW overheat"); + if (!remove) { + state->stateTopic = "~/state/master/dhw/overheat"; + state->category = HA::Category::DIAGNOSTIC; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->deviceClass = "problem"; + state->icon = "mdi:thermometer-alert"; + state->enabledByDefault = false; + state->expireAfter = stateExpiration; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_CASCADE_CONTROL_INPUT: { + auto state = std::make_unique("cascade_control_input", "Cascade control input"); + if (!remove) { + state->stateTopic = "~/state/master/cascade_control/input"; + state->category = HA::Category::DIAGNOSTIC; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->icon = "mdi:import"; + state->enabledByDefault = false; + state->expireAfter = stateExpiration; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_CASCADE_CONTROL_OUTPUT: { + auto state = std::make_unique("cascade_control_output", "Cascade control output"); + if (!remove) { + state->stateTopic = "~/state/master/cascade_control/output"; + state->category = HA::Category::DIAGNOSTIC; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->icon = "mdi:export"; + state->enabledByDefault = false; + state->expireAfter = stateExpiration; + } + entity = std::move(state); + break; + } + + default: { + return false; + } + } + + if (remove) { + return haDiscovery->unpublish(std::move(entity)) == HA::Error::SUCCESS; + + } else { + return haDiscovery->publish(std::move(entity)) == HA::Error::SUCCESS; + } +} + +static std::string makeDynamicSensorId(const Sensors::Settings& sensor, Sensors::ValueType valueType) { + std::string id = sensor.slug; + if (id.empty()) { + return {}; + } + const bool multiple = sensor.type == Sensors::Type::BLUETOOTH || sensor.type == Sensors::Type::DHT11 || sensor.type == Sensors::Type::DHT22; + if (!multiple) { + return valueType == Sensors::ValueType::PRIMARY ? id : std::string(); + } + + switch (valueType) { + case Sensors::ValueType::TEMPERATURE: + return id + "_temp"; + case Sensors::ValueType::HUMIDITY: + return id + "_humidity"; + case Sensors::ValueType::BATTERY: + return id + "_battery"; + case Sensors::ValueType::RSSI: + return id + "_rssi"; + default: + return {}; + } +} + +static const char* getDynamicSensorIcon(Sensors::Purpose purpose) { + switch (purpose) { + case Sensors::Purpose::OUTDOOR_TEMP: + return "mdi:home-thermometer-outline"; + case Sensors::Purpose::INDOOR_TEMP: + return "mdi:home-thermometer"; + case Sensors::Purpose::HEATING_TEMP: + return "mdi:radiator"; + case Sensors::Purpose::HEATING_RETURN_TEMP: + case Sensors::Purpose::DHW_RETURN_TEMP: + return "mdi:heating-coil"; + case Sensors::Purpose::DHW_TEMP: + case Sensors::Purpose::DHW_FLOW_RATE: + return "mdi:faucet"; + case Sensors::Purpose::EXHAUST_TEMP: + return "mdi:smoke"; + case Sensors::Purpose::TEMPERATURE: + return "mdi:thermometer-lines"; + case Sensors::Purpose::MODULATION_LEVEL: + return "mdi:fire-circle"; + case Sensors::Purpose::POWER_FACTOR: + case Sensors::Purpose::POWER: + return "mdi:chart-bar"; + case Sensors::Purpose::FAN_SPEED: + return "mdi:fan"; + case Sensors::Purpose::PRESSURE: + return "mdi:gauge"; + case Sensors::Purpose::HUMIDITY: + return "mdi:water-percent"; + default: + return nullptr; + } +} + +void publishDynamicSensor(const Sensors::Settings& sensor, Sensors::ValueType valueType, bool enabledByDefault) { + #if !USE_BLE + if (sensor.type == Sensors::Type::BLUETOOTH) { + return; + } + #endif + + auto id = makeDynamicSensorId(sensor, valueType); + if (id.empty()) { + return; + } + + const UnitSystem unit = settings.system.unitSystem; + auto entity = std::make_unique(std::move(id), sensor.name); + entity->icon = getDynamicSensorIcon(sensor.purpose); + entity->availabilityTopic = mqttTopic(S_SENSORS, sensor.slug, S_CONNECTED); + entity->payloadAvailable = S_TRUE; + entity->payloadNotAvailable = S_FALSE; + entity->expireAfter = 2u * MQTT_SENSOR_REPUBLISH_INTERVAL / 1000u; + entity->enabledByDefault = enabledByDefault; + + switch (sensor.purpose) { + case Sensors::Purpose::OUTDOOR_TEMP: + case Sensors::Purpose::INDOOR_TEMP: + case Sensors::Purpose::HEATING_TEMP: + case Sensors::Purpose::HEATING_RETURN_TEMP: + case Sensors::Purpose::DHW_TEMP: + case Sensors::Purpose::DHW_RETURN_TEMP: + case Sensors::Purpose::EXHAUST_TEMP: + case Sensors::Purpose::TEMPERATURE: + entity->deviceClass = S_TEMPERATURE; + if (unit == UnitSystem::METRIC) { + entity->unit = "°C"; + + } else if (unit == UnitSystem::IMPERIAL) { + entity->unit = "°F"; + } + break; + + case Sensors::Purpose::DHW_FLOW_RATE: + entity->deviceClass = "volume_flow_rate"; + if (unit == UnitSystem::METRIC) { + entity->unit = "L/min"; + + } else if (unit == UnitSystem::IMPERIAL) { + entity->unit = "gal/min"; + } + break; + + case Sensors::Purpose::MODULATION_LEVEL: + case Sensors::Purpose::POWER_FACTOR: + entity->deviceClass = "power_factor"; + entity->unit = "%"; + break; + + case Sensors::Purpose::POWER: + entity->deviceClass = "power"; + entity->unit = "kW"; + break; + + case Sensors::Purpose::FAN_SPEED: + entity->unit = "RPM"; + break; + + case Sensors::Purpose::CO2: + entity->deviceClass = "carbon_dioxide"; + entity->unit = "ppm"; + break; + + case Sensors::Purpose::PRESSURE: + entity->deviceClass = "pressure"; + if (unit == UnitSystem::METRIC) { + entity->unit = "bar"; + + } else if (unit == UnitSystem::IMPERIAL) { + entity->unit = "psi"; + } + break; + + case Sensors::Purpose::HUMIDITY: + entity->deviceClass = S_HUMIDITY; + entity->unit = "%"; + break; + + default: + break; + } + + if (sensor.type == Sensors::Type::BLUETOOTH || sensor.type == Sensors::Type::DHT11 || sensor.type == Sensors::Type::DHT22) { + switch (valueType) { + case Sensors::ValueType::TEMPERATURE: + entity->name += " "; + entity->name += S_TEMPERATURE; + entity->stateTopic = mqttTopic(S_SENSORS, sensor.slug, S_TEMPERATURE); + entity->deviceClass = S_TEMPERATURE; + if (unit == UnitSystem::METRIC) { + entity->unit = "°C"; + + } else if (unit == UnitSystem::IMPERIAL) { + entity->unit = "°F"; + } + break; + + case Sensors::ValueType::HUMIDITY: + entity->name += " "; + entity->name += S_HUMIDITY; + entity->stateTopic = mqttTopic(S_SENSORS, sensor.slug, S_HUMIDITY); + entity->deviceClass = S_HUMIDITY; + entity->unit = "%"; + break; + + case Sensors::ValueType::BATTERY: + entity->name += " "; + entity->name += S_BATTERY; + entity->stateTopic = mqttTopic(S_SENSORS, sensor.slug, S_BATTERY); + entity->deviceClass = S_BATTERY; + entity->unit = "%"; + entity->category = HA::Category::DIAGNOSTIC; + break; + + case Sensors::ValueType::RSSI: + entity->name += " "; + entity->name += S_RSSI; + entity->stateTopic = mqttTopic(S_SENSORS, sensor.slug, S_RSSI); + entity->deviceClass = "signal_strength"; + entity->unit = "dBm"; + entity->category = HA::Category::DIAGNOSTIC; + break; + + default: + return; + } + + } else { + entity->stateTopic = mqttTopic(S_SENSORS, sensor.slug, S_VALUE); + } + + haDiscovery->publish(std::move(entity)); +} + +void publishDynamicManualSensor(const Sensors::Settings& sensor, bool enabledByDefault) { + auto id = makeDynamicSensorId(sensor, Sensors::ValueType::PRIMARY); + if (id.empty()) { + return; + } + + const UnitSystem unit = settings.system.unitSystem; + auto entity = std::make_unique(std::move(id), sensor.name); + entity->icon = getDynamicSensorIcon(sensor.purpose); + entity->category = HA::Category::CONFIG; + entity->enabledByDefault = enabledByDefault; + entity->stateTopic = mqttTopic(S_SENSORS, sensor.slug, S_VALUE); + entity->commandTopic = entity->stateTopic + "/set"; + entity->mode = HA::NumberMode::BOX; + entity->step = 0.01f; + entity->min.reset(); + entity->max.reset(); + + switch (sensor.purpose) { + case Sensors::Purpose::OUTDOOR_TEMP: + case Sensors::Purpose::INDOOR_TEMP: + case Sensors::Purpose::HEATING_TEMP: + case Sensors::Purpose::HEATING_RETURN_TEMP: + case Sensors::Purpose::DHW_TEMP: + case Sensors::Purpose::DHW_RETURN_TEMP: + case Sensors::Purpose::EXHAUST_TEMP: + case Sensors::Purpose::TEMPERATURE: + entity->deviceClass = S_TEMPERATURE; + if (unit == UnitSystem::METRIC) { + entity->unit = "°C"; + entity->min = -99; + entity->max = 99; + + } else if (unit == UnitSystem::IMPERIAL) { + entity->unit = "°F"; + entity->min = -147; + entity->max = 211; + } + break; + + case Sensors::Purpose::DHW_FLOW_RATE: + entity->deviceClass = "volume_flow_rate"; + if (unit == UnitSystem::METRIC) { + entity->unit = "L/min"; + + } else if (unit == UnitSystem::IMPERIAL) { + entity->unit = "gal/min"; + } + break; + + case Sensors::Purpose::MODULATION_LEVEL: + case Sensors::Purpose::POWER_FACTOR: + entity->deviceClass = "power_factor"; + entity->unit = "%"; + break; + + case Sensors::Purpose::POWER: + entity->deviceClass = "power"; + entity->unit = "kW"; + break; + + case Sensors::Purpose::FAN_SPEED: + entity->unit = "RPM"; + break; + + case Sensors::Purpose::CO2: + entity->deviceClass = "carbon_dioxide"; + entity->unit = "ppm"; + break; + + case Sensors::Purpose::PRESSURE: + entity->deviceClass = "pressure"; + if (unit == UnitSystem::METRIC) { + entity->unit = "bar"; + + } else if (unit == UnitSystem::IMPERIAL) { + entity->unit = "psi"; + } + break; + + case Sensors::Purpose::HUMIDITY: + entity->deviceClass = S_HUMIDITY; + entity->unit = "%"; + break; + + default: + break; + } + + haDiscovery->publish(std::move(entity)); +} + +void deleteDynamicSensor(const Sensors::Settings& sensor, Sensors::ValueType valueType) { + auto id = makeDynamicSensorId(sensor, valueType); + if (id.empty()) { + return; + } + + if (sensor.type == Sensors::Type::MANUAL) { + haDiscovery->unpublish(std::move(id), ""); + return; + } + + haDiscovery->unpublish(std::move(id), ""); +} + +void publishConnectionDynamicSensor(const Sensors::Settings& sensor, bool enabledByDefault) { + auto entity = std::make_unique( + std::string(sensor.slug) + "_connected", std::string(sensor.name) + " connected" + ); + entity->category = HA::Category::DIAGNOSTIC; + entity->deviceClass = "connectivity"; + entity->stateTopic = mqttTopic(S_SENSORS, sensor.slug, S_CONNECTED); + entity->payloadOn = S_TRUE; + entity->payloadOff = S_FALSE; + entity->enabledByDefault = enabledByDefault; + entity->expireAfter = 2u * MQTT_SENSOR_REPUBLISH_INTERVAL / 1000u; + haDiscovery->publish(std::move(entity)); +} + +void deleteConnectionDynamicSensor(const Sensors::Settings& sensor) { + haDiscovery->unpublish(std::string(sensor.slug) + "_connected", ""); +} + +void publishSignalQualityDynamicSensor(const Sensors::Settings& sensor, bool enabledByDefault) { + auto entity = std::make_unique( + std::string(sensor.slug) + "_signal_quality", std::string(sensor.name) + " signal quality" + ); + entity->category = HA::Category::DIAGNOSTIC; + entity->stateTopic = mqttTopic(S_SENSORS, sensor.slug, S_SIGNAL_QUALITY); + entity->unit = "%"; + entity->icon = "mdi:signal"; + entity->enabledByDefault = enabledByDefault; + entity->expireAfter = 2u * MQTT_SENSOR_REPUBLISH_INTERVAL / 1000u; + haDiscovery->publish(std::move(entity)); +} + +void deleteSignalQualityDynamicSensor(const Sensors::Settings& sensor) { + haDiscovery->unpublish(std::string(sensor.slug) + "_signal_quality", ""); +} diff --git a/src/idf_component.yml b/src/idf_component.yml deleted file mode 100644 index 8f66bbe..0000000 --- a/src/idf_component.yml +++ /dev/null @@ -1,3 +0,0 @@ -dependencies: - idf: ">=5.3.2" - h2zero/esp-nimble-cpp: ">=2.2.1" \ No newline at end of file diff --git a/src/leds.cpp b/src/leds.cpp new file mode 100644 index 0000000..18091d3 --- /dev/null +++ b/src/leds.cpp @@ -0,0 +1,90 @@ +#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE + +#include +#include + +static Blinker blinker; + +static Task ledStatusTask("LED status", [](void*) { + uint8_t errors[4]; + uint8_t errCount = 0; + static uint8_t errPos = 0; + static unsigned long endBlinkTime = 0; + static bool ledOn = false; + static uint8_t configuredGpio = GPIO_IS_NOT_CONFIGURED; + + if (settings.system.statusLedGpio != configuredGpio) { + if (configuredGpio != GPIO_IS_NOT_CONFIGURED) { + digitalWrite(configuredGpio, LOW); + pinMode(configuredGpio, DISABLED); + } + + if (GPIO_IS_VALID_OUTPUT(settings.system.statusLedGpio)) { + configuredGpio = settings.system.statusLedGpio; + pinMode(configuredGpio, OUTPUT); + digitalWrite(configuredGpio, LOW); + blinker.init(configuredGpio); + + } else if (configuredGpio != GPIO_IS_NOT_CONFIGURED) { + configuredGpio = GPIO_IS_NOT_CONFIGURED; + } + } + + if (configuredGpio == GPIO_IS_NOT_CONFIGURED) { + return; + } + + if (!isNetworkConnected()) { + errors[errCount++] = 2; + } + + if (!vars.slave.connected) { + errors[errCount++] = 3; + } + + if (vars.slave.fault.active) { + errors[errCount++] = 4; + } + + if (vars.emergency.state) { + errors[errCount++] = 5; + } + + + if (blinker.ready()) { + endBlinkTime = millis(); + } + + if (!blinker.running() && millis() - endBlinkTime >= 5000) { + if (errCount == 0) { + if (!ledOn) { + digitalWrite(configuredGpio, HIGH); + ledOn = true; + } + + return; + + } else if (ledOn) { + digitalWrite(configuredGpio, LOW); + ledOn = false; + endBlinkTime = millis(); + return; + } + + if (errPos >= errCount) { + errPos = 0; + + // end of error list + blinker.blink(10, 50, 50); + + } else { + blinker.blink(errors[errPos++], 300, 300); + } + } + + blinker.tick(); +}); + +void initLeds() { + systemTaskManager.addTask(ledStatusTask.setInterval(100)); +} diff --git a/src/logging.cpp b/src/logging.cpp new file mode 100644 index 0000000..c3b678c --- /dev/null +++ b/src/logging.cpp @@ -0,0 +1,238 @@ +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +static_assert(CONFIG_LOG_VERSION == 2, "OTGateway requires an SDK built with Log v2"); +static_assert(CONFIG_LOG_DYNAMIC_LEVEL_CONTROL, "Runtime log levels require dynamic level control"); + +static std::atomic loggingQueue{nullptr}; +static std::atomic activeSerial{false}; +static std::atomic activeWebSerial{false}; +static thread_local bool writingOutputs = false; + +// Return the full byte count, like snprintf, so only long records need a second pass. +static size_t formatLogRecord(esp_log_msg_t& message, char* buffer, size_t capacity) { + const auto& options = message.config.opts; + size_t prefixLength = 0; + const char* suffix = ""; + + if (options.require_formatting) { + const auto level = options.log_level; + if (level >= ESP_LOG_MAX) { + return 0; + } + + const char* color = ""; + #if ESP_LOG_SUPPORT_COLOR && !ESP_LOG_COLOR_DISABLED + static const char* const colors[ESP_LOG_MAX] = { + "", LOG_COLOR_E, LOG_COLOR_W, LOG_COLOR_I, LOG_COLOR(LOG_COLOR_CYAN), LOG_COLOR(LOG_COLOR_MAGENTA) + }; + if (!options.dis_color) { + color = colors[level]; + } + #endif + + char timestamp[32] = {}; + if (!options.dis_timestamp) { + esp_log_timestamp_str(false, message.timestamp, timestamp); + } + + int written = snprintf( + buffer, capacity, "%s%s%s%s[%c]%s%s%s ", + options.dis_timestamp ? "" : "[", + timestamp, + options.dis_timestamp ? "" : "]", + color, + "\0EWIDV"[level], + message.tag ? "[" : "", + message.tag ? message.tag : "", + message.tag ? "]" : "" + ); + if (written < 0) { + return 0; + } + + prefixLength = written; + suffix = *color ? LOG_RESET_COLOR "\n" : "\n"; + } + + size_t offset = std::min(prefixLength, capacity - 1); + va_list args; + va_copy(args, message.args); + int bodyLength = vsnprintf(buffer + offset, capacity - offset, message.format, args); + va_end(args); + if (bodyLength < 0) { + return 0; + } + + size_t suffixOffset = prefixLength + bodyLength; + size_t length = suffixOffset + strlen(suffix); + if (length < capacity) { + memcpy(buffer + suffixOffset, suffix, length - suffixOffset + 1); + } + return length; +} + +static void __attribute__((noinline)) enqueueLogRecord(RingbufHandle_t queue, esp_log_msg_t& message) { + char local[128]; + size_t length = formatLogRecord(message, local, sizeof(local)); + if (length == 0 || length >= xRingbufferGetMaxItemSize(queue)) { + return; + } + + if (length < sizeof(local)) { + xRingbufferSend(queue, local, length + 1, 0); + return; + } + + char* buffer = static_cast(malloc(length + 1)); + if (buffer != nullptr) { + if (formatLogRecord(message, buffer, length + 1) == length) { + xRingbufferSend(queue, buffer, length + 1, 0); + } + + free(buffer); + } +} + +extern "C" { + void __real_esp_log_format(esp_log_msg_t* message); + + void IRAM_ATTR __wrap_esp_log_format(esp_log_msg_t* message) { + RingbufHandle_t queue = loggingQueue.load(std::memory_order_acquire); + if (message->config.opts.constrained_env || writingOutputs || queue == nullptr) { + __real_esp_log_format(message); + return; + } + + const bool hasOutput = activeSerial.load(std::memory_order_relaxed) || + activeWebSerial.load(std::memory_order_relaxed); + + if (hasOutput) { + enqueueLogRecord(queue, *message); + } + } +} + +static void writeOutput(Print& output, const uint8_t* buffer, size_t size) { + while (size > 0) { + size_t written = output.write(buffer, size); + if (written == 0 || written > size) { + return; + } + + buffer += written; + size -= written; + } +} + +static void setLoggingLevel(esp_log_level_t level) { + esp_log_level_set("*", level); + + // prevents loop with WebSerial in case we reach some error logs in esp_async_ws like WS message queue overflow + esp_log_level_set("async_tcp", ESP_LOG_NONE); + esp_log_level_set("async_ws", ESP_LOG_NONE); +} + +void drainLoggingSerial() { + if (activeSerial.load(std::memory_order_relaxed)) { + // Drain only the current RX backlog; continuous input must not starve tasks. + int available = Serial.available(); + while (available-- > 0) { + Serial.read(); + } + } +} + +static Task sendLogsTask("Send logs", [](void*) { + // Bound each pass so continuous logging cannot starve System tasks. + size_t remaining = LOGGING_QUEUE_SIZE; + const unsigned long started = millis(); + RingbufHandle_t queue = loggingQueue.load(std::memory_order_acquire); + + while (remaining > 0 && millis() - started < 10) { + size_t size = 0; + auto* buffer = static_cast(xRingbufferReceive(queue, &size, 0)); + + if (buffer == nullptr) { + break; + } + + // A transport may itself log during a write on this task. + writingOutputs = true; + if (activeSerial.load(std::memory_order_relaxed)) { + writeOutput(Serial, buffer, size - 1); + } + + if (activeWebSerial.load(std::memory_order_relaxed) && webSerial != nullptr) { + if (webSerial->getConnectionCount() > 0) { + writeOutput(*webSerial, buffer, size - 1); + } + } + writingOutputs = false; + + vRingbufferReturnItem(queue, buffer); + remaining = size >= remaining ? 0 : remaining - size; + } +}); + +Task configureLoggingTask("Configure logging", Task::Type::ONCE, [](void*) { + static unsigned int currentSerialBaudrate = 0; + unsigned int newSerialBaudrate = settings.system.serial.enabled ? settings.system.serial.baudrate : 0; + if (currentSerialBaudrate != newSerialBaudrate) { + if (newSerialBaudrate == 0) { + Serial.end(); + } + + if (newSerialBaudrate != 0) { + #if ARDUINO_USB_CDC_ON_BOOT && ARDUINO_USB_MODE + Serial.setTxBufferSize(512); + Serial.setTxTimeoutMs(0); + #endif + + Serial.begin(newSerialBaudrate); + } + + currentSerialBaudrate = newSerialBaudrate; + } + + activeSerial.store(currentSerialBaudrate != 0, std::memory_order_relaxed); + activeWebSerial.store(settings.system.webSerial.enabled && webSerial != nullptr, std::memory_order_relaxed); + + setLoggingLevel(settings.system.logLevel); +}); + +bool initLogging() { + if (loggingQueue.load(std::memory_order_relaxed) != nullptr) { + return false; + } + + RingbufHandle_t queue = xRingbufferCreate(LOGGING_QUEUE_SIZE, RINGBUF_TYPE_NOSPLIT); + if (queue == nullptr) { + return false; + } + + #if !CONFIG_LOG_API_CONSTRAINED_ENV_SAFE + // The native formatter uses the vprintf hook even in an ISR on these SDK builds. + esp_log_set_vprintf(esp_rom_vprintf); + #endif + + configureLoggingTask.forceRun(); + loggingQueue.store(queue, std::memory_order_release); + + systemTaskManager.addTask(configureLoggingTask); + systemTaskManager.addTask(sendLogsTask.setInterval(10)); + + return true; +} diff --git a/src/main.cpp b/src/main.cpp index 9ffb67d..4aaa4a0 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,247 +1,72 @@ -#define ARDUINOJSON_USE_DOUBLE 0 -#define ARDUINOJSON_USE_LONG_LONG 0 +#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE -#include -#include -#include -#include -#include +#include +#include +#include -#include "defines.h" -#include "strings.h" +#include -#include -#include -#include "CrashRecorder.h" -#include "Sensors.h" -#include "Settings.h" -#include "utils.h" - -#if defined(ARDUINO_ARCH_ESP32) - #include -#elif defined(ARDUINO_ARCH_ESP8266) - #include -#else - #error Wrong board. Supported boards: esp8266, esp32 +#if ARDUINO_USB_CDC_ON_BOOT && !ARDUINO_USB_MODE + #include #endif -#include -#include -#include "MqttTask.h" -#include "OpenThermTask.h" -#include "SensorsTask.h" -#include "RegulatorTask.h" -#include "PortalTask.h" -#include "MainTask.h" +#ifndef ARDUINO_ARCH_ESP32 + #error Only ESP32 boards are supported +#endif -using namespace NetworkUtils; +#include // Vars -ESPTelnetStream* telnetStream = nullptr; -NetworkMgr* network = nullptr; Sensors::Result sensorsResults[SENSORS_AMOUNT]; -FileData fsNetworkSettings(&LittleFS, "/network.conf", 'n', &networkSettings, sizeof(networkSettings), 1000); -FileData fsSettings(&LittleFS, "/settings.conf", 's', &settings, sizeof(settings), 60000); -FileData fsSensorsSettings(&LittleFS, "/sensors.conf", 'e', &sensorsSettings, sizeof(sensorsSettings), 60000); - -// Tasks -MqttTask* tMqtt; -OpenThermTask* tOt; -SensorsTask* tSensors; -RegulatorTask* tRegulator; -PortalTask* tPortal; -MainTask* tMain; +TaskManager appTaskManager("App"); -void setup() { - CrashRecorder::init(); +extern "C" void app_main() { + // https://github.com/espressif/arduino-esp32/blob/master/cores/esp32/main.cpp + #if defined(F_XTAL_MHZ) && !CONFIG_IDF_TARGET_ESP32S2 + rtc_clk_xtal_freq_update((rtc_xtal_freq_t)F_XTAL_MHZ); + rtc_clk_cpu_freq_set_xtal(); + #endif + + #ifdef F_CPU + setCpuFrequencyMhz(F_CPU / 1000000); + #endif + + #if ARDUINO_USB_DFU_ON_BOOT && !ARDUINO_USB_MODE + USB.enableDFU(); + #endif + + #if ARDUINO_USB_ON_BOOT && !ARDUINO_USB_MODE + USB.begin(); + #endif + + initArduino(); + initCoreDumpMetrics(); Sensors::setMaxSensors(SENSORS_AMOUNT); Sensors::settings = sensorsSettings; Sensors::results = sensorsResults; + TaskManager::configureWDT(60, true); LittleFS.begin(); - Log.setLevel(TinyLogger::Level::VERBOSE); - Log.setServiceTemplate("\033[1m[%s]\033[22m"); - Log.setLevelTemplate("\033[1m[%s]\033[22m"); - Log.setMsgPrefix("\033[m "); - Log.setDateTemplate("\033[1m[%H:%M:%S]\033[22m"); - Log.setDateCallback([] { - unsigned int time = millis() / 1000; - int sec = time % 60; - int min = time % 3600 / 60; - int hour = time / 3600; - - return tm{sec, min, hour}; - }); - - Serial.begin(115200); - #if ARDUINO_USB_MODE - Serial.setTxBufferSize(512); - #endif - Log.addStream(&Serial); - Log.print("\n\n\r"); - - // - // Network settings - // The network file has to survive updates, this ensures it doesn't get wiped when the structure is modified - fsNetworkSettings.addWithoutWipe(true); - - switch (fsNetworkSettings.read()) { - case FD_FS_ERR: - Log.swarningln(FPSTR(L_NETWORK_SETTINGS), F("Filesystem error, load default")); - break; - case FD_FILE_ERR: - Log.swarningln(FPSTR(L_NETWORK_SETTINGS), F("Bad data, load default")); - break; - case FD_WRITE: - Log.sinfoln(FPSTR(L_NETWORK_SETTINGS), F("Not found, load default")); - break; - case FD_ADD: - case FD_READ: - Log.sinfoln(FPSTR(L_NETWORK_SETTINGS), F("Loaded")); - break; - default: - break; + if (!initLogging()) { + std::abort(); } - // generate hostname if it is empty - if (!strlen(networkSettings.hostname)) { - strcpy(networkSettings.hostname, getChipId("otgateway-").c_str()); - fsNetworkSettings.update(); + initConfig(); + initNetwork(); + initControl(); + initRegulator(); + initLeds(); + initMqtt(); + initPortal(); + initOpenTherm(); + initSystem(); + initSensors(); + + // App runs control and MQTT tasks + if (!appTaskManager.asyncStart(4608, 4, tskNO_AFFINITY, 100, false)) { + esp_system_abort("Failed to start App task manager"); } - - network = (new NetworkMgr) - ->setHostname(networkSettings.hostname) - ->setStaCredentials( - strlen(networkSettings.sta.ssid) ? networkSettings.sta.ssid : nullptr, - strlen(networkSettings.sta.password) ? networkSettings.sta.password : nullptr, - networkSettings.sta.channel - )->setApCredentials( - strlen(networkSettings.ap.ssid) ? networkSettings.ap.ssid : nullptr, - strlen(networkSettings.ap.password) ? networkSettings.ap.password : nullptr, - networkSettings.ap.channel - ) - ->setUseDhcp(networkSettings.useDhcp) - ->setStaticConfig( - networkSettings.staticConfig.ip, - networkSettings.staticConfig.gateway, - networkSettings.staticConfig.subnet, - networkSettings.staticConfig.dns - ); - - // - // Settings - switch (fsSettings.read()) { - case FD_FS_ERR: - Log.swarningln(FPSTR(L_SETTINGS), F("Filesystem error, load default")); - break; - case FD_FILE_ERR: - Log.swarningln(FPSTR(L_SETTINGS), F("Bad data, load default")); - break; - case FD_WRITE: - Log.sinfoln(FPSTR(L_SETTINGS), F("Not found, load default")); - break; - case FD_ADD: - case FD_READ: - Log.sinfoln(FPSTR(L_SETTINGS), F("Loaded")); - - if (strcmp(SETTINGS_VALID_VALUE, settings.validationValue) != 0) { - Log.swarningln(FPSTR(L_SETTINGS), F("Not valid, set default and restart...")); - fsSettings.reset(); - ::delay(5000); - ESP.restart(); - } - break; - default: - break; - } - - // ethernet (W5500) is configured from the network settings, after they are loaded - network - ->setEthernet(networkSettings.ethernet.enabled) - ->setEthernetPins( - networkSettings.ethernet.w5500.clk, - networkSettings.ethernet.w5500.mosi, - networkSettings.ethernet.w5500.miso, - networkSettings.ethernet.w5500.cs, - networkSettings.ethernet.w5500.irq, - networkSettings.ethernet.w5500.rst - ); - - // generate mqtt prefix if it is empty - if (!strlen(settings.mqtt.prefix)) { - strcpy(settings.mqtt.prefix, getChipId("otgateway_").c_str()); - fsSettings.update(); - } - - // Logs settings - if (!settings.system.serial.enabled) { - Serial.end(); - Log.clearStreams(); - - } else if (settings.system.serial.baudrate != 115200) { - Serial.end(); - Log.clearStreams(); - - Serial.begin(settings.system.serial.baudrate); - Log.addStream(&Serial); - } - - if (settings.system.telnet.enabled) { - telnetStream = new ESPTelnetStream; - telnetStream->setKeepAliveInterval(500); - Log.addStream(telnetStream); - } - - if (settings.system.logLevel >= TinyLogger::Level::SILENT && settings.system.logLevel <= TinyLogger::Level::VERBOSE) { - Log.setLevel(static_cast(settings.system.logLevel)); - } - - // - // Sensors settings - switch (fsSensorsSettings.read()) { - case FD_FS_ERR: - Log.swarningln(FPSTR(L_SENSORS), F("Filesystem error, load default")); - break; - case FD_FILE_ERR: - Log.swarningln(FPSTR(L_SENSORS), F("Bad data, load default")); - break; - case FD_WRITE: - Log.sinfoln(FPSTR(L_SENSORS), F("Not found, load default")); - break; - case FD_ADD: - case FD_READ: - Log.sinfoln(FPSTR(L_SENSORS), F("Loaded")); - default: - break; - } - - // - // Make tasks - tMqtt = new MqttTask(false, 500); - Scheduler.start(tMqtt); - - tOt = new OpenThermTask(true, 750); - Scheduler.start(tOt); - - tSensors = new SensorsTask(true, 1000); - Scheduler.start(tSensors); - - tRegulator = new RegulatorTask(true, 10000); - Scheduler.start(tRegulator); - - tPortal = new PortalTask(true, 0); - Scheduler.start(tPortal); - - tMain = new MainTask(true, 100); - Scheduler.start(tMain); - - Scheduler.begin(); -} - -void loop() { -#if defined(ARDUINO_ARCH_ESP32) - vTaskDelete(NULL); -#endif + ESP_LOGI(L_MAIN, "Started %s task manager", appTaskManager.name()); } diff --git a/src/mqtt.cpp b/src/mqtt.cpp new file mode 100644 index 0000000..0a3e625 --- /dev/null +++ b/src/mqtt.cpp @@ -0,0 +1,1912 @@ +#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE + +#include +#include "StructSnapshot.h" +#include "StructTimestampMap.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static std::unique_ptr mqttClient; + +// Keep the applied prefix separate from settings until MQTT is reconfigured. +static std::string mqttPrefix; // NOLINT(runtime/string) +static std::atomic mqttConnectedAt{0}; +static unsigned long mqttPublishedSensorAt[SENSORS_AMOUNT] = {}; + +// Only App accesses snapshots and the sorted publication timestamps. +static StructSnapshot settingsSnapshot(settings); +static StructSnapshot varsSnapshot(vars); +static StructTimestampMap<96> mqttPublishTimes; + +static std::atomic mqttRefreshRequested{false}; +static std::atomic mqttHaRefreshRequested{false}; +// Discovery and its synchronous publisher run only on App. +static std::bitset mqttHaPendingEntities; +static std::bitset mqttHaPendingSensors; + +Task* mqttPublishSettingsTask = nullptr; +Task* mqttPublishStateTask = nullptr; +Task* mqttPublishSensorsTask = nullptr; +static Task* mqttReconfigureSensorsTask = nullptr; +static Task* mqttPublishHaTask = nullptr; + +// Protect the MQTT change queue and publication timestamps across HTTP/native callbacks. +static std::mutex mqttSensorsMutex; + +struct MqttSensorChange { + uint8_t sensorId; + std::optional previousSettings; +}; +static std::list mqttSensorChanges; + +// The caller holds mqttSensorsMutex. +static bool isSensorReconfigurationPending(uint8_t sensorId) { + return std::any_of(mqttSensorChanges.begin(), mqttSensorChanges.end(), [sensorId](const auto& change) { + return change.sensorId == sensorId; + }); +} + +static bool isMqttBlocked() { + return upgrading || restartTask.scheduled() || restartTask.active(); +} + +static bool isMqttReady() { + return settings.mqtt.enabled && isNetworkConnected() && !isMqttBlocked() && + !mqttConfigureTask.scheduled() && isMqttConnected(); +} + +static bool isMqttReadyForPublish() { + const unsigned long connectedAt = mqttConnectedAt.load(); + return isMqttReady() && connectedAt && millis() - connectedAt > 30000u; +} + +std::string mqttTopic(std::initializer_list parts) { + size_t length = mqttPrefix.size(); + for (const auto part : parts) { + length += 1 + part.size(); + } + + std::string topic; + topic.reserve(length); + topic.append(mqttPrefix); + for (const auto part : parts) { + topic += '/'; + topic.append(part); + } + return topic; +} + +static bool publishValue(const std::string& topic, std::string_view value) { + const bool published = mqttClient->publish(topic.c_str(), value, true); + + ESP_LOGD( + L_MQTT, "%s publish topic: %s, value: %.*s", + published ? "Successfully" : "Failed", + topic.c_str(), + static_cast(value.size()), + value.empty() ? "" : value.data() + ); + + return published; +} + +static bool publishValue(const std::string& topic, const char* value) { + return publishValue(topic, std::string_view(value)); +} + +static bool publishValue(const std::string& topic, bool value) { + return publishValue(topic, value ? S_TRUE : S_FALSE); +} + +static bool publishValue(const std::string& topic, float value, uint8_t decimals = 2) { + if (!std::isfinite(value)) { + // Remove an obsolete retained reading instead of publishing nan/inf. + return publishValue(topic, ""); + } + + char payload[64]; + const int length = snprintf(payload, sizeof(payload), "%.*f", decimals, value); + if (length < 0 || static_cast(length) >= sizeof(payload)) { + return false; + } + + if (decimals) { + char* end = payload + length - 1; + while (*end == '0') { + *end-- = '\0'; + } + if (*end == '.') { + *end = '\0'; + } + } + + return publishValue(topic, payload); +} + +static void collectMqttChanges() { + if (mqttRefreshRequested.exchange(false)) { + mqttPublishTimes.resetAll(); + } + + if (!settingsSnapshot.equals(&settings.system.unitSystem)) { + mqttPublishTimes.reset({ + &settings.heating.target, &settings.heating.minTemp, &settings.heating.maxTemp, + &settings.heating.overheatProtection.highTemp, &settings.heating.overheatProtection.lowTemp, + &settings.heating.freezeProtection.highTemp, &settings.heating.freezeProtection.lowTemp, + &settings.dhw.target, &settings.dhw.minTemp, &settings.dhw.maxTemp, + &settings.dhw.overheatProtection.highTemp, &settings.dhw.overheatProtection.lowTemp, + &settings.pid.minTemp, &settings.pid.maxTemp, &settings.emergency.target + }); + + mqttPublishTimes.reset({ + &vars.slave.heating.minTemp, &vars.slave.heating.maxTemp, + &vars.slave.dhw.minTemp, &vars.slave.dhw.maxTemp, + &vars.master.heating.setpointTemp, &vars.master.heating.targetTemp, + &vars.master.heating.currentTemp, &vars.master.heating.returnTemp, + &vars.master.heating.indoorTemp, &vars.master.heating.outdoorTemp, + &vars.master.heating.minTemp, &vars.master.heating.maxTemp, + &vars.master.dhw.targetTemp, &vars.master.dhw.currentTemp, &vars.master.dhw.returnTemp, + &vars.master.dhw.minTemp, &vars.master.dhw.maxTemp + }); + settingsSnapshot.set(&settings.system.unitSystem); + } + + if (!settingsSnapshot.equals(&settings.equitherm.enabled)) { + mqttPublishTimes.reset({&settings.pid.minTemp, &settings.pid.maxTemp}); + } +} + +template +static bool publishField( + StructSnapshot& snapshot, const Field* field, + unsigned long intervalMs, Publish publish, float tolerance = 0.0001f +) { + const unsigned long now = millis(); + unsigned long& lastPublishAt = mqttPublishTimes.get(field); + if (lastPublishAt != 0 && now - lastPublishAt < intervalMs && snapshot.equals(field, tolerance)) { + return false; + } + + const Field value = *field; + if (publish(value)) { + lastPublishAt = now; + snapshot.set(field, &value); + } + + // A failed send still consumes this pass; unchanged state allows a retry. + return true; +} + +template +static bool publishField( + StructSnapshot& snapshot, const Field* field, + unsigned long intervalMs, const char* topicSuffix +) { + return publishField(snapshot, field, intervalMs, [topicSuffix](const Field& value) { + const auto topic = mqttTopic(topicSuffix); + if constexpr (std::is_enum_v) { + return publishValue(topic, std::to_string(static_cast>(value))); + + } else if constexpr (std::is_integral_v && !std::is_same_v) { + return publishValue(topic, std::to_string(value)); + + } else { + return publishValue(topic, value); + } + }); +} + +static bool publishHeatingSettings(unsigned long intervalMs) { + bool published = publishField(settingsSnapshot, &settings.heating.enabled, intervalMs, "settings/heating/enabled"); + if (published) { + return true; + } + + published = publishField(settingsSnapshot, &settings.heating.turbo, intervalMs, "settings/heating/turbo"); + if (published) { + return true; + } + + published = publishField( + settingsSnapshot, &settings.heating.target, intervalMs, [](float value) { + return publishValue( + mqttTopic("settings/heating/target"), + convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField(settingsSnapshot, &settings.heating.hysteresis.enabled, intervalMs, "settings/heating/hysteresis/enabled"); + if (published) { + return true; + } + + published = publishField( + settingsSnapshot, &settings.heating.hysteresis.value, intervalMs, [](float value) { + return publishValue( + mqttTopic("settings/heating/hysteresis/value"), + value, + 3 + ); + } + ); + if (published) { + return true; + } + + published = publishField( + settingsSnapshot, &settings.heating.turboFactor, intervalMs, [](float value) { + return publishValue(mqttTopic("settings/heating/turbo_factor"), value, 3); + } + ); + if (published) { + return true; + } + + published = publishField( + settingsSnapshot, &settings.heating.minTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("settings/heating/min_temp"), + convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField( + settingsSnapshot, &settings.heating.maxTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("settings/heating/max_temp"), + convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField(settingsSnapshot, &settings.heating.maxModulation, intervalMs, "settings/heating/max_modulation"); + if (published) { + return true; + } + + published = publishField(settingsSnapshot, &settings.heating.indoorTempAvgType, intervalMs, "settings/heating/indoor_temp_avg_type"); + if (published) { + return true; + } + + published = publishField(settingsSnapshot, &settings.heating.outdoorTempAvgType, intervalMs, "settings/heating/outdoor_temp_avg_type"); + if (published) { + return true; + } + + published = publishField( + settingsSnapshot, &settings.heating.overheatProtection.highTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("settings/heating/overheat_protection/high_temp"), + value == 0 + ? 0 + : convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField( + settingsSnapshot, &settings.heating.overheatProtection.lowTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("settings/heating/overheat_protection/low_temp"), + value == 0 + ? 0 + : convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField( + settingsSnapshot, &settings.heating.freezeProtection.highTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("settings/heating/freeze_protection/high_temp"), + convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField( + settingsSnapshot, &settings.heating.freezeProtection.lowTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("settings/heating/freeze_protection/low_temp"), + convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + return false; +} + +static bool publishDhwSettings(unsigned long intervalMs) { + bool published = publishField(settingsSnapshot, &settings.dhw.enabled, intervalMs, "settings/dhw/enabled"); + if (published) { + return true; + } + + published = publishField( + settingsSnapshot, &settings.dhw.target, intervalMs, [](float value) { + return publishValue( + mqttTopic("settings/dhw/target"), + convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 1 + ); + } + ); + if (published) { + return true; + } + + published = publishField( + settingsSnapshot, &settings.dhw.minTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("settings/dhw/min_temp"), + convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField( + settingsSnapshot, &settings.dhw.maxTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("settings/dhw/max_temp"), + convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField(settingsSnapshot, &settings.dhw.maxModulation, intervalMs, "settings/dhw/max_modulation"); + if (published) { + return true; + } + + published = publishField( + settingsSnapshot, &settings.dhw.overheatProtection.highTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("settings/dhw/overheat_protection/high_temp"), + value == 0 + ? 0 + : convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField( + settingsSnapshot, &settings.dhw.overheatProtection.lowTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("settings/dhw/overheat_protection/low_temp"), + value == 0 + ? 0 + : convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + return false; +} + +static bool publishPidSettings(unsigned long intervalMs) { + bool published = publishField(settingsSnapshot, &settings.pid.enabled, intervalMs, "settings/pid/enabled"); + if (published) { + return true; + } + + published = publishField( + settingsSnapshot, &settings.pid.p_factor, intervalMs, [](float value) { + return publishValue(mqttTopic("settings/pid/p_factor"), value, 3); + } + ); + if (published) { + return true; + } + + published = publishField( + settingsSnapshot, &settings.pid.i_factor, intervalMs, [](float value) { + return publishValue(mqttTopic("settings/pid/i_factor"), value, 4); + }, 0.00005f + ); + if (published) { + return true; + } + + published = publishField( + settingsSnapshot, &settings.pid.d_factor, intervalMs, [](float value) { + return publishValue(mqttTopic("settings/pid/d_factor"), value, 1); + } + ); + if (published) { + return true; + } + + published = publishField(settingsSnapshot, &settings.pid.dt, intervalMs, "settings/pid/dt"); + if (published) { + return true; + } + + published = publishField( + settingsSnapshot, &settings.pid.minTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("settings/pid/min_temp"), + settings.equitherm.enabled + ? value + : convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField( + settingsSnapshot, &settings.pid.maxTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("settings/pid/max_temp"), + settings.equitherm.enabled + ? value + : convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField(settingsSnapshot, &settings.pid.deadband.enabled, intervalMs, "settings/pid/deadband/enabled"); + if (published) { + return true; + } + + published = publishField( + settingsSnapshot, &settings.pid.deadband.p_multiplier, intervalMs, [](float value) { + return publishValue( + mqttTopic("settings/pid/deadband/p_multiplier"), + value, + 3 + ); + } + ); + if (published) { + return true; + } + + published = publishField( + settingsSnapshot, &settings.pid.deadband.i_multiplier, intervalMs, [](float value) { + return publishValue( + mqttTopic("settings/pid/deadband/i_multiplier"), + value, + 3 + ); + } + ); + if (published) { + return true; + } + + published = publishField( + settingsSnapshot, &settings.pid.deadband.d_multiplier, intervalMs, [](float value) { + return publishValue( + mqttTopic("settings/pid/deadband/d_multiplier"), + value, + 3 + ); + } + ); + if (published) { + return true; + } + + published = publishField(settingsSnapshot, &settings.pid.deadband.thresholdHigh, intervalMs, "settings/pid/deadband/threshold_high"); + if (published) { + return true; + } + + published = publishField(settingsSnapshot, &settings.pid.deadband.thresholdLow, intervalMs, "settings/pid/deadband/threshold_low"); + if (published) { + return true; + } + return false; +} + +static bool publishEquithermSettings(unsigned long intervalMs) { + bool published = publishField(settingsSnapshot, &settings.equitherm.enabled, intervalMs, "settings/equitherm/enabled"); + if (published) { + return true; + } + + published = publishField( + settingsSnapshot, &settings.equitherm.slope, intervalMs, [](float value) { + return publishValue(mqttTopic("settings/equitherm/slope"), value, 3); + } + ); + if (published) { + return true; + } + + published = publishField( + settingsSnapshot, &settings.equitherm.exponent, intervalMs, [](float value) { + return publishValue(mqttTopic("settings/equitherm/exponent"), value, 3); + } + ); + if (published) { + return true; + } + + published = publishField(settingsSnapshot, &settings.equitherm.shift, intervalMs, "settings/equitherm/shift"); + if (published) { + return true; + } + + published = publishField( + settingsSnapshot, &settings.equitherm.targetDiffFactor, intervalMs, [](float value) { + return publishValue( + mqttTopic("settings/equitherm/target_diff_factor"), + value, + 3 + ); + } + ); + if (published) { + return true; + } + return false; +} + +static bool publishEmergencySettings(unsigned long intervalMs) { + bool published = publishField(settingsSnapshot, &settings.emergency.target, intervalMs, [](float value) { + return publishValue( + mqttTopic("settings/emergency/target"), + convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + }); + + return published; +} + +static bool publishSlaveState(unsigned long intervalMs) { + bool published = publishField(varsSnapshot, &vars.slave.memberId, intervalMs, "state/slave/member_id"); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.slave.flags, intervalMs, "state/slave/flags"); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.slave.type, intervalMs, "state/slave/type"); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.slave.appVersion, intervalMs, "state/slave/app_version"); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.slave.protocolVersion, intervalMs, "state/slave/protocol_version"); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.slave.connected, intervalMs, "state/slave/connected"); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.slave.flame, intervalMs, "state/slave/flame"); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.slave.cooling.active, intervalMs, "state/slave/cooling/active"); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.slave.cooling.setpoint, intervalMs, "state/slave/cooling/setpoint"); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.slave.modulation.min, intervalMs, "state/slave/modulation/min"); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.slave.modulation.max, intervalMs, "state/slave/modulation/max"); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.slave.power.min, intervalMs, "state/slave/power/min"); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.slave.power.max, intervalMs, "state/slave/power/max"); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.slave.heating.active, intervalMs, "state/slave/heating/active"); + if (published) { + return true; + } + + published = publishField( + varsSnapshot, &vars.slave.heating.minTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("state/slave/heating/min_temp"), + convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField( + varsSnapshot, &vars.slave.heating.maxTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("state/slave/heating/max_temp"), + convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.slave.dhw.active, intervalMs, "state/slave/dhw/active"); + if (published) { + return true; + } + + published = publishField( + varsSnapshot, &vars.slave.dhw.minTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("state/slave/dhw/min_temp"), + convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField( + varsSnapshot, &vars.slave.dhw.maxTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("state/slave/dhw/max_temp"), + convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.slave.fault.active, intervalMs, "state/slave/fault/active"); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.slave.fault.code, intervalMs, "state/slave/fault/code"); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.slave.diag.active, intervalMs, "state/slave/diag/active"); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.slave.diag.code, intervalMs, "state/slave/diag/code"); + if (published) { + return true; + } + return false; +} + +static bool publishMasterState(unsigned long intervalMs) { + const unsigned long now = millis(); + + { + static unsigned long lastPublishAt = 0; + if (now - lastPublishAt >= intervalMs) { + publishValue(mqttTopic("state/master/uptime"), std::to_string(now / 1000u)); + lastPublishAt = now; // force + return true; + } + } + + bool published = publishField(varsSnapshot, &vars.master.heating.enabled, intervalMs, "state/master/heating/enabled"); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.master.heating.blocking, intervalMs, "state/master/heating/blocking"); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.master.heating.smartControl, intervalMs, "state/master/heating/smart_control"); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.master.heating.overheat, intervalMs, "state/master/heating/overheat"); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.master.heating.freezing, intervalMs, "state/master/heating/freezing"); + if (published) { + return true; + } + + published = publishField( + varsSnapshot, &vars.master.heating.setpointTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("state/master/heating/setpoint_temp"), + value == 0 + ? 0 + : convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField( + varsSnapshot, &vars.master.heating.targetTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("state/master/heating/target_temp"), + value == 0 + ? 0 + : convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField( + varsSnapshot, &vars.master.heating.currentTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("state/master/heating/current_temp"), + convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField( + varsSnapshot, &vars.master.heating.returnTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("state/master/heating/return_temp"), + convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField( + varsSnapshot, &vars.master.heating.indoorTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("state/master/heating/indoor_temp"), + convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField( + varsSnapshot, &vars.master.heating.outdoorTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("state/master/heating/outdoor_temp"), + convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField( + varsSnapshot, &vars.master.heating.minTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("state/master/heating/min_temp"), + convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField( + varsSnapshot, &vars.master.heating.maxTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("state/master/heating/max_temp"), + convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.master.dhw.enabled, intervalMs, "state/master/dhw/enabled"); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.master.dhw.overheat, intervalMs, "state/master/dhw/overheat"); + if (published) { + return true; + } + + published = publishField( + varsSnapshot, &vars.master.dhw.targetTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("state/master/dhw/target_temp"), + value == 0 + ? 0 + : convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField( + varsSnapshot, &vars.master.dhw.currentTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("state/master/dhw/current_temp"), + convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField( + varsSnapshot, &vars.master.dhw.returnTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("state/master/dhw/return_temp"), + convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField( + varsSnapshot, &vars.master.dhw.minTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("state/master/dhw/min_temp"), + convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField( + varsSnapshot, &vars.master.dhw.maxTemp, intervalMs, [](float value) { + return publishValue( + mqttTopic("state/master/dhw/max_temp"), + convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + } + ); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.network.rssi, intervalMs, "state/master/network/rssi"); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.emergency.state, intervalMs, "state/master/emergency/state"); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.externalPump.state, intervalMs, "state/master/ext_pump/state"); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.cascadeControl.input, intervalMs, "state/master/cascade_control/input"); + if (published) { + return true; + } + + published = publishField(varsSnapshot, &vars.cascadeControl.output, intervalMs, "state/master/cascade_control/output"); + if (published) { + return true; + } + return false; +} + +static void publishState(unsigned long intervalMs) { + const unsigned long now = millis(); + + { + static unsigned long lastPublishAt = 0; + if (now - lastPublishAt >= 5000UL) { + publishValue(mqttTopic("status"), "online"); + lastPublishAt = now; // force + return; + } + } + + publishSlaveState(intervalMs); + publishMasterState(intervalMs); +} + +static bool isCommandValid(const std::string& topic, std::string_view payload) { + if (payload.empty()) { + return false; + } + + // These bounds keep commands within RX 512: MycilaMQTT does not expose fragment metadata. + if (topic.size() > 128 || payload.size() > 64 || topic.find('\0') != std::string::npos) { + ESP_LOGW(L_MQTT_MSG, "Invalid scalar command size or topic"); + return false; + } + + return true; +} + +static bool publishSensor(const Sensors::Settings& sensor, const Sensors::Result& result) { + if (!sensor.slug[0]) { + return false; + } + + if (!publishValue(mqttTopic(S_SENSORS, sensor.slug, S_CONNECTED), result.connected)) { + return false; + } + + if (sensor.type == Sensors::Type::BLUETOOTH || sensor.type == Sensors::Type::DALLAS_TEMP + || sensor.type == Sensors::Type::DHT11 || sensor.type == Sensors::Type::DHT22) { + if (!publishValue(mqttTopic(S_SENSORS, sensor.slug, S_SIGNAL_QUALITY), std::to_string(result.signalQuality))) { + return false; + } + } + + if (sensor.type == Sensors::Type::BLUETOOTH || sensor.type == Sensors::Type::DHT11 || sensor.type == Sensors::Type::DHT22) { + const bool published = publishValue( + mqttTopic(S_SENSORS, sensor.slug, S_TEMPERATURE), + convertTemp( + result.values[static_cast(Sensors::ValueType::TEMPERATURE)], + UnitSystem::METRIC, settings.system.unitSystem + ), + 3 + ); + + if (!published) { + return false; + } + + if (!publishValue(mqttTopic(S_SENSORS, sensor.slug, S_HUMIDITY), result.values[static_cast(Sensors::ValueType::HUMIDITY)], 3)) { + return false; + } + + if (sensor.type == Sensors::Type::BLUETOOTH) { + if (!publishValue(mqttTopic(S_SENSORS, sensor.slug, S_BATTERY), result.values[static_cast(Sensors::ValueType::BATTERY)], 1)) { + return false; + } + + if (!publishValue(mqttTopic(S_SENSORS, sensor.slug, S_RSSI), result.values[static_cast(Sensors::ValueType::RSSI)], 0)) { + return false; + } + } + + } else { + const bool published = publishValue( + mqttTopic(S_SENSORS, sensor.slug, S_VALUE), + Sensors::convertValue( + sensor, Sensors::ValueType::PRIMARY, + result.values[static_cast(Sensors::ValueType::PRIMARY)], + UnitSystem::METRIC, settings.system.unitSystem + ), + 3 + ); + + if (!published) { + return false; + } + } + + return true; +} + +static bool purgeSensor(const char* slug) { + if (slug == nullptr || !slug[0]) { + return true; + } + + const char* fields[] = {S_CONNECTED, S_SIGNAL_QUALITY, S_VALUE, S_TEMPERATURE, S_HUMIDITY, S_BATTERY, S_RSSI}; + for (const auto field : fields) { + const std::string topic = mqttTopic(S_SENSORS, slug, field); + + if (!mqttClient->publish(topic.c_str(), {}, true)) { + return false; + } + } + + return true; +} + +void requestReconfigureMqttSensor(uint8_t sensorId, std::optional previousSettings) { + if (!Sensors::isValidSensorId(sensorId)) { + return; + } + + { + std::lock_guard lock(mqttSensorsMutex); + const auto pending = std::find_if(mqttSensorChanges.begin(), mqttSensorChanges.end(), [sensorId](const auto& change) { + return change.sensorId == sensorId; + }); + + if (pending == mqttSensorChanges.end()) { + mqttSensorChanges.push_back({sensorId, std::move(previousSettings)}); + + } else if (!pending->previousSettings && previousSettings) { + // Keep the first settings whose old MQTT identity may need cleanup. + pending->previousSettings = std::move(previousSettings); + } + } + + // If SDK stop holds the lock, pending changes stay queued for a periodic run. + std::unique_lock taskLock(mqttMutex, std::try_to_lock); + if (taskLock.owns_lock() && mqttReconfigureSensorsTask) { + mqttReconfigureSensorsTask->requestEarlyRun(); + } +} + +void requestPublishMqttSensor(uint8_t sensorId) { + if (!Sensors::isValidSensorId(sensorId)) { + return; + } + + { + std::lock_guard lock(mqttSensorsMutex); + mqttPublishedSensorAt[sensorId] = 0; + } + + // stopMqtt holds this lock while waiting for the MQTT callback to finish. + // If busy, the cleared timestamp still triggers the next periodic publication. + std::unique_lock taskLock(mqttMutex, std::try_to_lock); + if (taskLock.owns_lock() && mqttPublishSensorsTask) { + mqttPublishSensorsTask->requestEarlyRun(); + } +} + +void requestReconfigureMqtt() { + mqttConfigureTask.setInterval(0).resume(); +} + +bool isMqttConnected() { + // Do not wait for SDK stop or access a client being destroyed. + std::unique_lock lock(mqttMutex, std::try_to_lock); + return lock.owns_lock() && mqttClient && mqttClient->isConnected(); +} + +void stopMqtt(bool destroy = false) { + std::lock_guard lock(mqttMutex); + if (mqttClient) { + mqttClient->end(); + } + + mqttConnectedAt.store(0); + mqttHaPendingEntities.reset(); + mqttHaPendingSensors.reset(); + + if (!destroy) { + return; + } + + if (mqttPublishSettingsTask) { + appTaskManager.removeTask(*mqttPublishSettingsTask); + delete mqttPublishSettingsTask; + mqttPublishSettingsTask = nullptr; + } + + if (mqttPublishStateTask) { + appTaskManager.removeTask(*mqttPublishStateTask); + delete mqttPublishStateTask; + mqttPublishStateTask = nullptr; + } + + if (mqttPublishSensorsTask) { + appTaskManager.removeTask(*mqttPublishSensorsTask); + delete mqttPublishSensorsTask; + mqttPublishSensorsTask = nullptr; + } + + if (mqttReconfigureSensorsTask) { + appTaskManager.removeTask(*mqttReconfigureSensorsTask); + delete mqttReconfigureSensorsTask; + mqttReconfigureSensorsTask = nullptr; + } + + if (mqttPublishHaTask) { + appTaskManager.removeTask(*mqttPublishHaTask); + delete mqttPublishHaTask; + mqttPublishHaTask = nullptr; + } + + haDiscovery.reset(); + mqttClient.reset(); + + std::string().swap(mqttPrefix); +} + +static float mqttValueToMetric(std::string_view path, float value) { + if (settings.equitherm.enabled && path.starts_with("pid/")) { + return value; + } + + if (value == 0 && path.find(S_OVERHEAT_PROTECTION) != std::string_view::npos) { + return value; + } + + const auto name = path.substr(path.find_last_of('/') + 1); + if (name == S_TARGET || name == S_MIN_TEMP || name == S_MAX_TEMP || name == S_HIGH_TEMP || name == S_LOW_TEMP) { + return convertTemp(value, settings.system.unitSystem, UnitSystem::METRIC); + } + + return value; +} + +static void subscribe() { + const auto onSettingCommand = [](const std::string& topic, const std::string_view& message) { + if (isMqttBlocked() || !settings.mqtt.enabled || mqttConfigureTask.scheduled() || mqttConfigureTask.active()) { + return; + } + + auto path = std::string_view(topic).substr(mqttPrefix.size()); + if (!path.starts_with("/settings/")) { + return; + } + + path.remove_prefix(sizeof("/settings/") - 1); + if (!path.ends_with("/set")) { + return; + } + + path.remove_suffix(sizeof("/set") - 1); + if (!isCommandValid(topic, message)) { + return; + } + + mqttClient->publish(topic.c_str(), {}, true); + const auto payload = trimPayload(message); + if (payload.size() > 32) { + ESP_LOGW( + L_MQTT_MSG, "Unsupported or invalid setting command: '%.*s'", + static_cast(payload.size()), payload.data() + ); + return; + } + + SettingResult result; + if (payload == S_TRUE || payload == S_FALSE) { + result = applySetting(settings, path, payload == S_TRUE); + + } else { + const auto parsed = parseNumber(payload); + if (parsed) { + result = applySetting(settings, path, mqttValueToMetric(path, *parsed)); + } + } + + if (!result.accepted) { + ESP_LOGW( + L_MQTT_MSG, "Unsupported or invalid setting command: '%.*s'", + static_cast(payload.size()), payload.empty() ? "" : payload.data() + ); + if (!result.changed) { + return; + } + } + + result.changed = normalizeSettings(settings) || result.changed; + if (result.changed) { + requestSaveSettings(); + } + + mqttPublishSettingsTask->requestEarlyRun(); + }; + + mqttClient->subscribe(mqttTopic(S_SETTINGS, "+/+/set"), onSettingCommand); + mqttClient->subscribe(mqttTopic(S_SETTINGS, "+/+/+/set"), onSettingCommand); + + mqttClient->subscribe(mqttTopic(S_ACTIONS, "+", "set"), [](const std::string& topic, const std::string_view& message) { + if (isMqttBlocked() || !settings.mqtt.enabled || mqttConfigureTask.scheduled() || mqttConfigureTask.active()) { + return; + } + + if (!isCommandValid(topic, message)) { + return; + } + + mqttClient->publish(topic.c_str(), {}, true); + + const auto payload = trimPayload(message); + if (payload != S_TRUE && payload != S_FALSE) { + ESP_LOGW(L_MQTT_MSG, "Invalid action value"); + return; + } + + auto action = std::string_view(topic).substr(mqttPrefix.size() + sizeof("/actions/") - 1); + action.remove_suffix(sizeof("/set") - 1); + + + if (!applyAction(action, payload == S_TRUE)) { + ESP_LOGW(L_MQTT_MSG, "Unsupported or blocked action"); + } + }); + + mqttClient->subscribe(mqttTopic(S_SENSORS, "+", S_VALUE, "set"), [](const std::string& topic, const std::string_view& message) { + if (isMqttBlocked() || !settings.mqtt.enabled || mqttConfigureTask.scheduled() || mqttConfigureTask.active()) { + return; + } + + if (!isCommandValid(topic, message)) { + return; + } + + mqttClient->publish(topic.c_str(), {}, true); + + const auto payload = trimPayload(message); + if (payload.size() > 32) { + ESP_LOGW( + L_MQTT_MSG, "Invalid manual sensor value: '%.*s'", + static_cast(payload.size()), payload.data() + ); + return; + } + + const auto parsed = parseNumber(payload); + if (!parsed) { + ESP_LOGW( + L_MQTT_MSG, "Invalid manual sensor value: '%.*s'", + static_cast(payload.size()), payload.empty() ? "" : payload.data() + ); + return; + } + + const auto slugStart = mqttPrefix.size() + strlen(S_SENSORS) + 2; + const std::string slug = topic.substr(slugStart, topic.find('/', slugStart) - slugStart); + if (slug.empty()) { + return; + } + + const auto sensorId = Sensors::setManualValueBySlug(slug, *parsed, settings.system.unitSystem); + if (!sensorId) { + ESP_LOGW(L_MQTT_MSG, "Unknown or disabled manual sensor"); + return; + } + + requestPublishMqttSensor(*sensorId); + }); +} + +static void connect() { + if (!mqttClient) { + std::lock_guard lock(mqttMutex); + + mqttClient = std::make_unique(); + mqttClient->setAsync(true); + mqttClient->setConfigHook([](esp_mqtt_client_config_t& config) { + config.session.last_will.qos = 1; + config.session.disable_clean_session = false; + config.network.timeout_ms = 3000; + config.network.reconnect_timeout_ms = MQTT_RECONNECT_INTERVAL; + config.buffer.size = 512; + config.buffer.out_size = 512; + config.outbox.limit = 8192; + config.task.stack_size = 4096; + config.task.priority = 2; + }); + + mqttClient->onConnect([] { + mqttConnectedAt.store(millis()); + mqttRefreshRequested.store(true); + mqttHaRefreshRequested.store(true); + { + std::lock_guard lock(mqttSensorsMutex); + memset(mqttPublishedSensorAt, 0, sizeof(mqttPublishedSensorAt)); + } + mqttPublishSettingsTask->requestEarlyRun(); + mqttPublishStateTask->requestEarlyRun(); + mqttPublishSensorsTask->requestEarlyRun(); + mqttReconfigureSensorsTask->requestEarlyRun(); + ESP_LOGI(L_MQTT, "Connected"); + }); + } + + // Update the local subscriptions; MQTT applies them when connected. + if (mqttPrefix != settings.mqtt.prefix || !haDiscovery) { + for (const auto& topic : mqttClient->getSubscribedTopics()) { + mqttClient->unsubscribe(topic.c_str()); + } + + mqttPrefix = settings.mqtt.prefix; + subscribe(); + } + + // Apply the current device metadata and MQTT prefix. + HA::Device haDevice{ + .id = mqttPrefix, + .name = PROJECT_NAME, + .version = BUILD_VERSION, + .model = PROJECT_NAME, + .manufacturer = PROJECT_REPO, + .url = std::string("http://") + getNetworkIp().toString().c_str() + "/", + }; + + // Create or update existing discovery + if (!haDiscovery) { + haDiscovery = std::make_unique( + std::move(haDevice), + mqttPrefix, + [](const char* topic, const std::string& payload) { + return mqttClient->publish(topic, payload, true) + ? HA::Error::SUCCESS + : HA::Error::ERR_MQTT_PUBLISHER; + } + ); + haDiscovery->setDiscoveryTopic(settings.mqtt.homeAssistantDiscoveryPrefix); + haDiscovery->setWillTopic("~/status"); + + } else { + haDiscovery->setDevice(std::move(haDevice)); + haDiscovery->setBaseTopic(mqttPrefix); + } + + // Start the connection after configuring discovery and subscriptions. + mqttClient->begin({ + .server = settings.mqtt.server, + .port = settings.mqtt.port, + .keepAlive = static_cast(settings.mqtt.interval * 10u), + .username = settings.mqtt.user, + .password = settings.mqtt.password, + .clientId = settings.mqtt.prefix, + .willTopic = mqttTopic("status"), + }); +} + +Task mqttConfigureTask("Configure MQTT", Task::Type::ONCE, [](void*) { + if (!settings.mqtt.enabled) { + stopMqtt(true); + return; + } + + if (!mqttPublishSettingsTask) { + auto* task = new Task("Publish MQTT settings", [](void*) { + const unsigned long intervalMs = settings.mqtt.interval * 1000UL; + collectMqttChanges(); + + if (publishEmergencySettings(intervalMs)) { + return; + } + + if (publishHeatingSettings(intervalMs)) { + return; + } + + if (publishDhwSettings(intervalMs)) { + return; + } + + if (publishEquithermSettings(intervalMs)) { + return; + } + + if (publishPidSettings(intervalMs)) { + return; + } + }); + + task->setInterval(50).setEnabledWhen(isMqttReadyForPublish); + appTaskManager.addTask(*task); + + std::lock_guard lock(mqttMutex); + mqttPublishSettingsTask = task; + } + + // Publish the current application and slave state. + if (!mqttPublishStateTask) { + auto* task = new Task("Publish MQTT state", [](void*) { + const unsigned long intervalMs = settings.mqtt.interval * 1000UL; + collectMqttChanges(); + publishState(intervalMs); + }); + + task->setInterval(50).setEnabledWhen(isMqttReadyForPublish); + appTaskManager.addTask(*task); + + std::lock_guard lock(mqttMutex); + mqttPublishStateTask = task; + } + + // Publish one discovery config per tick, without retaining Component objects. + if (!mqttPublishHaTask) { + auto* task = new Task("Publish HA discovery", [](void*) { + static bool discoveryEnabled = settings.mqtt.homeAssistantDiscovery; + static UnitSystem unitSystem = settings.system.unitSystem; + static bool equithermEnabled = settings.equitherm.enabled; + static unsigned short interval = settings.mqtt.interval; + static uint8_t heatingMinTemp = vars.slave.heating.minTemp; + static uint8_t heatingMaxTemp = vars.slave.heating.maxTemp; + static bool dhwSupport = settings.opentherm.options.dhwSupport; + static bool smartControl = vars.master.heating.smartControl; + static float heatingMinSetpointTemp = vars.master.heating.minTemp; + static float heatingMaxSetpointTemp = vars.master.heating.maxTemp; + static uint8_t dhwMinTemp = settings.dhw.minTemp; + static uint8_t dhwMaxTemp = settings.dhw.maxTemp; + static uint8_t dhwBoilerMinTemp = vars.slave.dhw.minTemp; + static uint8_t dhwBoilerMaxTemp = vars.slave.dhw.maxTemp; + + // Observe metadata dependencies regardless of the settings entry point. + if (discoveryEnabled != settings.mqtt.homeAssistantDiscovery) { + discoveryEnabled = settings.mqtt.homeAssistantDiscovery; + mqttHaRefreshRequested.store(true); + } + + // Apply the new discovery prefix and request a full HA refresh. + if (haDiscovery->getDiscoveryTopic() != settings.mqtt.homeAssistantDiscoveryPrefix) { + const auto statusTopic = haDiscovery->getDiscoveryTopic() + "/status"; + mqttClient->unsubscribe(statusTopic.c_str()); + haDiscovery->setDiscoveryTopic(settings.mqtt.homeAssistantDiscoveryPrefix); + mqttHaRefreshRequested.store(true); + } + + if (unitSystem != settings.system.unitSystem) { + unitSystem = settings.system.unitSystem; + mqttHaPendingEntities + .set(HA_ENTITY_HEATING_MIN_TEMP) + .set(HA_ENTITY_HEATING_MAX_TEMP) + .set(HA_ENTITY_PID_MIN_TEMP) + .set(HA_ENTITY_PID_MAX_TEMP) + .set(HA_ENTITY_HEATING_CLIMATE) + .set(HA_ENTITY_DHW_MIN_TEMP) + .set(HA_ENTITY_DHW_MAX_TEMP) + .set(HA_ENTITY_DHW_CLIMATE); + mqttHaPendingSensors.set(); + } + + if (equithermEnabled != settings.equitherm.enabled) { + equithermEnabled = settings.equitherm.enabled; + mqttHaPendingEntities.set(HA_ENTITY_PID_MIN_TEMP); + mqttHaPendingEntities.set(HA_ENTITY_PID_MAX_TEMP); + } + + if (interval != settings.mqtt.interval) { + interval = settings.mqtt.interval; + mqttHaPendingEntities.set(); + } + + if (heatingMinTemp != vars.slave.heating.minTemp) { + heatingMinTemp = vars.slave.heating.minTemp; + mqttHaPendingEntities.set(HA_ENTITY_HEATING_MIN_TEMP); + mqttHaPendingEntities.set(HA_ENTITY_HEATING_MAX_TEMP); + } + + if (heatingMaxTemp != vars.slave.heating.maxTemp) { + heatingMaxTemp = vars.slave.heating.maxTemp; + mqttHaPendingEntities.set(HA_ENTITY_HEATING_MIN_TEMP); + mqttHaPendingEntities.set(HA_ENTITY_HEATING_MAX_TEMP); + } + + if (dhwSupport != settings.opentherm.options.dhwSupport) { + dhwSupport = settings.opentherm.options.dhwSupport; + mqttHaPendingEntities + .set(HA_ENTITY_DHW_MIN_TEMP) + .set(HA_ENTITY_DHW_MAX_TEMP) + .set(HA_ENTITY_DHW) + .set(HA_ENTITY_DHW_CLIMATE) + .set(HA_ENTITY_DHW_OVERHEAT); + } + + if (smartControl != vars.master.heating.smartControl) { + smartControl = vars.master.heating.smartControl; + mqttHaPendingEntities.set(HA_ENTITY_HEATING_CLIMATE); + } + + if (heatingMinSetpointTemp != vars.master.heating.minTemp) { + heatingMinSetpointTemp = vars.master.heating.minTemp; + mqttHaPendingEntities.set(HA_ENTITY_HEATING_CLIMATE); + } + + if (heatingMaxSetpointTemp != vars.master.heating.maxTemp) { + heatingMaxSetpointTemp = vars.master.heating.maxTemp; + mqttHaPendingEntities.set(HA_ENTITY_HEATING_CLIMATE); + } + + if (dhwMinTemp != settings.dhw.minTemp) { + dhwMinTemp = settings.dhw.minTemp; + mqttHaPendingEntities.set(HA_ENTITY_DHW_CLIMATE); + } + + if (dhwMaxTemp != settings.dhw.maxTemp) { + dhwMaxTemp = settings.dhw.maxTemp; + mqttHaPendingEntities.set(HA_ENTITY_DHW_CLIMATE); + } + + if (dhwBoilerMinTemp != vars.slave.dhw.minTemp) { + dhwBoilerMinTemp = vars.slave.dhw.minTemp; + mqttHaPendingEntities.set(HA_ENTITY_DHW_MIN_TEMP); + mqttHaPendingEntities.set(HA_ENTITY_DHW_MAX_TEMP); + } + + if (dhwBoilerMaxTemp != vars.slave.dhw.maxTemp) { + dhwBoilerMaxTemp = vars.slave.dhw.maxTemp; + mqttHaPendingEntities.set(HA_ENTITY_DHW_MIN_TEMP); + mqttHaPendingEntities.set(HA_ENTITY_DHW_MAX_TEMP); + } + + if (mqttHaRefreshRequested.exchange(false)) { + const auto statusTopic = haDiscovery->getDiscoveryTopic() + "/status"; + const auto topics = mqttClient->getSubscribedTopics(); + const bool subscribed = std::find(topics.begin(), topics.end(), statusTopic) != topics.end(); + + if (settings.mqtt.homeAssistantDiscovery && !subscribed) { + mqttClient->subscribe(statusTopic, [](const std::string&, const std::string_view& message) { + if (message == "online") { + mqttHaRefreshRequested.store(true); + } + }); + + } else if (!settings.mqtt.homeAssistantDiscovery && subscribed) { + mqttClient->unsubscribe(statusTopic.c_str()); + } + + mqttHaPendingEntities.set(); + mqttHaPendingSensors.set(); + } + + for (size_t index = 0; index < mqttHaPendingEntities.size(); index++) { + if (!mqttHaPendingEntities.test(index)) { + continue; + } + + const bool published = publishHaEntity(static_cast(index), !settings.mqtt.homeAssistantDiscovery); + if (published) { + mqttHaPendingEntities.reset(index); + + } else { + ESP_LOGD(L_MQTT, "HA publication deferred"); + } + + break; + } + + for (uint8_t sensorId = 0; sensorId < SENSORS_AMOUNT; sensorId++) { + if (!mqttHaPendingSensors.test(sensorId)) { + continue; + } + + mqttHaPendingSensors.reset(sensorId); + if (settings.mqtt.homeAssistantDiscovery) { + requestReconfigureMqttSensor(sensorId); + + } else { + auto sensor = Sensors::getSettings(sensorId); + if (sensor) { + requestReconfigureMqttSensor(sensorId, std::move(sensor)); + } + } + + break; + } + }); + + task->setInterval(250).setEnabledWhen(isMqttReadyForPublish); + appTaskManager.addTask(*task); + + std::lock_guard lock(mqttMutex); + mqttPublishHaTask = task; + } + + // Rebuild sensor discovery and clear old readings in the same queue handler. + if (!mqttReconfigureSensorsTask) { + auto* task = new Task("Reconfigure MQTT sensors", [](void*) { + if (haDiscovery->getDiscoveryTopic() != settings.mqtt.homeAssistantDiscoveryPrefix) { + return; + } + + std::unique_lock lock(mqttSensorsMutex, std::try_to_lock); + if (!lock.owns_lock() || mqttSensorChanges.empty()) { + return; + } + + MqttSensorChange change = mqttSensorChanges.front(); + const auto sensor = Sensors::getSettings(change.sensorId); + mqttSensorChanges.pop_front(); + mqttPublishedSensorAt[change.sensorId] = 0; + lock.unlock(); + + const auto& [sensorId, prevSettings] = change; + const bool metadataChanged = + prevSettings && + (!sensor || + prevSettings->enabled != sensor->enabled || + strcmp(prevSettings->name, sensor->name) != 0 || + strcmp(prevSettings->slug, sensor->slug) != 0 || + prevSettings->purpose != sensor->purpose || + prevSettings->type != sensor->type); + + // Metadata changes replace entities; disabling discovery removes them. + if (prevSettings && Sensors::hasEnabledAndValid(*prevSettings) + && (metadataChanged || !settings.mqtt.homeAssistantDiscovery)) { + deleteConnectionDynamicSensor(*prevSettings); + deleteSignalQualityDynamicSensor(*prevSettings); + + switch (prevSettings->type) { + case Sensors::Type::BLUETOOTH: + deleteDynamicSensor(*prevSettings, Sensors::ValueType::TEMPERATURE); + deleteDynamicSensor(*prevSettings, Sensors::ValueType::HUMIDITY); + deleteDynamicSensor(*prevSettings, Sensors::ValueType::BATTERY); + deleteDynamicSensor(*prevSettings, Sensors::ValueType::RSSI); + break; + + case Sensors::Type::DHT11: + case Sensors::Type::DHT22: + deleteDynamicSensor(*prevSettings, Sensors::ValueType::TEMPERATURE); + deleteDynamicSensor(*prevSettings, Sensors::ValueType::HUMIDITY); + break; + + default: + deleteDynamicSensor(*prevSettings); + break; + } + } + + // Hardware, calibration and discovery-only refreshes keep retained readings. + if (prevSettings && prevSettings->slug[0] && metadataChanged) { + purgeSensor(prevSettings->slug); + } + + if (settings.mqtt.homeAssistantDiscovery && sensor && Sensors::hasEnabledAndValid(*sensor)) { + if (sensor->type == Sensors::Type::BLUETOOTH || sensor->type == Sensors::Type::DALLAS_TEMP + || sensor->type == Sensors::Type::DHT11 || sensor->type == Sensors::Type::DHT22) { + publishConnectionDynamicSensor(*sensor); + publishSignalQualityDynamicSensor(*sensor); + + } else if (sensor->type == Sensors::Type::NTC_10K_TEMP) { + publishConnectionDynamicSensor(*sensor); + } + + switch (sensor->type) { + case Sensors::Type::BLUETOOTH: + publishDynamicSensor(*sensor, Sensors::ValueType::TEMPERATURE); + publishDynamicSensor(*sensor, Sensors::ValueType::HUMIDITY); + publishDynamicSensor(*sensor, Sensors::ValueType::BATTERY); + publishDynamicSensor(*sensor, Sensors::ValueType::RSSI, false); + break; + + case Sensors::Type::DHT11: + case Sensors::Type::DHT22: + publishDynamicSensor(*sensor, Sensors::ValueType::TEMPERATURE); + publishDynamicSensor(*sensor, Sensors::ValueType::HUMIDITY); + break; + + case Sensors::Type::MANUAL: + publishDynamicManualSensor(*sensor); + break; + + default: + publishDynamicSensor(*sensor); + break; + } + } + + mqttPublishSensorsTask->requestEarlyRun(); + }); + + task->setInterval(500).setEnabledWhen(isMqttReady); + appTaskManager.addTask(*task); + + std::lock_guard lock(mqttMutex); + mqttReconfigureSensorsTask = task; + } + + // Publish sensor readings after startup and pending subscription changes. + if (!mqttPublishSensorsTask) { + auto* task = new Task("Publish MQTT sensors", [](void*) { + static UnitSystem publishedUnitSystem = UnitSystem::METRIC; + if (publishedUnitSystem != settings.system.unitSystem) { + std::lock_guard lock(mqttSensorsMutex); + memset(mqttPublishedSensorAt, 0, sizeof(mqttPublishedSensorAt)); + publishedUnitSystem = settings.system.unitSystem; + } + + const unsigned long changeDelay = mqttPublishSensorsTask->earlyRunRequested() ? 0u : 1000u; + for (uint8_t sensorId = 0; sensorId < SENSORS_AMOUNT; sensorId++) { + std::optional snapshot; + { + std::lock_guard lock(mqttSensorsMutex); + if (isSensorReconfigurationPending(sensorId)) { + continue; + } + + // Keep physical updates after this cutoff pending for the next publication. + const unsigned long snapshotAt = millis(); + snapshot = Sensors::getSnapshot(sensorId); + if (!snapshot || !Sensors::hasEnabledAndValid(snapshot->settings)) { + continue; + } + + const unsigned long publishedAt = mqttPublishedSensorAt[sensorId]; + if (publishedAt) { + const auto now = millis(); + const auto elapsed = now - publishedAt; + const bool changed = now - snapshot->result.updatedAt <= elapsed; + + if (elapsed <= MQTT_SENSOR_REPUBLISH_INTERVAL && (!changed || elapsed < changeDelay)) { + continue; + } + } + + // A newer manual value can reset this timestamp while the snapshot is publishing. + mqttPublishedSensorAt[sensorId] = snapshotAt; + } + + if (!publishSensor(snapshot->settings, snapshot->result)) { + { + std::lock_guard lock(mqttSensorsMutex); + mqttPublishedSensorAt[sensorId] = 0; + } + ESP_LOGD(L_MQTT, "Sensor publication deferred"); + } + } + }); + + task->setInterval(500).setEnabledWhen([] { + if (!isMqttReadyForPublish()) { + return false; + } + + std::lock_guard lock(mqttSensorsMutex); + return mqttSensorChanges.empty(); + }); + appTaskManager.addTask(*task); + + std::lock_guard lock(mqttMutex); + mqttPublishSensorsTask = task; + } + + // Call end() to reset the connection + stopMqtt(false); + + if (!isNetworkConnected()) { + return; + } + + // Call begin() to reconnect + connect(); + + if (!mqttClient->isEnabled()) { + stopMqtt(false); + + // Preserve a newer reconfiguration request instead of replacing it with backoff. + if (!mqttConfigureTask.scheduled()) { + mqttConfigureTask.resume(MQTT_RECONNECT_INTERVAL); + } + + ESP_LOGE(L_MQTT, "Failed to start MQTT client"); + return; + } +}); + +void initMqtt() { + onNetworkEvent([](NetworkEvent event) { + if (event == NetworkEvent::CONNECTED || event == NetworkEvent::DISCONNECTED || event == NetworkEvent::EVENTS_OVERFLOW) { + requestReconfigureMqtt(); + } + }); + + // Keep only the configuration dispatcher when MQTT publications are disabled. + mqttConfigureTask.pause().setEnabledWhen([] { + return !upgrading && !restartTask.scheduled() && !restartTask.active(); + }); + + appTaskManager.addTask(mqttConfigureTask); +} diff --git a/src/network.cpp b/src/network.cpp new file mode 100644 index 0000000..36f8f61 --- /dev/null +++ b/src/network.cpp @@ -0,0 +1,1195 @@ +#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE + +#include + +#include +#include +#include +#if USE_ETHERNET + #include + #include + #include +#endif +#include +#include +#include +#include +#include +#include +#include + +// Requests and state shared with other workers. +static std::atomic reconnectRequested{false}; +static std::atomic staStarted{false}; +static std::atomic apStarted{false}; +static std::atomic staState{NetworkState::NETWORK_DISABLED}; +static std::atomic apState{NetworkState::NETWORK_DISABLED}; +#if USE_ETHERNET +static std::atomic ethStarted{false}; +static std::atomic ethState{NetworkState::NETWORK_DISABLED}; +#endif + +// Subscriptions are fixed before the worker starts. +static std::vector networkCallbacks; +static std::vector stateCallbacks; + +// Framework callbacks only copy events. Driver and service operations stay in this worker. +struct PendingNetworkEvent { + uint32_t value; // IPv4 address for STA_GOT_IP, ETH_GOT_IP and AP_STARTED. + NetworkEvent event; + uint16_t reason; // Wi-Fi disconnect reason. +}; + +static constexpr size_t NETWORK_EVENT_QUEUE_LENGTH = 32; +static StaticQueue_t networkEventQueueStorage; +static uint8_t networkEventBuffer[NETWORK_EVENT_QUEUE_LENGTH * sizeof(PendingNetworkEvent)]; +static QueueHandle_t networkEventQueue = nullptr; +static std::atomic networkEventsOverflowed{false}; +static std::atomic networkRecoveryRequested{false}; + +// Station state and timers; only the system worker accesses these values. +static unsigned long lastConnectionAttempt = 0; +static unsigned long connectedTime = 0; +static unsigned long disconnectedTime = 0; +static unsigned long lastRssiUpdate = 0; +static uint32_t connectedIp = 0; +static uint8_t disconnectReason = 0; +static bool staAssociated = false; +static bool connectionPending = false; +static bool ntpStarted = false; + +// Fallback access point +static unsigned long lastApAttempt = 0; +static uint32_t apIp = 0; +static uint8_t apClients = 0; + +// Full driver recovery +static unsigned long lastNetworkRecoveryAttempt = 0; +static bool recoveryPending = false; + +// DNS is asynchronous in the current framework; it needs no polling task. +static bool webServerReady = false; +static DNSServer dnsServer; +static bool dnsStarted = false; +static bool mdnsStarted = false; +static unsigned long lastDnsAttempt = 0; +static unsigned long lastMdnsAttempt = 0; +static char mdnsHostname[sizeof(networkSettings.hostname)] = {}; +static void stopMdns(); + +// Event subscriptions +void onNetworkEvent(NetworkEventCallback callback) { + if (!callback) { + return; + } + + for (auto registered : networkCallbacks) { + if (registered == callback) { + return; + } + } + + networkCallbacks.push_back(callback); +} + +void onNetworkStateChange(NetworkStateCallback callback) { + if (callback) { + stateCallbacks.push_back(std::move(callback)); + } +} + +// Published interface state +NetworkState getNetworkState(NetworkMode mode) { + if (mode == NetworkMode::STA) { + return staState.load(); + } + + if (mode == NetworkMode::AP) { + return apState.load(); + } + + #if USE_ETHERNET + if (mode == NetworkMode::ETH) { + return ethState.load(); + } + #endif + + return NetworkState::NETWORK_DISABLED; +} + +bool isNetworkConnected() { + return getNetworkState(NetworkMode::STA) == NetworkState::NETWORK_CONNECTED || + getNetworkState(NetworkMode::ETH) == NetworkState::NETWORK_CONNECTED; +} + +NetworkMode getNetworkMode() { + if (getNetworkState(NetworkMode::STA) == NetworkState::NETWORK_CONNECTED) { + return NetworkMode::STA; + } + + if (getNetworkState(NetworkMode::ETH) == NetworkState::NETWORK_CONNECTED) { + return NetworkMode::ETH; + } + + return apStarted.load() ? NetworkMode::AP : NetworkMode::NONE; +} + +const char* getNetworkConnectionType() { + switch (getNetworkMode()) { + case NetworkMode::ETH: + return S_ETHERNET; + case NetworkMode::STA: + return "wifi"; + case NetworkMode::AP: + return "wifi-ap"; + default: + return "none"; + } +} + +static NetworkInterface& getNetworkInterface() { + const NetworkMode mode = getNetworkMode(); + + #if USE_ETHERNET + if (mode == NetworkMode::ETH) { + return ETH; + } + #endif + + if (mode == NetworkMode::AP) { + return WiFi.AP; + } + + return WiFi.STA; +} + +IPAddress getNetworkIp() { + return getNetworkInterface().localIP(); +} + +IPAddress getNetworkSubnet() { + return getNetworkInterface().subnetMask(); +} + +IPAddress getNetworkGateway() { + return getNetworkInterface().gatewayIP(); +} + +IPAddress getNetworkDns() { + return getNetworkInterface().dnsIP(); +} + +String getNetworkMac() { + return getNetworkInterface().macAddress(); +} + +bool isEthernetConfigured(const NetworkSettings& config) { + #if USE_ETHERNET + const auto& gpios = config.ethernet.w5500; + + return config.ethernet.type == EthernetType::W5500 && + GPIO_IS_VALID_OUTPUT(gpios.clk) && + GPIO_IS_VALID_OUTPUT(gpios.mosi) && + GPIO_IS_VALID_INPUT(gpios.miso) && + GPIO_IS_VALID_OUTPUT(gpios.cs) && + GPIO_IS_VALID_INPUT(gpios.irq) && + GPIO_IS_VALID_OUTPUT(gpios.rst); + #else + (void)config; + return false; + #endif +} + +bool isNetworkInterfaceStarted(NetworkMode mode) { + if (mode == NetworkMode::STA) { + return staStarted.load(); + } + + #if USE_ETHERNET + if (mode == NetworkMode::ETH) { + return ethStarted.load(); + } + #endif + + if (mode == NetworkMode::AP) { + return apStarted.load(); + } + + return false; +} + +// Requests from other tasks; driver operations run in the system worker. +void reconnectNetwork() { + reconnectRequested.store(true); +} + +// State transitions and notifications +static void notifyNetworkEvent(NetworkEvent event) { + for (auto callback : networkCallbacks) { + callback(event); + } +} + +static void setNetworkState(NetworkMode mode, NetworkState next) { + auto* state = mode == NetworkMode::STA ? &staState : &apState; + #if USE_ETHERNET + if (mode == NetworkMode::ETH) { + state = ðState; + } + #endif + + const NetworkState previous = state->load(); + if (previous == next) { + return; + } + + const bool uplink = mode == NetworkMode::STA || mode == NetworkMode::ETH; + if (uplink) { + if (previous == NetworkState::NETWORK_CONNECTED) { + disconnectedTime = millis(); + connectedIp = 0; + vars.network.rssi = 0; + ntpStarted = false; + Sensors::setConnectionStatusByType(Sensors::Type::MANUAL, false, false); + } + + if (next == NetworkState::NETWORK_CONNECTED) { + connectedTime = millis(); + } + } + + // Publish before callbacks so getters and JSON already reflect the new state. + state->store(next); + for (auto& callback : stateCallbacks) { + callback(mode, previous, next); + } + + if (uplink) { + if (next == NetworkState::NETWORK_CONNECTED) { + notifyNetworkEvent(NetworkEvent::CONNECTED); + + } else if (previous == NetworkState::NETWORK_CONNECTED) { + notifyNetworkEvent(NetworkEvent::DISCONNECTED); + } + } +} + +// Framework events +static void queueNetworkEvent(NetworkEvent event, uint32_t value = 0, uint16_t reason = 0) { + const PendingNetworkEvent pending{value, event, reason}; + + // Never wait here: this worker can be waiting for the framework inside STA/AP.begin(). + if (xQueueSend(networkEventQueue, &pending, 0) != pdTRUE) { + networkEventsOverflowed.store(true); + } +} + +static void handleNetworkEvent(arduino_event_id_t event, arduino_event_info_t info) { + // This callback runs in the Arduino event task; only copy the event data here. + switch (event) { + // Station + case ARDUINO_EVENT_WIFI_STA_START: + queueNetworkEvent(NetworkEvent::STA_STARTED); + break; + case ARDUINO_EVENT_WIFI_STA_STOP: + queueNetworkEvent(NetworkEvent::STA_STOPPED); + break; + case ARDUINO_EVENT_WIFI_STA_CONNECTED: + queueNetworkEvent(NetworkEvent::STA_CONNECTED); + break; + case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: + queueNetworkEvent(NetworkEvent::STA_DISCONNECTED, 0, info.wifi_sta_disconnected.reason); + break; + case ARDUINO_EVENT_WIFI_STA_GOT_IP: + queueNetworkEvent(NetworkEvent::STA_GOT_IP, info.got_ip.ip_info.ip.addr); + break; + case ARDUINO_EVENT_WIFI_STA_LOST_IP: + queueNetworkEvent(NetworkEvent::STA_LOST_IP); + break; + case ARDUINO_EVENT_WIFI_STA_GOT_IP6: + queueNetworkEvent(NetworkEvent::STA_GOT_IP6); + break; + + // Access point + case ARDUINO_EVENT_WIFI_AP_START: + queueNetworkEvent(NetworkEvent::AP_STARTED, static_cast(WiFi.AP.localIP())); + break; + case ARDUINO_EVENT_WIFI_AP_STOP: + queueNetworkEvent(NetworkEvent::AP_STOPPED); + break; + case ARDUINO_EVENT_WIFI_AP_STACONNECTED: + queueNetworkEvent(NetworkEvent::AP_CLIENT_CONNECTED); + break; + case ARDUINO_EVENT_WIFI_AP_STADISCONNECTED: + queueNetworkEvent(NetworkEvent::AP_CLIENT_DISCONNECTED, 0, info.wifi_ap_stadisconnected.reason); + break; + case ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED: + queueNetworkEvent(NetworkEvent::AP_CLIENT_GOT_IP); + break; + case ARDUINO_EVENT_WIFI_AP_GOT_IP6: + queueNetworkEvent(NetworkEvent::AP_GOT_IP6); + break; + + #if USE_ETHERNET + case ARDUINO_EVENT_ETH_START: + queueNetworkEvent(NetworkEvent::ETH_STARTED); + break; + case ARDUINO_EVENT_ETH_STOP: + queueNetworkEvent(NetworkEvent::ETH_STOPPED); + break; + case ARDUINO_EVENT_ETH_CONNECTED: + queueNetworkEvent(NetworkEvent::ETH_CONNECTED); + break; + case ARDUINO_EVENT_ETH_DISCONNECTED: + queueNetworkEvent(NetworkEvent::ETH_DISCONNECTED); + break; + case ARDUINO_EVENT_ETH_GOT_IP: + queueNetworkEvent(NetworkEvent::ETH_GOT_IP, info.got_ip.ip_info.ip.addr); + break; + case ARDUINO_EVENT_ETH_LOST_IP: + queueNetworkEvent(NetworkEvent::ETH_LOST_IP); + break; + case ARDUINO_EVENT_ETH_GOT_IP6: + queueNetworkEvent(NetworkEvent::ETH_GOT_IP6); + break; + #endif + + default: + break; + } +} + +static void postInterfaceStopped(arduino_event_id_t type) { + // Interface teardown can remove native STOP handlers. Keep our notification ordered + // after already queued framework START/GOT_IP events and before the next start. + arduino_event_t event{}; + event.event_id = type; + if (!Network.postEvent(&event)) { + ESP_LOGE(L_NETWORK, "Failed post interface stop, reset network requested"); + networkRecoveryRequested.store(true); + } +} + +// WiFi interfaces +static bool shouldEnableWifiRadio() { + return networkSettings.type == NetworkMode::STA; +} + +static void fallbackToWifi() { + ESP_LOGW(L_NETWORK, "Ethernet unavailable, switching to WiFi"); + networkSettings.type = NetworkMode::STA; +} + +static void configureWifiRadio() { + // Apply the existing channel policy after the WiFi driver has started. + const wifi_country_t country = { + "JP", + 1, + 14, + CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER, + WIFI_COUNTRY_POLICY_MANUAL + }; + + esp_wifi_set_country(&country); + //WiFi.setSleep(USE_BLE ? WIFI_PS_MIN_MODEM : WIFI_PS_NONE); + WiFi.setSleep(WIFI_PS_NONE); +} + +static void stopAccessPoint() { + stopMdns(); + if (!WiFi.AP.end()) { + ESP_LOGE(L_NETWORK, "Failed stop AP, reset WiFi requested"); + networkRecoveryRequested.store(true); + return; + } + + postInterfaceStopped(ARDUINO_EVENT_WIFI_AP_STOP); +} + +static void startAccessPoint() { + if (!shouldEnableWifiRadio()) { + return; + } + + lastApAttempt = millis(); + setNetworkState(NetworkMode::AP, NetworkState::AP_STARTING); + + // Keep STA available for scans and retries while the fallback AP is running. + WiFi.STA.begin(); + if (!WiFi.AP.begin()) { + // begin() can enable AP but time out before its STARTED event arrives. + stopAccessPoint(); + setNetworkState(NetworkMode::AP, NetworkState::NETWORK_DISABLED); + ESP_LOGE(L_NETWORK, "Failed start AP"); + return; + } + + configureWifiRadio(); + WiFi.AP.setHostname(networkSettings.hostname); + + const bool apCreated = WiFi.AP.create( + networkSettings.wifi.ap.ssid, + networkSettings.wifi.ap.password[0] ? networkSettings.wifi.ap.password : nullptr, + networkSettings.wifi.ap.channel + ); + if (!apCreated) { + stopAccessPoint(); + setNetworkState(NetworkMode::AP, NetworkState::NETWORK_DISABLED); + ESP_LOGE(L_NETWORK, "Failed configure AP"); + return; + } + + WiFi.scanNetworks(true, true, true); +} + +static bool resetWifi() { + const bool restoreAp = WiFi.AP.started(); + connectionPending = false; + stopMdns(); + + // A failed driver reset must also respect the retry cooldown. + lastConnectionAttempt = millis(); + if (!WiFi.mode(WIFI_OFF)) { + ESP_LOGE(L_NETWORK, "Failed reset WiFi"); + return false; + } + + postInterfaceStopped(ARDUINO_EVENT_WIFI_STA_STOP); + if (restoreAp) { + postInterfaceStopped(ARDUINO_EVENT_WIFI_AP_STOP); + } + + lastConnectionAttempt = 0; + if (restoreAp && shouldEnableWifiRadio()) { + startAccessPoint(); + } + + return true; +} + +static bool stopStation() { + const bool wasStarted = WiFi.STA.started(); + // mDNS keeps netif pointers; release them before the driver destroys STA. + stopMdns(); + if (!WiFi.STA.end()) { + ESP_LOGW(L_NETWORK, "Failed stop STA, reset WiFi requested"); + return false; + } + + if (wasStarted) { + postInterfaceStopped(ARDUINO_EVENT_WIFI_STA_STOP); + } + + lastConnectionAttempt = 0; + connectionPending = false; + return true; +} + +static bool startNetworkConnection() { + if (!shouldEnableWifiRadio()) { + return false; + } + + if (!WiFi.STA.begin()) { + return false; + } + + // Cancel an unfinished attempt without destroying the netif used by mDNS. + const esp_err_t result = esp_wifi_disconnect(); + if (result != ESP_OK && result != ESP_ERR_WIFI_NOT_CONNECT) { + ESP_LOGW(L_NETWORK, "Failed cancel STA connection: %s", esp_err_to_name(result)); + return false; + } + + configureWifiRadio(); + WiFi.STA.setAutoReconnect(false); + WiFi.STA.setScanMethod(WIFI_ALL_CHANNEL_SCAN); + WiFi.STA.setSortMethod(WIFI_CONNECT_AP_BY_SIGNAL); + + if (!WiFi.STA.setHostname(networkSettings.hostname)) { + ESP_LOGE(L_NETWORK, "Set hostname '%s': fail", networkSettings.hostname); + } + + if (networkSettings.useDhcp) { + if (!WiFi.STA.config()) { + return false; + } + + } else { + IPAddress ip, gateway, subnet, dns; + ip.fromString(networkSettings.staticConfig.ip); + gateway.fromString(networkSettings.staticConfig.gateway); + subnet.fromString(networkSettings.staticConfig.subnet); + dns.fromString(networkSettings.staticConfig.dns); + + if (!WiFi.STA.config(ip, gateway, subnet, dns)) { + return false; + } + } + + setNetworkState( + NetworkMode::STA, + connectedTime ? NetworkState::NETWORK_RECONNECTING : NetworkState::NETWORK_CONNECTING + ); + + return WiFi.STA.connect( + networkSettings.wifi.sta.ssid, + networkSettings.wifi.sta.password[0] ? networkSettings.wifi.sta.password : nullptr, + networkSettings.wifi.sta.channel + ); +} + +// Ethernet driver +#if USE_ETHERNET +static bool stopEthernet() { + stopMdns(); + ethStarted.store(false); + setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_DISABLED); + ETH.end(); + + // end() can return before releasing a partially initialized driver. + if (ETH.handle() != nullptr || ETH.netif() != nullptr) { + if (ETH.netif() != nullptr) { + ETH.setRoutePrio(0); + esp_netif_action_stop(ETH.netif(), ETH_EVENT, ETHERNET_EVENT_STOP, nullptr); + } + ESP_LOGE(L_NETWORK, "Failed release Ethernet driver"); + return false; + } + + // end() removes the device, but leaves the SPI bus with its previous GPIOs. + const esp_err_t result = spi_bus_free(SPI2_HOST); + if (result != ESP_OK && result != ESP_ERR_INVALID_STATE) { + ESP_LOGE(L_NETWORK, "Failed release Ethernet SPI bus: %s", esp_err_to_name(result)); + return false; + } + + postInterfaceStopped(ARDUINO_EVENT_ETH_STOP); + return true; +} + +static bool configureEthernet() { + ETH.setHostname(networkSettings.hostname); + if (networkSettings.useDhcp) { + return ETH.config(); + } + + IPAddress ip, gateway, subnet, dns; + ip.fromString(networkSettings.staticConfig.ip); + gateway.fromString(networkSettings.staticConfig.gateway); + subnet.fromString(networkSettings.staticConfig.subnet); + dns.fromString(networkSettings.staticConfig.dns); + return ETH.config(ip, gateway, subnet, dns); +} + +static bool startEthernet() { + if ((ETH.handle() != nullptr || ETH.netif() != nullptr) && !stopEthernet()) { + return false; + } + + const auto& gpios = networkSettings.ethernet.w5500; + ESP_LOGI(L_NETWORK, "Initialize W5500 Ethernet"); + if (!ETH.begin( + ETH_PHY_W5500, 1, gpios.cs, gpios.irq, gpios.rst, + SPI2_HOST, gpios.clk, gpios.miso, gpios.mosi, 12 + )) { + ESP_LOGE(L_NETWORK, "W5500 initialization failed, check GPIOs and wiring"); + stopEthernet(); + return false; + } + + ethStarted.store(true); + setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_CONNECTING); + return true; +} + +#endif + +// Station connection and recovery timeouts +static void updateConnection() { + if (!networkSettings.wifi.sta.ssid[0]) { + return; + } + + // Let the portal scan finish before starting another connection or recovery. + if (WiFi.scanComplete() == WIFI_SCAN_RUNNING) { + return; + } + + if (connectionPending) { + if (millis() - lastConnectionAttempt < 10000) { + return; + } + + connectionPending = false; + lastConnectionAttempt = millis(); + setNetworkState(NetworkMode::STA, NetworkState::NETWORK_TIMEOUT); + + ESP_LOGD( + L_NETWORK, + "Connection attempt timed out. Status: %d", + WiFi.STA.status() + ); + } + + // Associated without IP: allow DHCP to recover before resetting the whole driver. + if (staAssociated) { + if (millis() - lastConnectionAttempt > 90000) { + ESP_LOGW(L_NETWORK, "Connection timeout, reset WiFi..."); + resetWifi(); + } + + return; + } + + if (!lastConnectionAttempt || millis() - lastConnectionAttempt > 15000) { + ESP_LOGI(L_NETWORK, "Try connect..."); + + connectionPending = startNetworkConnection(); + lastConnectionAttempt = millis(); + + if (!connectionPending) { + setNetworkState(NetworkMode::STA, NetworkState::NETWORK_TIMEOUT); + ESP_LOGW(L_NETWORK, "Failed start connection"); + } + } +} + +// Fallback access point +static void updateAccessPoint() { + if (isNetworkConnected()) { + if (apStarted.load() && millis() - connectedTime > 15000 && !apClients) { + ESP_LOGI(L_NETWORK, "Stop AP because STA connected"); + stopAccessPoint(); + } + + return; + } + + if (!apStarted.load() && (!networkSettings.wifi.sta.ssid[0] || millis() - disconnectedTime > 185000)) { + if (!lastApAttempt || millis() - lastApAttempt > 15000) { + ESP_LOGI(L_NETWORK, "Start fallback AP"); + startAccessPoint(); + } + } +} + +// Captive DNS and mDNS +static void stopCaptiveDns(bool complete = false) { + if (!dnsStarted) { + return; + } + + dnsServer.stop(); + dnsStarted = false; + lastDnsAttempt = 0; + + if (complete) { + setNetworkState(NetworkMode::AP, NetworkState::PORTAL_COMPLETE); + } + + setNetworkState( + NetworkMode::AP, + apStarted.load() ? NetworkState::AP_STARTED : NetworkState::NETWORK_DISABLED + ); + notifyNetworkEvent(NetworkEvent::PORTAL_STOPPED); + ESP_LOGD(L_PORTAL_DNSSERVER, "Stopped"); +} + +static void stopMdns() { + if (mdnsStarted) { + MDNS.end(); + mdnsStarted = false; + lastMdnsAttempt = 0; + notifyNetworkEvent(NetworkEvent::MDNS_STOPPED); + ESP_LOGD(L_PORTAL_WEBSERVER, "mDNS disabled"); + } +} + +static void updateNetworkServices() { + // Serve captive DNS only while HTTP is ready and no upstream connection exists. + const bool captive = webServerReady && apStarted.load() && apIp && !isNetworkConnected(); + + if (!captive) { + stopCaptiveDns(isNetworkConnected()); + + } else if (!dnsStarted && (!lastDnsAttempt || millis() - lastDnsAttempt >= 5000)) { + lastDnsAttempt = millis(); + setNetworkState(NetworkMode::AP, NetworkState::PORTAL_STARTING); + + if (dnsServer.start(53, "*", IPAddress(apIp))) { + dnsStarted = true; + setNetworkState(NetworkMode::AP, NetworkState::PORTAL_STARTED); + notifyNetworkEvent(NetworkEvent::PORTAL_STARTED); + ESP_LOGD(L_PORTAL_DNSSERVER, "Started: AP up"); + + } else { + dnsServer.stop(); + setNetworkState(NetworkMode::AP, NetworkState::AP_STARTED); + ESP_LOGE(L_PORTAL_DNSSERVER, "Failed start DNS"); + } + } + + // mDNS tracks native interface/IP events without restarting the responder. + const bool enableMdns = webServerReady && settings.portal.mdns; + + if (!enableMdns) { + stopMdns(); + + } else { + if (mdnsStarted && strcmp(mdnsHostname, networkSettings.hostname) != 0) { + stopMdns(); + lastMdnsAttempt = 0; + } + + if (!mdnsStarted && (!lastMdnsAttempt || millis() - lastMdnsAttempt >= 5000)) { + lastMdnsAttempt = millis(); + bool started = MDNS.begin(networkSettings.hostname); + + if (started) { + started = MDNS.addService("http", "tcp", 80); + } + + if (started) { + strcpy(mdnsHostname, networkSettings.hostname); + mdnsStarted = true; + notifyNetworkEvent(NetworkEvent::MDNS_STARTED); + ESP_LOGD(L_PORTAL_WEBSERVER, "mDNS enabled and service added"); + + } else { + MDNS.end(); + ESP_LOGE(L_PORTAL_WEBSERVER, "Failed start mDNS"); + } + } + } +} + +// Event processing and recovery +static void processNetworkEvent(const PendingNetworkEvent& pending) { + switch (pending.event) { + // Station + case NetworkEvent::STA_STARTED: + if (!shouldEnableWifiRadio()) { + return; + } + + // Repeated START must not invalidate an active connection. + if (staStarted.exchange(true)) { + break; + } + + if (connectionPending) { + setNetworkState( + NetworkMode::STA, + connectedTime ? NetworkState::NETWORK_RECONNECTING : NetworkState::NETWORK_CONNECTING + ); + + } else { + setNetworkState(NetworkMode::STA, NetworkState::NETWORK_ENABLED); + } + break; + + case NetworkEvent::STA_STOPPED: { + const bool started = staStarted.exchange(false); + staAssociated = false; + disconnectReason = 0; + setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISABLED); + if (!started) { + return; + } + break; + } + + case NetworkEvent::STA_CONNECTED: + if (!shouldEnableWifiRadio()) { + return; + } + + // Association alone does not confirm a usable IP address. + staAssociated = true; + break; + + case NetworkEvent::STA_GOT_IP: + if (!shouldEnableWifiRadio() || !pending.value) { + return; + } + + // GOT_IP confirms both DHCP and configured static IPv4 after association. + // IP changes invalidate the previous client session, including A -> B -> A. + if (getNetworkState(NetworkMode::STA) == NetworkState::NETWORK_CONNECTED && connectedIp != pending.value) { + disconnectReason = 0; + setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISCONNECTED); + } + + staAssociated = true; + connectedIp = pending.value; + if (getNetworkState(NetworkMode::STA) != NetworkState::NETWORK_CONNECTED) { + vars.network.rssi = WiFi.STA.RSSI(); + lastRssiUpdate = millis(); + setNetworkState(NetworkMode::STA, NetworkState::NETWORK_CONNECTED); + } + break; + + case NetworkEvent::STA_DISCONNECTED: + staAssociated = false; + disconnectReason = pending.reason; + setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISCONNECTED); + break; + + case NetworkEvent::STA_LOST_IP: + // Keep association so the DHCP recovery timeout remains active. + disconnectReason = 0; + setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISCONNECTED); + break; + + #if USE_ETHERNET + case NetworkEvent::ETH_STARTED: + if (!ethStarted.load() || networkSettings.type != NetworkMode::ETH) { + return; + } + + // Apply after native START so a preceding STOP cannot clear the static-IP state. + if (!configureEthernet()) { + ESP_LOGE(L_NETWORK, "Failed configure Ethernet IPv4"); + setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_TIMEOUT); + break; + } + + if (getNetworkState(NetworkMode::ETH) == NetworkState::NETWORK_DISABLED) { + setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_ENABLED); + } + break; + + case NetworkEvent::ETH_STOPPED: + setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_DISABLED); + break; + + case NetworkEvent::ETH_CONNECTED: + if (!ethStarted.load() || networkSettings.type != NetworkMode::ETH) { + return; + } + + if (getNetworkState(NetworkMode::ETH) != NetworkState::NETWORK_CONNECTED) { + setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_CONNECTING); + } + break; + + case NetworkEvent::ETH_GOT_IP: + if (!ethStarted.load() || networkSettings.type != NetworkMode::ETH) { + return; + } + + if (!pending.value || !ETH.connected() || !ETH.hasIP()) { + return; + } + + if (getNetworkState(NetworkMode::ETH) == NetworkState::NETWORK_CONNECTED && connectedIp != pending.value) { + setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_DISCONNECTED); + } + + connectedIp = pending.value; + if (getNetworkState(NetworkMode::ETH) != NetworkState::NETWORK_CONNECTED) { + vars.network.rssi = 0; + setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_CONNECTED); + } + break; + + case NetworkEvent::ETH_DISCONNECTED: + case NetworkEvent::ETH_LOST_IP: + setNetworkState( + NetworkMode::ETH, + ethStarted.load() ? NetworkState::NETWORK_DISCONNECTED : NetworkState::NETWORK_DISABLED + ); + break; + #endif + + // Access point + case NetworkEvent::AP_STARTED: + if (!shouldEnableWifiRadio()) { + return; + } + + // Preserve clients and captive portal state on a repeated START. + if (apStarted.exchange(true)) { + break; + } + + apIp = pending.value; + apClients = 0; + setNetworkState(NetworkMode::AP, NetworkState::AP_STARTED); + break; + + case NetworkEvent::AP_STOPPED: { + stopCaptiveDns(); + const bool started = apStarted.exchange(false); + apIp = 0; + apClients = 0; + setNetworkState(NetworkMode::AP, NetworkState::NETWORK_DISABLED); + if (!started) { + return; + } + break; + } + + case NetworkEvent::AP_CLIENT_CONNECTED: + if (apClients < UINT8_MAX) { + ++apClients; + } + ESP_LOGI(L_NETWORK, "AP client connected, clients: %hhu", apClients); + break; + + case NetworkEvent::AP_CLIENT_DISCONNECTED: + if (apClients) { + --apClients; + } + ESP_LOGI(L_NETWORK, "AP client disconnected, clients: %hhu, reason: %hu", apClients, pending.reason); + break; + + default: + break; + } + + notifyNetworkEvent(pending.event); +} + +static void processNetworkEvents() { + const bool overflowed = networkEventsOverflowed.exchange(false); + const bool recoveryRequested = networkRecoveryRequested.exchange(false); + + if (overflowed || recoveryRequested) { + // Lost events invalidate published state immediately, even during the reset cooldown. + xQueueReset(networkEventQueue); + stopCaptiveDns(); + stopMdns(); + + staStarted.store(false); + staAssociated = false; + setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISABLED); + + apStarted.store(false); + setNetworkState(NetworkMode::AP, NetworkState::NETWORK_DISABLED); + + #if USE_ETHERNET + setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_DISABLED); + #endif + + if (overflowed) { + ESP_LOGW(L_NETWORK, "Network event queue overflow, reset network requested"); + notifyNetworkEvent(NetworkEvent::EVENTS_OVERFLOW); + } + + recoveryPending = true; + } + + if (recoveryPending) { + // Limit driver resets, but keep the published state offline while waiting. + if (lastNetworkRecoveryAttempt && millis() - lastNetworkRecoveryAttempt < 15000) { + return; + } + + lastNetworkRecoveryAttempt = millis(); + // Keep callbacks nonblocking; recover through the existing full-reset path. + ESP_LOGW(L_NETWORK, "Reset network after event failure..."); + #if USE_ETHERNET + if (ethStarted.load() && !stopEthernet()) { + fallbackToWifi(); + } + #endif + + if (!resetWifi()) { + return; + } + + recoveryPending = false; + } + + // Bound each pass so event bursts leave time for the rest of the worker. + PendingNetworkEvent pending; + for (size_t count = 0; count < NETWORK_EVENT_QUEUE_LENGTH; ++count) { + if (xQueueReceive(networkEventQueue, &pending, 0) != pdTRUE) { + break; + } + + processNetworkEvent(pending); + } +} + +// Connection services +static void updateRssi() { + if (getNetworkMode() == NetworkMode::STA && millis() - lastRssiUpdate >= 1000) { + vars.network.rssi = WiFi.STA.RSSI(); + lastRssiUpdate = millis(); + } +} + +static void updateNtp() { + if (!ntpStarted && settings.system.ntp.server[0]) { + configTime(0, 0, settings.system.ntp.server); + setenv("TZ", settings.system.ntp.timezone, 1); + tzset(); + ntpStarted = true; + } +} + +static void logNetworkState(NetworkMode mode, NetworkState previous, NetworkState state) { + if (mode != networkSettings.type) { + return; + } + + if (state == NetworkState::NETWORK_CONNECTED) { + ESP_LOGI( + L_NETWORK, + "Connected, downtime: %lu s., IP: %s, RSSI: %hhd", + (millis() - disconnectedTime) / 1000, + IPAddress(connectedIp).toString().c_str(), + vars.network.rssi + ); + + } else if (previous == NetworkState::NETWORK_CONNECTED) { + ESP_LOGI( + L_NETWORK, + "Disconnected, reason: %hhu, uptime: %lu s.", + disconnectReason, + (millis() - connectedTime) / 1000 + ); + } +} + +// Tasks +static Task networkStartTask("Start network services", Task::Type::ONCE, [](void*) { + if (webServerReady || (!isNetworkInterfaceStarted(NetworkMode::AP) && !isNetworkConnected())) { + return; + } + + webServer->begin(); + webServerReady = true; + configureLoggingTask.resume(); + ESP_LOGD(L_PORTAL_WEBSERVER, "Started: AP up or uplink connected"); +}); + +static Task reconnectTask("Reconnect network", Task::Type::ONCE, [](void*) { + ESP_LOGI(L_NETWORK, "Reconnecting..."); + + #if USE_ETHERNET + if (ethStarted.load() && !stopEthernet()) { + fallbackToWifi(); + } + #endif + + if (shouldEnableWifiRadio()) { + if (!stopStation()) { + networkRecoveryRequested.store(true); + } + + } else if (!resetWifi()) { + networkRecoveryRequested.store(true); + } +}); + +static Task networkTask("Network", [](void*) { + // Delay explicit reconnects so the HTTP handler can finish its response. + if (reconnectRequested.exchange(false)) { + reconnectTask.resume(5000); + } + + // Apply queued transitions before using the interfaces and services. + processNetworkEvents(); + if (!isNetworkConnected()) { + Sensors::setConnectionStatusByType(Sensors::Type::MANUAL, false, false); + } + + if (recoveryPending || networkRecoveryRequested.load() || networkEventsOverflowed.load()) { + return; + } + + updateRssi(); + updateNetworkServices(); + + // Continue processing events and services during the reconnect delay. + if (!reconnectTask.paused()) { + return; + } + + if (networkSettings.type == NetworkMode::ETH && !isEthernetConfigured()) { + #if USE_ETHERNET + if (ethStarted.load()) { + stopEthernet(); + } + #endif + fallbackToWifi(); + } + + if (networkSettings.type == NetworkMode::ETH) { + if (WiFi.getMode() != WIFI_OFF && !resetWifi()) { + networkRecoveryRequested.store(true); + return; + } + + #if USE_ETHERNET + if (!ethStarted.load() && !startEthernet()) { + fallbackToWifi(); + } + #endif + + if (isNetworkConnected()) { + updateNtp(); + } + return; + } + + #if USE_ETHERNET + if (ethStarted.load()) { + stopEthernet(); + } + #endif + + if (isNetworkConnected()) { + if (connectionPending) { + connectionPending = false; + lastConnectionAttempt = millis(); + } + + updateNtp(); + updateAccessPoint(); + + } else { + updateAccessPoint(); + updateConnection(); + } +}); + +// Initialization +void initNetwork() { + // The queue must exist before registering framework callbacks or starting WiFi. + networkEventQueue = xQueueCreateStatic( + NETWORK_EVENT_QUEUE_LENGTH, + sizeof(PendingNetworkEvent), + networkEventBuffer, + &networkEventQueueStorage + ); + + if (!networkEventQueue) { + ESP_LOGE(L_NETWORK, "Failed create network event queue"); + std::abort(); + } + + dnsServer.setTTL(0); + dnsServer.setErrorReplyCode(DNSReplyCode::NoError); + + onNetworkEvent([](NetworkEvent event) { + if (!webServerReady && (event == NetworkEvent::AP_STARTED || event == NetworkEvent::CONNECTED)) { + networkStartTask.resume(); + } + }); + + Network.begin(); + Network.onEvent(handleNetworkEvent); + onNetworkStateChange(logNetworkState); + WiFi.persistent(false); + WiFi.STA.setAutoReconnect(false); + Network.setHostname(networkSettings.hostname); + + systemTaskManager.addTask(reconnectTask); + systemTaskManager.addTask(networkTask.setInterval(100)); + systemTaskManager.addTask(networkStartTask); +} diff --git a/src/opentherm.cpp b/src/opentherm.cpp new file mode 100644 index 0000000..779f009 --- /dev/null +++ b/src/opentherm.cpp @@ -0,0 +1,2351 @@ +#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE + +#include +#include + +#include +#include + +// Application state and ID polling belong to this manager; the library owns RMT. +TaskManager openthermTaskManager("OpenTherm"); + +static const unsigned short masterReadyTime = 60000u; +static const unsigned int resetBusInterval = 120000u; +static const unsigned short heatingSetpointWriteInterval = 60000u; +static const unsigned short roomSetpointWriteInterval = 60000u; +static const unsigned short dhwSetpointWriteInterval = 60000u; +static const unsigned short ch2SetpointWriteInterval = 60000u; +static const unsigned int initializingInterval = 1800000u; +static const char responseMismatchMessage[] = "Response mismatch: expected %04x, received %04x"; +static const char unrepresentableTemperatureLimitsMessage[] = "Received temperature limits cannot be represented in system units"; + +static ESP32OT::ESP32OT slave; +static unsigned long busConfiguredTime = 0; +static unsigned long connectedTime = 0; +static unsigned long disconnectedTime = 0; +static unsigned long resetBusTime = 0; +static unsigned long initializedTime = 0; +static unsigned long lastSuccessStatusResponse = 0; +static unsigned long heatingSetpointWriteTime = 0; +static unsigned long dhwSetpointWriteTime = 0; +static unsigned long ch2SetpointWriteTime = 0; +static unsigned long roomSetpointWriteTime = 0; +static unsigned long ch2RoomSetpointWriteTime = 0; +static std::atomic configuredRxLedGpio{GPIO_IS_NOT_CONFIGURED}; + + +static bool canUseBus() { + return !restartTask.scheduled() && slave.isInitialized() && + slave.getConfig().rxGpio == settings.opentherm.inGpio && + slave.getConfig().txGpio == settings.opentherm.outGpio; +} + +static bool isMasterReady() { + return millis() - busConfiguredTime > masterReadyTime; +} + +static bool getSlaveChannelEnabled(const bool enabled, const ChannelDisablingAction action); +static float getSlaveChannelSetpoint(const bool enabled, const float temperature, const ChannelDisablingAction action); +static bool needWriteRoomSetpoint(const float target); +static bool needWriteRoomSetpointCh2(const float target); +static bool needWriteDhwSetpoint(const float target); +static bool needWriteHeatingSetpoint(const float target); +static bool needWriteCh2Setpoint(const float target); + +static bool getSlaveChannelEnabled(const bool enabled, const ChannelDisablingAction action) { + return enabled || action == ChannelDisablingAction::ZERO_SETPOINT; +} + +static float getSlaveChannelSetpoint(const bool enabled, const float temperature, const ChannelDisablingAction action) { + if (!enabled && action != ChannelDisablingAction::OFF) { + return 0.0f; + } + + return temperature; +} + +static float getHeatingChannelSetpoint() { + return getSlaveChannelSetpoint( + vars.master.heating.enabled, + settings.opentherm.options.nativeOTC + ? vars.master.heating.targetTemp + : vars.master.heating.setpointTemp, + settings.opentherm.heatingDisablingAction + ); +} + +static float getDhwChannelSetpoint() { + return getSlaveChannelSetpoint( + vars.master.dhw.enabled, vars.master.dhw.targetTemp, settings.opentherm.dhwDisablingAction + ); +} + +static float getCh2ChannelSetpoint() { + return getSlaveChannelSetpoint( + vars.master.ch2.enabled, vars.master.ch2.targetTemp, settings.opentherm.ch2DisablingAction + ); +} + +static bool needWriteRoomSetpoint(const float target) { + if (!std::isfinite(target)) { + return false; + } + + return !roomSetpointWriteTime || + millis() - roomSetpointWriteTime > roomSetpointWriteInterval || + isFloatDifferent(target, vars.slave.heating.roomTargetTemp, 0.05f); +} + +static bool needWriteRoomSetpointCh2(const float target) { + if (!std::isfinite(target)) { + return false; + } + + return !ch2RoomSetpointWriteTime || + millis() - ch2RoomSetpointWriteTime > roomSetpointWriteInterval || + isFloatDifferent(target, vars.slave.ch2.roomTargetTemp, 0.05f); +} + +static bool needWriteDhwSetpoint(const float target) { + if (!std::isfinite(target)) { + return false; + } + + return !dhwSetpointWriteTime || + millis() - dhwSetpointWriteTime > dhwSetpointWriteInterval || + isFloatDifferent(target, vars.slave.dhw.targetTemp, 0.05f); +} + +static bool needWriteHeatingSetpoint(const float target) { + if (!std::isfinite(target)) { + return false; + } + + return !heatingSetpointWriteTime || + millis() - heatingSetpointWriteTime > heatingSetpointWriteInterval || + isFloatDifferent(target, vars.slave.heating.targetTemp, 0.05f); +} + +static bool needWriteCh2Setpoint(const float target) { + if (!std::isfinite(target)) { + return false; + } + + return !ch2SetpointWriteTime || + millis() - ch2SetpointWriteTime > ch2SetpointWriteInterval || + isFloatDifferent(target, vars.slave.ch2.targetTemp, 0.05f); +} + +// ONCE identification steps keep their own callbacks and completion handling. +static Task readSlaveVersionTask("Read slave version", Task::Type::ONCE, [](void*) { + const auto response = slave.sendRequest( + ESP32OT::Messages::ProductVersion(ESP32OT::MessageID::SlaveVersion) + ); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive slave version"); + return; + } + + vars.slave.appVersion = response.getVersion(); + vars.slave.type = response.getProductType(); + + ESP_LOGI( + L_OT, "Received slave app version: %u, type: %u", + vars.slave.appVersion, vars.slave.type + ); +}); + +static Task writeMasterVersionTask("Write master version", Task::Type::ONCE, [](void*) { + const ESP32OT::Messages::ProductVersion request( + ESP32OT::MessageID::MasterVersion, + vars.master.type, + vars.master.appVersion + ); + const auto response = slave.sendRequest(request); + + if (!response.isSuccess() || response.getVersion() != request.getVersion() || response.getProductType() != request.getProductType()) { + ESP_LOGW(L_OT, "Failed set master version"); + return; + } + + ESP_LOGI( + L_OT, "Set master version: %u, type: %u", + vars.master.appVersion, vars.master.type + ); +}); + +static Task readSlaveProtocolTask("Read slave protocol", Task::Type::ONCE, [](void*) { + const auto response = slave.sendRequest( + ESP32OT::Messages::Float(ESP32OT::MessageID::OpenThermVersionSlave) + ); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive slave OT version"); + return; + } + + vars.slave.protocolVersion = response.get(); + + ESP_LOGI(L_OT, "Received slave OT version: %f", vars.slave.protocolVersion); +}); + +static Task writeMasterProtocolTask("Write master protocol", Task::Type::ONCE, [](void*) { + const ESP32OT::Messages::Float request( + ESP32OT::MessageID::OpenThermVersionMaster, + vars.master.protocolVersion + ); + const auto response = slave.sendRequest(request); + + if (!response.isSuccess() || response.getData() != request.getData()) { + ESP_LOGW(L_OT, "Failed set master OT version"); + return; + } + + ESP_LOGI(L_OT, "Set master OT version: %f", vars.master.protocolVersion); +}); + +static Task readSlaveConfigTask("Read slave config", Task::Type::ONCE, [](void*) { + const auto response = slave.sendRequest(ESP32OT::Messages::SlaveConfig()); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive slave config"); + return; + } + + vars.slave.memberId = response.getMemberId(); + vars.slave.flags = response.getHighByte(); + + ESP_LOGI( + L_OT, "Received slave member id: %u, flags: %u", + vars.slave.memberId, vars.slave.flags + ); +}); + +static Task writeMasterConfigTask("Write master config", Task::Type::ONCE, [](void*) { + const uint8_t id = vars.master.memberId; + const uint8_t flags = vars.master.flags; + const uint8_t memberId = id > 0 ? id : vars.slave.memberId; + const uint8_t configFlags = flags > 0 ? flags : vars.slave.flags; + const ESP32OT::Messages::MasterConfig request(configFlags, memberId); + if (request.getData()) { + const auto response = slave.sendRequest(request); + + if (!response.isSuccess() || response.getData() != request.getData()) { + ESP_LOGW(L_OT, "Failed set master config"); + return; + } + } + + ESP_LOGI( + L_OT, "Set master member id: %u, flags: %u", + vars.master.memberId, vars.master.flags + ); +}); + +// Keep initialization scheduled until completion; ONCE pauses before its callback. +static Task initializeSlaveTask("Initialize slave", [](void*) { + ESP_LOGI(L_OT, "Initializing..."); + + readSlaveVersionTask.resume().tryRun(); + writeMasterVersionTask.resume().tryRun(); + readSlaveProtocolTask.resume().tryRun(); + writeMasterProtocolTask.resume().tryRun(); + readSlaveConfigTask.resume().tryRun(); + writeMasterConfigTask.resume().tryRun(); + + if (!canUseBus() || !vars.slave.connected) { + return; + } + + initializeSlaveTask.pause(); + initializedTime = millis(); +}); + +static void onDisconnectSlave() { + if (vars.slave.connected) { + ESP_LOGW( + L_OT, + "Disconnected, uptime: %lu s.", + (millis() - connectedTime) / 1000 + ); + + // Mark sensors as disconnected + Sensors::setConnectionStatusByType(Sensors::Type::OT_OUTDOOR_TEMP, false); + Sensors::setConnectionStatusByType(Sensors::Type::OT_HEATING_TEMP, false); + Sensors::setConnectionStatusByType(Sensors::Type::OT_HEATING_RETURN_TEMP, false); + Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_TEMP, false); + Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_TEMP2, false); + Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_FLOW_RATE, false); + Sensors::setConnectionStatusByType(Sensors::Type::OT_CH2_TEMP, false); + Sensors::setConnectionStatusByType(Sensors::Type::OT_EXHAUST_TEMP, false); + Sensors::setConnectionStatusByType(Sensors::Type::OT_HEAT_EXCHANGER_TEMP, false); + Sensors::setConnectionStatusByType(Sensors::Type::OT_PRESSURE, false); + Sensors::setConnectionStatusByType(Sensors::Type::OT_MODULATION_LEVEL, false); + Sensors::setConnectionStatusByType(Sensors::Type::OT_CURRENT_POWER, false); + Sensors::setConnectionStatusByType(Sensors::Type::OT_EXHAUST_CO2, false); + Sensors::setConnectionStatusByType(Sensors::Type::OT_EXHAUST_FAN_SPEED, false); + Sensors::setConnectionStatusByType(Sensors::Type::OT_SUPPLY_FAN_SPEED, false); + Sensors::setConnectionStatusByType(Sensors::Type::OT_SOLAR_STORAGE_TEMP, false); + Sensors::setConnectionStatusByType(Sensors::Type::OT_SOLAR_COLLECTOR_TEMP, false); + Sensors::setConnectionStatusByType(Sensors::Type::OT_FAN_SPEED_SETPOINT, false); + Sensors::setConnectionStatusByType(Sensors::Type::OT_FAN_SPEED_CURRENT, false); + + Sensors::setConnectionStatusByType(Sensors::Type::OT_BURNER_STARTS, false); + Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_BURNER_STARTS, false); + Sensors::setConnectionStatusByType(Sensors::Type::OT_HEATING_PUMP_STARTS, false); + Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_PUMP_STARTS, false); + Sensors::setConnectionStatusByType(Sensors::Type::OT_BURNER_HOURS, false); + Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_BURNER_HOURS, false); + Sensors::setConnectionStatusByType(Sensors::Type::OT_HEATING_PUMP_HOURS, false); + Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_PUMP_HOURS, false); + Sensors::setConnectionStatusByType(Sensors::Type::OT_COOLING_HOURS, false); + + initializeSlaveTask.resume(); + disconnectedTime = millis(); + vars.slave.connected = false; + } + + vars.slave.heating.enabled = false; + vars.slave.heating.active = false; + vars.slave.dhw.enabled = false; + vars.slave.dhw.active = false; + vars.slave.ch2.active = false; + vars.slave.flame = false; + vars.slave.cooling.active = false; + vars.slave.cooling.setpoint = 0; + vars.slave.fault.active = false; + vars.slave.fault.code = 0; + vars.slave.diag.active = false; + vars.slave.diag.code = 0; +} + +static bool isSlaveReady() { + return canUseBus() && vars.slave.connected && !initializeSlaveTask.scheduled(); +} + +static bool isInitializingSlave() { + return canUseBus() && vars.slave.connected && initializeSlaveTask.running(); +} + + +static void updateMasterState() { + // Heating settings + vars.master.heating.enabled = + isMasterReady() && + settings.heating.enabled && + (vars.master.heating.freezing || (vars.cascadeControl.input && !vars.master.heating.blocking)) && + !vars.master.heating.overheat; + + // DHW settings + vars.master.dhw.enabled = + isMasterReady() && + settings.opentherm.options.dhwSupport && + settings.dhw.enabled && + !vars.master.dhw.overheat; + vars.master.dhw.targetTemp = settings.dhw.target; + vars.master.dhw.minTemp = settings.dhw.minTemp; + vars.master.dhw.maxTemp = settings.dhw.maxTemp; + + // CH2 settings + vars.master.ch2.enabled = + settings.opentherm.options.ch2AlwaysEnabled || + (settings.opentherm.options.heatingToCh2 && vars.master.heating.enabled) || + (settings.opentherm.options.dhwToCh2 && vars.master.dhw.enabled); + + if (settings.opentherm.options.heatingToCh2) { + vars.master.ch2.targetTemp = !settings.opentherm.options.nativeOTC + ? vars.master.heating.setpointTemp + : vars.master.heating.targetTemp; + + } else if (settings.opentherm.options.dhwToCh2) { + vars.master.ch2.targetTemp = vars.master.dhw.targetTemp; + } + + if (isSlaveReady()) { + if (vars.master.heating.enabled != vars.slave.heating.enabled) { + vars.slave.heating.enabled = vars.master.heating.enabled; + ESP_LOGI(L_OT_HEATING, vars.master.heating.enabled ? "Enabled" : "Disabled"); + } + + if (vars.master.dhw.enabled != vars.slave.dhw.enabled) { + vars.slave.dhw.enabled = vars.master.dhw.enabled; + ESP_LOGI(L_OT_DHW, vars.master.dhw.enabled ? "Enabled" : "Disabled"); + } + } +} + +static Task configureDriverTask("Configure OpenTherm driver", Task::Type::ONCE, [](void*) { + // Stop the current bus before changing GPIO. + if (!slave.end()) { + ESP_LOGW(L_OT, "Failed stop"); + return; + } + + onDisconnectSlave(); + + if (!GPIO_IS_VALID_INPUT(settings.opentherm.inGpio) || !GPIO_IS_VALID_OUTPUT(settings.opentherm.outGpio)) { + ESP_LOGW( + L_OT, + "Not started. GPIO IN: %hhu or GPIO OUT: %hhu is not valid", + settings.opentherm.inGpio, + settings.opentherm.outGpio + ); + return; + } + + #ifdef OT_BYPASS_RELAY_GPIO + pinMode(OT_BYPASS_RELAY_GPIO, OUTPUT); + digitalWrite(OT_BYPASS_RELAY_GPIO, true); + #endif + + // Configure the existing driver. + ESP32OT::ESP32OT::Config config; + config.rxGpio = static_cast(settings.opentherm.inGpio); + config.txGpio = static_cast(settings.opentherm.outGpio); + + // Log formatting stays on the RMT worker; transport output runs on System. + config.stackSize = 4096; + if (!slave.setConfig(config)) { + ESP_LOGW(L_OT, "Failed configure"); + return; + } + + // flags + busConfiguredTime = millis(); + resetBusTime = millis(); + initializeSlaveTask.resume(); + heatingSetpointWriteTime = 0; + dhwSetpointWriteTime = 0; + ch2SetpointWriteTime = 0; + roomSetpointWriteTime = 0; + ch2RoomSetpointWriteTime = 0; + + ESP_LOGI(L_OT, "Started. GPIO IN: %hhu, GPIO OUT: %hhu", settings.opentherm.inGpio, settings.opentherm.outGpio); + + slave.onStatusChange([](const ESP32OT::ESP32OT::StatusEvent& event) { + const auto& response = event.message; + if (!response.isComplete()) { + return; + } + + ESP_LOGD( + L_OT, + "ID: %3d; Request: %8lx; Response: %8lx; Msg type: %s; Attempt: %2d; Status: %s", + static_cast(ESP32OT::Protocol::Frame::getId(response.getRequest())), + static_cast(response.getRequest()), + static_cast(response.hasFrame() ? response.getRaw() : 0), + response.hasFrame() ? ESP32OT::Protocol::Frame::typeToString(response.getType()) : "NONE", + response.getAttempt(), + ESP32OT::Protocol::Frame::statusToString(response.getStatus()) + ); + + if (response.isSuccess()) { + // The manager may reconfigure the LED after sendRequest() returns. + const uint8_t rxLedGpio = configuredRxLedGpio.load(); + if (rxLedGpio != GPIO_IS_NOT_CONFIGURED) { + digitalWrite(rxLedGpio, HIGH); + delayMicroseconds(2000); + digitalWrite(rxLedGpio, LOW); + } + } + }); +}); + +static Task maintainOpenThermTask("Maintain OpenTherm", [](void*) { + if (slave.getConfig().rxGpio != settings.opentherm.inGpio || slave.getConfig().txGpio != settings.opentherm.outGpio) { + // Apply changed GPIO before any bus exchange in this manager pass. + configureDriverTask.resume().tryRun(); + + } else if (vars.master.memberId != settings.opentherm.memberId || vars.master.flags != settings.opentherm.flags) { + initializeSlaveTask.resume(); + vars.master.memberId = settings.opentherm.memberId; + vars.master.flags = settings.opentherm.flags; + + } else if (millis() - initializedTime > initializingInterval) { + initializeSlaveTask.resume(); + } + + // Apply channel settings even while the bus is unavailable. + updateMasterState(); + + if (slave.getConfig().rxGpio != settings.opentherm.inGpio || slave.getConfig().txGpio != settings.opentherm.outGpio) { + maintainOpenThermTask.setInterval(5000); + return; + + } else if (!slave.isInitialized()) { + // A fatal error can leave the RMT worker alive until end() succeeds. + onDisconnectSlave(); + + if (!slave.end() || !slave.begin()) { + ESP_LOGW(L_OT, "Failed begin"); + + maintainOpenThermTask.setInterval(5000); + return; + } + } + + // Retry failures after 5 seconds; otherwise check settings on each pass. + maintainOpenThermTask.setInterval(0); + + // RX LED GPIO setup + const uint8_t rxLedGpio = configuredRxLedGpio.load(); + if (settings.opentherm.rxLedGpio != rxLedGpio) { + configuredRxLedGpio.store(GPIO_IS_NOT_CONFIGURED); + if (rxLedGpio != GPIO_IS_NOT_CONFIGURED) { + digitalWrite(rxLedGpio, LOW); + } + + if (GPIO_IS_VALID_OUTPUT(settings.opentherm.rxLedGpio)) { + pinMode(settings.opentherm.rxLedGpio, OUTPUT); + digitalWrite(settings.opentherm.rxLedGpio, LOW); + configuredRxLedGpio.store(settings.opentherm.rxLedGpio); + } + } +}); + +static Task readStatusTask("Read boiler status", [](void*) { + updateMasterState(); + + // Set boiler status LB + // Some boilers require this, although this is against protocol + uint8_t statusLb = 0; + + // Immergas fix + // https://arduino.ru/forum/programmirovanie/termostat-opentherm-na-esp8266?page=15#comment-649392 + if (settings.opentherm.options.immergasFix) { + statusLb = 0xCA; + } + + // Mode flags follow the channel request, before applying its disabling action. + + // Summer/winter mode + bool summerWinterMode = settings.opentherm.options.summerWinterMode; + if (settings.opentherm.options.heatingStateToSummerWinterMode) { + summerWinterMode = vars.master.heating.enabled == summerWinterMode; + } + + // DHW blocking + bool dhwBlocking = settings.opentherm.options.dhwBlocking; + if (settings.opentherm.options.dhwStateAsDhwBlocking) { + dhwBlocking = vars.master.dhw.enabled == dhwBlocking; + } + + ESP32OT::Messages::Status request(0, statusLb); + 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) + .setOutsideTemperatureCompensationEnabled(settings.opentherm.options.nativeOTC) + .setCh2Enabled(getSlaveChannelEnabled( + vars.master.ch2.enabled, settings.opentherm.ch2DisablingAction + )) + .setSummerWinterMode(summerWinterMode) + .setDhwBlocking(dhwBlocking); + + const auto response = slave.sendRequest(request); + const bool validStatus = response.isSuccess(); + if (!validStatus) { + ESP_LOGW( + L_OT, + "Failed receive boiler status: %s", + ESP32OT::Protocol::Frame::statusToString(response.getStatus()) + ); + + } else { + lastSuccessStatusResponse = millis(); + vars.slave.heating.active = response.isCentralHeatingActive(); + vars.slave.dhw.active = settings.opentherm.options.dhwSupport ? response.isHotWaterActive() : false; + vars.slave.flame = response.isFlameOn(); + vars.slave.cooling.active = response.isCoolingActive(); + vars.slave.ch2.active = response.isCh2Active(); + vars.slave.fault.active = response.isFault(); + + if (!settings.opentherm.options.ignoreDiagState) { + vars.slave.diag.active = response.isDiagnostic(); + + } else if (vars.slave.diag.active) { + vars.slave.diag.active = false; + } + + if (!vars.slave.fault.active && vars.slave.fault.code != 0) { + vars.slave.fault.code = 0; + } + + if (!vars.slave.diag.active && vars.slave.diag.code != 0) { + vars.slave.diag.code = 0; + } + + ESP_LOGI( + L_OT, "Received boiler status. Heating: %hhu; DHW: %hhu; flame: %hhu; cooling: %hhu; channel 2: %hhu; fault: %hhu; diag: %hhu", + vars.slave.heating.active, vars.slave.dhw.active, + vars.slave.flame, vars.slave.cooling.active, vars.slave.ch2.active, vars.slave.fault.active, vars.slave.diag.active + ); + } + + if (!vars.slave.connected && validStatus) { + ESP_LOGI( + L_OT, + "Connected, downtime: %lu s.", + (millis() - disconnectedTime) / 1000 + ); + + connectedTime = millis(); + vars.slave.connected = true; + } + + // 5 request retries + // 1000ms maximum response waiting time + // 100ms delay between requests + // +15% + // 5 * (1000 + 100) * 1.15 = 6325 ms + if (vars.slave.connected && !validStatus && millis() - lastSuccessStatusResponse > 6325) { + onDisconnectSlave(); + } + + // If boiler is disconnected, no need try setting other OT stuff + if (!vars.slave.connected) { + // reset bus + if (millis() - disconnectedTime > resetBusInterval) { + if (millis() - resetBusTime > resetBusInterval) { + ESP_LOGI(L_OT, "Reset bus..."); + + if (!slave.end()) { + ESP_LOGW(L_OT, "Failed stop"); + } + + resetBusTime = millis(); + ::delay(5000); + } + } + + } else { + std::unique_lock mqttLock(mqttMutex, std::try_to_lock); + if (mqttLock.owns_lock() && mqttPublishStateTask) { + mqttPublishStateTask->requestEarlyRun(); + } + } +}); + +static Task writeHeatingSetpointTask("Write heating setpoint", [](void*) { + // Target heating temp + const float targetTemp = getHeatingChannelSetpoint(); + + // Set max heating temp + if (settings.opentherm.options.maxTempSyncWithTargetTemp) { + const auto request = ESP32OT::Messages::Float::writeTemperature( + ESP32OT::MessageID::MaxTSet, + targetTemp + ); + const auto response = slave.sendRequest(request); + + if (response.isSuccess() && response.getData() == request.getData()) { + ESP_LOGI( + L_OT_HEATING, "Set max heating temp: %.2f", + targetTemp + ); + + } else { + ESP_LOGW( + L_OT_HEATING, "Failed set max heating temp: %.2f", + targetTemp + ); + } + } + + // Set target heating temp + const auto request = ESP32OT::Messages::Float::writeTemperature( + ESP32OT::MessageID::TSet, + targetTemp + ); + const auto response = slave.sendRequest(request); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT_HEATING, "Failed set target temp"); + return; + } + + vars.slave.heating.targetTemp = response.get(); + + if (response.getData() != request.getData()) { + ESP_LOGW( + L_OT_HEATING, responseMismatchMessage, + request.getData(), response.getData() + ); + return; + } + + heatingSetpointWriteTime = millis(); + + ESP_LOGI( + L_OT_HEATING, "Set target temp: %.2f (response: %.2f)", + targetTemp, vars.slave.heating.targetTemp + ); +}); + +static Task writeDhwSetpointTask("Write DHW setpoint", [](void*) { + // Target dhw temp + const float targetTemp = getDhwChannelSetpoint(); + + // Set DHW temp + const auto request = ESP32OT::Messages::Float::writeTemperature( + ESP32OT::MessageID::TdhwSet, + targetTemp + ); + const auto response = slave.sendRequest(request); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT_DHW, "Failed set temp"); + return; + } + + vars.slave.dhw.targetTemp = response.get(); + + if (response.getData() != request.getData()) { + ESP_LOGW( + L_OT_DHW, responseMismatchMessage, + request.getData(), response.getData() + ); + return; + } + + dhwSetpointWriteTime = millis(); + + ESP_LOGI( + L_OT_DHW, "Set temp: %.2f (response: %.2f)", + targetTemp, vars.slave.dhw.targetTemp + ); +}); + +static Task writeCh2SetpointTask("Write CH2 setpoint", [](void*) { + // Target CH2 heating temp + const float targetTemp = getCh2ChannelSetpoint(); + + // Set CH2 temp + const auto request = ESP32OT::Messages::Float::writeTemperature( + ESP32OT::MessageID::TsetCH2, + targetTemp + ); + const auto response = slave.sendRequest(request); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT_CH2, "Failed set temp"); + return; + } + + vars.slave.ch2.targetTemp = response.get(); + + if (response.getData() != request.getData()) { + ESP_LOGW( + L_OT_CH2, responseMismatchMessage, + request.getData(), response.getData() + ); + return; + } + + ch2SetpointWriteTime = millis(); + + ESP_LOGI( + L_OT_CH2, "Set temp: %.2f (response: %.2f)", + targetTemp, vars.slave.ch2.targetTemp + ); +}); + +static Task writeRoomSetpointTask("Write room setpoint", [](void*) { + // Target indoor temp + const float& targetTemp = vars.master.heating.targetTemp; + + // Set target indoor temp + const auto request = ESP32OT::Messages::Float::writeTemperature( + ESP32OT::MessageID::TrSet, + targetTemp + ); + const auto response = slave.sendRequest(request); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT_HEATING, "Failed set target indoor temp"); + return; + } + + vars.slave.heating.roomTargetTemp = response.get(); + + if (response.getData() != request.getData()) { + ESP_LOGW( + L_OT_HEATING, responseMismatchMessage, + request.getData(), response.getData() + ); + return; + } + + roomSetpointWriteTime = millis(); + + ESP_LOGI( + L_OT_HEATING, "Set target indoor temp: %.2f (response: %.2f)", + targetTemp, vars.slave.heating.roomTargetTemp + ); +}); + +static Task writeRoomSetpointCh2Task("Write CH2 room setpoint", [](void*) { + // Target indoor temp + const float& targetTemp = vars.master.heating.targetTemp; + + // Set target CH2 temp + const auto request = ESP32OT::Messages::Float::writeTemperature( + ESP32OT::MessageID::TrSetCH2, + targetTemp + ); + const auto response = slave.sendRequest(request); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT_HEATING, "Failed set target CH2 indoor temp"); + return; + } + + vars.slave.ch2.roomTargetTemp = response.get(); + + if (response.getData() != request.getData()) { + ESP_LOGW( + L_OT_HEATING, responseMismatchMessage, + request.getData(), response.getData() + ); + return; + } + + ch2RoomSetpointWriteTime = millis(); + + ESP_LOGI( + L_OT_HEATING, "Set target CH2 indoor temp: %.2f (response: %.2f)", + targetTemp, vars.slave.ch2.roomTargetTemp + ); +}); + +static Task writeMaxModulationTask("Write maximum modulation", [](void*) { + // Set max modulation level + uint8_t maxModulation = vars.slave.modulation.max; + if (vars.slave.heating.active) { + maxModulation = settings.heating.maxModulation; + + } else if (vars.slave.dhw.active) { + maxModulation = settings.dhw.maxModulation; + + } else { + // This fixes the inability to enable channels if + // the maximum modulation level has become zero for some reason. + + if (vars.master.heating.enabled && maxModulation < settings.heating.maxModulation) { + maxModulation = settings.heating.maxModulation; + } + + if (vars.master.dhw.enabled && maxModulation < settings.dhw.maxModulation) { + maxModulation = settings.dhw.maxModulation; + } + } + + const ESP32OT::Messages::Float request(ESP32OT::MessageID::MaxRelModLevelSetting, maxModulation); + const auto response = slave.sendRequest(request); + + if (!response.isSuccess()) { + ESP_LOGW( + L_OT, "Failed set max modulation: %hhu%% (response: %hhu%%)", + maxModulation, vars.slave.modulation.max + ); + return; + } + + vars.slave.modulation.max = response.get(); + + if (response.getData() != request.getData()) { + ESP_LOGW( + L_OT, responseMismatchMessage, + request.getData(), response.getData() + ); + return; + } + + ESP_LOGI( + L_OT, "Set max modulation: %hhu%% (response: %hhu%%)", + maxModulation, vars.slave.modulation.max + ); +}); + +static Task writeCoolingSetpointTask("Write cooling setpoint", [](void*) { + // Set cooling setpoint = heating max modulation + const ESP32OT::Messages::Float request( + ESP32OT::MessageID::CoolingControl, + settings.heating.maxModulation + ); + const auto response = slave.sendRequest(request); + + if (!response.isSuccess()) { + ESP_LOGW( + L_OT, "Failed set cooling setpoint: %hhu%% (response: %hhu%%)", + settings.heating.maxModulation, vars.slave.cooling.setpoint + ); + return; + } + + vars.slave.cooling.setpoint = response.get(); + + if (response.getData() != request.getData()) { + ESP_LOGW( + L_OT, responseMismatchMessage, + request.getData(), response.getData() + ); + return; + } + + ESP_LOGI( + L_OT, "Set cooling setpoint: %hhu%% (response: %hhu%%)", + settings.heating.maxModulation, vars.slave.cooling.setpoint + ); +}); + +// Fault reset action +static Task writeFaultResetTask("Write fault reset", [](void*) { + const auto response = slave.sendRequest(ESP32OT::Messages::RemoteRequest(1)); + if (!response.isSuccess() || response.getRequestCode() != 1 || response.getResponseCode() < 128) { + ESP_LOGE(L_OT, "Boiler fault reset failed"); + return; + } + + slave.sendRequest(ESP32OT::Messages::RemoteRequest(0)); + ESP_LOGI(L_OT, "Boiler fault reset successfully"); +}); + +// Diag reset action +static Task writeDiagnosticResetTask("Write diagnostic reset", [](void*) { + const auto response = slave.sendRequest(ESP32OT::Messages::RemoteRequest(10)); + if (!response.isSuccess() || response.getRequestCode() != 10 || response.getResponseCode() < 128) { + ESP_LOGE(L_OT, "Boiler diagnostic reset failed"); + return; + } + + slave.sendRequest(ESP32OT::Messages::RemoteRequest(0)); + ESP_LOGI(L_OT, "Boiler diagnostic reset successfully"); +}); + +Task writeRoomTemperatureTask("Write room temperature", [](void*) { + // Current indoor temp + const float& indoorTemp = vars.master.heating.indoorTemp; + + // Set current indoor temp + const auto request = ESP32OT::Messages::Float::writeTemperature( + ESP32OT::MessageID::Tr, + indoorTemp + ); + const auto response = slave.sendRequest(request); + + 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 (response: %.2f)", + indoorTemp, vars.slave.heating.indoorTemp + ); +}); + +Task writeRoomTemperatureCh2Task("Write CH2 room temperature", [](void*) { + // Current indoor temp + const float& indoorTemp = vars.master.heating.indoorTemp; + + const auto request = ESP32OT::Messages::Float::writeTemperature( + ESP32OT::MessageID::TrCH2, + indoorTemp + ); + const auto response = slave.sendRequest(request); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT_HEATING, "Failed set current CH2 indoor temp"); + return; + } + + vars.slave.ch2.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 CH2 indoor temp: %.2f (response: %.2f)", + indoorTemp, vars.slave.ch2.indoorTemp + ); +}); + +static Task readModulationTask("Read modulation", [](void*) { + // Update modulation level + if (vars.slave.flame) { + const auto response = slave.sendRequest(ESP32OT::Messages::Float(ESP32OT::MessageID::RelModLevel)); + const float value = response.get(); + + if (!response.isSuccess() || value < 0) { + ESP_LOGW(L_OT, "Failed receive modulation level"); + return; + } + + vars.slave.modulation.current = value; + + float power = 0.0f; + if (settings.opentherm.maxPower > 0.1f) { + power += settings.opentherm.minPower; + + if (vars.slave.modulation.current > 0) { + power += ( + settings.opentherm.maxPower - settings.opentherm.minPower + ) / 100.0f * vars.slave.modulation.current; + } + } + vars.slave.power.current = power; + + ESP_LOGI( + L_OT, "Received modulation level: %hhu%%, power: %.2f of %.2f kW (min: %.2f kW)", + vars.slave.modulation.current, vars.slave.power.current, + settings.opentherm.maxPower, settings.opentherm.minPower + ); + + // Modulation level sensors + Sensors::setValueByType( + Sensors::Type::OT_MODULATION_LEVEL, vars.slave.modulation.current, + Sensors::ValueType::PRIMARY, true, true + ); + + // Power sensors + Sensors::setValueByType( + Sensors::Type::OT_CURRENT_POWER, vars.slave.power.current, + Sensors::ValueType::PRIMARY, true, true + ); + + } else { + vars.slave.modulation.current = 0; + vars.slave.power.current = 0.0f; + + // Modulation level sensors + Sensors::setValueByType( + Sensors::Type::OT_MODULATION_LEVEL, vars.slave.modulation.current, + Sensors::ValueType::PRIMARY, true, true + ); + + // Power sensors + Sensors::setValueByType( + Sensors::Type::OT_CURRENT_POWER, vars.slave.power.current, + Sensors::ValueType::PRIMARY, true, true + ); + } +}); + +static Task readDhwTemperatureTask("Read DHW temperature", [](void*) { + // Update DHW temp + const auto response = slave.sendRequest(ESP32OT::Messages::Float(ESP32OT::MessageID::Tdhw)); + const float value = response.get(); + + if (!response.isSuccess() || value <= 0) { + ESP_LOGW(L_OT_DHW, "Failed receive temp"); + return; + } + + vars.slave.dhw.currentTemp = value; + + ESP_LOGI( + L_OT_DHW, "Received temp: %.2f", + vars.slave.dhw.currentTemp + ); + + Sensors::setValueByType( + Sensors::Type::OT_DHW_TEMP, vars.slave.dhw.currentTemp, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readDhwTemperature2Task("Read DHW temperature 2", [](void*) { + // Update DHW temp 2 + const auto response = slave.sendRequest(ESP32OT::Messages::Float(ESP32OT::MessageID::Tdhw2)); + const float value = response.get(); + + if (!response.isSuccess() || value <= 0) { + ESP_LOGW(L_OT_DHW, "Failed receive temp 2"); + return; + } + + vars.slave.dhw.currentTemp2 = value; + + ESP_LOGI( + L_OT_DHW, "Received temp 2: %.2f", + vars.slave.dhw.currentTemp2 + ); + + Sensors::setValueByType( + Sensors::Type::OT_DHW_TEMP2, vars.slave.dhw.currentTemp2, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readDhwFlowTask("Read DHW flow", [](void*) { + // Update DHW flow rate + const auto response = slave.sendRequest(ESP32OT::Messages::Float(ESP32OT::MessageID::DHWFlowRate)); + float value = response.get(); + + if (!response.isSuccess() || value < 0) { + ESP_LOGW(L_OT_DHW, "Failed receive flow rate"); + return; + } + + // no minuscule values + // some boilers send a response of 0.06 when there is no flow + if (value < 0.1f) { + value = 0.0f; + } + + vars.slave.dhw.flowRate = value; + + ESP_LOGI( + L_OT_DHW, "Received flow rate: %.2f", + vars.slave.dhw.flowRate + ); + + Sensors::setValueByType( + Sensors::Type::OT_DHW_FLOW_RATE, vars.slave.dhw.flowRate, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readHeatingTemperatureTask("Read heating temperature", [](void*) { + // Update heating temp + const auto response = slave.sendRequest(ESP32OT::Messages::Float(ESP32OT::MessageID::Tboiler)); + const float value = response.get(); + + if (!response.isSuccess() || value <= 0) { + ESP_LOGW(L_OT_HEATING, "Failed receive temp"); + return; + } + + vars.slave.heating.currentTemp = value; + + ESP_LOGI( + L_OT_HEATING, "Received temp: %.2f", + vars.slave.heating.currentTemp + ); + + Sensors::setValueByType( + Sensors::Type::OT_HEATING_TEMP, vars.slave.heating.currentTemp, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readHeatingReturnTemperatureTask("Read return temperature", [](void*) { + // Update heating return temp + const auto response = slave.sendRequest(ESP32OT::Messages::Float(ESP32OT::MessageID::Tret)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT_HEATING, "Failed receive return temp"); + return; + } + + vars.slave.heating.returnTemp = response.get(); + + ESP_LOGI( + L_OT_HEATING, "Received return temp: %.2f", + vars.slave.heating.returnTemp + ); + + Sensors::setValueByType( + Sensors::Type::OT_HEATING_RETURN_TEMP, vars.slave.heating.returnTemp, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readCh2TemperatureTask("Read CH2 temperature", [](void*) { + // Update CH2 temp + const auto response = slave.sendRequest(ESP32OT::Messages::Float(ESP32OT::MessageID::TflowCH2)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT_CH2, "Failed receive temp"); + return; + } + + vars.slave.ch2.currentTemp = response.get(); + + ESP_LOGI( + L_OT_CH2, "Received temp: %.2f", + vars.slave.ch2.currentTemp + ); + + Sensors::setValueByType( + Sensors::Type::OT_CH2_TEMP, vars.slave.ch2.currentTemp, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readExhaustTemperatureTask("Read exhaust temperature", [](void*) { + // Update exhaust temp + const auto response = slave.sendRequest(ESP32OT::Messages::Int16(ESP32OT::MessageID::Texhaust)); + const float value = response.getInt(); + + if (!response.isSuccess() || !isValidTemp(value, UnitSystem::METRIC, -40, 500)) { + ESP_LOGW(L_OT, "Failed receive exhaust temp"); + return; + } + + vars.slave.exhaust.temp = value; + + ESP_LOGI( + L_OT, "Received exhaust temp: %.2f", + vars.slave.exhaust.temp + ); + + Sensors::setValueByType( + Sensors::Type::OT_EXHAUST_TEMP, vars.slave.exhaust.temp, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readHeatExchangerTemperatureTask("Read heat exchanger temperature", [](void*) { + // Update heat exchanger temp + const auto response = slave.sendRequest(ESP32OT::Messages::Float(ESP32OT::MessageID::TboilerHeatExchanger)); + const float value = response.get(); + + if (!response.isSuccess() || value <= 0) { + ESP_LOGW(L_OT, "Failed receive heat exchanger temp"); + return; + } + + vars.slave.heatExchangerTemp = value; + + ESP_LOGI( + L_OT, "Received heat exchanger temp: %.2f", + vars.slave.heatExchangerTemp + ); + + Sensors::setValueByType( + Sensors::Type::OT_HEAT_EXCHANGER_TEMP, vars.slave.heatExchangerTemp, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readOutdoorTemperatureTask("Read outdoor temperature", [](void*) { + // Update outdoor temp + const auto response = slave.sendRequest(ESP32OT::Messages::Float(ESP32OT::MessageID::Toutside)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive outdoor temp"); + return; + } + + vars.slave.heating.outdoorTemp = response.get(); + + ESP_LOGI( + L_OT, "Received outdoor temp: %.2f", + vars.slave.heating.outdoorTemp + ); + + Sensors::setValueByType( + Sensors::Type::OT_OUTDOOR_TEMP, vars.slave.heating.outdoorTemp, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readSolarStorageTemperatureTask("Read solar storage temperature", [](void*) { + // Update solar storage temp + const auto response = slave.sendRequest(ESP32OT::Messages::Float(ESP32OT::MessageID::Tstorage)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive solar storage temp"); + return; + } + + vars.slave.solar.storage = response.get(); + + ESP_LOGI( + L_OT, "Received solar storage temp: %.2f", + vars.slave.solar.storage + ); + + Sensors::setValueByType( + Sensors::Type::OT_SOLAR_STORAGE_TEMP, vars.slave.solar.storage, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readSolarCollectorTemperatureTask("Read solar collector temperature", [](void*) { + // Update solar collector temp + const auto response = slave.sendRequest(ESP32OT::Messages::Float(ESP32OT::MessageID::Tcollector)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive solar collector temp"); + return; + } + + vars.slave.solar.collector = response.get(); + + ESP_LOGI( + L_OT, "Received solar collector temp: %.2f", + vars.slave.solar.collector + ); + + Sensors::setValueByType( + Sensors::Type::OT_SOLAR_COLLECTOR_TEMP, vars.slave.solar.collector, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readFanSpeedTask("Read fan speed", [](void*) { + // Update fan speed + const auto response = slave.sendRequest(ESP32OT::Messages::FanSpeed()); + + if (!response.isSuccess()) { + return; + } + + vars.slave.fanSpeed.setpoint = response.getSetpointHz(); + vars.slave.fanSpeed.current = response.getActualHz(); + + ESP_LOGI( + L_OT, "Received fan speed, setpoint: %hhu%%, current: %hhu%%", + vars.slave.fanSpeed.setpoint, vars.slave.fanSpeed.current + ); + + Sensors::setValueByType( + Sensors::Type::OT_FAN_SPEED_SETPOINT, vars.slave.fanSpeed.setpoint, + Sensors::ValueType::PRIMARY, true, true + ); + Sensors::setValueByType( + Sensors::Type::OT_FAN_SPEED_CURRENT, vars.slave.fanSpeed.current, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readPressureTask("Read pressure", [](void*) { + // Update pressure + const auto response = slave.sendRequest(ESP32OT::Messages::Float(ESP32OT::MessageID::CHPressure)); + const float value = response.get(); + + if (!response.isSuccess() || value < 0) { + ESP_LOGW(L_OT, "Failed receive pressure"); + return; + } + + vars.slave.pressure = value; + + ESP_LOGI( + L_OT, "Received pressure: %.2f", + vars.slave.pressure + ); + + Sensors::setValueByType( + Sensors::Type::OT_PRESSURE, vars.slave.pressure, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readExhaustCo2Task("Read exhaust CO2", [](void*) { + // Update exhaust CO2 + const auto response = slave.sendRequest(ESP32OT::Messages::UInt16(ESP32OT::MessageID::CO2exhaust)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive exhaust CO2"); + return; + } + + vars.slave.exhaust.co2 = response.getUInt(); + + ESP_LOGI( + L_OT, "Received exhaust CO2: %hu ppm", + vars.slave.exhaust.co2 + ); + + Sensors::setValueByType( + Sensors::Type::OT_EXHAUST_CO2, vars.slave.exhaust.co2, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readExhaustFanSpeedTask("Read exhaust fan speed", [](void*) { + // Update exhaust fan speed + const auto response = slave.sendRequest(ESP32OT::Messages::UInt16(ESP32OT::MessageID::RPMexhaust)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive exhaust fan speed"); + return; + } + + vars.slave.exhaust.fanSpeed = response.getUInt(); + + ESP_LOGI( + L_OT, "Received exhaust fan speed: %hu rpm", + vars.slave.exhaust.fanSpeed + ); + + Sensors::setValueByType( + Sensors::Type::OT_EXHAUST_FAN_SPEED, vars.slave.exhaust.fanSpeed, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readSupplyFanSpeedTask("Read supply fan speed", [](void*) { + // Update supply fan speed + const auto response = slave.sendRequest(ESP32OT::Messages::UInt16(ESP32OT::MessageID::RPMsupply)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive supply fan speed"); + return; + } + + vars.slave.fanSpeed.supply = response.getUInt(); + + ESP_LOGI( + L_OT, "Received supply fan speed: %hu rpm", + vars.slave.fanSpeed.supply + ); + + Sensors::setValueByType( + Sensors::Type::OT_SUPPLY_FAN_SPEED, vars.slave.fanSpeed.supply, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task writeYearTask("Write year", [](void*) { + struct tm boilerTime; + if (getLocalTime(&boilerTime, 0)) { + const ESP32OT::Messages::UInt16 request(ESP32OT::MessageID::Year, (boilerTime.tm_year + 1900) & 0xFFFF); + const auto response = slave.sendRequest(request); + + if (!response.isSuccess() || response.getData() != request.getData()) { + ESP_LOGI(L_OT, "Failed set year of date"); + return; + } + + ESP_LOGI(L_OT, "Year of date set successfully"); + } +}); + +static Task writeDayAndMonthTask("Write date", [](void*) { + // Other operations can run between clock writes; use the current date. + struct tm boilerTime; + if (getLocalTime(&boilerTime, 0)) { + const uint8_t month = (boilerTime.tm_mon + 1) & 0xFF; + const ESP32OT::Messages::Date request(month, boilerTime.tm_mday & 0xFF); + const auto response = slave.sendRequest(request); + + if (!response.isSuccess() || response.getData() != request.getData()) { + ESP_LOGI(L_OT, "Failed set day and month of date"); + return; + } + + ESP_LOGI(L_OT, "Day and month of date set successfully"); + } +}); + +static Task writeTimeTask("Write time", [](void*) { + struct tm boilerTime; + if (getLocalTime(&boilerTime, 0)) { + const uint8_t dayOfWeek = boilerTime.tm_wday == 0 ? 7 : boilerTime.tm_wday; + const ESP32OT::Messages::DayTime request(dayOfWeek, boilerTime.tm_hour, boilerTime.tm_min & 0x3F); + + const auto response = slave.sendRequest(request); + + if (!response.isSuccess() || response.getData() != request.getData()) { + ESP_LOGI(L_OT, "Failed set time"); + return; + } + + ESP_LOGI(L_OT, "Time set successfully"); + } +}); + +static Task readPowerLimitsTask("Read power limits", [](void*) { + // Get min modulation level & max power + const auto response = slave.sendRequest(ESP32OT::Messages::Capacity()); + + if (!response.isSuccess() || response.getMinModulation() > 100) { + ESP_LOGW(L_OT, "Failed receive min modulation and max power"); + return; + } + + vars.slave.modulation.min = response.getMinModulation(); + vars.slave.power.max = response.getMaxCapacity(); + vars.slave.power.min = vars.slave.modulation.min > 0 && vars.slave.power.max > 0.1f + ? (vars.slave.modulation.min * 0.01f) * vars.slave.power.max + : 0.0f; + + ESP_LOGI( + L_OT, "Received min modulation: %hhu%%, max power: %.2f kW", + vars.slave.modulation.min, vars.slave.power.max + ); + + if (settings.heating.maxModulation < vars.slave.modulation.min) { + settings.heating.maxModulation = vars.slave.modulation.min; + requestSaveSettings(); + + ESP_LOGW( + L_SETTINGS_HEATING, "Updated min modulation: %hhu%%", + settings.heating.maxModulation + ); + } + + if (settings.dhw.maxModulation < vars.slave.modulation.min) { + settings.dhw.maxModulation = vars.slave.modulation.min; + requestSaveSettings(); + + ESP_LOGW( + L_SETTINGS_DHW, "Updated min modulation: %hhu%%", + settings.dhw.maxModulation + ); + } + + if (fabsf(settings.opentherm.maxPower) < 0.1f && vars.slave.power.max > 0.1f) { + settings.opentherm.maxPower = vars.slave.power.max; + settings.opentherm.minPower = vars.slave.power.min; + + requestSaveSettings(); + ESP_LOGW( + L_SETTINGS_OT, "Updated power, min: %.2f kW, max: %.2f kW", + settings.opentherm.minPower, settings.opentherm.maxPower + ); + } +}); + +static Task readDhwLimitsTask("Read DHW limits", [](void*) { + // Get DHW min/max temp (if necessary) + if (settings.opentherm.options.dhwSupport && settings.opentherm.options.getMinMaxTemp) { + const auto response = slave.sendRequest( + ESP32OT::Messages::TemperatureBounds(ESP32OT::MessageID::TdhwSetUBTdhwSetLB) + ); + int8_t minTemp = response.getLower(); + int8_t maxTemp = response.getUpper(); + + if (response.isSuccess() && minTemp >= 0 && maxTemp > 0 && maxTemp > minTemp) { + vars.slave.dhw.minTemp = minTemp; + vars.slave.dhw.maxTemp = maxTemp; + + float convertedMinTemp = ceilf(vars.slave.dhw.minTemp); + float convertedMaxTemp = floorf(vars.slave.dhw.maxTemp); + + convertedMinTemp = constrain(convertedMinTemp, 0.0f, 255.0f); + convertedMaxTemp = constrain(convertedMaxTemp, 0.0f, 255.0f); + + // Integer settings need two distinct limits within their storage range. + if (convertedMinTemp >= convertedMaxTemp) { + ESP_LOGW(L_OT_DHW, unrepresentableTemperatureLimitsMessage); + return; + } + + ESP_LOGI( + L_OT_DHW, "Received min temp: %hhu (converted: %.0f), max temp: %hhu (converted: %.0f)", + vars.slave.dhw.minTemp, convertedMinTemp, vars.slave.dhw.maxTemp, convertedMaxTemp + ); + + if (settings.dhw.minTemp < convertedMinTemp) { + settings.dhw.minTemp = static_cast(convertedMinTemp); + requestSaveSettings(); + + ESP_LOGW(L_SETTINGS_DHW, "Updated min temp: %hhu", settings.dhw.minTemp); + } + + if (settings.dhw.maxTemp > convertedMaxTemp) { + settings.dhw.maxTemp = static_cast(convertedMaxTemp); + requestSaveSettings(); + + ESP_LOGW(L_SETTINGS_DHW, "Updated max temp: %hhu", settings.dhw.maxTemp); + } + + if (settings.dhw.minTemp >= settings.dhw.maxTemp) { + settings.dhw.minTemp = static_cast(convertedMinTemp); + settings.dhw.maxTemp = static_cast(convertedMaxTemp); + requestSaveSettings(); + + ESP_LOGW(L_SETTINGS_DHW, "Updated min temp: %hhu, max temp: %hhu", settings.dhw.minTemp, settings.dhw.maxTemp); + } + + } else { + ESP_LOGW(L_OT_DHW, "Failed receive min/max temp"); + } + } + + if (settings.dhw.minTemp >= settings.dhw.maxTemp) { + settings.dhw.minTemp = DEFAULT_DHW_MIN_TEMP; + settings.dhw.maxTemp = DEFAULT_DHW_MAX_TEMP; + requestSaveSettings(); + } +}); + +static Task readHeatingLimitsTask("Read heating limits", [](void*) { + // Get heating min/max temp + if (settings.opentherm.options.getMinMaxTemp) { + const auto response = slave.sendRequest( + ESP32OT::Messages::TemperatureBounds(ESP32OT::MessageID::MaxTSetUBMaxTSetLB) + ); + int8_t minTemp = response.getLower(); + int8_t maxTemp = response.getUpper(); + + if (response.isSuccess() && minTemp >= 0 && maxTemp > 0 && maxTemp > minTemp) { + vars.slave.heating.minTemp = minTemp; + vars.slave.heating.maxTemp = maxTemp; + + float convertedMinTemp = ceilf(vars.slave.heating.minTemp); + float convertedMaxTemp = floorf(vars.slave.heating.maxTemp); + + convertedMinTemp = constrain(convertedMinTemp, 0.0f, 255.0f); + convertedMaxTemp = constrain(convertedMaxTemp, 0.0f, 255.0f); + + // Integer settings need two distinct limits within their storage range. + if (convertedMinTemp >= convertedMaxTemp) { + ESP_LOGW(L_OT_HEATING, unrepresentableTemperatureLimitsMessage); + return; + } + + ESP_LOGI( + L_OT_HEATING, "Received min temp: %hhu (converted: %.0f), max temp: %hhu (converted: %.0f)", + vars.slave.heating.minTemp, convertedMinTemp, vars.slave.heating.maxTemp, convertedMaxTemp + ); + + if (settings.heating.minTemp < convertedMinTemp) { + settings.heating.minTemp = static_cast(convertedMinTemp); + requestSaveSettings(); + + ESP_LOGW(L_SETTINGS_HEATING, "Updated min temp: %hhu", settings.heating.minTemp); + } + + if (settings.heating.maxTemp > convertedMaxTemp) { + settings.heating.maxTemp = static_cast(convertedMaxTemp); + requestSaveSettings(); + + ESP_LOGW(L_SETTINGS_HEATING, "Updated max temp: %hhu", settings.heating.maxTemp); + } + + if (settings.heating.minTemp >= settings.heating.maxTemp) { + settings.heating.minTemp = static_cast(convertedMinTemp); + settings.heating.maxTemp = static_cast(convertedMaxTemp); + requestSaveSettings(); + + ESP_LOGW(L_SETTINGS_HEATING, "Updated min temp: %hhu, max temp: %hhu", settings.heating.minTemp, settings.heating.maxTemp); + } + + } else { + ESP_LOGW(L_OT_HEATING, "Failed receive min/max temp"); + } + } + + if (settings.heating.minTemp >= settings.heating.maxTemp) { + settings.heating.minTemp = DEFAULT_HEATING_MIN_TEMP; + settings.heating.maxTemp = DEFAULT_HEATING_MAX_TEMP; + requestSaveSettings(); + } +}); + +static Task readFaultTask("Read fault code", [](void*) { + // Get fault code + const auto response = slave.sendRequest(ESP32OT::Messages::Fault()); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive fault code"); + return; + } + + vars.slave.fault.code = response.getOemFaultCode(); + + ESP_LOGI( + L_OT, "Received fault code: %hhu (0x%02X)", + vars.slave.fault.code, vars.slave.fault.code + ); +}); + +static Task readDiagnosticTask("Read diagnostic code", [](void*) { + // Get diagnostic code + const auto response = slave.sendRequest(ESP32OT::Messages::UInt16(ESP32OT::MessageID::OEMDiagnosticCode)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive diag code"); + return; + } + + vars.slave.diag.code = response.getUInt(); + + ESP_LOGI( + L_OT, "Received diag code: %hu (0x%02X)", + vars.slave.diag.code, vars.slave.diag.code + ); +}); + +static Task readBurnerStartsTask("Read burner starts", [](void*) { + // Update burner starts + const auto response = slave.sendRequest(ESP32OT::Messages::UInt16(ESP32OT::MessageID::SuccessfulBurnerStarts)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive burner starts"); + return; + } + + vars.slave.stats.burnerStarts = response.getUInt(); + + ESP_LOGI(L_OT, "Received burner starts: %hu", vars.slave.stats.burnerStarts); + + Sensors::setValueByType( + Sensors::Type::OT_BURNER_STARTS, vars.slave.stats.burnerStarts, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readDhwBurnerStartsTask("Read DHW burner starts", [](void*) { + // Update DHW burner starts + const auto response = slave.sendRequest(ESP32OT::Messages::UInt16(ESP32OT::MessageID::DHWBurnerStarts)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive DHW burner starts"); + return; + } + + vars.slave.stats.dhwBurnerStarts = response.getUInt(); + + ESP_LOGI(L_OT, "Received DHW burner starts: %hu", vars.slave.stats.dhwBurnerStarts); + + Sensors::setValueByType( + Sensors::Type::OT_DHW_BURNER_STARTS, vars.slave.stats.dhwBurnerStarts, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readHeatingPumpStartsTask("Read heating pump starts", [](void*) { + // Update heating pump starts + const auto response = slave.sendRequest(ESP32OT::Messages::UInt16(ESP32OT::MessageID::CHPumpStarts)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive heating pump starts"); + return; + } + + vars.slave.stats.heatingPumpStarts = response.getUInt(); + + ESP_LOGI(L_OT, "Received heating pump starts: %hu", vars.slave.stats.heatingPumpStarts); + + Sensors::setValueByType( + Sensors::Type::OT_HEATING_PUMP_STARTS, vars.slave.stats.heatingPumpStarts, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readDhwPumpStartsTask("Read DHW pump starts", [](void*) { + // Update DHW pump starts + const auto response = slave.sendRequest(ESP32OT::Messages::UInt16(ESP32OT::MessageID::DHWPumpValveStarts)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive DHW pump starts"); + return; + } + + vars.slave.stats.dhwPumpStarts = response.getUInt(); + + ESP_LOGI(L_OT, "Received DHW pump starts: %hu", vars.slave.stats.dhwPumpStarts); + + Sensors::setValueByType( + Sensors::Type::OT_DHW_PUMP_STARTS, vars.slave.stats.dhwPumpStarts, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readBurnerHoursTask("Read burner hours", [](void*) { + // Update burner hours + const auto response = slave.sendRequest(ESP32OT::Messages::UInt16(ESP32OT::MessageID::BurnerOperationHours)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive burner hours"); + return; + } + + vars.slave.stats.burnerHours = response.getUInt(); + + ESP_LOGI(L_OT, "Received burner hours: %hu", vars.slave.stats.burnerHours); + + Sensors::setValueByType( + Sensors::Type::OT_BURNER_HOURS, vars.slave.stats.burnerHours, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readDhwBurnerHoursTask("Read DHW burner hours", [](void*) { + // Update DHW burner hours + const auto response = slave.sendRequest(ESP32OT::Messages::UInt16(ESP32OT::MessageID::DHWBurnerOperationHours)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive DHW burner hours"); + return; + } + + vars.slave.stats.dhwBurnerHours = response.getUInt(); + + ESP_LOGI(L_OT, "Received DHW burner hours: %hu", vars.slave.stats.dhwBurnerHours); + + Sensors::setValueByType( + Sensors::Type::OT_DHW_BURNER_HOURS, vars.slave.stats.dhwBurnerHours, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readHeatingPumpHoursTask("Read heating pump hours", [](void*) { + // Update heating pump hours + const auto response = slave.sendRequest(ESP32OT::Messages::UInt16(ESP32OT::MessageID::CHPumpOperationHours)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive heating pump hours"); + return; + } + + vars.slave.stats.heatingPumpHours = response.getUInt(); + + ESP_LOGI(L_OT, "Received heating pump hours: %hu", vars.slave.stats.heatingPumpHours); + + Sensors::setValueByType( + Sensors::Type::OT_HEATING_PUMP_HOURS, vars.slave.stats.heatingPumpHours, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readDhwPumpHoursTask("Read DHW pump hours", [](void*) { + // Update DHW pump hours + const auto response = slave.sendRequest(ESP32OT::Messages::UInt16(ESP32OT::MessageID::DHWPumpValveOperationHours)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive DHW pump hours"); + return; + } + + vars.slave.stats.dhwPumpHours = response.getUInt(); + + ESP_LOGI(L_OT, "Received DHW pump hours: %hu", vars.slave.stats.dhwPumpHours); + + Sensors::setValueByType( + Sensors::Type::OT_DHW_PUMP_HOURS, vars.slave.stats.dhwPumpHours, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readCoolingHoursTask("Read cooling hours", [](void*) { + // Update cooling hours + const auto response = slave.sendRequest(ESP32OT::Messages::UInt16(ESP32OT::MessageID::CoolingOperationHours)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive cooling hours"); + return; + } + + vars.slave.stats.coolingHours = response.getUInt(); + + ESP_LOGI(L_OT, "Received cooling hours: %hu", vars.slave.stats.coolingHours); + + Sensors::setValueByType( + Sensors::Type::OT_COOLING_HOURS, vars.slave.stats.coolingHours, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +// Status may force this task while running its own onDone. +static void onOperationDone(const Task&, uint32_t) { + if (readStatusTask.idle()) { + readStatusTask.tryRun(); + } + + if (esp_log_level_get(L_OT) >= ESP_LOG_VERBOSE) { + static uint32_t lastManagerStack = UINT32_MAX; + static uint32_t lastWorkerStack = UINT32_MAX; + const uint32_t managerStack = uxTaskGetStackHighWaterMark(nullptr); + const uint32_t workerStack = slave.getWorkerStackHighWaterMark(); + if (workerStack > 0 && (managerStack < lastManagerStack || workerStack < lastWorkerStack)) { + ESP_LOGV( + L_OT, "Stack free: manager %lu, RMT worker %lu bytes", + static_cast(managerStack), static_cast(workerStack) + ); + lastManagerStack = managerStack; + lastWorkerStack = workerStack; + } + } +} + +void initOpenTherm() { + // Configure OpenTherm before polling the boiler. + configureDriverTask.setEnabledWhen([] { + return !restartTask.scheduled(); + }).resume(); + openthermTaskManager.addTask(configureDriverTask); + + // Reconfigure GPIO and track initialization requirements. + maintainOpenThermTask.setEnabledWhen([] { + return !restartTask.scheduled(); + }); + openthermTaskManager.addTask(maintainOpenThermTask); + + // Exchange boiler status and monitor the connection. + readStatusTask.setInterval(750) + .setEnabledWhen(canUseBus) + .onDone([](const Task&, uint32_t) { + // Both tasks can reach each other's onDone; never re-enter an active task. + if (vars.slave.flame || vars.slave.modulation.current > 0) { + if (readModulationTask.idle() && readModulationTask.enabled()) { + readModulationTask.forceRun(); + } + } + }); + openthermTaskManager.addTask(readStatusTask); + + // Identify the slave before enabling ordinary operations. + initializeSlaveTask.setEnabledWhen([] { + return canUseBus() && vars.slave.connected; + }); + openthermTaskManager.addTask(initializeSlaveTask); + + // Read the boiler application version. + readSlaveVersionTask.setEnabledWhen(isInitializingSlave) + .onDone(onOperationDone); + openthermTaskManager.addTask(readSlaveVersionTask); + + // Write the master application version. + writeMasterVersionTask.setEnabledWhen(isInitializingSlave) + .onDone(onOperationDone); + openthermTaskManager.addTask(writeMasterVersionTask); + + // Read the boiler OpenTherm version. + readSlaveProtocolTask.setEnabledWhen(isInitializingSlave) + .onDone(onOperationDone); + openthermTaskManager.addTask(readSlaveProtocolTask); + + // Write the master OpenTherm version. + writeMasterProtocolTask.setEnabledWhen(isInitializingSlave) + .onDone(onOperationDone); + openthermTaskManager.addTask(writeMasterProtocolTask); + + // Read the boiler configuration. + readSlaveConfigTask.setEnabledWhen(isInitializingSlave) + .onDone(onOperationDone); + openthermTaskManager.addTask(readSlaveConfigTask); + + // Write the master configuration. + writeMasterConfigTask.setEnabledWhen(isInitializingSlave) + .onDone(onOperationDone); + openthermTaskManager.addTask(writeMasterConfigTask); + + // Write the heating water setpoint and optional maximum temperature. + writeHeatingSetpointTask.setInterval(750) + .setEnabledWhen([] { + return isSlaveReady() && needWriteHeatingSetpoint(getHeatingChannelSetpoint()); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(writeHeatingSetpointTask); + + // Write the DHW temperature setpoint. + writeDhwSetpointTask.setInterval(750) + .setEnabledWhen([] { + return isSlaveReady() && + settings.opentherm.options.dhwSupport && + needWriteDhwSetpoint(getDhwChannelSetpoint()); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(writeDhwSetpointTask); + + // Write the CH2 water temperature setpoint. + writeCh2SetpointTask.setInterval(750) + .setEnabledWhen([] { + if (!isSlaveReady()) { + return false; + } + + if (settings.opentherm.options.heatingToCh2 || settings.opentherm.options.dhwToCh2) { + return needWriteCh2Setpoint(getCh2ChannelSetpoint()); + } + + // Without mirroring, only write the setpoint to disable CH2. + if (!vars.master.ch2.enabled && settings.opentherm.ch2DisablingAction != ChannelDisablingAction::OFF) { + return needWriteCh2Setpoint(getCh2ChannelSetpoint()); + } + + return false; + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(writeCh2SetpointTask); + + // Write the heating room setpoint for native OTC. + writeRoomSetpointTask.setInterval(750) + .setEnabledWhen([] { + return isSlaveReady() && + settings.opentherm.options.nativeOTC && + needWriteRoomSetpoint(vars.master.heating.targetTemp); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(writeRoomSetpointTask); + + // Write the mirrored CH2 room setpoint for native OTC. + writeRoomSetpointCh2Task.setInterval(750) + .setEnabledWhen([] { + return isSlaveReady() && + settings.opentherm.options.nativeOTC && + settings.opentherm.options.heatingToCh2 && + needWriteRoomSetpointCh2(vars.master.heating.targetTemp); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(writeRoomSetpointCh2Task); + + // Write the maximum relative modulation level. + writeMaxModulationTask.setInterval(5000) + .setEnabledWhen(isSlaveReady) + .onDone(onOperationDone); + openthermTaskManager.addTask(writeMaxModulationTask); + + // Write the cooling control signal. + writeCoolingSetpointTask.setInterval(5000) + .setEnabledWhen([] { + return isSlaveReady() && settings.opentherm.options.coolingSupport; + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(writeCoolingSetpointTask); + + // Execute pending boiler fault reset requests. + writeFaultResetTask.setInterval(750) + .setEnabledWhen([] { + return isSlaveReady() && vars.slave.fault.active && + (vars.actions.resetFault || settings.opentherm.options.autoFaultReset); + }) + .onDone([](const Task& task, uint32_t elapsed) { + vars.actions.resetFault = false; + onOperationDone(task, elapsed); + }); + openthermTaskManager.addTask(writeFaultResetTask); + + // Execute pending service reset requests. + writeDiagnosticResetTask.setInterval(750) + .setEnabledWhen([] { + return isSlaveReady() && vars.slave.diag.active && + (vars.actions.resetDiagnostic || settings.opentherm.options.autoDiagReset); + }) + .onDone([](const Task& task, uint32_t elapsed) { + vars.actions.resetDiagnostic = false; + onOperationDone(task, elapsed); + }); + openthermTaskManager.addTask(writeDiagnosticResetTask); + + // Send the current indoor temperature. + writeRoomTemperatureTask.setInterval(60000) + .setEnabledWhen([] { + return isSlaveReady() && + (settings.opentherm.options.nativeOTC || settings.opentherm.options.alwaysSendIndoorTemp); + }) + .onDone([](const Task& task, uint32_t elapsed) { + writeRoomTemperatureTask.setInterval(60000); + onOperationDone(task, elapsed); + }); + openthermTaskManager.addTask(writeRoomTemperatureTask); + + // Send the current indoor temperature to CH2. + writeRoomTemperatureCh2Task.setInterval(60000) + .setEnabledWhen([] { + return isSlaveReady() && + (settings.opentherm.options.nativeOTC || settings.opentherm.options.alwaysSendIndoorTemp) && + settings.opentherm.options.heatingToCh2; + }) + .onDone([](const Task& task, uint32_t elapsed) { + writeRoomTemperatureCh2Task.setInterval(60000); + onOperationDone(task, elapsed); + }); + openthermTaskManager.addTask(writeRoomTemperatureCh2Task); + + // Read relative modulation and calculate current power. + readModulationTask.setInterval(15000) + .setEnabledWhen([] { + return isSlaveReady() && + (Sensors::getAmountByType(Sensors::Type::OT_MODULATION_LEVEL, true) || + Sensors::getAmountByType(Sensors::Type::OT_CURRENT_POWER, true)); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readModulationTask); + + // Read the primary DHW temperature. + readDhwTemperatureTask.setInterval(5000) + .setEnabledWhen([] { + return isSlaveReady() && + settings.opentherm.options.dhwSupport && + Sensors::getAmountByType(Sensors::Type::OT_DHW_TEMP, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readDhwTemperatureTask); + + // Read the second DHW temperature. + readDhwTemperature2Task.setInterval(5000) + .setEnabledWhen([] { + return isSlaveReady() && + settings.opentherm.options.dhwSupport && + Sensors::getAmountByType(Sensors::Type::OT_DHW_TEMP2, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readDhwTemperature2Task); + + // Read the DHW flow rate. + readDhwFlowTask.setInterval(5000) + .setEnabledWhen([] { + return isSlaveReady() && + settings.opentherm.options.dhwSupport && + Sensors::getAmountByType(Sensors::Type::OT_DHW_FLOW_RATE, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readDhwFlowTask); + + // Read the heating supply temperature. + readHeatingTemperatureTask.setInterval(5000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_HEATING_TEMP, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readHeatingTemperatureTask); + + // Read the heating return temperature. + readHeatingReturnTemperatureTask.setInterval(5000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_HEATING_RETURN_TEMP, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readHeatingReturnTemperatureTask); + + // Read the CH2 water temperature. + readCh2TemperatureTask.setInterval(5000) + .setEnabledWhen([] { + return isSlaveReady() && + Sensors::getAmountByType(Sensors::Type::OT_CH2_TEMP, true) && + vars.master.ch2.enabled && !settings.opentherm.options.nativeOTC; + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readCh2TemperatureTask); + + // Read the exhaust temperature. + readExhaustTemperatureTask.setInterval(5000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_EXHAUST_TEMP, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readExhaustTemperatureTask); + + // Read the boiler heat exchanger temperature. + readHeatExchangerTemperatureTask.setInterval(5000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_HEAT_EXCHANGER_TEMP, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readHeatExchangerTemperatureTask); + + // Read the outdoor temperature. + readOutdoorTemperatureTask.setInterval(5000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_OUTDOOR_TEMP, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readOutdoorTemperatureTask); + + // Read the solar storage temperature. + readSolarStorageTemperatureTask.setInterval(5000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_SOLAR_STORAGE_TEMP, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readSolarStorageTemperatureTask); + + // Read the solar collector temperature. + readSolarCollectorTemperatureTask.setInterval(5000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_SOLAR_COLLECTOR_TEMP, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readSolarCollectorTemperatureTask); + + // Read the requested and actual relative fan speeds. + readFanSpeedTask.setInterval(5000) + .setEnabledWhen([] { + return isSlaveReady() && + (Sensors::getAmountByType(Sensors::Type::OT_FAN_SPEED_SETPOINT, true) || + Sensors::getAmountByType(Sensors::Type::OT_FAN_SPEED_CURRENT, true)); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readFanSpeedTask); + + // Read the heating circuit pressure. + readPressureTask.setInterval(15000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_PRESSURE, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readPressureTask); + + // Read the exhaust CO2 concentration. + readExhaustCo2Task.setInterval(15000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_EXHAUST_CO2, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readExhaustCo2Task); + + // Read the exhaust fan speed. + readExhaustFanSpeedTask.setInterval(15000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_EXHAUST_FAN_SPEED, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readExhaustFanSpeedTask); + + // Read the supply fan speed. + readSupplyFanSpeedTask.setInterval(15000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_SUPPLY_FAN_SPEED, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readSupplyFanSpeedTask); + + // Write the current year. + writeYearTask.setInterval(600000) + .setEnabledWhen([] { + return isSlaveReady() && settings.opentherm.options.setDateAndTime; + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(writeYearTask); + + // Write the current day and month. + writeDayAndMonthTask.setInterval(600000) + .setEnabledWhen([] { + return isSlaveReady() && settings.opentherm.options.setDateAndTime; + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(writeDayAndMonthTask); + + // Write the current weekday and time. + writeTimeTask.setInterval(600000) + .setEnabledWhen([] { + return isSlaveReady() && settings.opentherm.options.setDateAndTime; + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(writeTimeTask); + + // Read minimum modulation and boiler power limits. + readPowerLimitsTask.setInterval(60000) + .setEnabledWhen(isSlaveReady) + .onDone(onOperationDone); + openthermTaskManager.addTask(readPowerLimitsTask); + + // Read and apply DHW temperature limits. + readDhwLimitsTask.setInterval(60000) + .setEnabledWhen(isSlaveReady) + .onDone(onOperationDone); + openthermTaskManager.addTask(readDhwLimitsTask); + + // Read and apply heating temperature limits. + readHeatingLimitsTask.setInterval(60000) + .setEnabledWhen(isSlaveReady) + .onDone(onOperationDone); + openthermTaskManager.addTask(readHeatingLimitsTask); + + // Read or clear the boiler fault code. + readFaultTask.setInterval(60000) + .setEnabledWhen([] { + return isSlaveReady() && vars.slave.fault.active; + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readFaultTask); + + // Read or clear the diagnostic code. + readDiagnosticTask.setInterval(60000) + .setEnabledWhen([] { + return isSlaveReady() && (vars.slave.diag.active || vars.slave.fault.active); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readDiagnosticTask); + + // Read the burner start counter. + readBurnerStartsTask.setInterval(60000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_BURNER_STARTS, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readBurnerStartsTask); + + // Read the DHW burner start counter. + readDhwBurnerStartsTask.setInterval(60000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_DHW_BURNER_STARTS, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readDhwBurnerStartsTask); + + // Read the heating pump start counter. + readHeatingPumpStartsTask.setInterval(60000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_HEATING_PUMP_STARTS, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readHeatingPumpStartsTask); + + // Read the DHW pump start counter. + readDhwPumpStartsTask.setInterval(60000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_DHW_PUMP_STARTS, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readDhwPumpStartsTask); + + // Read accumulated burner operating hours. + readBurnerHoursTask.setInterval(60000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_BURNER_HOURS, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readBurnerHoursTask); + + // Read accumulated DHW burner operating hours. + readDhwBurnerHoursTask.setInterval(60000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_DHW_BURNER_HOURS, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readDhwBurnerHoursTask); + + // Read accumulated heating pump operating hours. + readHeatingPumpHoursTask.setInterval(60000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_HEATING_PUMP_HOURS, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readHeatingPumpHoursTask); + + // Read accumulated DHW pump operating hours. + readDhwPumpHoursTask.setInterval(60000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_DHW_PUMP_HOURS, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readDhwPumpHoursTask); + + // Read accumulated cooling operating hours. + readCoolingHoursTask.setInterval(60000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_COOLING_HOURS, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readCoolingHoursTask); + + + // Start + if (!openthermTaskManager.asyncStart(4096, 5, 0, 10, false)) { + esp_system_abort("Failed to start OpenTherm task manager"); + } + + ESP_LOGI(L_MAIN, "Started %s task manager", openthermTaskManager.name()); +} diff --git a/src/portal.cpp b/src/portal.cpp new file mode 100644 index 0000000..988219c --- /dev/null +++ b/src/portal.cpp @@ -0,0 +1,1181 @@ +#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE + +#include +#include +//#define PORTAL_CACHE "max-age=86400" +#define PORTAL_CACHE nullptr + +#include +#include +#include +#include +#include +#include +#include +#include +#if USE_ETHERNET + #include +#endif +#include + +#include +#include + +#include +#include +#include +#include + +WebSerial* webSerial = nullptr; +AsyncWebServer* webServer = nullptr; + +static RequestInterface getRequestInterface(AsyncWebServerRequest* request) { + if (request == nullptr || request->client() == nullptr) { + return RequestInterface::UNKNOWN; + } + + // Classify the connection by its destination address. + const IPAddress localIP = request->client()->localIP(); + if (localIP == IPAddress(0, 0, 0, 0)) { + return RequestInterface::UNKNOWN; + } + + const IPAddress apIP = WiFi.AP.localIP(); + const IPAddress staIP = WiFi.STA.localIP(); + const bool matchesAp = localIP == apIP; + const bool matchesSta = localIP == staIP; + #if USE_ETHERNET + const bool matchesEth = localIP == ETH.localIP(); + #else + const bool matchesEth = false; + #endif + + if (matchesAp + matchesSta + matchesEth > 1) { + // Matching interface addresses cannot identify the connection. + return RequestInterface::UNKNOWN; + } + + if (localIP == apIP) { + return RequestInterface::AP; + } + + if (localIP == staIP) { + return RequestInterface::STA; + } + + if (matchesEth) { + return RequestInterface::ETH; + } + + return RequestInterface::UNKNOWN; +} + +static void onCaptivePortal(AsyncWebServerRequest *request) { + const auto& url = request->url(); + + if (url.equals("/connecttest.txt")) { + request->redirect("http://logout.net", 302); + + ESP_LOGD(L_PORTAL_CAPTIVE, "Redirect to http://logout.net with 302 code"); + + } else if (url.equals("/wpad.dat")) { + request->send(404); + + ESP_LOGD(L_PORTAL_CAPTIVE, "Send empty page with 404 code"); + + } else if (url.equals("/success.txt")) { + request->send(200); + + ESP_LOGD(L_PORTAL_CAPTIVE, "Send empty page with 200 code"); + + } else { + std::string portalUrl; + portalUrl.reserve(7 + 15 + 1); + portalUrl = "http://"; + portalUrl += WiFi.AP.localIP().toString().c_str(); + portalUrl += '/'; + + request->redirect(portalUrl.c_str(), 302); + + ESP_LOGD(L_PORTAL_CAPTIVE, "Redirect to portal page with 302 code"); + } +} + +static bool isAuthenticationRequired(AsyncWebServerRequest* request) { + if (isNetworkInterfaceStarted(NetworkMode::AP) && getRequestInterface(request) == RequestInterface::AP) { + return false; + } + + return settings.portal.auth && strlen(settings.portal.password); +} + +static AsyncWebServerResponse* setDownloadFilename(AsyncWebServerResponse* response, const char* type, const char* extension) { + const time_t now = time(nullptr); + + tm localNow {}; + localtime_r(&now, &localNow); + + char localNowValue[20]; + strftime(localNowValue, sizeof(localNowValue), "%Y-%m-%d-%H-%M-%S", &localNow); + + char contentDisposition[96]; + snprintf( + contentDisposition, sizeof(contentDisposition), + "attachment; filename=\"%s_%s_%s.%s\"", + networkSettings.hostname, localNowValue, type, extension + ); + response->addHeader("Content-Disposition", contentDisposition); + + return response; +} + +// Authenticate requests +static AsyncMiddlewareFunction authMiddleware([](AsyncWebServerRequest *request, ArMiddlewareNext next) { + if (!isAuthenticationRequired(request)) { + return next(); + } + + if (request->authenticate(settings.portal.login, settings.portal.password, PROJECT_NAME)) { + return next(); + } + + return request->requestAuthentication(AsyncAuthType::AUTH_BASIC, PROJECT_NAME, "Authentication failed"); +}); + +static void initWebSerial() { + // Register before System starts. Unbuffered WebSerial preserves newlines inside each record. + webSerial = new WebSerial(); + webSerial->begin(webServer, nullptr, "/webserial"); + + webServer->addMiddleware([](AsyncWebServerRequest* request, ArMiddlewareNext next) { + if (request->url().equals("/webserial")) { + if (!settings.system.webSerial.enabled) { + request->send(404); + return; + } + + // Refresh credentials before each handshake, including after re-enabling. + if (isAuthenticationRequired(request)) { + webSerial->setAuthentication(settings.portal.login, settings.portal.password); + } else { + webSerial->setAuthentication("", ""); + } + } + next(); + }); +} + +static void routes() { + // Redirect to index page + webServer->on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + request->redirect("/index.html"); + }); + + // Serve index page + webServer->serveStatic("/index.html", LittleFS, "/pages/index.html", PORTAL_CACHE); + + // Serve dashboard page + webServer->serveStatic("/dashboard.html", LittleFS, "/pages/dashboard.html", PORTAL_CACHE) + .addMiddleware(&authMiddleware); + + // Serve network settings page + webServer->serveStatic("/network.html", LittleFS, "/pages/network.html", PORTAL_CACHE) + .addMiddleware(&authMiddleware); + + // Serve settings page + webServer->serveStatic("/settings.html", LittleFS, "/pages/settings.html", PORTAL_CACHE) + .addMiddleware(&authMiddleware); + + // Serve sensors page + webServer->serveStatic("/sensors.html", LittleFS, "/pages/sensors.html", PORTAL_CACHE) + .addMiddleware(&authMiddleware); + + // Serve upgrade page + webServer->serveStatic("/upgrade.html", LittleFS, "/pages/upgrade.html", PORTAL_CACHE) + .addMiddleware(&authMiddleware); + + // Serve logs page + webServer->serveStatic("/logs.html", LittleFS, "/pages/logs.html", PORTAL_CACHE) + .addMiddleware(&authMiddleware); + + // Handle unmatched requests + webServer->onNotFound([](AsyncWebServerRequest *request) { + const auto& url = request->url(); + ESP_LOGD(L_PORTAL_WEBSERVER, "Page not found, uri: %s", url.c_str()); + + if (url.equals("/index.html")) { + request->send(200, "text/plain", "The file system is not flashed!"); + + } else if (getNetworkState(NetworkMode::AP) == NetworkState::PORTAL_STARTED && getRequestInterface(request) == RequestInterface::AP) { + onCaptivePortal(request); + + } else { + request->send(404, "text/plain", "Page not found"); + } + }); + + // Serve static assets + webServer->serveStatic("/robots.txt", LittleFS, "/static/robots.txt", PORTAL_CACHE); + webServer->serveStatic("/favicon.ico", LittleFS, "/static/images/favicon.ico", PORTAL_CACHE); + webServer->serveStatic("/static", LittleFS, "/static", PORTAL_CACHE); +} + +static void restApi() { + // Handle OTA updates + auto upgradeHandler = (new UpgradeHandler("/api/upgrade")) + ->setBeforeUpgradeCallback([](AsyncWebServerRequest *request, UpgradeHandler::UpgradeType type) -> bool { + // Upload callbacks run before middleware; reject before pausing tasks or writing. + if (isAuthenticationRequired(request) && !request->authenticate(settings.portal.login, settings.portal.password, PROJECT_NAME)) { + return false; + + } else if (restartTask.scheduled() || restartTask.active()) { + return false; + } + + // UpgradeHandler invokes this callback for every upload chunk. + if (upgrading) { + return true; + } + + // Prepare for upgrade and pause App tasks + upgrading = true; + appTaskManager.pause(); + + // App owns MQTT; finish its current callback before stopping the client. + if (!appTaskManager.waitForPaused(5000)) { + upgrading = false; + + if (!restartTask.scheduled() && !restartTask.active()) { + appTaskManager.resume(); + } + + ESP_LOGW(L_PORTAL_OTA, "App task manager pause not confirmed, upgrade cancelled"); + return false; + } + + // Stop MQTT after App has paused + stopMqtt(false); + + // An MQTT command already in flight may have scheduled a restart before end(). + if (restartTask.scheduled() || restartTask.active()) { + upgrading = false; + return false; + } + + // Pause sensor tasks + sensorsTaskManager.pause(); + if (!sensorsTaskManager.waitForPaused(5000)) { + requestReconfigureMqtt(); + upgrading = false; + + if (!restartTask.scheduled() && !restartTask.active()) { + appTaskManager.resume(); + sensorsTaskManager.resume(); + } + + ESP_LOGW(L_PORTAL_OTA, "Sensors task manager pause not confirmed, upgrade cancelled"); + return false; + } + + // Pause OpenTherm tasks + openthermTaskManager.pause(); + if (!openthermTaskManager.waitForPaused(5000)) { + requestReconfigureMqtt(); + upgrading = false; + + if (!restartTask.scheduled() && !restartTask.active()) { + appTaskManager.resume(); + sensorsTaskManager.resume(); + openthermTaskManager.resume(); + } + + ESP_LOGW(L_PORTAL_OTA, "OpenTherm task manager pause not confirmed, upgrade cancelled"); + return false; + } + + return true; + })->setAfterUpgradeCallback([](AsyncWebServerRequest *request, const UpgradeHandler::UpgradeResult& fwResult, const UpgradeHandler::UpgradeResult& fsResult) { + if (request && isAuthenticationRequired(request) && !request->authenticate(settings.portal.login, settings.portal.password, PROJECT_NAME)) { + return request->requestAuthentication(AsyncAuthType::AUTH_BASIC, PROJECT_NAME, "Authentication failed"); + } + + // Process upgrade results + unsigned short status = 406; + if (fwResult.status == UpgradeHandler::UpgradeStatus::SUCCESS || fsResult.status == UpgradeHandler::UpgradeStatus::SUCCESS) { + status = 202; + + // Schedule restart after a successful upgrade + if (!restartTask.scheduled() && !restartTask.active()) { + restartTask.resume(15000); + } + + } else { + requestReconfigureMqtt(); + } + + // Resume tasks after a failed upgrade + upgrading = false; + if (status != 202 && !restartTask.scheduled() && !restartTask.active()) { + appTaskManager.resume(); + sensorsTaskManager.resume(); + openthermTaskManager.resume(); + } + + if (!request) { + return; + } + + // Prepare response + auto *response = new AsyncJsonResponse(); + auto& doc = response->getRoot(); + + auto fwDoc = doc["firmware"].to(); + fwDoc["status"] = static_cast(fwResult.status); + fwDoc["error"] = fwResult.error; + + auto fsDoc = doc["filesystem"].to(); + fsDoc["status"] = static_cast(fsResult.status); + fsDoc["error"] = fsResult.error; + + // Send response + response->setLength(); + response->setCode(status); + request->send(response); + }); + upgradeHandler->addMiddleware(&authMiddleware); + webServer->addHandler(upgradeHandler); + + + // Get backup + webServer->on("/api/backup/save", HTTP_GET, [](AsyncWebServerRequest *request) { + // Prepare response + auto *response = new AsyncJsonResponse(); + auto& doc = response->getRoot(); + + // Add network settings + auto networkDoc = doc[S_NETWORK].to(); + toJson(networkSettings, networkDoc); + + // Add main settings + auto settingsDoc = doc[S_SETTINGS].to(); + toJson(settings.system, settingsDoc[S_SYSTEM].to()); + toJson(settings.portal, settingsDoc[S_PORTAL].to()); + toJson(settings.opentherm, settingsDoc[S_OPENTHERM].to()); + toJson(settings.mqtt, settingsDoc[S_MQTT].to()); + toJson(settings.emergency, settingsDoc[S_EMERGENCY].to()); + toJson(settings.heating, settingsDoc[S_HEATING].to()); + toJson(settings.dhw, settingsDoc[S_DHW].to()); + toJson(settings.equitherm, settingsDoc[S_EQUITHERM].to()); + toJson(settings.pid, settingsDoc[S_PID].to()); + toJson(settings.externalPump, settingsDoc[S_EXTERNAL_PUMP].to()); + toJson(settings.cascadeControl, settingsDoc[S_CASCADE_CONTROL].to()); + + // Add sensor settings + for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { + if (const auto sensor = Sensors::getSettings(sensorId)) { + auto sensorsettingsDoc = doc[S_SENSORS][sensorId].to(); + toJson(sensorId, *sensor, sensorsettingsDoc); + } + } + + // Send response + response->setLength(); + request->send(setDownloadFilename(response, "backup", "json")); + }).addMiddleware(&authMiddleware); + + + // Request restart + webServer->on("/api/restart", HTTP_POST, [](AsyncWebServerRequest *request) { + if (upgrading || restartTask.scheduled() || restartTask.active()) { + return request->send(503); + } + + // Schedule restart + restartTask.resume(15000); + request->send(202); + }).addMiddleware(&authMiddleware); + + + // Get network settings + webServer->on("/api/network/settings", HTTP_GET, [](AsyncWebServerRequest *request) { + // Prepare response + auto *response = new AsyncJsonResponse(); + auto& doc = response->getRoot(); + toJson(networkSettings, doc); + #if USE_ETHERNET + doc[S_ETHERNET][S_CONFIGURED] = isEthernetConfigured(); + #endif + + // Send response + response->setLength(); + request->send(response); + }).addMiddleware(&authMiddleware); + + + // Set network settings + auto& networkSettingsHandler = webServer->on("/api/network/settings", HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) { + if (upgrading || restartTask.scheduled() || restartTask.active()) { + return request->send(503); + + } else if (!requestDoc.is() || !requestDoc.size()) { + return request->send(400); + } + + // Apply network settings + const auto result = fromJson(requestDoc, networkSettings); + if (result.changed) { + // Request network settings save + requestSaveNetworkSettings(); + } + requestDoc.clear(); + + // If the noresponse parameter is provided, + // simply return HTTP 200/201 with an empty body. + if (request->hasParam("noresponse")) { + request->send(result.changed ? 201 : 200); + + } else { + // Prepare response + auto *response = new AsyncJsonResponse(); + auto& responseDoc = response->getRoot(); + toJson(networkSettings, responseDoc); + #if USE_ETHERNET + responseDoc[S_ETHERNET][S_CONFIGURED] = isEthernetConfigured(); + #endif + + // Send response + response->setLength(); + response->setCode(result.changed ? 201 : 200); + request->send(response); + } + + // Reconnect network + if (result.changed && !request->hasParam("noreconnect")) { + // Queue the response before a network reset can disconnect this request. + reconnectNetwork(); + } + }); + networkSettingsHandler.setMaxContentLength(1024); + networkSettingsHandler.addMiddleware(&authMiddleware); + + + // Scan Wi-Fi + webServer->on("/api/network/scan", HTTP_GET, [](AsyncWebServerRequest *request) { + // Ethernet mode must not start the Wi-Fi radio for a scan. + if (networkSettings.type != NetworkMode::STA) { + request->send(409); + return; + } + + // Read scan status + auto apCount = WiFi.scanComplete(); + + switch (apCount) { + case WIFI_SCAN_FAILED: + // Start asynchronous scan + WiFi.scanNetworks(true, true, true); + request->send(404); + break; + + case WIFI_SCAN_RUNNING: + request->send(202); + break; + + default: + // Prepare response + auto *response = new AsyncJsonResponse(true); + auto& doc = response->getRoot(); + for (short int i = 0; i < apCount; i++) { + doc[i][S_SSID] = WiFi.SSID(i); + doc[i][S_BSSID] = WiFi.BSSIDstr(i); + doc[i][S_SIGNAL_QUALITY] = rssiToSignalQuality(WiFi.RSSI(i)); + doc[i][S_CHANNEL] = WiFi.channel(i); + doc[i][S_HIDDEN] = !WiFi.SSID(i).length(); + doc[i][S_AUTH] = WiFi.encryptionType(i); + } + + // Send response + response->setLength(); + request->send(response); + + // Release scan results + WiFi.scanDelete(); + } + }).addMiddleware(&authMiddleware); + + + // Get settings + webServer->on(AsyncURIMatcher::prefix("/api/settings/"), HTTP_GET, [](AsyncWebServerRequest *request) { + // Parse settings section + const auto& url = request->url(); + const auto section = std::string_view(url.c_str(), url.length()) + .substr(sizeof("/api/settings/") - 1); + + // Prepare response + auto *response = new AsyncJsonResponse(); + auto& doc = response->getRoot(); + + // Add section settings + if (section == S_SYSTEM) { + toJson(settings.system, doc); + + } else if (section == S_PORTAL) { + toJson(settings.portal, doc); + + } else if (section == S_OPENTHERM) { + toJson(settings.opentherm, doc); + + } else if (section == S_MQTT) { + toJson(settings.mqtt, doc); + + } else if (section == S_EMERGENCY) { + toJson(settings.emergency, doc); + + } else if (section == S_HEATING) { + toJson(settings.heating, doc); + + } else if (section == S_DHW) { + toJson(settings.dhw, doc); + + } else if (section == S_PID) { + toJson(settings.pid, doc); + + } else if (section == S_EQUITHERM) { + toJson(settings.equitherm, doc); + + } else if (section == S_EXTERNAL_PUMP) { + toJson(settings.externalPump, doc); + + } else if (section == S_CASCADE_CONTROL) { + toJson(settings.cascadeControl, doc); + + } else { + delete response; + return request->send(404); + } + + // Send response + response->setLength(); + request->send(response); + }).addMiddleware(&authMiddleware); + + + // Set settings + auto& settingsHandler = webServer->on(AsyncURIMatcher::prefix("/api/settings/"), HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) { + if (upgrading || restartTask.scheduled() || restartTask.active()) { + return request->send(503); + + } else if (!requestDoc.is() || !requestDoc.size()) { + return request->send(400); + } + + // Parse settings section + const auto& url = request->url(); + const auto section = std::string_view(url.c_str(), url.length()) + .substr(sizeof("/api/settings/") - 1); + + // Apply section settings + bool mqttChanged = false; + SettingResult result; + if (section == S_SYSTEM) { + result = fromJson(requestDoc, settings.system); + + } else if (section == S_PORTAL) { + result = fromJson(requestDoc, settings.portal); + + } else if (section == S_OPENTHERM) { + result = fromJson(requestDoc, settings.opentherm); + + } else if (section == S_MQTT) { + const auto previousMqtt = settings.mqtt; + result = fromJson(requestDoc, settings.mqtt); + mqttChanged = previousMqtt.enabled != settings.mqtt.enabled || + previousMqtt.port != settings.mqtt.port || + previousMqtt.interval != settings.mqtt.interval || + strcmp(previousMqtt.server, settings.mqtt.server) != 0 || + strcmp(previousMqtt.user, settings.mqtt.user) != 0 || + strcmp(previousMqtt.password, settings.mqtt.password) != 0 || + strcmp(previousMqtt.prefix, settings.mqtt.prefix) != 0; + + } else if (section == S_EMERGENCY) { + result = fromJson(requestDoc, settings.emergency); + + } else if (section == S_HEATING) { + result = fromJson(requestDoc, settings.heating); + + } else if (section == S_DHW) { + result = fromJson(requestDoc, settings.dhw); + + } else if (section == S_PID) { + result = fromJson(requestDoc, settings.pid); + + } else if (section == S_EQUITHERM) { + result = fromJson(requestDoc, settings.equitherm); + + } else if (section == S_EXTERNAL_PUMP) { + result = fromJson(requestDoc, settings.externalPump); + + } else if (section == S_CASCADE_CONTROL) { + result = fromJson(requestDoc, settings.cascadeControl); + + } else { + return request->send(404); + } + + // Normalize settings + result.changed = normalizeSettings(settings) || result.changed; + if (result.changed) { + // Request settings save and logging update + requestSaveSettings(); + configureLoggingTask.resume(); + + // Request MQTT reconfiguration + if (mqttChanged) { + requestReconfigureMqtt(); + } + + // Request MQTT settings publication + // If busy, the periodic task will publish the current settings. + std::unique_lock lock(mqttMutex, std::try_to_lock); + if (lock.owns_lock() && mqttPublishSettingsTask) { + mqttPublishSettingsTask->requestEarlyRun(); + } + } + requestDoc.clear(); + + // If the noresponse parameter is provided, + // simply return HTTP 200/201 with an empty body. + if (request->hasParam("noresponse")) { + return request->send(result.changed ? 201 : 200); + } + + // Prepare response + auto *response = new AsyncJsonResponse(); + auto& responseDoc = response->getRoot(); + + // Add section settings + if (section == S_SYSTEM) { + toJson(settings.system, responseDoc); + + } else if (section == S_PORTAL) { + toJson(settings.portal, responseDoc); + + } else if (section == S_OPENTHERM) { + toJson(settings.opentherm, responseDoc); + + } else if (section == S_MQTT) { + toJson(settings.mqtt, responseDoc); + + } else if (section == S_EMERGENCY) { + toJson(settings.emergency, responseDoc); + + } else if (section == S_HEATING) { + toJson(settings.heating, responseDoc); + + } else if (section == S_DHW) { + toJson(settings.dhw, responseDoc); + + } else if (section == S_PID) { + toJson(settings.pid, responseDoc); + + } else if (section == S_EQUITHERM) { + toJson(settings.equitherm, responseDoc); + + } else if (section == S_EXTERNAL_PUMP) { + toJson(settings.externalPump, responseDoc); + + } else if (section == S_CASCADE_CONTROL) { + toJson(settings.cascadeControl, responseDoc); + } + + // Send response + response->setLength(); + response->setCode(result.changed ? 201 : 200); + request->send(response); + }); + settingsHandler.setMaxContentLength(3072); + settingsHandler.addMiddleware(&authMiddleware); + + + // Get sensors list + webServer->on("/api/sensors", HTTP_GET, [](AsyncWebServerRequest *request) { + // Prepare response + bool detailed = request->hasParam("detailed"); + auto *response = new AsyncJsonResponse(true); + auto& responseDoc = response->getRoot(); + + // Build sensor list + for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { + if (detailed) { + if (const auto snapshot = Sensors::getSnapshot(sensorId)) { + responseDoc[sensorId][S_ENABLED] = snapshot->settings.enabled; + responseDoc[sensorId][S_NAME] = static_cast(snapshot->settings.name); + responseDoc[sensorId][S_SLUG] = static_cast(snapshot->settings.slug); + responseDoc[sensorId][S_PURPOSE] = static_cast(snapshot->settings.purpose); + toJson(snapshot->settings, snapshot->result, responseDoc[sensorId]); + } + + } else if (const auto sensor = Sensors::getSettings(sensorId)) { + responseDoc[sensorId] = static_cast(sensor->name); + } + } + + // Send response + response->setLength(); + request->send(response); + }).addMiddleware(&authMiddleware); + + + // Get sensor settings + webServer->on(AsyncURIMatcher::exact("/api/sensor"), HTTP_GET, [](AsyncWebServerRequest *request) { + if (!request->hasParam("id")) { + return request->send(400); + } + + // Parse sensor ID + const auto& id = request->getParam("id")->value(); + const auto sensorId = Sensors::parseId(id.c_str()); + if (!sensorId) { + return request->send(404); + } + + // Get sensor settings for response + const auto sensor = Sensors::getSettings(*sensorId); + if (!sensor) { + return request->send(404); + } + + // Prepare response + auto *response = new AsyncJsonResponse(); + auto& doc = response->getRoot(); + toJson(*sensorId, *sensor, doc); + + // Send response + response->setLength(); + request->send(response); + }).addMiddleware(&authMiddleware); + + + // Set sensor settings + auto& sensorSettingsHandler = webServer->on(AsyncURIMatcher::exact("/api/sensor"), HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) { + if (upgrading || restartTask.scheduled() || restartTask.active()) { + return request->send(503); + + } else if (!requestDoc.is() || !requestDoc.size()) { + return request->send(400); + + } else if (!request->hasParam("id")) { + return request->send(400); + } + + // Parse sensor ID + auto& id = request->getParam("id")->value(); + const auto sensorId = Sensors::parseId(id.c_str()); + if (!sensorId) { + return request->send(404); + } + + // Apply sensor settings + Sensors::Settings previousSettings; + bool isDifferent = false; + SettingResult result; + { + std::lock_guard lock(Sensors::mutex); + if (Sensors::settings == nullptr || Sensors::results == nullptr) { + return request->send(404); + } + + auto& sensor = Sensors::settings[*sensorId]; + previousSettings = sensor; + + result = fromJson(requestDoc, sensor); + if (result.changed) { + isDifferent |= previousSettings.enabled != sensor.enabled; + isDifferent |= strcmp(previousSettings.name, sensor.name) != 0; + isDifferent |= strcmp(previousSettings.slug, sensor.slug) != 0; + isDifferent |= previousSettings.purpose != sensor.purpose; + isDifferent |= previousSettings.type != sensor.type; + + bool resetResult = previousSettings.enabled != sensor.enabled; + resetResult |= previousSettings.type != sensor.type; + resetResult |= previousSettings.gpio != sensor.gpio; + resetResult |= !Sensors::isEqualAddress(previousSettings.address, sensor.address); + + // A different source must provide its own readings and filter baseline. + if (resetResult) { + Sensors::results[*sensorId] = {}; + Sensors::results[*sensorId].updatedAt = millis(); + } + } + } + + if (result.changed) { + // Request MQTT sensor reconfiguration + if (isDifferent) { + requestReconfigureMqttSensor(*sensorId, previousSettings); + } + + // Request sensor settings save + requestSaveSensorsSettings(); + } + requestDoc.clear(); + + // If the noresponse parameter is provided, + // simply return HTTP 200/201 with an empty body. + if (request->hasParam("noresponse")) { + return request->send(result.changed ? 201 : 200); + } + + // Prepare response + auto *response = new AsyncJsonResponse(); + auto& responseDoc = response->getRoot(); + if (const auto sensor = Sensors::getSettings(*sensorId)) { + toJson(*sensorId, *sensor, responseDoc); + } + + // Send response + response->setLength(); + response->setCode(result.changed ? 201 : 200); + request->send(response); + }); + sensorSettingsHandler.setMaxContentLength(1024); + sensorSettingsHandler.addMiddleware(&authMiddleware); + + + // Get sensor measurements + webServer->on(AsyncURIMatcher::exact("/api/sensor/value"), HTTP_GET, [](AsyncWebServerRequest *request) { + if (!request->hasParam("id")) { + return request->send(400); + } + + // Parse sensor ID + const auto& id = request->getParam("id")->value(); + const auto sensorId = Sensors::parseId(id.c_str()); + if (!sensorId) { + return request->send(404); + } + + // Get sensor snapshot for response + const auto sensor = Sensors::getSnapshot(*sensorId); + if (!sensor) { + return request->send(404); + } + + // Prepare response + auto *response = new AsyncJsonResponse(); + auto& doc = response->getRoot(); + toJson(sensor->settings, sensor->result, doc); + + // Send response + response->setLength(); + request->send(response); + }).addMiddleware(&authMiddleware); + + + // Set sensor value (JSON) + auto& sensorValueHandler = webServer->on(AsyncURIMatcher::exact("/api/sensor/value"), HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) { + if (upgrading || restartTask.scheduled() || restartTask.active()) { + return request->send(503); + + } else if (!requestDoc.is() || !requestDoc.size()) { + return request->send(400); + + } else if (!request->hasParam("id") || !requestDoc[S_VALUE].is()) { + return request->send(400); + } + + // Read sensor value + const auto value = requestDoc[S_VALUE].as(); + requestDoc.clear(); + + // Parse sensor ID + const auto& id = request->getParam("id")->value(); + const auto sensorId = Sensors::parseId(id.c_str()); + if (!sensorId) { + return request->send(404); + } + + // Try to set sensor value + if (!Sensors::setManualValueById(*sensorId, value, settings.system.unitSystem)) { + return request->send(400); + } + + // Request MQTT publication + requestPublishMqttSensor(*sensorId); + + // If the noresponse parameter is provided, + // simply return HTTP 201 with an empty body. + if (request->hasParam("noresponse")) { + return request->send(201); + } + + // Get sensor snapshot for response + const auto sensor = Sensors::getSnapshot(*sensorId); + if (!sensor) { + return request->send(404); + } + + // Prepare response + auto *response = new AsyncJsonResponse(); + auto& responseDoc = response->getRoot(); + toJson(sensor->settings, sensor->result, responseDoc); + + // Send response + response->setLength(); + response->setCode(201); + request->send(response); + }); + sensorValueHandler.setMaxContentLength(64); + sensorValueHandler.addMiddleware(&authMiddleware); + + + // Set sensor value (form) + webServer->on(AsyncURIMatcher::exact("/api/sensor/value"), HTTP_POST, [](AsyncWebServerRequest *request) { + if (upgrading || restartTask.scheduled() || restartTask.active()) { + return request->send(503); + + } else if (request->contentLength() > 64) { + return request->send(413); + + } else if (!request->hasParam("id")) { + return request->send(400); + } + + // Parse sensor ID + const auto& id = request->getParam("id")->value(); + const auto sensorId = Sensors::parseId(id.c_str()); + if (!sensorId) { + return request->send(404); + } + + // Read POST payload + const auto* parameter = request->getParam(S_VALUE, true); + if (parameter == nullptr) { + parameter = request->getParam("body", true); + } + + if (parameter == nullptr) { + return request->send(400); + } + + // Validate payload length + const auto& text = parameter->value(); + const auto payload = trimPayload(std::string_view(text.c_str(), text.length())); + if (payload.size() > 32) { + return request->send(400); + } + + // Parse numeric value + const auto value = parseNumber(payload.data(), payload.size()); + if (!value) { + return request->send(400); + } + + // Try to set sensor value + if (!Sensors::setManualValueById(*sensorId, *value, settings.system.unitSystem)) { + return request->send(400); + } + + // Request MQTT publication + requestPublishMqttSensor(*sensorId); + + // If the noresponse parameter is provided, + // simply return HTTP 201 with an empty body. + if (request->hasParam("noresponse")) { + return request->send(201); + } + + // Get sensor snapshot for response + const auto sensor = Sensors::getSnapshot(*sensorId); + if (!sensor) { + return request->send(404); + } + + // Prepare response + auto *response = new AsyncJsonResponse(); + auto& responseDoc = response->getRoot(); + toJson(sensor->settings, sensor->result, responseDoc); + + // Send response + response->setLength(); + response->setCode(201); + request->send(response); + }).addMiddleware(&authMiddleware); + + + // Get vars + webServer->on("/api/vars", HTTP_GET, [](AsyncWebServerRequest *request) { + // Prepare response + auto *response = new AsyncJsonResponse(); + auto& doc = response->getRoot(); + toJson(vars, doc); + + // Send response + response->setLength(); + request->send(response); + }); + + // Set vars + auto& varsHandler = webServer->on("/api/vars", HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) { + if (upgrading || restartTask.scheduled() || restartTask.active()) { + return request->send(503); + + } else if (!requestDoc.is() || !requestDoc.size()) { + return request->send(400); + } + + // Apply requested actions + const auto result = fromJson(requestDoc, vars); + requestDoc.clear(); + + // Prepare response + auto *response = new AsyncJsonResponse(); + auto& responseDoc = response->getRoot(); + toJson(vars, responseDoc); + + // Send response + response->setLength(); + response->setCode(result.changed ? 201 : 200); + request->send(response); + + if (result.changed) { + // Request MQTT state publication + // If busy, the periodic task will publish the current state. + std::unique_lock lock(mqttMutex, std::try_to_lock); + if (lock.owns_lock() && mqttPublishStateTask) { + mqttPublishStateTask->requestEarlyRun(); + } + } + }); + varsHandler.setMaxContentLength(1536); + varsHandler.addMiddleware(&authMiddleware); + + // Get info + webServer->on("/api/info", HTTP_GET, [](AsyncWebServerRequest *request) { + // Prepare response + auto *response = new AsyncJsonResponse(); + auto& doc = response->getRoot(); + + #if USE_ETHERNET + doc[S_FEATURES][S_ETHERNET] = true; + #endif + + // Add system information + auto docSystem = doc[S_SYSTEM].to(); + docSystem[S_RESET_REASON] = getResetReason(); + docSystem[S_UPTIME] = millis() / 1000; + + // Add network information + const bool isConnected = isNetworkConnected(); + const bool wifiUplink = getNetworkMode() == NetworkMode::STA; + auto docNetwork = doc[S_NETWORK].to(); + docNetwork[S_HOSTNAME] = networkSettings.hostname; + docNetwork[S_MAC] = getNetworkMac(); + docNetwork[S_CONNECTED] = isConnected; + docNetwork[S_CONNECTION_TYPE] = getNetworkConnectionType(); + docNetwork[S_SSID] = wifiUplink ? WiFi.STA.SSID() : ""; + docNetwork[S_SIGNAL_QUALITY] = wifiUplink ? rssiToSignalQuality(WiFi.STA.RSSI()) : 0; + docNetwork[S_CHANNEL] = wifiUplink ? WiFi.channel() : 0; + docNetwork[S_IP] = isConnected ? getNetworkIp().toString() : ""; + docNetwork[S_SUBNET] = isConnected ? getNetworkSubnet().toString() : ""; + docNetwork[S_GATEWAY] = isConnected ? getNetworkGateway().toString() : ""; + docNetwork[S_DNS] = isConnected ? getNetworkDns().toString() : ""; + + // Add build information + auto docBuild = doc[S_BUILD].to(); + docBuild[S_VERSION] = BUILD_VERSION; + docBuild[S_COMMIT] = BUILD_COMMIT; + docBuild[S_DATE] = __DATE__ " " __TIME__; + docBuild[S_ENV] = BUILD_ENV; + docBuild[S_CORE] = ESP.getCoreVersion(); + docBuild[S_SDK] = ESP.getSdkVersion(); + + // Add memory metrics + const auto memory = getMemoryMetrics(); + auto docHeap = doc[S_HEAP].to(); + docHeap[S_TOTAL] = memory.heap.total; + docHeap[S_FREE] = memory.heap.total_free_bytes; + docHeap[S_MIN_FREE] = memory.heap.minimum_free_bytes; + docHeap[S_MAX_FREE_BLOCK] = memory.heap.largest_free_block; + docHeap[S_MIN_MAX_FREE_BLOCK] = memory.heap.minLargestBlock; + + auto docPsram = doc[S_PSRAM].to(); + docPsram[S_TOTAL] = memory.psram.total; + docPsram[S_FREE] = memory.psram.total_free_bytes; + docPsram[S_MIN_FREE] = memory.psram.minimum_free_bytes; + docPsram[S_MAX_FREE_BLOCK] = memory.psram.largest_free_block; + + // Add chip information + auto docChip = doc[S_CHIP].to(); + docChip[S_MODEL] = ESP.getChipModel(); + docChip[S_REV] = ESP.getChipRevision(); + docChip[S_CORES] = ESP.getChipCores(); + docChip[S_FREQ] = ESP.getCpuFreqMHz(); + + // Add flash information + auto docFlash = doc[S_FLASH].to(); + docFlash[S_SIZE] = ESP.getFlashChipSize(); + + // Send response + response->setLength(); + request->send(response); + }); + + // Get coredump + webServer->on("/api/coredump", HTTP_GET, [](AsyncWebServerRequest* request) { + // Locate core dump image + size_t address = 0; + size_t size = 0; + + const esp_err_t image = esp_core_dump_image_get(&address, &size); + if (image != ESP_OK) { + request->send(image == ESP_ERR_NOT_FOUND ? 404 : 500); + return; + } + + // Validate core dump image + if (esp_core_dump_image_check() != ESP_OK) { + request->send(500); + return; + } + + // Validate core dump partition + const esp_partition_t* partition = esp_partition_find_first( + ESP_PARTITION_TYPE_DATA, + ESP_PARTITION_SUBTYPE_DATA_COREDUMP, + nullptr + ); + if (partition == nullptr || partition->address != address || size > partition->size) { + request->send(500); + return; + } + + // Prepare core dump download + auto* response = request->beginResponse("application/octet-stream", size, + [partition, size](uint8_t* buffer, size_t maximum, size_t index) -> size_t { + if (index >= size) { + return 0; + } + + // Read core dump chunk + const size_t remaining = size - index; + const size_t count = remaining < maximum ? remaining : maximum; + if (esp_partition_read(partition, index, buffer, count) != ESP_OK) { + return 0; + } + + return count; + }); + + // Send response + request->send(setDownloadFilename(response, "coredump", "bin")); + }).addMiddleware(&authMiddleware); +} + +// Initialize portal +void initPortal() { + webServer = new AsyncWebServer(80); + initWebSerial(); + routes(); + restApi(); +} diff --git a/src/regulator.cpp b/src/regulator.cpp new file mode 100644 index 0000000..31d6227 --- /dev/null +++ b/src/regulator.cpp @@ -0,0 +1,316 @@ +#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE + +#include + +#include +#include + +static PID pidRegulator; + +static float heatingTarget = 0.0f; +static bool equithermEnabled = false; +static float equithermResult = 0.0f; +static float pidResult = 0.0f; +static bool indoorSensorsConnected = false; + +static Task equithermTask("Equitherm", Task::Type::ONCE, [](void*) { + float etResult = settings.heating.target + settings.equitherm.shift; + + if (settings.heating.maxTemp > settings.heating.target) { + float tempDelta = settings.heating.target - vars.master.heating.outdoorTemp; + float maxPoint = settings.heating.target - ( + settings.heating.maxTemp - settings.heating.target + ) / settings.equitherm.slope; + + float sf = (settings.heating.maxTemp - settings.heating.target) / pow( + settings.heating.target - maxPoint, + 1.0f / settings.equitherm.exponent + ); + etResult = settings.heating.target + settings.equitherm.shift + sf * ( + tempDelta >= 0 + ? pow(tempDelta, 1.0f / settings.equitherm.exponent) + : -(pow(-(tempDelta), 1.0f / settings.equitherm.exponent)) + ); + } + + if (indoorSensorsConnected && !settings.pid.enabled && !settings.heating.turbo) { + etResult += constrain( + settings.heating.target - vars.master.heating.indoorTemp, + -3.0f, + 3.0f + ) * settings.equitherm.targetDiffFactor; + } + + if (!std::isfinite(etResult)) { + etResult = settings.heating.target + settings.equitherm.shift; + } + + etResult = constrain(etResult, settings.heating.minTemp, settings.heating.maxTemp); + + if (isFloatDifferent(equithermResult, etResult, 0.05f)) { + equithermResult = etResult; + ESP_LOGI(L_REGULATOR_EQUITHERM, "New result: %.2f", etResult); + } +}); + +static Task pidTask("PID", Task::Type::FOREVER, [](void*) { + // Reset before disabling + if (!settings.pid.enabled) { + if (pidRegulator.isEnabled()) { + pidRegulator.pause(); + pidRegulator.reset(); + ESP_LOGI(L_REGULATOR_PID, "Disabled and reset"); + } + + return; + } + + // Configure regulation modes + pidRegulator.setProportionalMode(PID::ProportionalMode::ON_ERROR); + pidRegulator.setIntegralCorrectionMode(PID::IntegralCorrectionMode::CLAMP); + pidRegulator.setDerivativeMode(PID::DerivativeMode::ON_ERROR); + pidRegulator.setReverse(false); + pidRegulator.setTimeSampling(false); + + // Update output limits + // Updating limits also recalculates the I-term, even when the limits are unchanged. + if (pidRegulator.getOutputMin() != settings.pid.minTemp || pidRegulator.getOutputMax() != settings.pid.maxTemp) { + pidRegulator.setOutputLimits(settings.pid.minTemp, settings.pid.maxTemp); + } + + // Pause so resume(value) resets the PID instead of keeping the previous integral. + if (equithermEnabled != settings.equitherm.enabled || std::isnan(pidRegulator.getITerm())) { + pidRegulator.pause(); + ESP_LOGI(L_REGULATOR_PID, "Reinitialization"); + } + + // Resume with the initial output + if (!pidRegulator.isEnabled()) { + // Initial output + pidRegulator.resume(settings.equitherm.enabled + ? 0.0f + : settings.heating.target + ); + + pidResult = pidRegulator.getOutput(); + equithermEnabled = settings.equitherm.enabled; + ESP_LOGI(L_REGULATOR_PID, "Resumed, initial output: %.2f, equitherm: %s", pidResult, equithermEnabled ? S_TRUE : S_FALSE); + } + + // Skip PID when heating is disabled + if (!settings.heating.enabled) { + return; + } + + // Keep the emergency target outside PID control + if (vars.emergency.state) { + return; + } + + // Let native OTC control the heating setpoint + if (settings.opentherm.options.nativeOTC) { + return; + } + + // Require an available indoor temperature sensor + if (!indoorSensorsConnected) { + return; + } + + // Prepare PID gains + // Use the scheduled period for I/D, excluding time when the task is disabled. + const float dt = pidTask.interval() / 1000.0f; + float kp = settings.heating.turbo ? 0.0f : settings.pid.p_factor; + float ki = settings.pid.i_factor * dt; + float kd = settings.pid.d_factor / dt; + + // Set room temperature target + pidRegulator.setSetpoint(settings.heating.target); + + // Check deadband + float error = settings.heating.target - vars.master.heating.indoorTemp; + bool hasDeadband = settings.pid.deadband.enabled && + (error > -(settings.pid.deadband.thresholdHigh)) && + (error < settings.pid.deadband.thresholdLow); + + // Apply deadband gains + if (hasDeadband) { + kp *= settings.pid.deadband.p_multiplier; + ki *= settings.pid.deadband.i_multiplier; + kd *= settings.pid.deadband.d_multiplier; + } + + // Apply PID gains + pidRegulator.setTunings(kp, ki, kd); + + // Calculate result + pidResult = pidRegulator.compute(vars.master.heating.indoorTemp); + + // Log PID state + ESP_LOGD( + L_REGULATOR_PID, + "Input: %.2f, setpoint: %.2f, error: %.2f, output: %.2f, P: %.2f, I: %.2f, D: %.2f", + pidRegulator.getInput(), pidRegulator.getSetpoint(), pidRegulator.getError(), pidRegulator.getOutput(), + pidRegulator.getPTerm(), pidRegulator.getITerm(), pidRegulator.getDTerm() + ); + ESP_LOGD( + L_REGULATOR_PID, + "dt: %.0f s, Kp: %.3f, Ki*dt: %.6g, Kd/dt: %.6g, limits: [%.2f, %.2f], deadband: %s, turbo: %s", + dt, pidRegulator.getKp(), pidRegulator.getKi(), pidRegulator.getKd(), + pidRegulator.getOutputMin(), pidRegulator.getOutputMax(), + hasDeadband ? S_TRUE : S_FALSE, settings.heating.turbo ? S_TRUE : S_FALSE + ); +}); + +static void turbo() { + if (settings.heating.turbo) { + if (!settings.heating.enabled || vars.emergency.state || !indoorSensorsConnected) { + settings.heating.turbo = false; + + } else if (!settings.pid.enabled && !settings.equitherm.enabled) { + settings.heating.turbo = false; + + } else if (fabsf(settings.heating.target - vars.master.heating.indoorTemp) <= 1.0f) { + settings.heating.turbo = false; + } + + if (!settings.heating.turbo) { + ESP_LOGI(L_REGULATOR, "Turbo mode auto disabled"); + } + } +} + +static void hysteresis() { + // Hysteresis also clears blocking when it is no longer applicable. + const bool useHysteresis = + settings.heating.hysteresis.enabled && indoorSensorsConnected && + (settings.equitherm.enabled || settings.pid.enabled || settings.opentherm.options.nativeOTC); + + if (useHysteresis) { + if (!vars.master.heating.blocking && vars.master.heating.indoorTemp - settings.heating.target + 0.0001f >= settings.heating.hysteresis.value) { + vars.master.heating.blocking = true; + + } else if (vars.master.heating.blocking && vars.master.heating.indoorTemp - settings.heating.target - 0.0001f <= -(settings.heating.hysteresis.value)) { + vars.master.heating.blocking = false; + } + + } else if (vars.master.heating.blocking) { + vars.master.heating.blocking = false; + } +} + +static inline float getHeatingMinSetpointTemp() { + return settings.opentherm.options.nativeOTC + ? vars.master.heating.minTemp + : settings.heating.minTemp; +} + +static inline float getHeatingMaxSetpointTemp() { + return settings.opentherm.options.nativeOTC + ? vars.master.heating.maxTemp + : settings.heating.maxTemp; +} + +static float getHeatingSetpointTemp() { + if (isFloatDifferent(heatingTarget, settings.heating.target, 0.0001f)) { + heatingTarget = settings.heating.target; + ESP_LOGI(L_REGULATOR, "New target: %.2f", settings.heating.target); + } + + if (vars.emergency.state) { + return settings.emergency.target; + + } else if (settings.opentherm.options.nativeOTC) { + return settings.heating.target; + } + + float setpoint = settings.heating.target; + if (settings.equitherm.enabled || settings.pid.enabled) { + setpoint = 0.0f; + + if (settings.equitherm.enabled) { + equithermTask.forceRun(); + setpoint += equithermResult; + } + + // Keep the last PID result when heating or the indoor sensor is unavailable. + if (settings.pid.enabled) { + setpoint += pidResult; + } + + if (settings.heating.turbo) { + setpoint += constrain( + settings.heating.target - vars.master.heating.indoorTemp, + -3.0f, + 3.0f + ) * settings.heating.turboFactor; + } + } + + if (vars.master.heating.freezing) { + setpoint = fmaxf( + setpoint, + static_cast(settings.heating.freezeProtection.lowTemp) + ); + } + + return setpoint; +} + +static Task regulatorTask("Regulator", [](void*) { + indoorSensorsConnected = Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::INDOOR_TEMP); + + if (pidTask.enabled()) { + const uint32_t pidInterval = settings.pid.dt * 1000u; + + if (pidTask.interval() != pidInterval) { + pidTask.setInterval(pidInterval); + } + } + + if (settings.equitherm.enabled || settings.pid.enabled || settings.opentherm.options.nativeOTC) { + vars.master.heating.smartControl = true; + vars.master.heating.minTemp = THERMOSTAT_INDOOR_MIN_TEMP; + vars.master.heating.maxTemp = THERMOSTAT_INDOOR_MAX_TEMP; + + } else { + vars.master.heating.smartControl = false; + vars.master.heating.minTemp = settings.heating.minTemp; + vars.master.heating.maxTemp = settings.heating.maxTemp; + } + + turbo(); + hysteresis(); + + const float setpointTemp = getHeatingSetpointTemp(); + vars.master.heating.targetTemp = settings.opentherm.options.nativeOTC + ? setpointTemp + : settings.heating.target; + vars.master.heating.setpointTemp = roundf(constrain( + setpointTemp, + getHeatingMinSetpointTemp(), + getHeatingMaxSetpointTemp() + ), 0); + + Sensors::setValueByType( + Sensors::Type::HEATING_SETPOINT_TEMP, vars.master.heating.setpointTemp, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +void initRegulator() { + // Pause so the first resume(value) initializes the integral for the selected mode. + pidRegulator.pause(); + + // Keep the PID task eligible until it has processed its own shutdown. + pidTask.setInterval(10000) + .setEnabledWhen([] { + return settings.pid.enabled || pidRegulator.isEnabled(); + }) + .resume(pidTask.interval()); + + // Apply mode changes and turbo auto-disable before a PID calculation due on the same pass. + appTaskManager.addTask(regulatorTask.setInterval(10000)); + appTaskManager.addTask(pidTask); + appTaskManager.addTask(equithermTask.pause()); +} diff --git a/src/sensors.cpp b/src/sensors.cpp new file mode 100644 index 0000000..cd1745a --- /dev/null +++ b/src/sensors.cpp @@ -0,0 +1,700 @@ +#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#if USE_BLE + #include + #include + #include "bluetooth.hpp" +#endif + +#if USE_BLE && defined(CONFIG_BT_NIMBLE_PINNED_TO_CORE) +static constexpr BaseType_t SENSORS_TASK_CORE = CONFIG_BT_NIMBLE_PINNED_TO_CORE; +#else +static constexpr BaseType_t SENSORS_TASK_CORE = tskNO_AFFINITY; +#endif + +TaskManager sensorsTaskManager("Sensors"); + +static const unsigned int wiredDisconnectTimeout = 180000u; +static const unsigned int wirelessDisconnectTimeout = 600000u; +static const unsigned short dallasSearchInterval = 60000u; +static const unsigned short dallasPollingInterval = 10000u; +static const unsigned short dhtPollingInterval = 15000; + +// OneWire +static std::unordered_map owInstances; +static std::unordered_map dallasInstances; +static std::unordered_map dallasSearchTime; +static std::unordered_map dallasLastPollingTime; +static std::unordered_map dallasPolling; + +#if USE_BLE +static BluetoothScanCallbacks bluetoothScanCallbacks; +static NimBLEScan* pBLEScan = nullptr; +static bool activeScanBle = false; +#endif + +static bool isEmptyAddress(const uint8_t *addr, const uint8_t length = 8) { + bool result = true; + + for (uint8_t i = 0; i < length; i++) { + if (addr[i] != 0) { + result = false; + break; + } + } + + return result; +} + +static void updateMasterValues() { + const float previousIndoorTemp = vars.master.heating.indoorTemp; + vars.master.heating.indoorTemp = Sensors::getMeanValueByPurpose( + Sensors::Purpose::INDOOR_TEMP, + Sensors::ValueType::PRIMARY, + settings.heating.indoorTempAvgType, + true, + 0.0f + ); + + if (previousIndoorTemp != vars.master.heating.indoorTemp) { + writeRoomTemperatureTask.requestEarlyRun(); + writeRoomTemperatureCh2Task.requestEarlyRun(); + } + + vars.master.heating.outdoorTemp = Sensors::getMeanValueByPurpose( + Sensors::Purpose::OUTDOOR_TEMP, + Sensors::ValueType::PRIMARY, + settings.heating.outdoorTempAvgType, + true, + 0.0f + ); + + vars.master.heating.currentTemp = Sensors::getMeanValueByPurpose( + Sensors::Purpose::HEATING_TEMP, + Sensors::ValueType::PRIMARY, + Sensors::AverageType::MEAN, + true, + 0.0f + ); + vars.master.heating.returnTemp = Sensors::getMeanValueByPurpose( + Sensors::Purpose::HEATING_RETURN_TEMP, + Sensors::ValueType::PRIMARY, + Sensors::AverageType::MEAN, + true, + 0.0f + ); + + vars.master.dhw.currentTemp = Sensors::getMeanValueByPurpose( + Sensors::Purpose::DHW_TEMP, + Sensors::ValueType::PRIMARY, + Sensors::AverageType::MEAN, + true, + 0.0f + ); + vars.master.dhw.returnTemp = Sensors::getMeanValueByPurpose( + Sensors::Purpose::DHW_RETURN_TEMP, + Sensors::ValueType::PRIMARY, + Sensors::AverageType::MEAN, + true, + 0.0f + ); +} + +static void makeDallasInstances() { + for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { + const auto sSensor = Sensors::getSettings(sensorId); + if (!sSensor) { + continue; + } + + if (!sSensor->enabled || sSensor->type != Sensors::Type::DALLAS_TEMP || sSensor->purpose == Sensors::Purpose::NOT_CONFIGURED || !GPIO_IS_VALID_OUTPUT(sSensor->gpio)) { + continue; + + } else if (dallasInstances.count(sSensor->gpio)) { + // no need to make instances + continue; + } + + auto& owInstance = owInstances[sSensor->gpio]; + owInstance.begin(sSensor->gpio); + owInstance.reset(); + + dallasSearchTime[sSensor->gpio] = 0; + dallasPolling[sSensor->gpio] = false; + dallasLastPollingTime[sSensor->gpio] = 0; + + auto& instance = dallasInstances[sSensor->gpio]; + instance.setOneWire(&owInstance); + instance.setWaitForConversion(false); + + ESP_LOGI(L_SENSORS_DALLAS, "Started on GPIO %hhu", sSensor->gpio); + } +} + +static void cleanDallasInstances() { + // for (auto& [gpio, instance] : dallasInstances) { + auto it = dallasInstances.begin(); + while (it != dallasInstances.end()) { + auto gpio = it->first; + bool instanceUsed = false; + + for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { + const auto sSensor = Sensors::getSettings(sensorId); + if (!sSensor) { + continue; + } + + if (!sSensor->enabled || sSensor->type != Sensors::Type::DALLAS_TEMP || sSensor->purpose == Sensors::Purpose::NOT_CONFIGURED) { + continue; + } + + if (sSensor->gpio == gpio) { + instanceUsed = true; + break; + } + } + + if (!instanceUsed) { + it = dallasInstances.erase(it); + owInstances.erase(gpio); + dallasSearchTime.erase(gpio); + dallasPolling.erase(gpio); + dallasLastPollingTime.erase(gpio); + + ESP_LOGI(L_SENSORS_DALLAS, "Stopped on GPIO %hhu", gpio); + continue; + } + + it++; + } +} + +static void searchDallasSensors() { + // search sensors on bus + for (auto& [gpio, instance] : dallasInstances) { + // do not search if polling! + if (dallasPolling[gpio]) { + continue; + } + + if (millis() - dallasSearchTime[gpio] < dallasSearchInterval) { + continue; + } + + dallasSearchTime[gpio] = millis(); + owInstances[gpio].reset(); + instance.begin(); + + ESP_LOGD( + L_SENSORS_DALLAS, + "GPIO %hhu, devices on bus: %hhu, DS18* devices: %hhu", + gpio, instance.getDeviceCount(), instance.getDS18Count() + ); + } +} + +static void fillingAddressesDallasSensors() { + // check & filling sensors address + for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { + const auto sSensor = Sensors::getSettings(sensorId); + if (!sSensor) { + continue; + } + + if (!sSensor->enabled || sSensor->type != Sensors::Type::DALLAS_TEMP || sSensor->purpose == Sensors::Purpose::NOT_CONFIGURED) { + continue; + + } else if (!dallasInstances.count(sSensor->gpio)) { + continue; + } + + // do nothing if address not empty + if (!isEmptyAddress(sSensor->address)) { + continue; + } + + // do nothing if polling + if (dallasPolling[sSensor->gpio]) { + continue; + } + + auto& instance = dallasInstances[sSensor->gpio]; + DeviceAddress devAddr; + for (uint8_t devId = 0; devId < instance.getDeviceCount(); devId++) { + if (!instance.getAddress(devAddr, devId)) { + continue; + } + + bool freeAddress = true; + + // checking address usage + for (uint8_t checkingSensorId = 0; checkingSensorId <= Sensors::getMaxSensorId(); checkingSensorId++) { + const auto sCheckingSensor = Sensors::getSettings(checkingSensorId); + if (!sCheckingSensor) { + continue; + } + if (sCheckingSensor->type != Sensors::Type::DALLAS_TEMP || checkingSensorId == sensorId) { + continue; + } + + if (sCheckingSensor->gpio != sSensor->gpio || isEmptyAddress(sCheckingSensor->address)) { + continue; + } + + if (Sensors::isEqualAddress(sCheckingSensor->address, devAddr)) { + freeAddress = false; + break; + } + } + + // address already in use + if (!freeAddress) { + continue; + } + + const bool addressSet = Sensors::setAddressById(sensorId, devAddr, [sensorId] { + requestReconfigureMqttSensor(sensorId); + requestSaveSensorsSettings(); + }); + if (!addressSet) { + break; + } + ESP_LOGD( + L_SENSORS_DALLAS, "GPIO %hhu, sensor #%hhu '%s', set address: %hhX:%hhX:%hhX:%hhX:%hhX:%hhX:%hhX:%hhX", + sSensor->gpio, sensorId, sSensor->name, + devAddr[0], devAddr[1], devAddr[2], devAddr[3], + devAddr[4], devAddr[5], devAddr[6], devAddr[7] + ); + + break; + } + } +} + +static bool isPollingDallasSensors() { + for (auto& [gpio, instance] : dallasInstances) { + if (dallasPolling.count(gpio) && dallasPolling[gpio]) { + return true; + } + } + + return false; +} + +static void pollingDallasSensors(bool newPolling = true) { + for (auto& [gpio, instance] : dallasInstances) { + unsigned long ts = millis(); + + if (dallasPolling[gpio]) { + unsigned long minPollingTime = instance.millisToWaitForConversion(12) * 2; + unsigned long estimatePollingTime = ts - dallasLastPollingTime[gpio]; + + // check conversion time + // isConversionComplete does not work with chinese clones! + if (estimatePollingTime < minPollingTime) { + continue; + } + + // read sensors data for current instance + for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { + const auto sSensor = Sensors::getSettings(sensorId); + if (!sSensor) { + continue; + } + + // only target & valid sensors + if (!sSensor->enabled || sSensor->type != Sensors::Type::DALLAS_TEMP || sSensor->purpose == Sensors::Purpose::NOT_CONFIGURED) { + continue; + + } else if (sSensor->gpio != gpio || isEmptyAddress(sSensor->address)) { + continue; + } + + float value = instance.getTempC(sSensor->address); + if (value == DEVICE_DISCONNECTED_C) { + ESP_LOGW( + L_SENSORS_DALLAS, "GPIO %hhu, sensor #%hhu '%s': failed receiving data", + sSensor->gpio, sensorId, sSensor->name + ); + + Sensors::adjustSignalQuality(sensorId, -1); + + continue; + } + + ESP_LOGD( + L_SENSORS_DALLAS, "GPIO %hhu, sensor #%hhu '%s', received data: %.2f", + sSensor->gpio, sensorId, sSensor->name, value + ); + + Sensors::adjustSignalQuality(sensorId, 1); + + // set sensor value + Sensors::setValueById( + sensorId, value, + Sensors::ValueType::TEMPERATURE, true, true + ); + } + + // reset polling flag + dallasPolling[gpio] = false; + + } else if (newPolling) { + auto estimateLastPollingTime = ts - dallasLastPollingTime[gpio]; + + // check last polling time + if (estimateLastPollingTime < dallasPollingInterval) { + continue; + } + + // start polling + instance.setResolution(12); + instance.requestTemperatures(); + dallasPolling[gpio] = true; + dallasLastPollingTime[gpio] = ts; + + ESP_LOGD(L_SENSORS_DALLAS, "GPIO %hhu, polling...", gpio); + } + } +} + +#if USE_BLE +static void scanBleSensors() { + if (!Sensors::getAmountByType(Sensors::Type::BLUETOOTH, true)) { + if (NimBLEDevice::isInitialized()) { + if (pBLEScan != nullptr) { + if (pBLEScan->isScanning()) { + pBLEScan->stop(); + + } else { + pBLEScan = nullptr; + } + } + + if (pBLEScan == nullptr) { + if (NimBLEDevice::deinit(true)) { + ESP_LOGI(L_SENSORS_BLE, "Deinitialized"); + + } else { + ESP_LOGW(L_SENSORS_BLE, "Unable to deinitialize!"); + } + } + } + + return; + } + + if (!NimBLEDevice::isInitialized() && millis() > 5000) { + if (NimBLEDevice::init(PROJECT_NAME)) { + ESP_LOGI(L_SENSORS_BLE, "Initialized"); + + #ifdef ESP_PWR_LVL_P20 + NimBLEDevice::setPower(ESP_PWR_LVL_P20); + #elifdef ESP_PWR_LVL_P9 + NimBLEDevice::setPower(ESP_PWR_LVL_P9); + #endif + + } else { + ESP_LOGW(L_SENSORS_BLE, "Unable to initialize!"); + return; + } + } + + if (pBLEScan == nullptr) { + pBLEScan = NimBLEDevice::getScan(); + pBLEScan->setCallbacks(bluetoothScanCallbacks); + #if MYNEWT_VAL(BLE_EXT_ADV) + pBLEScan->setPhy(NimBLEScan::Phy::SCAN_ALL); + #endif + pBLEScan->setDuplicateFilter(false); + pBLEScan->setMaxResults(0); + pBLEScan->setInterval(10000); + pBLEScan->setWindow(10000); + + ESP_LOGI(L_SENSORS_BLE, "Scanning initialized"); + } + + // BLE and WiFi share the radio. Pause scanning while AP clients are connected + // to keep the portal responsive and avoid disconnects. + if (isNetworkInterfaceStarted(NetworkMode::AP) && WiFi.AP.stationCount() > 0) { + if (pBLEScan->isScanning()) { + if (!pBLEScan->stop()) { + ESP_LOGW(L_SENSORS_BLE, "Unable to stop scanning for WiFi AP"); + return; + } + + ESP_LOGI(L_SENSORS_BLE, "Scanning paused for AP clients"); + } + + return; + } + + if (!pBLEScan->isScanning()) { + activeScanBle = !activeScanBle; + pBLEScan->setActiveScan(activeScanBle); + + if (pBLEScan->start(30000, false, false)) { + ESP_LOGI( + L_SENSORS_BLE, + "%s scanning started", + activeScanBle ? "Active" : "Passive" + ); + + } else { + ESP_LOGI(L_SENSORS_BLE, "Unable to start scanning"); + } + } +} +#endif + +static void updateConnectionStatus() { + for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { + Sensors::updateConnectionStatusById(sensorId, wiredDisconnectTimeout, wirelessDisconnectTimeout); + } +} + +static bool canRunSensors() { + return !upgrading && !restartTask.scheduled() && !restartTask.active(); +} + +static Task readDallasSensorsTask("Read Dallas sensors", [](void*) { + pollingDallasSensors(false); +}); + +static Task pollDhtSensorsTask("Poll DHT sensors", [](void*) { + static DHT instance; + static uint8_t lastPollingSensorId{0}; + static std::unordered_map lastPollingTime(2); + + if (instance.isPolling()) { + return; + } + + for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { + const auto sSensor = Sensors::getSettings(sensorId); + if (!sSensor) { + continue; + } + + if (!sSensor->enabled || sSensor->purpose == Sensors::Purpose::NOT_CONFIGURED) { + continue; + } + + if (sSensor->type != Sensors::Type::DHT11 && sSensor->type != Sensors::Type::DHT22) { + continue; + } + + if (lastPollingTime.count(sSensor->gpio) && millis() - lastPollingTime[sSensor->gpio] < dhtPollingInterval) { + continue; + } + + const auto sensorGpio = static_cast(sSensor->gpio); + DHT::Type sensorType = DHT::Type::DHT22; + if (sSensor->type == Sensors::Type::DHT11) { + sensorType = DHT::Type::DHT11; + + } else if (sSensor->type == Sensors::Type::DHT22) { + sensorType = DHT::Type::DHT22; + } + + if (lastPollingSensorId != sensorId || instance.getGpio() != sensorGpio || instance.getType() != sensorType) { + instance.reset(); + instance.onData([sensorId, gpio = sSensor->gpio](float humidity, float temperature) { + const auto sSensor = Sensors::getSettings(sensorId); + if (!sSensor) { + lastPollingTime[gpio] = millis(); + return; + } + + ESP_LOGD( + L_SENSORS_DHT, "GPIO %hhu, sensor #%hhu '%s', temp: %.2f, humidity: %.2f%%", + sSensor->gpio, sensorId, sSensor->name, temperature, humidity + ); + + // set temperature + Sensors::setValueById( + sensorId, temperature, + Sensors::ValueType::TEMPERATURE, true, true + ); + + // set humidity + Sensors::setValueById(sensorId, humidity, Sensors::ValueType::HUMIDITY, true, true); + + Sensors::adjustSignalQuality(sensorId, 1); + lastPollingTime[gpio] = millis(); + }); + + instance.onError([sensorId, gpio = sSensor->gpio](DHT::Status status) { + const auto sSensor = Sensors::getSettings(sensorId); + if (!sSensor) { + lastPollingTime[gpio] = millis(); + return; + } + + ESP_LOGW( + L_SENSORS_DHT, "GPIO %hhu, sensor #%hhu '%s': failed receiving data (err: %s)", + sSensor->gpio, sensorId, sSensor->name, DHT::statusToString(status) + ); + + Sensors::adjustSignalQuality(sensorId, -1); + lastPollingTime[gpio] = millis(); + }); + + if (instance.setup(sensorGpio, sensorType)) { + ESP_LOGI(L_SENSORS_DHT, "Started on GPIO %hhu", sSensor->gpio); + + } else { + ESP_LOGW( + L_SENSORS_DHT, "Failed to start on GPIO %hhu (err: %s)", + sSensor->gpio, DHT::statusToString(instance.getStatus()) + ); + } + } + + lastPollingSensorId = sensorId; + if (!instance.poll()) { + lastPollingTime[sSensor->gpio] = millis(); + } + + break; + } +}); + +static Task maintainDallasSensorsTask("Maintain Dallas sensors", [](void*) { + cleanDallasInstances(); + makeDallasInstances(); + searchDallasSensors(); + fillingAddressesDallasSensors(); + pollingDallasSensors(); +}); + +static Task readNtcSensorsTask("Read NTC sensors", [](void*) { + for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { + const auto sSensor = Sensors::getSettings(sensorId); + if (!sSensor) { + continue; + } + + if (!sSensor->enabled || sSensor->type != Sensors::Type::NTC_10K_TEMP || sSensor->purpose == Sensors::Purpose::NOT_CONFIGURED) { + continue; + } + + const auto value = analogReadMilliVolts(sSensor->gpio); + if (value < DEFAULT_NTC_VLOW_THRESHOLD || value > DEFAULT_NTC_VHIGH_THRESHOLD) { + Sensors::setConnectionStatusById(sensorId, false, false); + + ESP_LOGW( + L_SENSORS_NTC, "GPIO %hhu, sensor #%hhu '%s', voltage is out of threshold: %.3f", + sSensor->gpio, sensorId, sSensor->name, (value / 1000.0f) + ); + + continue; + } + + const float sensorResistance = value > 1 + ? DEFAULT_NTC_REF_RESISTANCE / (DEFAULT_NTC_VREF / static_cast(value) - 1.0f) + : 0.0f; + const float rawTemp = 1.0f / ( + 1.0f / (DEFAULT_NTC_NOMINAL_TEMP + 273.15f) + + log(sensorResistance / DEFAULT_NTC_NOMINAL_RESISTANCE) / DEFAULT_NTC_BETA_FACTOR + ) - 273.15f; + + ESP_LOGD( + L_SENSORS_NTC, "GPIO %hhu, sensor #%hhu '%s', raw temp: %.2f, raw voltage: %.3f, raw resistance: %.2f", + sSensor->gpio, sensorId, sSensor->name, rawTemp, (value / 1000.0f), sensorResistance + ); + + // set temp + Sensors::setValueById( + sensorId, rawTemp, + Sensors::ValueType::TEMPERATURE, true, true + ); + } +}); + +#if USE_BLE +static Task scanBleSensorsTask("Scan BLE sensors", [](void*) { + scanBleSensors(); +}); +#endif + +static Task updateSensorsTask("Update sensor states", [](void*) { + updateConnectionStatus(); + updateMasterValues(); +}); + +void initSensors() { + dallasLastPollingTime.reserve(2); + owInstances.reserve(2); + dallasInstances.reserve(2); + dallasSearchTime.reserve(2); + dallasPolling.reserve(2); + + readDallasSensorsTask.setInterval(1000) + .setEnabledWhen([] { + return canRunSensors() && isPollingDallasSensors(); + }); + sensorsTaskManager.addTask(readDallasSensorsTask); + + pollDhtSensorsTask.setInterval(1000) + .setEnabledWhen([] { + return canRunSensors() && ( + Sensors::getAmountByType(Sensors::Type::DHT11, true) || + Sensors::getAmountByType(Sensors::Type::DHT22, true) + ); + }); + sensorsTaskManager.addTask(pollDhtSensorsTask); + + maintainDallasSensorsTask.setEnabledWhen([] { + return canRunSensors() && ( + !dallasInstances.empty() || + Sensors::getAmountByType(Sensors::Type::DALLAS_TEMP, true) + ); + }) + .resume(15000); + sensorsTaskManager.addTask(maintainDallasSensorsTask); + + readNtcSensorsTask.setEnabledWhen([] { + return canRunSensors() && Sensors::getAmountByType(Sensors::Type::NTC_10K_TEMP, true); + }) + .resume(15000); + sensorsTaskManager.addTask(readNtcSensorsTask); + + #if USE_BLE + scanBleSensorsTask.setEnabledWhen([] { + return canRunSensors() && ( + NimBLEDevice::isInitialized() || + Sensors::getAmountByType(Sensors::Type::BLUETOOTH, true) + ); + }) + .onDone([](const Task&, uint32_t) { + if (scanBleSensorsTask.interval() != 1000) { + scanBleSensorsTask.setInterval(1000); + } + }) + .resume(15000); + sensorsTaskManager.addTask(scanBleSensorsTask); + #endif + + updateSensorsTask.setInterval(1000).setEnabledWhen(canRunSensors); + sensorsTaskManager.addTask(updateSensorsTask); + + + // Start + if (!sensorsTaskManager.asyncStart(4096, 4, SENSORS_TASK_CORE, 1000, false)) { + esp_system_abort("Failed to start Sensors task manager"); + } + + ESP_LOGI(L_MAIN, "Started %s task manager", sensorsTaskManager.name()); +} diff --git a/src/strings.h b/src/strings.h deleted file mode 100644 index b858e49..0000000 --- a/src/strings.h +++ /dev/null @@ -1,235 +0,0 @@ -#pragma once -#ifndef PROGMEM - #define PROGMEM -#endif - -const char L_SETTINGS[] PROGMEM = "SETTINGS"; -const char L_SETTINGS_OT[] PROGMEM = "SETTINGS.OT"; -const char L_SETTINGS_DHW[] PROGMEM = "SETTINGS.DHW"; -const char L_SETTINGS_HEATING[] PROGMEM = "SETTINGS.HEATING"; -const char L_NETWORK[] PROGMEM = "NETWORK"; -const char L_NETWORK_SETTINGS[] PROGMEM = "NETWORK.SETTINGS"; -const char L_PORTAL_WEBSERVER[] PROGMEM = "PORTAL.WEBSERVER"; -const char L_PORTAL_DNSSERVER[] PROGMEM = "PORTAL.DNSSERVER"; -const char L_PORTAL_CAPTIVE[] PROGMEM = "PORTAL.CAPTIVE"; -const char L_PORTAL_OTA[] PROGMEM = "PORTAL.OTA"; -const char L_MAIN[] PROGMEM = "MAIN"; -const char L_MQTT[] PROGMEM = "MQTT"; -const char L_MQTT_HA[] PROGMEM = "MQTT.HA"; -const char L_MQTT_MSG[] PROGMEM = "MQTT.MSG"; -const char L_OT[] PROGMEM = "OT"; -const char L_OT_DHW[] PROGMEM = "OT.DHW"; -const char L_OT_HEATING[] PROGMEM = "OT.HEATING"; -const char L_OT_CH2[] PROGMEM = "OT.CH2"; -const char L_SENSORS[] PROGMEM = "SENSORS"; -const char L_SENSORS_SETTINGS[] PROGMEM = "SENSORS.SETTINGS"; -const char L_SENSORS_DALLAS[] PROGMEM = "SENSORS.DALLAS"; -const char L_SENSORS_NTC[] PROGMEM = "SENSORS.NTC"; -const char L_SENSORS_BLE[] PROGMEM = "SENSORS.BLE"; -const char L_REGULATOR[] PROGMEM = "REGULATOR"; -const char L_REGULATOR_PID[] PROGMEM = "REGULATOR.PID"; -const char L_REGULATOR_EQUITHERM[] PROGMEM = "REGULATOR.EQUITHERM"; -const char L_CASCADE_INPUT[] PROGMEM = "CASCADE.INPUT"; -const char L_CASCADE_OUTPUT[] PROGMEM = "CASCADE.OUTPUT"; -const char L_EXTPUMP[] PROGMEM = "EXTPUMP"; - - -const char S_ACTION[] PROGMEM = "action"; -const char S_ACTIONS[] PROGMEM = "actions"; -const char S_ACTIVE[] PROGMEM = "active"; -const char S_ADDRESS[] PROGMEM = "address"; -const char S_ANTI_STUCK_INTERVAL[] PROGMEM = "antiStuckInterval"; -const char S_ANTI_STUCK_TIME[] PROGMEM = "antiStuckTime"; -const char S_AP[] PROGMEM = "ap"; -const char S_APP_VERSION[] PROGMEM = "appVersion"; -const char S_AUTH[] PROGMEM = "auth"; -const char S_AUTO_DIAG_RESET[] PROGMEM = "autoDiagReset"; -const char S_AUTO_FAULT_RESET[] PROGMEM = "autoFaultReset"; -const char S_BACKTRACE[] PROGMEM = "backtrace"; -const char S_BATTERY[] PROGMEM = "battery"; -const char S_BAUDRATE[] PROGMEM = "baudrate"; -const char S_BLE[] PROGMEM = "ble"; -const char S_BLOCKING[] PROGMEM = "blocking"; -const char S_BSSID[] PROGMEM = "bssid"; -const char S_BUILD[] PROGMEM = "build"; -const char S_CASCADE_CONTROL[] PROGMEM = "cascadeControl"; -const char S_CHANNEL[] PROGMEM = "channel"; -const char S_CH2_ALWAYS_ENABLED[] PROGMEM = "ch2AlwaysEnabled"; -const char S_CHIP[] PROGMEM = "chip"; -const char S_CLK[] PROGMEM = "clk"; -const char S_CODE[] PROGMEM = "code"; -const char S_CONNECTED[] PROGMEM = "connected"; -const char S_CONFIGURED[] PROGMEM = "configured"; -const char S_CONNECTION_TYPE[] PROGMEM = "connectionType"; -const char S_CONTINUES[] PROGMEM = "continues"; -const char S_COOLING[] PROGMEM = "cooling"; -const char S_COOLING_SUPPORT[] PROGMEM = "coolingSupport"; -const char S_CORE[] PROGMEM = "core"; -const char S_CORES[] PROGMEM = "cores"; -const char S_CRASH[] PROGMEM = "crash"; -const char S_CS[] PROGMEM = "cs"; -const char S_CURRENT_TEMP[] PROGMEM = "currentTemp"; -const char S_DATA[] PROGMEM = "data"; -const char S_DATE[] PROGMEM = "date"; -const char S_DEADBAND[] PROGMEM = "deadband"; -const char S_DHW[] PROGMEM = "dhw"; -const char S_DHW_BLOCKING[] PROGMEM = "dhwBlocking"; -const char S_DHW_STATE_AS_DHW_BLOCKING[] PROGMEM = "dhwStateAsDhwBlocking"; -const char S_DHW_SUPPORT[] PROGMEM = "dhwSupport"; -const char S_DHW_TO_CH2[] PROGMEM = "dhwToCh2"; -const char S_DIAG[] PROGMEM = "diag"; -const char S_DNS[] PROGMEM = "dns"; -const char S_DT[] PROGMEM = "dt"; -const char S_D_FACTOR[] PROGMEM = "d_factor"; -const char S_D_MULTIPLIER[] PROGMEM = "d_multiplier"; -const char S_EMERGENCY[] PROGMEM = "emergency"; -const char S_ENABLED[] PROGMEM = "enabled"; -const char S_ENV[] PROGMEM = "env"; -const char S_EPC[] PROGMEM = "epc"; -const char S_EQUITHERM[] PROGMEM = "equitherm"; -const char S_ETHERNET[] PROGMEM = "ethernet"; -const char S_EXPONENT[] PROGMEM = "exponent"; -const char S_EXTERNAL_PUMP[] PROGMEM = "externalPump"; -const char S_FACTOR[] PROGMEM = "factor"; -const char S_FAULT[] PROGMEM = "fault"; -const char S_FEATURES[] PROGMEM = "features"; -const char S_FREEZE_PROTECTION[] PROGMEM = "freezeProtection"; -const char S_FREEZING[] PROGMEM = "freezing"; -const char S_FILTERING[] PROGMEM = "filtering"; -const char S_FILTERING_FACTOR[] PROGMEM = "filteringFactor"; -const char S_FLAGS[] PROGMEM = "flags"; -const char S_FLAME[] PROGMEM = "flame"; -const char S_FLASH[] PROGMEM = "flash"; -const char S_FREE[] PROGMEM = "free"; -const char S_FREQ[] PROGMEM = "freq"; -const char S_GATEWAY[] PROGMEM = "gateway"; -const char S_GET_MIN_MAX_TEMP[] PROGMEM = "getMinMaxTemp"; -const char S_GPIO[] PROGMEM = "gpio"; -const char S_HEAP[] PROGMEM = "heap"; -const char S_HEATING[] PROGMEM = "heating"; -const char S_HEATING_TO_CH2[] PROGMEM = "heatingToCh2"; -const char S_HEATING_STATE_TO_SUMMER_WINTER_MODE[] PROGMEM = "heatingStateToSummerWinterMode"; -const char S_HIDDEN[] PROGMEM = "hidden"; -const char S_HIGH_TEMP[] PROGMEM = "highTemp"; -const char S_HOME_ASSISTANT_DISCOVERY[] PROGMEM = "homeAssistantDiscovery"; -const char S_HOSTNAME[] PROGMEM = "hostname"; -const char S_HUMIDITY[] PROGMEM = "humidity"; -const char S_HYSTERESIS[] PROGMEM = "hysteresis"; -const char S_ID[] PROGMEM = "id"; -const char S_IGNORE_DIAG_STATE[] PROGMEM = "ignoreDiagState"; -const char S_IMMERGAS_FIX[] PROGMEM = "immergasFix"; -const char S_ALWAYS_SEND_INDOOR_TEMP[] PROGMEM = "alwaysSendIndoorTemp"; -const char S_INDOOR_TEMP[] PROGMEM = "indoorTemp"; -const char S_INDOOR_TEMP_CONTROL[] PROGMEM = "indoorTempControl"; -const char S_IN_GPIO[] PROGMEM = "inGpio"; -const char S_INPUT[] PROGMEM = "input"; -const char S_INTERVAL[] PROGMEM = "interval"; -const char S_INVERT_STATE[] PROGMEM = "invertState"; -const char S_IP[] PROGMEM = "ip"; -const char S_IRQ[] PROGMEM = "irq"; -const char S_I_FACTOR[] PROGMEM = "i_factor"; -const char S_I_MULTIPLIER[] PROGMEM = "i_multiplier"; -const char S_LOGIN[] PROGMEM = "login"; -const char S_LOG_LEVEL[] PROGMEM = "logLevel"; -const char S_LOW_TEMP[] PROGMEM = "lowTemp"; -const char S_MAC[] PROGMEM = "mac"; -const char S_MASTER[] PROGMEM = "master"; -const char S_MAX[] PROGMEM = "max"; -const char S_MAX_FREE_BLOCK[] PROGMEM = "maxFreeBlock"; -const char S_MAX_MODULATION[] PROGMEM = "maxModulation"; -const char S_MAX_POWER[] PROGMEM = "maxPower"; -const char S_MAX_TEMP[] PROGMEM = "maxTemp"; -const char S_MAX_TEMP_SYNC_WITH_TARGET_TEMP[] PROGMEM = "maxTempSyncWithTargetTemp"; -const char S_MDNS[] PROGMEM = "mdns"; -const char S_MEMBER_ID[] PROGMEM = "memberId"; -const char S_MIN[] PROGMEM = "min"; -const char S_MIN_FREE[] PROGMEM = "minFree"; -const char S_MIN_MAX_FREE_BLOCK[] PROGMEM = "minMaxFreeBlock"; -const char S_MIN_POWER[] PROGMEM = "minPower"; -const char S_MIN_TEMP[] PROGMEM = "minTemp"; -const char S_MISO[] PROGMEM = "miso"; -const char S_MODEL[] PROGMEM = "model"; -const char S_MOSI[] PROGMEM = "mosi"; -const char S_MODULATION[] PROGMEM = "modulation"; -const char S_MQTT[] PROGMEM = "mqtt"; -const char S_NAME[] PROGMEM = "name"; -const char S_NATIVE_OTC[] PROGMEM = "nativeOTC"; -const char S_NETWORK[] PROGMEM = "network"; -const char S_NTP[] PROGMEM = "ntp"; -const char S_OFFSET[] PROGMEM = "offset"; -const char S_ON_ENABLED_HEATING[] PROGMEM = "onEnabledHeating"; -const char S_ON_FAULT[] PROGMEM = "onFault"; -const char S_ON_LOSS_CONNECTION[] PROGMEM = "onLossConnection"; -const char S_OPENTHERM[] PROGMEM = "opentherm"; -const char S_OPTIONS[] PROGMEM = "options"; -const char S_OUTDOOR_TEMP[] PROGMEM = "outdoorTemp"; -const char S_OUT_GPIO[] PROGMEM = "outGpio"; -const char S_OUTPUT[] PROGMEM = "output"; -const char S_OVERHEAT[] PROGMEM = "overheat"; -const char S_OVERHEAT_PROTECTION[] PROGMEM = "overheatProtection"; -const char S_PASSWORD[] PROGMEM = "password"; -const char S_PID[] PROGMEM = "pid"; -const char S_PORT[] PROGMEM = "port"; -const char S_PINS[] PROGMEM = "pins"; -const char S_PORTAL[] PROGMEM = "portal"; -const char S_POST_CIRCULATION_TIME[] PROGMEM = "postCirculationTime"; -const char S_POWER[] PROGMEM = "power"; -const char S_PREFIX[] PROGMEM = "prefix"; -const char S_PROTOCOL_VERSION[] PROGMEM = "protocolVersion"; -const char S_PURPOSE[] PROGMEM = "purpose"; -const char S_P_FACTOR[] PROGMEM = "p_factor"; -const char S_P_MULTIPLIER[] PROGMEM = "p_multiplier"; -const char S_REAL_SIZE[] PROGMEM = "realSize"; -const char S_REASON[] PROGMEM = "reason"; -const char S_RESET_DIAGNOSTIC[] PROGMEM = "resetDiagnostic"; -const char S_RESET_FAULT[] PROGMEM = "resetFault"; -const char S_RESET_REASON[] PROGMEM = "resetReason"; -const char S_RESTART[] PROGMEM = "restart"; -const char S_RETURN_TEMP[] PROGMEM = "returnTemp"; -const char S_REV[] PROGMEM = "rev"; -const char S_RSSI[] PROGMEM = "rssi"; -const char S_RST[] PROGMEM = "rst"; -const char S_RX_LED_GPIO[] PROGMEM = "rxLedGpio"; -const char S_SDK[] PROGMEM = "sdk"; -const char S_SENSORS[] PROGMEM = "sensors"; -const char S_SERIAL[] PROGMEM = "serial"; -const char S_SERVER[] PROGMEM = "server"; -const char S_SETTINGS[] PROGMEM = "settings"; -const char S_SET_DATE_AND_TIME[] PROGMEM = "setDateAndTime"; -const char S_SHIFT[] PROGMEM = "shift"; -const char S_SIGNAL_QUALITY[] PROGMEM = "signalQuality"; -const char S_SIZE[] PROGMEM = "size"; -const char S_SLAVE[] PROGMEM = "slave"; -const char S_SLOPE[] PROGMEM = "slope"; -const char S_SSID[] PROGMEM = "ssid"; -const char S_STARTED[] PROGMEM = "started"; -const char S_STA[] PROGMEM = "sta"; -const char S_STATE[] PROGMEM = "state"; -const char S_STATIC_CONFIG[] PROGMEM = "staticConfig"; -const char S_STATUS_LED_GPIO[] PROGMEM = "statusLedGpio"; -const char S_SETPOINT[] PROGMEM = "setpoint"; -const char S_SETPOINT_TEMP[] PROGMEM = "setpointTemp"; -const char S_SUBNET[] PROGMEM = "subnet"; -const char S_SUMMER_WINTER_MODE[] PROGMEM = "summerWinterMode"; -const char S_SYSTEM[] PROGMEM = "system"; -const char S_TARGET[] PROGMEM = "target"; -const char S_TARGET_DIFF_FACTOR[] PROGMEM = "targetDiffFactor"; -const char S_TARGET_TEMP[] PROGMEM = "targetTemp"; -const char S_TELNET[] PROGMEM = "telnet"; -const char S_TEMPERATURE[] PROGMEM = "temperature"; -const char S_THRESHOLD_HIGH[] PROGMEM = "thresholdHigh"; -const char S_THRESHOLD_LOW[] PROGMEM = "thresholdLow"; -const char S_THRESHOLD_TIME[] PROGMEM = "thresholdTime"; -const char S_TIMEZONE[] PROGMEM = "timezone"; -const char S_TOTAL[] PROGMEM = "total"; -const char S_TRESHOLD_TIME[] PROGMEM = "tresholdTime"; -const char S_TURBO[] PROGMEM = "turbo"; -const char S_TURBO_FACTOR[] PROGMEM = "turboFactor"; -const char S_TYPE[] PROGMEM = "type"; -const char S_UNIT_SYSTEM[] PROGMEM = "unitSystem"; -const char S_UPTIME[] PROGMEM = "uptime"; -const char S_USE[] PROGMEM = "use"; -const char S_USE_DHCP[] PROGMEM = "useDhcp"; -const char S_USER[] PROGMEM = "user"; -const char S_VALUE[] PROGMEM = "value"; -const char S_VERSION[] PROGMEM = "version"; diff --git a/src/system.cpp b/src/system.cpp new file mode 100644 index 0000000..d777d62 --- /dev/null +++ b/src/system.cpp @@ -0,0 +1,143 @@ +#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE + +#include +#include +#include + +TaskManager systemTaskManager("System"); + +std::string getResetReason() { + std::string value; + + switch (esp_reset_reason()) { + case ESP_RST_POWERON: + value = "Reset due to power-on event"; + break; + + case ESP_RST_EXT: + value = "Reset by external pin"; + break; + + case ESP_RST_SW: + value = "Software reset via esp_restart"; + break; + + case ESP_RST_PANIC: + value = "Software reset due to exception/panic"; + break; + + case ESP_RST_INT_WDT: + value = "Reset (software or hardware) due to interrupt watchdog"; + break; + + case ESP_RST_TASK_WDT: + value = "Reset due to task watchdog"; + break; + + case ESP_RST_WDT: + value = "Reset due to other watchdogs"; + break; + + case ESP_RST_DEEPSLEEP: + value = "Reset after exiting deep sleep mode"; + break; + + case ESP_RST_BROWNOUT: + value = "Brownout reset (software or hardware)"; + break; + + case ESP_RST_SDIO: + value = "Reset over SDIO"; + break; + + case ESP_RST_UNKNOWN: + default: + value = "unknown"; + break; + + } + + return value; +} + +static unsigned long lastHeapInfo = 0; +static unsigned int minFreeHeap = 0; +static unsigned int minLargestFreeBlock = 0; + +Task restartTask("Restart", Task::Type::ONCE, [](void*) { + ESP_LOGI(L_MAIN, "Restart preparation started"); + appTaskManager.pause(); + sensorsTaskManager.pause(); + openthermTaskManager.pause(); + + // Finish application callbacks and onDone before saving, including with critical heap. + appTaskManager.waitForPaused(); + sensorsTaskManager.waitForPaused(); + openthermTaskManager.waitForPaused(); + saveSettingsNow(); + + // Yield to FreeRTOS/IDF tasks before resetting the device. + ::delay(250); + ESP.restart(); +}); + +// Maintenance +static Task maintenanceTask("System maintenance", [](void*) { + getMemoryMetrics(); + drainLoggingSerial(); +}); + +// Heap monitoring remains active while the App manager is paused. +static Task heapTask("Heap monitoring", [](void*) { + const auto memory = getMemoryMetrics(); + unsigned int freeHeap = memory.heap.total_free_bytes; + unsigned int maxFreeBlockHeap = memory.heap.largest_free_block; + + /*if (freeHeap < 2048 || maxFreeBlockHeap < 2048) { + if (!upgrading) { + esp_system_abort("OTGateway: low internal heap"); + } + }*/ + + if (esp_log_level_get(L_MAIN) < ESP_LOG_VERBOSE) { + return; + } + + size_t currentMinFreeHeap = memory.heap.minimum_free_bytes; + size_t minFreeHeapDiff = 0; + if (currentMinFreeHeap < minFreeHeap || minFreeHeap == 0) { + minFreeHeapDiff = minFreeHeap ? minFreeHeap - currentMinFreeHeap : 0; + minFreeHeap = currentMinFreeHeap; + } + + size_t currentMinLargestFreeBlock = memory.heap.minLargestBlock; + size_t minLargestFreeBlockDiff = 0; + if (currentMinLargestFreeBlock < minLargestFreeBlock || minLargestFreeBlock == 0) { + minLargestFreeBlockDiff = minLargestFreeBlock ? minLargestFreeBlock - currentMinLargestFreeBlock : 0; + minLargestFreeBlock = currentMinLargestFreeBlock; + } + + if (millis() - lastHeapInfo > 20000 || minFreeHeapDiff > 0 || minLargestFreeBlockDiff > 0) { + ESP_LOGV( + L_MAIN, + "Free heap size: %u of %u bytes (min: %u, diff: %u), max free block: %u (min: %u, diff: %u, frag: %hhu%%)", + freeHeap, memory.heap.total, minFreeHeap, minFreeHeapDiff, + maxFreeBlockHeap, minLargestFreeBlock, minLargestFreeBlockDiff, memory.heap.fragmentation + ); + lastHeapInfo = millis(); + } +}); + +// Initialization +void initSystem() { + systemTaskManager.addTask(restartTask); + systemTaskManager.addTask(maintenanceTask.setInterval(100)); + systemTaskManager.addTask(heapTask.setInterval(100)); + + + // System keeps maintenance, networking and restart handling active during App pauses. + if (!systemTaskManager.asyncStart(5120, 3, tskNO_AFFINITY, 100, false)) { + esp_system_abort("Failed to start System task manager"); + } + ESP_LOGI(L_MAIN, "Started %s task manager", systemTaskManager.name()); +} diff --git a/src/utils.h b/src/utils.h deleted file mode 100644 index 4df88cc..0000000 --- a/src/utils.h +++ /dev/null @@ -1,2303 +0,0 @@ -#include - -String getChipId(const char* prefix = nullptr, const char* suffix = nullptr) { - String chipId; - chipId.reserve( - 6 - + (prefix != nullptr ? strlen(prefix) : 0) - + (suffix != nullptr ? strlen(suffix) : 0) - ); - - if (prefix != nullptr) { - chipId.concat(prefix); - } - - uint32_t cid = 0; - #if defined(ARDUINO_ARCH_ESP8266) - cid = ESP.getChipId(); - #elif defined(ARDUINO_ARCH_ESP32) - // https://github.com/espressif/arduino-esp32/blob/master/libraries/ESP32/examples/ChipID/GetChipID/GetChipID.ino - for (uint8_t i = 0; i < 17; i = i + 8) { - cid |= ((ESP.getEfuseMac() >> (40 - i)) & 0xff) << i; - } - #endif - - chipId += String(cid, HEX); - - if (suffix != nullptr) { - chipId.concat(suffix); - } - - chipId.trim(); - return chipId; -} - -bool isLeapYear(short year) { - if (year % 4 != 0) { - return false; - } - - if (year % 100 != 0) { - return true; - } - - return (year % 400) == 0; -} - -// convert UTC tm time to time_t epoch time -// source: https://github.com/cyberman54/ESP32-Paxcounter/blob/master/src/timekeeper.cpp -time_t mkgmtime(const struct tm *ptm) { - const int SecondsPerMinute = 60; - const int SecondsPerHour = 3600; - const int SecondsPerDay = 86400; - const int DaysOfMonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; - time_t secs = 0; - // tm_year is years since 1900 - int year = ptm->tm_year + 1900; - for (int y = 1970; y < year; ++y) { - secs += (isLeapYear(y) ? 366 : 365) * SecondsPerDay; - } - // tm_mon is month from 0..11 - for (int m = 0; m < ptm->tm_mon; ++m) { - secs += DaysOfMonth[m] * SecondsPerDay; - if (m == 1 && isLeapYear(year)) - secs += SecondsPerDay; - } - secs += (ptm->tm_mday - 1) * SecondsPerDay; - secs += ptm->tm_hour * SecondsPerHour; - secs += ptm->tm_min * SecondsPerMinute; - secs += ptm->tm_sec; - return secs; -} - -inline bool isDigit(const char* ptr) { - char* endPtr; - auto tmp = strtol(ptr, &endPtr, 10); - return *endPtr == 0; -} - -inline float liter2gallon(float value) { - return value / 4.546091879f; -} - -inline float gallon2liter(float value) { - return value * 4.546091879f; -} - -float convertVolume(float value, const UnitSystem unitFrom, const UnitSystem unitTo) { - if (unitFrom == UnitSystem::METRIC && unitTo == UnitSystem::IMPERIAL) { - value = liter2gallon(value); - - } else if (unitFrom == UnitSystem::IMPERIAL && unitTo == UnitSystem::METRIC) { - value = gallon2liter(value); - } - - return value; -} - -inline float bar2psi(float value) { - return value * 14.5038f; -} - -inline float psi2bar(float value) { - return value / 14.5038f; -} - -float convertPressure(float value, const UnitSystem unitFrom, const UnitSystem unitTo) { - if (unitFrom == UnitSystem::METRIC && unitTo == UnitSystem::IMPERIAL) { - value = bar2psi(value); - - } else if (unitFrom == UnitSystem::IMPERIAL && unitTo == UnitSystem::METRIC) { - value = psi2bar(value); - } - - return value; -} - -inline float c2f(float value) { - return (9.0f / 5.0f) * value + 32.0f; -} - -inline float f2c(float value) { - return (value - 32.0f) * (5.0f / 9.0f); -} - -float convertTemp(float value, const UnitSystem unitFrom, const UnitSystem unitTo) { - if (unitFrom == UnitSystem::METRIC && unitTo == UnitSystem::IMPERIAL) { - value = c2f(value); - - } else if (unitFrom == UnitSystem::IMPERIAL && unitTo == UnitSystem::METRIC) { - value = f2c(value); - } - - return value; -} - -inline bool isValidTemp(const float value, UnitSystem unit, const float min = 0.1f, const float max = 99.9f, const UnitSystem minMaxUnit = UnitSystem::METRIC) { - return value >= convertTemp(min, minMaxUnit, unit) && value <= convertTemp(max, minMaxUnit, unit); -} - -float roundf(float value, uint8_t decimals = 2) { - if (decimals == 0) { - return (int)(value + 0.5f); - - } else if (abs(value) < 0.00000001f) { - return 0.0f; - } - - float multiplier = pow10(decimals); - value += 0.5f / multiplier * (value < 0.0f ? -1.0f : 1.0f); - return (int)(value * multiplier) / multiplier; -} - -inline size_t getTotalHeap() { - #if defined(ARDUINO_ARCH_ESP32) - return ESP.getHeapSize(); - #elif defined(ARDUINO_ARCH_ESP8266) - return 81920; - #else - return 99999; - #endif -} - -size_t getFreeHeap(bool getMinValue = false) { - #if defined(ARDUINO_ARCH_ESP32) - return getMinValue ? ESP.getMinFreeHeap() : ESP.getFreeHeap(); - - #elif defined(ARDUINO_ARCH_ESP8266) - static size_t minValue = 0; - size_t value = ESP.getFreeHeap(); - - if (value < minValue || minValue == 0) { - minValue = value; - } - - return getMinValue ? minValue : value; - #else - return 0; - #endif -} - -size_t getMaxFreeBlockHeap(bool getMinValue = false) { - static size_t minValue = 0; - size_t value = 0; - - #if defined(ARDUINO_ARCH_ESP32) - value = ESP.getMaxAllocHeap(); - - size_t minHeapValue = getFreeHeap(true); - if (minHeapValue < minValue || minValue == 0) { - minValue = minHeapValue; - } - #elif defined(ARDUINO_ARCH_ESP8266) - value = ESP.getMaxFreeBlockSize(); - #endif - - if (value < minValue || minValue == 0) { - minValue = value; - } - - return getMinValue ? minValue : value; -} - -inline uint8_t getHeapFrag() { - return 100 - getMaxFreeBlockHeap() * 100.0 / getFreeHeap(); -} - -String getResetReason() { - String value; - - #if defined(ARDUINO_ARCH_ESP8266) - value = ESP.getResetReason(); - #elif defined(ARDUINO_ARCH_ESP32) - switch (esp_reset_reason()) { - case ESP_RST_POWERON: - value = F("Reset due to power-on event"); - break; - - case ESP_RST_EXT: - value = F("Reset by external pin"); - break; - - case ESP_RST_SW: - value = F("Software reset via esp_restart"); - break; - - case ESP_RST_PANIC: - value = F("Software reset due to exception/panic"); - break; - - case ESP_RST_INT_WDT: - value = F("Reset (software or hardware) due to interrupt watchdog"); - break; - - case ESP_RST_TASK_WDT: - value = F("Reset due to task watchdog"); - break; - - case ESP_RST_WDT: - value = F("Reset due to other watchdogs"); - break; - - case ESP_RST_DEEPSLEEP: - value = F("Reset after exiting deep sleep mode"); - break; - - case ESP_RST_BROWNOUT: - value = F("Brownout reset (software or hardware)"); - break; - - case ESP_RST_SDIO: - value = F("Reset over SDIO"); - break; - - case ESP_RST_UNKNOWN: - default: - value = F("unknown"); - break; - - } - #else - value = F("unknown"); - #endif - - return value; -} - -template -void arr2str(String& str, T arr[], size_t length) { - char buffer[12]; - for (size_t i = 0; i < length; i++) { - auto addr = arr[i]; - if (!addr) { - continue; - } - - sprintf(buffer, "0x%08X ", addr); - str.concat(buffer); - } - - str.trim(); -} - -void networkSettingsToJson(const NetworkSettings& src, JsonVariant dst) { - dst[FPSTR(S_HOSTNAME)] = src.hostname; - - dst[FPSTR(S_USE_DHCP)] = src.useDhcp; - dst[FPSTR(S_STATIC_CONFIG)][FPSTR(S_IP)] = src.staticConfig.ip; - dst[FPSTR(S_STATIC_CONFIG)][FPSTR(S_GATEWAY)] = src.staticConfig.gateway; - dst[FPSTR(S_STATIC_CONFIG)][FPSTR(S_SUBNET)] = src.staticConfig.subnet; - dst[FPSTR(S_STATIC_CONFIG)][FPSTR(S_DNS)] = src.staticConfig.dns; - - dst[FPSTR(S_AP)][FPSTR(S_SSID)] = src.ap.ssid; - dst[FPSTR(S_AP)][FPSTR(S_PASSWORD)] = src.ap.password; - dst[FPSTR(S_AP)][FPSTR(S_CHANNEL)] = src.ap.channel; - - dst[FPSTR(S_STA)][FPSTR(S_SSID)] = src.sta.ssid; - dst[FPSTR(S_STA)][FPSTR(S_PASSWORD)] = src.sta.password; - dst[FPSTR(S_STA)][FPSTR(S_CHANNEL)] = src.sta.channel; - - #if USE_ETHERNET - auto ethernet = dst[FPSTR(S_ETHERNET)].to(); - - ethernet[FPSTR(S_ENABLED)] = src.ethernet.enabled; - - auto pins = ethernet[FPSTR(S_PINS)].to(); - pins[FPSTR(S_CLK)] = src.ethernet.w5500.clk; - pins[FPSTR(S_MOSI)] = src.ethernet.w5500.mosi; - pins[FPSTR(S_MISO)] = src.ethernet.w5500.miso; - pins[FPSTR(S_CS)] = src.ethernet.w5500.cs; - pins[FPSTR(S_IRQ)] = src.ethernet.w5500.irq; - pins[FPSTR(S_RST)] = src.ethernet.w5500.rst; - #endif -} - -bool jsonToEthernetPins(const JsonVariantConst src, NetworkSettings& dst, bool& changed); - -bool jsonToNetworkSettings(const JsonVariantConst src, NetworkSettings& dst) { - bool changed = false; - - // hostname - if (!src[FPSTR(S_HOSTNAME)].isNull()) { - String value = src[FPSTR(S_HOSTNAME)].as(); - - if (value.length() < sizeof(dst.hostname) && !value.equals(dst.hostname)) { - strcpy(dst.hostname, value.c_str()); - changed = true; - } - } - - // use dhcp - if (src[FPSTR(S_USE_DHCP)].is()) { - dst.useDhcp = src[FPSTR(S_USE_DHCP)].as(); - changed = true; - } - - - // static config - if (!src[FPSTR(S_STATIC_CONFIG)][FPSTR(S_IP)].isNull()) { - String value = src[FPSTR(S_STATIC_CONFIG)][FPSTR(S_IP)].as(); - - if (value.length() < sizeof(dst.staticConfig.ip) && !value.equals(dst.staticConfig.ip)) { - strcpy(dst.staticConfig.ip, value.c_str()); - changed = true; - } - } - - if (!src[FPSTR(S_STATIC_CONFIG)][FPSTR(S_GATEWAY)].isNull()) { - String value = src[FPSTR(S_STATIC_CONFIG)][FPSTR(S_GATEWAY)].as(); - - if (value.length() < sizeof(dst.staticConfig.gateway) && !value.equals(dst.staticConfig.gateway)) { - strcpy(dst.staticConfig.gateway, value.c_str()); - changed = true; - } - } - - if (!src[FPSTR(S_STATIC_CONFIG)][FPSTR(S_SUBNET)].isNull()) { - String value = src[FPSTR(S_STATIC_CONFIG)][FPSTR(S_SUBNET)].as(); - - if (value.length() < sizeof(dst.staticConfig.subnet) && !value.equals(dst.staticConfig.subnet)) { - strcpy(dst.staticConfig.subnet, value.c_str()); - changed = true; - } - } - - if (!src[FPSTR(S_STATIC_CONFIG)][FPSTR(S_DNS)].isNull()) { - String value = src[FPSTR(S_STATIC_CONFIG)][FPSTR(S_DNS)].as(); - - if (value.length() < sizeof(dst.staticConfig.dns) && !value.equals(dst.staticConfig.dns)) { - strcpy(dst.staticConfig.dns, value.c_str()); - changed = true; - } - } - - - // ap - if (!src[FPSTR(S_AP)][FPSTR(S_SSID)].isNull()) { - String value = src[FPSTR(S_AP)][FPSTR(S_SSID)].as(); - - if (value.length() < sizeof(dst.ap.ssid) && !value.equals(dst.ap.ssid)) { - strcpy(dst.ap.ssid, value.c_str()); - changed = true; - } - } - - if (!src[FPSTR(S_AP)][FPSTR(S_PASSWORD)].isNull()) { - String value = src[FPSTR(S_AP)][FPSTR(S_PASSWORD)].as(); - - if (value.length() < sizeof(dst.ap.password) && !value.equals(dst.ap.password)) { - strcpy(dst.ap.password, value.c_str()); - changed = true; - } - } - - if (!src[FPSTR(S_AP)][FPSTR(S_CHANNEL)].isNull()) { - unsigned char value = src[FPSTR(S_AP)][FPSTR(S_CHANNEL)].as(); - - if (value >= 0 && value < 12) { - dst.ap.channel = value; - changed = true; - } - } - - - // sta - if (!src[FPSTR(S_STA)][FPSTR(S_SSID)].isNull()) { - String value = src[FPSTR(S_STA)][FPSTR(S_SSID)].as(); - - if (value.length() < sizeof(dst.sta.ssid) && !value.equals(dst.sta.ssid)) { - strcpy(dst.sta.ssid, value.c_str()); - changed = true; - } - } - - if (!src[FPSTR(S_STA)][FPSTR(S_PASSWORD)].isNull()) { - String value = src[FPSTR(S_STA)][FPSTR(S_PASSWORD)].as(); - - if (value.length() < sizeof(dst.sta.password) && !value.equals(dst.sta.password)) { - strcpy(dst.sta.password, value.c_str()); - changed = true; - } - } - - if (!src[FPSTR(S_STA)][FPSTR(S_CHANNEL)].isNull()) { - unsigned char value = src[FPSTR(S_STA)][FPSTR(S_CHANNEL)].as(); - - if (value >= 0 && value < 12) { - dst.sta.channel = value; - changed = true; - } - } - - - // ethernet - if (src[FPSTR(S_ETHERNET)][FPSTR(S_ENABLED)].is()) { - bool value = src[FPSTR(S_ETHERNET)][FPSTR(S_ENABLED)].as(); - - if (value != dst.ethernet.enabled) { - dst.ethernet.enabled = value; - changed = true; - } - } - - jsonToEthernetPins(src[FPSTR(S_ETHERNET)][FPSTR(S_PINS)], dst, changed); - - return changed; -} - -void settingsToJson(const Settings& src, JsonVariant dst, bool safe = false) { - if (!safe) { - auto system = dst[FPSTR(S_SYSTEM)].to(); - system[FPSTR(S_LOG_LEVEL)] = static_cast(src.system.logLevel); - - auto serial = system[FPSTR(S_SERIAL)].to(); - serial[FPSTR(S_ENABLED)] = src.system.serial.enabled; - serial[FPSTR(S_BAUDRATE)] = src.system.serial.baudrate; - - auto telnet = system[FPSTR(S_TELNET)].to(); - telnet[FPSTR(S_ENABLED)] = src.system.telnet.enabled; - telnet[FPSTR(S_PORT)] = src.system.telnet.port; - - auto ntp = system[FPSTR(S_NTP)].to(); - ntp[FPSTR(S_SERVER)] = src.system.ntp.server; - ntp[FPSTR(S_TIMEZONE)] = src.system.ntp.timezone; - - system[FPSTR(S_UNIT_SYSTEM)] = static_cast(src.system.unitSystem); - system[FPSTR(S_STATUS_LED_GPIO)] = src.system.statusLedGpio; - - auto portal = dst[FPSTR(S_PORTAL)].to(); - portal[FPSTR(S_AUTH)] = src.portal.auth; - portal[FPSTR(S_LOGIN)] = src.portal.login; - portal[FPSTR(S_PASSWORD)] = src.portal.password; - portal[FPSTR(S_MDNS)] = src.portal.mdns; - - auto opentherm = dst[FPSTR(S_OPENTHERM)].to(); - opentherm[FPSTR(S_UNIT_SYSTEM)] = static_cast(src.opentherm.unitSystem); - opentherm[FPSTR(S_IN_GPIO)] = src.opentherm.inGpio; - opentherm[FPSTR(S_OUT_GPIO)] = src.opentherm.outGpio; - opentherm[FPSTR(S_RX_LED_GPIO)] = src.opentherm.rxLedGpio; - opentherm[FPSTR(S_MEMBER_ID)] = src.opentherm.memberId; - opentherm[FPSTR(S_FLAGS)] = src.opentherm.flags; - opentherm[FPSTR(S_MIN_POWER)] = roundf(src.opentherm.minPower, 2); - opentherm[FPSTR(S_MAX_POWER)] = roundf(src.opentherm.maxPower, 2); - - auto otOptions = opentherm[FPSTR(S_OPTIONS)].to(); - otOptions[FPSTR(S_DHW_SUPPORT)] = src.opentherm.options.dhwSupport; - otOptions[FPSTR(S_COOLING_SUPPORT)] = src.opentherm.options.coolingSupport; - otOptions[FPSTR(S_SUMMER_WINTER_MODE)] = src.opentherm.options.summerWinterMode; - otOptions[FPSTR(S_HEATING_STATE_TO_SUMMER_WINTER_MODE)] = src.opentherm.options.heatingStateToSummerWinterMode; - otOptions[FPSTR(S_CH2_ALWAYS_ENABLED)] = src.opentherm.options.ch2AlwaysEnabled; - otOptions[FPSTR(S_HEATING_TO_CH2)] = src.opentherm.options.heatingToCh2; - otOptions[FPSTR(S_DHW_TO_CH2)] = src.opentherm.options.dhwToCh2; - otOptions[FPSTR(S_DHW_BLOCKING)] = src.opentherm.options.dhwBlocking; - otOptions[FPSTR(S_DHW_STATE_AS_DHW_BLOCKING)] = src.opentherm.options.dhwStateAsDhwBlocking; - otOptions[FPSTR(S_MAX_TEMP_SYNC_WITH_TARGET_TEMP)] = src.opentherm.options.maxTempSyncWithTargetTemp; - otOptions[FPSTR(S_GET_MIN_MAX_TEMP)] = src.opentherm.options.getMinMaxTemp; - otOptions[FPSTR(S_IGNORE_DIAG_STATE)] = src.opentherm.options.ignoreDiagState; - otOptions[FPSTR(S_AUTO_FAULT_RESET)] = src.opentherm.options.autoFaultReset; - otOptions[FPSTR(S_AUTO_DIAG_RESET)] = src.opentherm.options.autoDiagReset; - otOptions[FPSTR(S_SET_DATE_AND_TIME)] = src.opentherm.options.setDateAndTime; - otOptions[FPSTR(S_ALWAYS_SEND_INDOOR_TEMP)] = src.opentherm.options.alwaysSendIndoorTemp; - otOptions[FPSTR(S_NATIVE_OTC)] = src.opentherm.options.nativeOTC; - otOptions[FPSTR(S_IMMERGAS_FIX)] = src.opentherm.options.immergasFix; - - - auto mqtt = dst[FPSTR(S_MQTT)].to(); - mqtt[FPSTR(S_ENABLED)] = src.mqtt.enabled; - mqtt[FPSTR(S_SERVER)] = src.mqtt.server; - mqtt[FPSTR(S_PORT)] = src.mqtt.port; - mqtt[FPSTR(S_USER)] = src.mqtt.user; - mqtt[FPSTR(S_PASSWORD)] = src.mqtt.password; - mqtt[FPSTR(S_PREFIX)] = src.mqtt.prefix; - mqtt[FPSTR(S_INTERVAL)] = src.mqtt.interval; - mqtt[FPSTR(S_HOME_ASSISTANT_DISCOVERY)] = src.mqtt.homeAssistantDiscovery; - - auto emergency = dst[FPSTR(S_EMERGENCY)].to(); - emergency[FPSTR(S_TARGET)] = roundf(src.emergency.target, 2); - emergency[FPSTR(S_TRESHOLD_TIME)] = src.emergency.tresholdTime; - } - - auto heating = dst[FPSTR(S_HEATING)].to(); - heating[FPSTR(S_ENABLED)] = src.heating.enabled; - heating[FPSTR(S_TURBO)] = src.heating.turbo; - heating[FPSTR(S_TARGET)] = roundf(src.heating.target, 2); - heating[FPSTR(S_HYSTERESIS)][FPSTR(S_ENABLED)] = src.heating.hysteresis.enabled; - heating[FPSTR(S_HYSTERESIS)][FPSTR(S_VALUE)] = roundf(src.heating.hysteresis.value, 3); - heating[FPSTR(S_HYSTERESIS)][FPSTR(S_ACTION)] = static_cast(src.heating.hysteresis.action); - heating[FPSTR(S_TURBO_FACTOR)] = roundf(src.heating.turboFactor, 3); - heating[FPSTR(S_MIN_TEMP)] = src.heating.minTemp; - heating[FPSTR(S_MAX_TEMP)] = src.heating.maxTemp; - heating[FPSTR(S_MAX_MODULATION)] = src.heating.maxModulation; - - auto heatingOverheatProtection = heating[FPSTR(S_OVERHEAT_PROTECTION)].to(); - heatingOverheatProtection[FPSTR(S_HIGH_TEMP)] = src.heating.overheatProtection.highTemp; - heatingOverheatProtection[FPSTR(S_LOW_TEMP)] = src.heating.overheatProtection.lowTemp; - - auto freezeProtection = heating[FPSTR(S_FREEZE_PROTECTION)].to(); - freezeProtection[FPSTR(S_HIGH_TEMP)] = src.heating.freezeProtection.highTemp; - freezeProtection[FPSTR(S_LOW_TEMP)] = src.heating.freezeProtection.lowTemp; - - auto dhw = dst[FPSTR(S_DHW)].to(); - dhw[FPSTR(S_ENABLED)] = src.dhw.enabled; - dhw[FPSTR(S_TARGET)] = roundf(src.dhw.target, 1); - dhw[FPSTR(S_MIN_TEMP)] = src.dhw.minTemp; - dhw[FPSTR(S_MAX_TEMP)] = src.dhw.maxTemp; - dhw[FPSTR(S_MAX_MODULATION)] = src.dhw.maxModulation; - - auto dhwOverheatProtection = dhw[FPSTR(S_OVERHEAT_PROTECTION)].to(); - dhwOverheatProtection[FPSTR(S_HIGH_TEMP)] = src.dhw.overheatProtection.highTemp; - dhwOverheatProtection[FPSTR(S_LOW_TEMP)] = src.dhw.overheatProtection.lowTemp; - - auto equitherm = dst[FPSTR(S_EQUITHERM)].to(); - equitherm[FPSTR(S_ENABLED)] = src.equitherm.enabled; - equitherm[FPSTR(S_SLOPE)] = roundf(src.equitherm.slope, 3); - equitherm[FPSTR(S_EXPONENT)] = roundf(src.equitherm.exponent, 3); - equitherm[FPSTR(S_SHIFT)] = roundf(src.equitherm.shift, 2); - equitherm[FPSTR(S_TARGET_DIFF_FACTOR)] = roundf(src.equitherm.targetDiffFactor, 3); - - auto pid = dst[FPSTR(S_PID)].to(); - pid[FPSTR(S_ENABLED)] = src.pid.enabled; - pid[FPSTR(S_P_FACTOR)] = roundf(src.pid.p_factor, 3); - pid[FPSTR(S_I_FACTOR)] = roundf(src.pid.i_factor, 4); - pid[FPSTR(S_D_FACTOR)] = roundf(src.pid.d_factor, 1); - pid[FPSTR(S_DT)] = src.pid.dt; - pid[FPSTR(S_MIN_TEMP)] = src.pid.minTemp; - pid[FPSTR(S_MAX_TEMP)] = src.pid.maxTemp; - - auto pidDeadband = pid[FPSTR(S_DEADBAND)].to(); - pidDeadband[FPSTR(S_ENABLED)] = src.pid.deadband.enabled; - pidDeadband[FPSTR(S_P_MULTIPLIER)] = src.pid.deadband.p_multiplier; - pidDeadband[FPSTR(S_I_MULTIPLIER)] = src.pid.deadband.i_multiplier; - pidDeadband[FPSTR(S_D_MULTIPLIER)] = src.pid.deadband.d_multiplier; - pidDeadband[FPSTR(S_THRESHOLD_HIGH)] = src.pid.deadband.thresholdHigh; - pidDeadband[FPSTR(S_THRESHOLD_LOW)] = src.pid.deadband.thresholdLow; - - if (!safe) { - auto externalPump = dst[FPSTR(S_EXTERNAL_PUMP)].to(); - externalPump[FPSTR(S_USE)] = src.externalPump.use; - externalPump[FPSTR(S_GPIO)] = src.externalPump.gpio; - externalPump[FPSTR(S_INVERT_STATE)] = src.externalPump.invertState; - externalPump[FPSTR(S_POST_CIRCULATION_TIME)] = roundf(src.externalPump.postCirculationTime / 60, 0); - externalPump[FPSTR(S_ANTI_STUCK_INTERVAL)] = roundf(src.externalPump.antiStuckInterval / 86400, 0); - externalPump[FPSTR(S_ANTI_STUCK_TIME)] = roundf(src.externalPump.antiStuckTime / 60, 0); - - auto cascadeControlInput = dst[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_INPUT)].to(); - cascadeControlInput[FPSTR(S_ENABLED)] = src.cascadeControl.input.enabled; - cascadeControlInput[FPSTR(S_GPIO)] = src.cascadeControl.input.gpio; - cascadeControlInput[FPSTR(S_INVERT_STATE)] = src.cascadeControl.input.invertState; - cascadeControlInput[FPSTR(S_THRESHOLD_TIME)] = src.cascadeControl.input.thresholdTime; - - auto cascadeControlOutput = dst[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_OUTPUT)].to(); - cascadeControlOutput[FPSTR(S_ENABLED)] = src.cascadeControl.output.enabled; - cascadeControlOutput[FPSTR(S_GPIO)] = src.cascadeControl.output.gpio; - cascadeControlOutput[FPSTR(S_INVERT_STATE)] = src.cascadeControl.output.invertState; - cascadeControlOutput[FPSTR(S_THRESHOLD_TIME)] = src.cascadeControl.output.thresholdTime; - cascadeControlOutput[FPSTR(S_ON_FAULT)] = src.cascadeControl.output.onFault; - cascadeControlOutput[FPSTR(S_ON_LOSS_CONNECTION)] = src.cascadeControl.output.onLossConnection; - cascadeControlOutput[FPSTR(S_ON_ENABLED_HEATING)] = src.cascadeControl.output.onEnabledHeating; - } -} - -inline void safeSettingsToJson(const Settings& src, JsonVariant dst) { - settingsToJson(src, dst, true); -} - -/** - * @brief Parse a single GPIO value: an empty string means "not configured" - * - * @return true if the key existed in the source document - */ -bool jsonToGpioValue(const JsonVariantConst src, const __FlashStringHelper* key, uint8_t& dst, bool& changed) { - if (src[key].isNull()) { - return false; - } - - if (src[key].is() && src[key].as().size() == 0) { - if (dst != GPIO_IS_NOT_CONFIGURED) { - dst = GPIO_IS_NOT_CONFIGURED; - changed = true; - } - - return true; - } - - unsigned char value = src[key].as(); - - if (GPIO_IS_VALID(value) && value != dst) { - dst = value; - changed = true; - } - - return true; -} - -/** - * @brief Parse the W5500 pinout from an object holding clk/mosi/miso/cs/irq/rst - * - * @return true if the source object exists - */ -bool jsonToEthernetPins(const JsonVariantConst src, NetworkSettings& dst, bool& changed) { - if (src.isNull()) { - return false; - } - - jsonToGpioValue(src, FPSTR(S_CLK), dst.ethernet.w5500.clk, changed); - jsonToGpioValue(src, FPSTR(S_MOSI), dst.ethernet.w5500.mosi, changed); - jsonToGpioValue(src, FPSTR(S_MISO), dst.ethernet.w5500.miso, changed); - jsonToGpioValue(src, FPSTR(S_CS), dst.ethernet.w5500.cs, changed); - jsonToGpioValue(src, FPSTR(S_IRQ), dst.ethernet.w5500.irq, changed); - jsonToGpioValue(src, FPSTR(S_RST), dst.ethernet.w5500.rst, changed); - - return true; -} - -bool jsonToSettings(const JsonVariantConst src, Settings& dst, bool safe = false) { - bool changed = false; - - if (!safe) { - // system - if (!src[FPSTR(S_SYSTEM)][FPSTR(S_LOG_LEVEL)].isNull()) { - uint8_t value = src[FPSTR(S_SYSTEM)][FPSTR(S_LOG_LEVEL)].as(); - - if (value != dst.system.logLevel && value >= TinyLogger::Level::SILENT && value <= TinyLogger::Level::VERBOSE) { - dst.system.logLevel = value; - changed = true; - } - } - - if (src[FPSTR(S_SYSTEM)][FPSTR(S_SERIAL)][FPSTR(S_ENABLED)].is()) { - bool value = src[FPSTR(S_SYSTEM)][FPSTR(S_SERIAL)][FPSTR(S_ENABLED)].as(); - - if (value != dst.system.serial.enabled) { - dst.system.serial.enabled = value; - changed = true; - } - } - - if (!src[FPSTR(S_SYSTEM)][FPSTR(S_SERIAL)][FPSTR(S_BAUDRATE)].isNull()) { - unsigned int value = src[FPSTR(S_SYSTEM)][FPSTR(S_SERIAL)][FPSTR(S_BAUDRATE)].as(); - - if (value == 9600 || value == 19200 || value == 38400 || value == 57600 || value == 74880 || value == 115200) { - if (value != dst.system.serial.baudrate) { - dst.system.serial.baudrate = value; - changed = true; - } - } - } - - if (src[FPSTR(S_SYSTEM)][FPSTR(S_TELNET)][FPSTR(S_ENABLED)].is()) { - bool value = src[FPSTR(S_SYSTEM)][FPSTR(S_TELNET)][FPSTR(S_ENABLED)].as(); - - if (value != dst.system.telnet.enabled) { - dst.system.telnet.enabled = value; - changed = true; - } - } - - if (!src[FPSTR(S_SYSTEM)][FPSTR(S_TELNET)][FPSTR(S_PORT)].isNull()) { - unsigned short value = src[FPSTR(S_SYSTEM)][FPSTR(S_TELNET)][FPSTR(S_PORT)].as(); - - if (value > 0 && value <= 65535 && value != dst.system.telnet.port) { - dst.system.telnet.port = value; - changed = true; - } - } - - if (!src[FPSTR(S_SYSTEM)][FPSTR(S_NTP)][FPSTR(S_SERVER)].isNull()) { - String value = src[FPSTR(S_SYSTEM)][FPSTR(S_NTP)][FPSTR(S_SERVER)].as(); - - if (value.length() < sizeof(dst.system.ntp.server) && !value.equals(dst.system.ntp.server)) { - strcpy(dst.system.ntp.server, value.c_str()); - changed = true; - } - } - - if (!src[FPSTR(S_SYSTEM)][FPSTR(S_NTP)][FPSTR(S_TIMEZONE)].isNull()) { - String value = src[FPSTR(S_SYSTEM)][FPSTR(S_NTP)][FPSTR(S_TIMEZONE)].as(); - - if (value.length() < sizeof(dst.system.ntp.timezone) && !value.equals(dst.system.ntp.timezone)) { - strcpy(dst.system.ntp.timezone, value.c_str()); - changed = true; - } - } - - if (!src[FPSTR(S_SYSTEM)][FPSTR(S_UNIT_SYSTEM)].isNull()) { - uint8_t value = src[FPSTR(S_SYSTEM)][FPSTR(S_UNIT_SYSTEM)].as(); - UnitSystem prevUnitSystem = dst.system.unitSystem; - - switch (value) { - case static_cast(UnitSystem::METRIC): - if (dst.system.unitSystem != UnitSystem::METRIC) { - dst.system.unitSystem = UnitSystem::METRIC; - changed = true; - } - break; - - case static_cast(UnitSystem::IMPERIAL): - if (dst.system.unitSystem != UnitSystem::IMPERIAL) { - dst.system.unitSystem = UnitSystem::IMPERIAL; - changed = true; - } - break; - - default: - break; - } - - // convert temps - if (dst.system.unitSystem != prevUnitSystem) { - dst.emergency.target = convertTemp(dst.emergency.target, prevUnitSystem, dst.system.unitSystem); - dst.heating.target = convertTemp(dst.heating.target, prevUnitSystem, dst.system.unitSystem); - dst.heating.minTemp = convertTemp(dst.heating.minTemp, prevUnitSystem, dst.system.unitSystem); - dst.heating.maxTemp = convertTemp(dst.heating.maxTemp, prevUnitSystem, dst.system.unitSystem); - dst.dhw.target = convertTemp(dst.dhw.target, prevUnitSystem, dst.system.unitSystem); - dst.dhw.minTemp = convertTemp(dst.dhw.minTemp, prevUnitSystem, dst.system.unitSystem); - dst.dhw.maxTemp = convertTemp(dst.dhw.maxTemp, prevUnitSystem, dst.system.unitSystem); - dst.pid.minTemp = convertTemp(dst.pid.minTemp, prevUnitSystem, dst.system.unitSystem); - dst.pid.maxTemp = convertTemp(dst.pid.maxTemp, prevUnitSystem, dst.system.unitSystem); - } - } - - if (!src[FPSTR(S_SYSTEM)][FPSTR(S_STATUS_LED_GPIO)].isNull()) { - if (src[FPSTR(S_SYSTEM)][FPSTR(S_STATUS_LED_GPIO)].is() && src[FPSTR(S_SYSTEM)][FPSTR(S_STATUS_LED_GPIO)].as().size() == 0) { - if (dst.system.statusLedGpio != GPIO_IS_NOT_CONFIGURED) { - dst.system.statusLedGpio = GPIO_IS_NOT_CONFIGURED; - changed = true; - } - - } else { - unsigned char value = src[FPSTR(S_SYSTEM)][FPSTR(S_STATUS_LED_GPIO)].as(); - - if (GPIO_IS_VALID(value) && value != dst.system.statusLedGpio) { - dst.system.statusLedGpio = value; - changed = true; - } - } - } - - // portal - if (src[FPSTR(S_PORTAL)][FPSTR(S_AUTH)].is()) { - bool value = src[FPSTR(S_PORTAL)][FPSTR(S_AUTH)].as(); - - if (value != dst.portal.auth) { - dst.portal.auth = value; - changed = true; - } - } - - if (!src[FPSTR(S_PORTAL)][FPSTR(S_LOGIN)].isNull()) { - String value = src[FPSTR(S_PORTAL)][FPSTR(S_LOGIN)].as(); - - if (value.length() < sizeof(dst.portal.login) && !value.equals(dst.portal.login)) { - strcpy(dst.portal.login, value.c_str()); - changed = true; - } - } - - if (!src[FPSTR(S_PORTAL)][FPSTR(S_PASSWORD)].isNull()) { - String value = src[FPSTR(S_PORTAL)][FPSTR(S_PASSWORD)].as(); - - if (value.length() < sizeof(dst.portal.password) && !value.equals(dst.portal.password)) { - strcpy(dst.portal.password, value.c_str()); - changed = true; - } - } - - if (dst.portal.auth && (!strlen(dst.portal.login) || !strlen(dst.portal.password))) { - dst.portal.auth = false; - changed = true; - } - - if (src[FPSTR(S_PORTAL)][FPSTR(S_MDNS)].is()) { - bool value = src[FPSTR(S_PORTAL)][FPSTR(S_MDNS)].as(); - - if (value != dst.portal.mdns) { - dst.portal.mdns = value; - changed = true; - } - } - - - // opentherm - if (!src[FPSTR(S_OPENTHERM)][FPSTR(S_UNIT_SYSTEM)].isNull()) { - uint8_t value = src[FPSTR(S_OPENTHERM)][FPSTR(S_UNIT_SYSTEM)].as(); - - switch (value) { - case static_cast(UnitSystem::METRIC): - if (dst.opentherm.unitSystem != UnitSystem::METRIC) { - dst.opentherm.unitSystem = UnitSystem::METRIC; - changed = true; - } - break; - - case static_cast(UnitSystem::IMPERIAL): - if (dst.opentherm.unitSystem != UnitSystem::IMPERIAL) { - dst.opentherm.unitSystem = UnitSystem::IMPERIAL; - changed = true; - } - break; - - default: - break; - } - } - - if (!src[FPSTR(S_OPENTHERM)][FPSTR(S_IN_GPIO)].isNull()) { - if (src[FPSTR(S_OPENTHERM)][FPSTR(S_IN_GPIO)].is() && src[FPSTR(S_OPENTHERM)][FPSTR(S_IN_GPIO)].as().size() == 0) { - if (dst.opentherm.inGpio != GPIO_IS_NOT_CONFIGURED) { - dst.opentherm.inGpio = GPIO_IS_NOT_CONFIGURED; - changed = true; - } - - } else { - unsigned char value = src[FPSTR(S_OPENTHERM)][FPSTR(S_IN_GPIO)].as(); - - if (GPIO_IS_VALID(value) && value != dst.opentherm.inGpio) { - dst.opentherm.inGpio = value; - changed = true; - } - } - } - - if (!src[FPSTR(S_OPENTHERM)][FPSTR(S_OUT_GPIO)].isNull()) { - if (src[FPSTR(S_OPENTHERM)][FPSTR(S_OUT_GPIO)].is() && src[FPSTR(S_OPENTHERM)][FPSTR(S_OUT_GPIO)].as().size() == 0) { - if (dst.opentherm.outGpio != GPIO_IS_NOT_CONFIGURED) { - dst.opentherm.outGpio = GPIO_IS_NOT_CONFIGURED; - changed = true; - } - - } else { - unsigned char value = src[FPSTR(S_OPENTHERM)][FPSTR(S_OUT_GPIO)].as(); - - if (GPIO_IS_VALID(value) && value != dst.opentherm.outGpio) { - dst.opentherm.outGpio = value; - changed = true; - } - } - } - - if (!src[FPSTR(S_OPENTHERM)][FPSTR(S_RX_LED_GPIO)].isNull()) { - if (src[FPSTR(S_OPENTHERM)][FPSTR(S_RX_LED_GPIO)].is() && src[FPSTR(S_OPENTHERM)][FPSTR(S_RX_LED_GPIO)].as().size() == 0) { - if (dst.opentherm.rxLedGpio != GPIO_IS_NOT_CONFIGURED) { - dst.opentherm.rxLedGpio = GPIO_IS_NOT_CONFIGURED; - changed = true; - } - - } else { - unsigned char value = src[FPSTR(S_OPENTHERM)][FPSTR(S_RX_LED_GPIO)].as(); - - if (GPIO_IS_VALID(value) && value != dst.opentherm.rxLedGpio) { - dst.opentherm.rxLedGpio = value; - changed = true; - } - } - } - - if (!src[FPSTR(S_OPENTHERM)][FPSTR(S_MEMBER_ID)].isNull()) { - auto value = src[FPSTR(S_OPENTHERM)][FPSTR(S_MEMBER_ID)].as(); - - if (value != dst.opentherm.memberId) { - dst.opentherm.memberId = value; - changed = true; - } - } - - if (!src[FPSTR(S_OPENTHERM)][FPSTR(S_FLAGS)].isNull()) { - auto value = src[FPSTR(S_OPENTHERM)][FPSTR(S_FLAGS)].as(); - - if (value != dst.opentherm.flags) { - dst.opentherm.flags = value; - changed = true; - } - } - - if (!src[FPSTR(S_OPENTHERM)][FPSTR(S_MIN_POWER)].isNull()) { - float value = src[FPSTR(S_OPENTHERM)][FPSTR(S_MIN_POWER)].as(); - - if (value >= 0 && value <= 1000 && fabsf(value - dst.opentherm.minPower) > 0.0001f) { - dst.opentherm.minPower = roundf(value, 2); - changed = true; - } - } - - if (!src[FPSTR(S_OPENTHERM)][FPSTR(S_MAX_POWER)].isNull()) { - float value = src[FPSTR(S_OPENTHERM)][FPSTR(S_MAX_POWER)].as(); - - if (value >= 0 && value <= 1000 && fabsf(value - dst.opentherm.maxPower) > 0.0001f) { - dst.opentherm.maxPower = roundf(value, 2); - changed = true; - } - } - - if (src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_DHW_SUPPORT)].is()) { - bool value = src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_DHW_SUPPORT)].as(); - - if (value != dst.opentherm.options.dhwSupport) { - dst.opentherm.options.dhwSupport = value; - changed = true; - } - } - - if (src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_COOLING_SUPPORT)].is()) { - bool value = src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_COOLING_SUPPORT)].as(); - - if (value != dst.opentherm.options.coolingSupport) { - dst.opentherm.options.coolingSupport = value; - changed = true; - } - } - - if (src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_SUMMER_WINTER_MODE)].is()) { - bool value = src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_SUMMER_WINTER_MODE)].as(); - - if (value != dst.opentherm.options.summerWinterMode) { - dst.opentherm.options.summerWinterMode = value; - changed = true; - } - } - - if (src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_HEATING_STATE_TO_SUMMER_WINTER_MODE)].is()) { - bool value = src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_HEATING_STATE_TO_SUMMER_WINTER_MODE)].as(); - - if (value != dst.opentherm.options.heatingStateToSummerWinterMode) { - dst.opentherm.options.heatingStateToSummerWinterMode = value; - changed = true; - } - } - - if (src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_CH2_ALWAYS_ENABLED)].is()) { - bool value = src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_CH2_ALWAYS_ENABLED)].as(); - - if (value != dst.opentherm.options.ch2AlwaysEnabled) { - dst.opentherm.options.ch2AlwaysEnabled = value; - - if (dst.opentherm.options.ch2AlwaysEnabled) { - dst.opentherm.options.heatingToCh2 = false; - dst.opentherm.options.dhwToCh2 = false; - } - - changed = true; - } - } - - if (src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_HEATING_TO_CH2)].is()) { - bool value = src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_HEATING_TO_CH2)].as(); - - if (value != dst.opentherm.options.heatingToCh2) { - dst.opentherm.options.heatingToCh2 = value; - - if (dst.opentherm.options.heatingToCh2) { - dst.opentherm.options.ch2AlwaysEnabled = false; - dst.opentherm.options.dhwToCh2 = false; - } - - changed = true; - } - } - - if (src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_DHW_TO_CH2)].is()) { - bool value = src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_DHW_TO_CH2)].as(); - - if (value != dst.opentherm.options.dhwToCh2) { - dst.opentherm.options.dhwToCh2 = value; - - if (dst.opentherm.options.dhwToCh2) { - dst.opentherm.options.ch2AlwaysEnabled = false; - dst.opentherm.options.heatingToCh2 = false; - } - - changed = true; - } - } - - if (src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_DHW_BLOCKING)].is()) { - bool value = src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_DHW_BLOCKING)].as(); - - if (value != dst.opentherm.options.dhwBlocking) { - dst.opentherm.options.dhwBlocking = value; - changed = true; - } - } - - if (src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_DHW_STATE_AS_DHW_BLOCKING)].is()) { - bool value = src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_DHW_STATE_AS_DHW_BLOCKING)].as(); - - if (value != dst.opentherm.options.dhwStateAsDhwBlocking) { - dst.opentherm.options.dhwStateAsDhwBlocking = value; - changed = true; - } - } - - if (src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_MAX_TEMP_SYNC_WITH_TARGET_TEMP)].is()) { - bool value = src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_MAX_TEMP_SYNC_WITH_TARGET_TEMP)].as(); - - if (value != dst.opentherm.options.maxTempSyncWithTargetTemp) { - dst.opentherm.options.maxTempSyncWithTargetTemp = value; - changed = true; - } - } - - if (src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_GET_MIN_MAX_TEMP)].is()) { - bool value = src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_GET_MIN_MAX_TEMP)].as(); - - if (value != dst.opentherm.options.getMinMaxTemp) { - dst.opentherm.options.getMinMaxTemp = value; - changed = true; - } - } - - if (src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_IGNORE_DIAG_STATE)].is()) { - bool value = src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_IGNORE_DIAG_STATE)].as(); - - if (value != dst.opentherm.options.ignoreDiagState) { - dst.opentherm.options.ignoreDiagState = value; - changed = true; - } - } - - if (src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_AUTO_FAULT_RESET)].is()) { - bool value = src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_AUTO_FAULT_RESET)].as(); - - if (value != dst.opentherm.options.autoFaultReset) { - dst.opentherm.options.autoFaultReset = value; - changed = true; - } - } - - if (src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_AUTO_DIAG_RESET)].is()) { - bool value = src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_AUTO_DIAG_RESET)].as(); - - if (value != dst.opentherm.options.autoDiagReset) { - dst.opentherm.options.autoDiagReset = value; - changed = true; - } - } - - if (src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_SET_DATE_AND_TIME)].is()) { - bool value = src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_SET_DATE_AND_TIME)].as(); - - if (value != dst.opentherm.options.setDateAndTime) { - dst.opentherm.options.setDateAndTime = value; - changed = true; - } - } - - if (src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_ALWAYS_SEND_INDOOR_TEMP)].is()) { - bool value = src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_ALWAYS_SEND_INDOOR_TEMP)].as(); - - if (value != dst.opentherm.options.alwaysSendIndoorTemp) { - dst.opentherm.options.alwaysSendIndoorTemp = value; - changed = true; - } - } - - if (src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_NATIVE_OTC)].is()) { - bool value = src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_NATIVE_OTC)].as(); - - if (value != dst.opentherm.options.nativeOTC) { - dst.opentherm.options.nativeOTC = value; - - if (value) { - dst.equitherm.enabled = false; - dst.pid.enabled = false; - } - - changed = true; - } - } - - if (src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_IMMERGAS_FIX)].is()) { - bool value = src[FPSTR(S_OPENTHERM)][FPSTR(S_OPTIONS)][FPSTR(S_IMMERGAS_FIX)].as(); - - if (value != dst.opentherm.options.immergasFix) { - dst.opentherm.options.immergasFix = value; - changed = true; - } - } - - // mqtt - if (src[FPSTR(S_MQTT)][FPSTR(S_ENABLED)].is()) { - bool value = src[FPSTR(S_MQTT)][FPSTR(S_ENABLED)].as(); - - if (value != dst.mqtt.enabled) { - dst.mqtt.enabled = value; - changed = true; - } - } - - if (!src[FPSTR(S_MQTT)][FPSTR(S_SERVER)].isNull()) { - String value = src[FPSTR(S_MQTT)][FPSTR(S_SERVER)].as(); - - if (value.length() < sizeof(dst.mqtt.server) && !value.equals(dst.mqtt.server)) { - strcpy(dst.mqtt.server, value.c_str()); - changed = true; - } - } - - if (!src[FPSTR(S_MQTT)][FPSTR(S_PORT)].isNull()) { - unsigned short value = src[FPSTR(S_MQTT)][FPSTR(S_PORT)].as(); - - if (value > 0 && value <= 65535 && value != dst.mqtt.port) { - dst.mqtt.port = value; - changed = true; - } - } - - if (!src[FPSTR(S_MQTT)][FPSTR(S_USER)].isNull()) { - String value = src[FPSTR(S_MQTT)][FPSTR(S_USER)].as(); - - if (value.length() < sizeof(dst.mqtt.user) && !value.equals(dst.mqtt.user)) { - strcpy(dst.mqtt.user, value.c_str()); - changed = true; - } - } - - if (!src[FPSTR(S_MQTT)][FPSTR(S_PASSWORD)].isNull()) { - String value = src[FPSTR(S_MQTT)][FPSTR(S_PASSWORD)].as(); - - if (value.length() < sizeof(dst.mqtt.password) && !value.equals(dst.mqtt.password)) { - strcpy(dst.mqtt.password, value.c_str()); - changed = true; - } - } - - if (!src[FPSTR(S_MQTT)][FPSTR(S_PREFIX)].isNull()) { - String value = src[FPSTR(S_MQTT)][FPSTR(S_PREFIX)].as(); - - if (value.length() < sizeof(dst.mqtt.prefix) && !value.equals(dst.mqtt.prefix)) { - strcpy(dst.mqtt.prefix, value.c_str()); - changed = true; - } - } - - if (!src[FPSTR(S_MQTT)][FPSTR(S_INTERVAL)].isNull()) { - unsigned short value = src[FPSTR(S_MQTT)][FPSTR(S_INTERVAL)].as(); - - if (value >= 3 && value <= 60 && value != dst.mqtt.interval) { - dst.mqtt.interval = value; - changed = true; - } - } - - if (src[FPSTR(S_MQTT)][FPSTR(S_HOME_ASSISTANT_DISCOVERY)].is()) { - bool value = src[FPSTR(S_MQTT)][FPSTR(S_HOME_ASSISTANT_DISCOVERY)].as(); - - if (value != dst.mqtt.homeAssistantDiscovery) { - dst.mqtt.homeAssistantDiscovery = value; - changed = true; - } - } - - - // emergency - if (!src[FPSTR(S_EMERGENCY)][FPSTR(S_TRESHOLD_TIME)].isNull()) { - unsigned short value = src[FPSTR(S_EMERGENCY)][FPSTR(S_TRESHOLD_TIME)].as(); - - if (value >= 60 && value <= 1800 && value != dst.emergency.tresholdTime) { - dst.emergency.tresholdTime = value; - changed = true; - } - } - } - - - // equitherm - if (src[FPSTR(S_EQUITHERM)][FPSTR(S_ENABLED)].is()) { - bool value = src[FPSTR(S_EQUITHERM)][FPSTR(S_ENABLED)].as(); - - if (!dst.opentherm.options.nativeOTC) { - if (value != dst.equitherm.enabled) { - dst.equitherm.enabled = value; - changed = true; - } - - } else if (dst.equitherm.enabled) { - dst.equitherm.enabled = false; - changed = true; - } - } - - if (!src[FPSTR(S_EQUITHERM)][FPSTR(S_SLOPE)].isNull()) { - float value = src[FPSTR(S_EQUITHERM)][FPSTR(S_SLOPE)].as(); - - if (value > 0.0f && value <= 10.0f && fabsf(value - dst.equitherm.slope) > 0.0001f) { - dst.equitherm.slope = roundf(value, 3); - changed = true; - } - } - - if (!src[FPSTR(S_EQUITHERM)][FPSTR(S_EXPONENT)].isNull()) { - float value = src[FPSTR(S_EQUITHERM)][FPSTR(S_EXPONENT)].as(); - - if (value > 0.0f && value <= 2.0f && fabsf(value - dst.equitherm.exponent) > 0.0001f) { - dst.equitherm.exponent = roundf(value, 3); - changed = true; - } - } - - if (!src[FPSTR(S_EQUITHERM)][FPSTR(S_SHIFT)].isNull()) { - float value = src[FPSTR(S_EQUITHERM)][FPSTR(S_SHIFT)].as(); - - if (value >= -15.0f && value <= 15.0f && fabsf(value - dst.equitherm.shift) > 0.0001f) { - dst.equitherm.shift = roundf(value, 2); - changed = true; - } - } - - if (!src[FPSTR(S_EQUITHERM)][FPSTR(S_TARGET_DIFF_FACTOR)].isNull()) { - float value = src[FPSTR(S_EQUITHERM)][FPSTR(S_TARGET_DIFF_FACTOR)].as(); - - if (value >= 0.0f && value <= 10.0f && fabsf(value - dst.equitherm.targetDiffFactor) > 0.0001f) { - dst.equitherm.targetDiffFactor = roundf(value, 3); - changed = true; - } - } - - - // pid - if (src[FPSTR(S_PID)][FPSTR(S_ENABLED)].is()) { - bool value = src[FPSTR(S_PID)][FPSTR(S_ENABLED)].as(); - - if (!dst.opentherm.options.nativeOTC) { - if (value != dst.pid.enabled) { - dst.pid.enabled = value; - changed = true; - } - - } else if (dst.pid.enabled) { - dst.pid.enabled = false; - changed = true; - } - } - - if (!src[FPSTR(S_PID)][FPSTR(S_P_FACTOR)].isNull()) { - float value = src[FPSTR(S_PID)][FPSTR(S_P_FACTOR)].as(); - - if (value > 0 && value <= 1000 && fabsf(value - dst.pid.p_factor) > 0.0001f) { - dst.pid.p_factor = roundf(value, 3); - changed = true; - } - } - - if (!src[FPSTR(S_PID)][FPSTR(S_I_FACTOR)].isNull()) { - float value = src[FPSTR(S_PID)][FPSTR(S_I_FACTOR)].as(); - - if (value >= 0 && value <= 100 && fabsf(value - dst.pid.i_factor) > 0.0001f) { - dst.pid.i_factor = roundf(value, 4); - changed = true; - } - } - - if (!src[FPSTR(S_PID)][FPSTR(S_D_FACTOR)].isNull()) { - float value = src[FPSTR(S_PID)][FPSTR(S_D_FACTOR)].as(); - - if (value >= 0 && value <= 100000 && fabsf(value - dst.pid.d_factor) > 0.0001f) { - dst.pid.d_factor = roundf(value, 1); - changed = true; - } - } - - if (!src[FPSTR(S_PID)][FPSTR(S_DT)].isNull()) { - unsigned short value = src[FPSTR(S_PID)][FPSTR(S_DT)].as(); - - if (value >= 30 && value <= 1800 && value != dst.pid.dt) { - dst.pid.dt = value; - changed = true; - } - } - - if (!src[FPSTR(S_PID)][FPSTR(S_MIN_TEMP)].isNull()) { - short value = src[FPSTR(S_PID)][FPSTR(S_MIN_TEMP)].as(); - - if (isValidTemp(value, dst.system.unitSystem, dst.equitherm.enabled ? -99.9f : 0.0f) && value != dst.pid.minTemp) { - dst.pid.minTemp = value; - changed = true; - } - } - - if (!src[FPSTR(S_PID)][FPSTR(S_MAX_TEMP)].isNull()) { - short value = src[FPSTR(S_PID)][FPSTR(S_MAX_TEMP)].as(); - - if (isValidTemp(value, dst.system.unitSystem) && value != dst.pid.maxTemp) { - dst.pid.maxTemp = value; - changed = true; - } - } - - if (dst.pid.maxTemp < dst.pid.minTemp) { - dst.pid.maxTemp = dst.pid.minTemp; - changed = true; - } - - if (src[FPSTR(S_PID)][FPSTR(S_DEADBAND)][FPSTR(S_ENABLED)].is()) { - bool value = src[FPSTR(S_PID)][FPSTR(S_DEADBAND)][FPSTR(S_ENABLED)].as(); - - if (value != dst.pid.deadband.enabled) { - dst.pid.deadband.enabled = value; - changed = true; - } - } - - if (!src[FPSTR(S_PID)][FPSTR(S_DEADBAND)][FPSTR(S_P_MULTIPLIER)].isNull()) { - float value = src[FPSTR(S_PID)][FPSTR(S_DEADBAND)][FPSTR(S_P_MULTIPLIER)].as(); - - if (value >= 0 && value <= 1 && fabsf(value - dst.pid.deadband.p_multiplier) > 0.0001f) { - dst.pid.deadband.p_multiplier = roundf(value, 3); - changed = true; - } - } - - if (!src[FPSTR(S_PID)][FPSTR(S_DEADBAND)][FPSTR(S_I_MULTIPLIER)].isNull()) { - float value = src[FPSTR(S_PID)][FPSTR(S_DEADBAND)][FPSTR(S_I_MULTIPLIER)].as(); - - if (value >= 0 && value <= 1 && fabsf(value - dst.pid.deadband.i_multiplier) > 0.0001f) { - dst.pid.deadband.i_multiplier = roundf(value, 3); - changed = true; - } - } - - if (!src[FPSTR(S_PID)][FPSTR(S_DEADBAND)][FPSTR(S_D_MULTIPLIER)].isNull()) { - float value = src[FPSTR(S_PID)][FPSTR(S_DEADBAND)][FPSTR(S_D_MULTIPLIER)].as(); - - if (value >= 0 && value <= 1 && fabsf(value - dst.pid.deadband.d_multiplier) > 0.0001f) { - dst.pid.deadband.d_multiplier = roundf(value, 3); - changed = true; - } - } - - if (!src[FPSTR(S_PID)][FPSTR(S_DEADBAND)][FPSTR(S_THRESHOLD_HIGH)].isNull()) { - float value = src[FPSTR(S_PID)][FPSTR(S_DEADBAND)][FPSTR(S_THRESHOLD_HIGH)].as(); - - if (value >= 0.0f && value <= 5.0f && fabsf(value - dst.pid.deadband.thresholdHigh) > 0.0001f) { - dst.pid.deadband.thresholdHigh = roundf(value, 2); - changed = true; - } - } - - if (!src[FPSTR(S_PID)][FPSTR(S_DEADBAND)][FPSTR(S_THRESHOLD_LOW)].isNull()) { - float value = src[FPSTR(S_PID)][FPSTR(S_DEADBAND)][FPSTR(S_THRESHOLD_LOW)].as(); - - if (value >= 0.0f && value <= 5.0f && fabsf(value - dst.pid.deadband.thresholdLow) > 0.0001f) { - dst.pid.deadband.thresholdLow = roundf(value, 2); - changed = true; - } - } - - - // heating - if (src[FPSTR(S_HEATING)][FPSTR(S_ENABLED)].is()) { - bool value = src[FPSTR(S_HEATING)][FPSTR(S_ENABLED)].as(); - - if (value != dst.heating.enabled) { - dst.heating.enabled = value; - changed = true; - } - } - - if (src[FPSTR(S_HEATING)][FPSTR(S_TURBO)].is()) { - bool value = src[FPSTR(S_HEATING)][FPSTR(S_TURBO)].as(); - - if (value != dst.heating.turbo) { - dst.heating.turbo = value; - changed = true; - } - } - - if (src[FPSTR(S_HEATING)][FPSTR(S_HYSTERESIS)][FPSTR(S_ENABLED)].is()) { - bool value = src[FPSTR(S_HEATING)][FPSTR(S_HYSTERESIS)][FPSTR(S_ENABLED)].as(); - - if (value != dst.heating.hysteresis.enabled) { - dst.heating.hysteresis.enabled = value; - changed = true; - } - } - - if (!src[FPSTR(S_HEATING)][FPSTR(S_HYSTERESIS)][FPSTR(S_VALUE)].isNull()) { - float value = src[FPSTR(S_HEATING)][FPSTR(S_HYSTERESIS)][FPSTR(S_VALUE)].as(); - - if (value >= 0.0f && value <= 15.0f && fabsf(value - dst.heating.hysteresis.value) > 0.0001f) { - dst.heating.hysteresis.value = roundf(value, 2); - changed = true; - } - } - - if (!src[FPSTR(S_HEATING)][FPSTR(S_HYSTERESIS)][FPSTR(S_ACTION)].isNull()) { - uint8_t value = src[FPSTR(S_HEATING)][FPSTR(S_HYSTERESIS)][FPSTR(S_ACTION)].as(); - - switch (value) { - case static_cast(HysteresisAction::DISABLE_HEATING): - case static_cast(HysteresisAction::SET_ZERO_TARGET): - if (static_cast(dst.heating.hysteresis.action) != value) { - dst.heating.hysteresis.action = static_cast(value); - changed = true; - } - break; - - default: - break; - } - } - - if (!src[FPSTR(S_HEATING)][FPSTR(S_TURBO_FACTOR)].isNull()) { - float value = src[FPSTR(S_HEATING)][FPSTR(S_TURBO_FACTOR)].as(); - - if (value >= 1.5f && value <= 10.0f && fabsf(value - dst.heating.turboFactor) > 0.0001f) { - dst.heating.turboFactor = roundf(value, 3); - changed = true; - } - } - - if (!src[FPSTR(S_HEATING)][FPSTR(S_MIN_TEMP)].isNull()) { - unsigned char value = src[FPSTR(S_HEATING)][FPSTR(S_MIN_TEMP)].as(); - - if (value != dst.heating.minTemp && value >= vars.slave.heating.minTemp && value < vars.slave.heating.maxTemp && value != dst.heating.maxTemp) { - dst.heating.minTemp = value; - changed = true; - } - } - - if (!src[FPSTR(S_HEATING)][FPSTR(S_MAX_TEMP)].isNull()) { - unsigned char value = src[FPSTR(S_HEATING)][FPSTR(S_MAX_TEMP)].as(); - - if (value != dst.heating.maxTemp && value > vars.slave.heating.minTemp && value <= vars.slave.heating.maxTemp && value != dst.heating.minTemp) { - dst.heating.maxTemp = value; - changed = true; - } - } - - if (dst.heating.maxTemp < dst.heating.minTemp) { - dst.heating.maxTemp = dst.heating.minTemp; - changed = true; - } - - - if (!src[FPSTR(S_HEATING)][FPSTR(S_MAX_MODULATION)].isNull()) { - unsigned char value = src[FPSTR(S_HEATING)][FPSTR(S_MAX_MODULATION)].as(); - - if (value > 0 && value <= 100 && value != dst.heating.maxModulation) { - dst.heating.maxModulation = value; - changed = true; - } - } - - if (!src[FPSTR(S_HEATING)][FPSTR(S_OVERHEAT_PROTECTION)][FPSTR(S_HIGH_TEMP)].isNull()) { - unsigned char value = src[FPSTR(S_HEATING)][FPSTR(S_OVERHEAT_PROTECTION)][FPSTR(S_HIGH_TEMP)].as(); - - if (isValidTemp(value, dst.system.unitSystem, 0.0f, 100.0f) && value != dst.heating.overheatProtection.highTemp) { - dst.heating.overheatProtection.highTemp = value; - changed = true; - } - } - - if (!src[FPSTR(S_HEATING)][FPSTR(S_OVERHEAT_PROTECTION)][FPSTR(S_LOW_TEMP)].isNull()) { - unsigned char value = src[FPSTR(S_HEATING)][FPSTR(S_OVERHEAT_PROTECTION)][FPSTR(S_LOW_TEMP)].as(); - - if (isValidTemp(value, dst.system.unitSystem, 0.0f, 99.0f) && value != dst.heating.overheatProtection.lowTemp) { - dst.heating.overheatProtection.lowTemp = value; - changed = true; - } - } - - if (dst.heating.overheatProtection.highTemp < dst.heating.overheatProtection.lowTemp) { - dst.heating.overheatProtection.highTemp = dst.heating.overheatProtection.lowTemp; - changed = true; - } - - if (!src[FPSTR(S_HEATING)][FPSTR(S_FREEZE_PROTECTION)][FPSTR(S_HIGH_TEMP)].isNull()) { - unsigned short value = src[FPSTR(S_HEATING)][FPSTR(S_FREEZE_PROTECTION)][FPSTR(S_HIGH_TEMP)].as(); - - if (isValidTemp(value, dst.system.unitSystem, 1, 50) && value != dst.heating.freezeProtection.highTemp) { - dst.heating.freezeProtection.highTemp = value; - changed = true; - } - } - - if (!src[FPSTR(S_HEATING)][FPSTR(S_FREEZE_PROTECTION)][FPSTR(S_LOW_TEMP)].isNull()) { - unsigned short value = src[FPSTR(S_HEATING)][FPSTR(S_FREEZE_PROTECTION)][FPSTR(S_LOW_TEMP)].as(); - - if (isValidTemp(value, dst.system.unitSystem, 1, 30) && value != dst.heating.freezeProtection.lowTemp) { - dst.heating.freezeProtection.lowTemp = value; - changed = true; - } - } - - if (dst.heating.freezeProtection.highTemp < dst.heating.freezeProtection.lowTemp) { - dst.heating.freezeProtection.highTemp = dst.heating.freezeProtection.lowTemp; - changed = true; - } - - - // dhw - if (src[FPSTR(S_DHW)][FPSTR(S_ENABLED)].is()) { - bool value = src[FPSTR(S_DHW)][FPSTR(S_ENABLED)].as(); - - if (value != dst.dhw.enabled) { - dst.dhw.enabled = value; - changed = true; - } - } - - if (!src[FPSTR(S_DHW)][FPSTR(S_MIN_TEMP)].isNull()) { - unsigned char value = src[FPSTR(S_DHW)][FPSTR(S_MIN_TEMP)].as(); - - if (value >= vars.slave.dhw.minTemp && value < vars.slave.dhw.maxTemp && value != dst.dhw.minTemp) { - dst.dhw.minTemp = value; - changed = true; - } - } - - if (!src[FPSTR(S_DHW)][FPSTR(S_MAX_TEMP)].isNull()) { - unsigned char value = src[FPSTR(S_DHW)][FPSTR(S_MAX_TEMP)].as(); - - if (value > vars.slave.dhw.minTemp && value <= vars.slave.dhw.maxTemp && value != dst.dhw.maxTemp) { - dst.dhw.maxTemp = value; - changed = true; - } - } - - if (dst.dhw.maxTemp < dst.dhw.minTemp) { - dst.dhw.maxTemp = dst.dhw.minTemp; - changed = true; - } - - if (!src[FPSTR(S_DHW)][FPSTR(S_MAX_MODULATION)].isNull()) { - unsigned char value = src[FPSTR(S_DHW)][FPSTR(S_MAX_MODULATION)].as(); - - if (value > 0 && value <= 100 && value != dst.dhw.maxModulation) { - dst.dhw.maxModulation = value; - changed = true; - } - } - - if (!src[FPSTR(S_DHW)][FPSTR(S_OVERHEAT_PROTECTION)][FPSTR(S_HIGH_TEMP)].isNull()) { - unsigned char value = src[FPSTR(S_DHW)][FPSTR(S_OVERHEAT_PROTECTION)][FPSTR(S_HIGH_TEMP)].as(); - - if (isValidTemp(value, dst.system.unitSystem, 0.0f, 100.0f) && value != dst.dhw.overheatProtection.highTemp) { - dst.dhw.overheatProtection.highTemp = value; - changed = true; - } - } - - if (!src[FPSTR(S_DHW)][FPSTR(S_OVERHEAT_PROTECTION)][FPSTR(S_LOW_TEMP)].isNull()) { - unsigned char value = src[FPSTR(S_DHW)][FPSTR(S_OVERHEAT_PROTECTION)][FPSTR(S_LOW_TEMP)].as(); - - if (isValidTemp(value, dst.system.unitSystem, 0.0f, 99.0f) && value != dst.dhw.overheatProtection.lowTemp) { - dst.dhw.overheatProtection.lowTemp = value; - changed = true; - } - } - - if (dst.dhw.overheatProtection.highTemp < dst.dhw.overheatProtection.lowTemp) { - dst.dhw.overheatProtection.highTemp = dst.dhw.overheatProtection.lowTemp; - changed = true; - } - - - if (!safe) { - // external pump - if (src[FPSTR(S_EXTERNAL_PUMP)][FPSTR(S_USE)].is()) { - bool value = src[FPSTR(S_EXTERNAL_PUMP)][FPSTR(S_USE)].as(); - - if (value != dst.externalPump.use) { - dst.externalPump.use = value; - changed = true; - } - } - - if (!src[FPSTR(S_EXTERNAL_PUMP)][FPSTR(S_GPIO)].isNull()) { - if (src[FPSTR(S_EXTERNAL_PUMP)][FPSTR(S_GPIO)].is() && src[FPSTR(S_EXTERNAL_PUMP)][FPSTR(S_GPIO)].as().size() == 0) { - if (dst.externalPump.gpio != GPIO_IS_NOT_CONFIGURED) { - dst.externalPump.gpio = GPIO_IS_NOT_CONFIGURED; - changed = true; - } - - } else { - unsigned char value = src[FPSTR(S_EXTERNAL_PUMP)][FPSTR(S_GPIO)].as(); - - if (GPIO_IS_VALID(value) && value != dst.externalPump.gpio) { - dst.externalPump.gpio = value; - changed = true; - } - } - } - - if (src[FPSTR(S_EXTERNAL_PUMP)][FPSTR(S_INVERT_STATE)].is()) { - bool value = src[FPSTR(S_EXTERNAL_PUMP)][FPSTR(S_INVERT_STATE)].as(); - - if (value != dst.externalPump.invertState) { - dst.externalPump.invertState = value; - changed = true; - } - } - - if (!src[FPSTR(S_EXTERNAL_PUMP)][FPSTR(S_POST_CIRCULATION_TIME)].isNull()) { - unsigned short value = src[FPSTR(S_EXTERNAL_PUMP)][FPSTR(S_POST_CIRCULATION_TIME)].as(); - - if (value >= 0 && value <= 120) { - value = value * 60; - - if (value != dst.externalPump.postCirculationTime) { - dst.externalPump.postCirculationTime = value; - changed = true; - } - } - } - - if (!src[FPSTR(S_EXTERNAL_PUMP)][FPSTR(S_ANTI_STUCK_INTERVAL)].isNull()) { - unsigned int value = src[FPSTR(S_EXTERNAL_PUMP)][FPSTR(S_ANTI_STUCK_INTERVAL)].as(); - - if (value >= 0 && value <= 366) { - value = value * 86400; - - if (value != dst.externalPump.antiStuckInterval) { - dst.externalPump.antiStuckInterval = value; - changed = true; - } - } - } - - if (!src[FPSTR(S_EXTERNAL_PUMP)][FPSTR(S_ANTI_STUCK_TIME)].isNull()) { - unsigned short value = src[FPSTR(S_EXTERNAL_PUMP)][FPSTR(S_ANTI_STUCK_TIME)].as(); - - if (value >= 0 && value <= 20) { - value = value * 60; - - if (value != dst.externalPump.antiStuckTime) { - dst.externalPump.antiStuckTime = value; - changed = true; - } - } - } - - - // cascade control - if (src[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_INPUT)][FPSTR(S_ENABLED)].is()) { - bool value = src[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_INPUT)][FPSTR(S_ENABLED)].as(); - - if (value != dst.cascadeControl.input.enabled) { - dst.cascadeControl.input.enabled = value; - changed = true; - } - } - - if (!src[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_INPUT)][FPSTR(S_GPIO)].isNull()) { - if (src[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_INPUT)][FPSTR(S_GPIO)].is() && src[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_INPUT)][FPSTR(S_GPIO)].as().size() == 0) { - if (dst.cascadeControl.input.gpio != GPIO_IS_NOT_CONFIGURED) { - dst.cascadeControl.input.gpio = GPIO_IS_NOT_CONFIGURED; - changed = true; - } - - } else { - unsigned char value = src[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_INPUT)][FPSTR(S_GPIO)].as(); - - if (GPIO_IS_VALID(value) && value != dst.cascadeControl.input.gpio) { - dst.cascadeControl.input.gpio = value; - changed = true; - } - } - } - - if (src[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_INPUT)][FPSTR(S_INVERT_STATE)].is()) { - bool value = src[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_INPUT)][FPSTR(S_INVERT_STATE)].as(); - - if (value != dst.cascadeControl.input.invertState) { - dst.cascadeControl.input.invertState = value; - changed = true; - } - } - - if (!src[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_INPUT)][FPSTR(S_THRESHOLD_TIME)].isNull()) { - unsigned short value = src[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_INPUT)][FPSTR(S_THRESHOLD_TIME)].as(); - - if (value >= 5 && value <= 600) { - if (value != dst.cascadeControl.input.thresholdTime) { - dst.cascadeControl.input.thresholdTime = value; - changed = true; - } - } - } - - if (src[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_OUTPUT)][FPSTR(S_ENABLED)].is()) { - bool value = src[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_OUTPUT)][FPSTR(S_ENABLED)].as(); - - if (value != dst.cascadeControl.output.enabled) { - dst.cascadeControl.output.enabled = value; - changed = true; - } - } - - if (!src[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_OUTPUT)][FPSTR(S_GPIO)].isNull()) { - if (src[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_OUTPUT)][FPSTR(S_GPIO)].is() && src[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_OUTPUT)][FPSTR(S_GPIO)].as().size() == 0) { - if (dst.cascadeControl.output.gpio != GPIO_IS_NOT_CONFIGURED) { - dst.cascadeControl.output.gpio = GPIO_IS_NOT_CONFIGURED; - changed = true; - } - - } else { - unsigned char value = src[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_OUTPUT)][FPSTR(S_GPIO)].as(); - - if (GPIO_IS_VALID(value) && value != dst.cascadeControl.output.gpio) { - dst.cascadeControl.output.gpio = value; - changed = true; - } - } - } - - if (src[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_OUTPUT)][FPSTR(S_INVERT_STATE)].is()) { - bool value = src[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_OUTPUT)][FPSTR(S_INVERT_STATE)].as(); - - if (value != dst.cascadeControl.output.invertState) { - dst.cascadeControl.output.invertState = value; - changed = true; - } - } - - if (!src[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_OUTPUT)][FPSTR(S_THRESHOLD_TIME)].isNull()) { - unsigned short value = src[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_OUTPUT)][FPSTR(S_THRESHOLD_TIME)].as(); - - if (value >= 5 && value <= 600) { - if (value != dst.cascadeControl.output.thresholdTime) { - dst.cascadeControl.output.thresholdTime = value; - changed = true; - } - } - } - - if (src[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_OUTPUT)][FPSTR(S_ON_FAULT)].is()) { - bool value = src[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_OUTPUT)][FPSTR(S_ON_FAULT)].as(); - - if (value != dst.cascadeControl.output.onFault) { - dst.cascadeControl.output.onFault = value; - changed = true; - } - } - - if (src[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_OUTPUT)][FPSTR(S_ON_LOSS_CONNECTION)].is()) { - bool value = src[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_OUTPUT)][FPSTR(S_ON_LOSS_CONNECTION)].as(); - - if (value != dst.cascadeControl.output.onLossConnection) { - dst.cascadeControl.output.onLossConnection = value; - changed = true; - } - } - - if (src[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_OUTPUT)][FPSTR(S_ON_ENABLED_HEATING)].is()) { - bool value = src[FPSTR(S_CASCADE_CONTROL)][FPSTR(S_OUTPUT)][FPSTR(S_ON_ENABLED_HEATING)].as(); - - if (value != dst.cascadeControl.output.onEnabledHeating) { - dst.cascadeControl.output.onEnabledHeating = value; - changed = true; - } - } - } - - // force check emergency target - { - float value = !src[FPSTR(S_EMERGENCY)][FPSTR(S_TARGET)].isNull() ? src[FPSTR(S_EMERGENCY)][FPSTR(S_TARGET)].as() : dst.emergency.target; - bool noRegulators = !dst.opentherm.options.nativeOTC; - bool valid = isValidTemp( - value, - dst.system.unitSystem, - noRegulators ? dst.heating.minTemp : THERMOSTAT_INDOOR_MIN_TEMP, - noRegulators ? dst.heating.maxTemp : THERMOSTAT_INDOOR_MAX_TEMP, - noRegulators ? dst.system.unitSystem : UnitSystem::METRIC - ); - - if (!valid) { - value = convertTemp( - noRegulators ? DEFAULT_HEATING_TARGET_TEMP : THERMOSTAT_INDOOR_DEFAULT_TEMP, - UnitSystem::METRIC, - dst.system.unitSystem - ); - } - - if (fabsf(dst.emergency.target - value) > 0.0001f) { - dst.emergency.target = roundf(value, 2); - changed = true; - } - } - - // force check heating target - { - bool indoorTempControl = dst.equitherm.enabled || dst.pid.enabled || dst.opentherm.options.nativeOTC; - float minTemp = indoorTempControl ? THERMOSTAT_INDOOR_MIN_TEMP : dst.heating.minTemp; - float maxTemp = indoorTempControl ? THERMOSTAT_INDOOR_MAX_TEMP : dst.heating.maxTemp; - - float value = !src[FPSTR(S_HEATING)][FPSTR(S_TARGET)].isNull() - ? src[FPSTR(S_HEATING)][FPSTR(S_TARGET)].as() - : dst.heating.target; - bool valid = isValidTemp( - value, - dst.system.unitSystem, - minTemp, - maxTemp, - dst.system.unitSystem - ); - - if (!valid) { - value = convertTemp( - indoorTempControl ? THERMOSTAT_INDOOR_DEFAULT_TEMP : DEFAULT_HEATING_TARGET_TEMP, - UnitSystem::METRIC, - dst.system.unitSystem - ); - } - - if (fabsf(dst.heating.target - value) > 0.0001f) { - dst.heating.target = roundf(value, 2); - changed = true; - } - } - - // force check dhw target - { - float value = !src[FPSTR(S_DHW)][FPSTR(S_TARGET)].isNull() - ? src[FPSTR(S_DHW)][FPSTR(S_TARGET)].as() - : dst.dhw.target; - bool valid = isValidTemp( - value, - dst.system.unitSystem, - dst.dhw.minTemp, - dst.dhw.maxTemp, - dst.system.unitSystem - ); - - if (!valid) { - value = convertTemp(DEFAULT_DHW_TARGET_TEMP, UnitSystem::METRIC, dst.system.unitSystem); - } - - if (fabsf(dst.dhw.target - value) > 0.0001f) { - dst.dhw.target = value; - changed = true; - } - } - - return changed; -} - -inline bool safeJsonToSettings(const JsonVariantConst src, Settings& dst) { - return jsonToSettings(src, dst, true); -} - -void sensorSettingsToJson(const uint8_t sensorId, const Sensors::Settings& src, JsonVariant dst) { - dst[FPSTR(S_ID)] = sensorId; - dst[FPSTR(S_ENABLED)] = src.enabled; - dst[FPSTR(S_NAME)] = src.name; - dst[FPSTR(S_PURPOSE)] = static_cast(src.purpose); - dst[FPSTR(S_TYPE)] = static_cast(src.type); - dst[FPSTR(S_GPIO)] = src.gpio; - - if (src.type == Sensors::Type::DALLAS_TEMP) { - char addr[24]; - sprintf_P( - addr, - PSTR("%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx"), - src.address[0], src.address[1], src.address[2], src.address[3], - src.address[4], src.address[5], src.address[6], src.address[7] - ); - dst[FPSTR(S_ADDRESS)] = String(addr); - - } else if (src.type == Sensors::Type::BLUETOOTH) { - char addr[18]; - sprintf_P( - addr, - PSTR("%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx"), - src.address[0], src.address[1], src.address[2], - src.address[3], src.address[4], src.address[5] - ); - dst[FPSTR(S_ADDRESS)] = String(addr); - - } else { - dst[FPSTR(S_ADDRESS)] = ""; - } - - dst[FPSTR(S_OFFSET)] = roundf(src.offset, 3); - dst[FPSTR(S_FACTOR)] = roundf(src.factor, 3); - dst[FPSTR(S_FILTERING)] = src.filtering; - dst[FPSTR(S_FILTERING_FACTOR)] = roundf(src.filteringFactor, 3); -} - -bool jsonToSensorSettings(const uint8_t sensorId, const JsonVariantConst src, Sensors::Settings& dst) { - if (sensorId > Sensors::getMaxSensorId()) { - return false; - } - - bool changed = false; - - // enabled - if (src[FPSTR(S_ENABLED)].is()) { - auto value = src[FPSTR(S_ENABLED)].as(); - - if (value != dst.enabled) { - dst.enabled = value; - changed = true; - } - } - - // name - if (!src[FPSTR(S_NAME)].isNull()) { - auto value = src[FPSTR(S_NAME)].as(); - Sensors::cleanName(value); - - if (value.length() < sizeof(dst.name) && !value.equals(dst.name)) { - strcpy(dst.name, value.c_str()); - changed = true; - } - } - - // purpose - if (!src[FPSTR(S_PURPOSE)].isNull()) { - uint8_t value = src[FPSTR(S_PURPOSE)].as(); - - switch (value) { - case static_cast(Sensors::Purpose::OUTDOOR_TEMP): - case static_cast(Sensors::Purpose::INDOOR_TEMP): - case static_cast(Sensors::Purpose::HEATING_TEMP): - case static_cast(Sensors::Purpose::HEATING_RETURN_TEMP): - case static_cast(Sensors::Purpose::DHW_TEMP): - case static_cast(Sensors::Purpose::DHW_RETURN_TEMP): - case static_cast(Sensors::Purpose::DHW_FLOW_RATE): - case static_cast(Sensors::Purpose::EXHAUST_TEMP): - case static_cast(Sensors::Purpose::MODULATION_LEVEL): - - case static_cast(Sensors::Purpose::NUMBER): - case static_cast(Sensors::Purpose::POWER_FACTOR): - case static_cast(Sensors::Purpose::POWER): - case static_cast(Sensors::Purpose::FAN_SPEED): - case static_cast(Sensors::Purpose::CO2): - case static_cast(Sensors::Purpose::PRESSURE): - case static_cast(Sensors::Purpose::HUMIDITY): - case static_cast(Sensors::Purpose::TEMPERATURE): - case static_cast(Sensors::Purpose::NOT_CONFIGURED): - if (static_cast(dst.purpose) != value) { - dst.purpose = static_cast(value); - changed = true; - } - break; - - default: - break; - } - } - - // type - if (!src[FPSTR(S_TYPE)].isNull()) { - uint8_t value = src[FPSTR(S_TYPE)].as(); - - switch (value) { - case static_cast(Sensors::Type::OT_OUTDOOR_TEMP): - case static_cast(Sensors::Type::OT_HEATING_TEMP): - case static_cast(Sensors::Type::OT_HEATING_RETURN_TEMP): - case static_cast(Sensors::Type::OT_DHW_TEMP): - case static_cast(Sensors::Type::OT_DHW_TEMP2): - case static_cast(Sensors::Type::OT_DHW_FLOW_RATE): - case static_cast(Sensors::Type::OT_CH2_TEMP): - case static_cast(Sensors::Type::OT_EXHAUST_TEMP): - case static_cast(Sensors::Type::OT_HEAT_EXCHANGER_TEMP): - case static_cast(Sensors::Type::OT_PRESSURE): - case static_cast(Sensors::Type::OT_MODULATION_LEVEL): - case static_cast(Sensors::Type::OT_CURRENT_POWER): - case static_cast(Sensors::Type::OT_EXHAUST_CO2): - case static_cast(Sensors::Type::OT_EXHAUST_FAN_SPEED): - case static_cast(Sensors::Type::OT_SUPPLY_FAN_SPEED): - case static_cast(Sensors::Type::OT_SOLAR_STORAGE_TEMP): - case static_cast(Sensors::Type::OT_SOLAR_COLLECTOR_TEMP): - case static_cast(Sensors::Type::OT_FAN_SPEED_SETPOINT): - case static_cast(Sensors::Type::OT_FAN_SPEED_CURRENT): - - case static_cast(Sensors::Type::OT_BURNER_STARTS): - case static_cast(Sensors::Type::OT_DHW_BURNER_STARTS): - case static_cast(Sensors::Type::OT_HEATING_PUMP_STARTS): - case static_cast(Sensors::Type::OT_DHW_PUMP_STARTS): - case static_cast(Sensors::Type::OT_BURNER_HOURS): - case static_cast(Sensors::Type::OT_DHW_BURNER_HOURS): - case static_cast(Sensors::Type::OT_HEATING_PUMP_HOURS): - case static_cast(Sensors::Type::OT_DHW_PUMP_HOURS): - case static_cast(Sensors::Type::OT_COOLING_HOURS): - - case static_cast(Sensors::Type::NTC_10K_TEMP): - case static_cast(Sensors::Type::DALLAS_TEMP): - case static_cast(Sensors::Type::BLUETOOTH): - case static_cast(Sensors::Type::HEATING_SETPOINT_TEMP): - case static_cast(Sensors::Type::MANUAL): - case static_cast(Sensors::Type::NOT_CONFIGURED): - if (static_cast(dst.type) != value) { - dst.type = static_cast(value); - changed = true; - } - break; - - default: - break; - } - } - - // gpio - if (!src[FPSTR(S_GPIO)].isNull()) { - if (dst.type != Sensors::Type::DALLAS_TEMP && dst.type != Sensors::Type::NTC_10K_TEMP) { - if (dst.gpio != GPIO_IS_NOT_CONFIGURED) { - dst.gpio = GPIO_IS_NOT_CONFIGURED; - changed = true; - } - - } else if (src[FPSTR(S_GPIO)].is() && src[FPSTR(S_GPIO)].as().size() == 0) { - if (dst.gpio != GPIO_IS_NOT_CONFIGURED) { - dst.gpio = GPIO_IS_NOT_CONFIGURED; - changed = true; - } - - } else { - unsigned char value = src[FPSTR(S_GPIO)].as(); - - if (GPIO_IS_VALID(value) && value != dst.gpio) { - dst.gpio = value; - changed = true; - } - } - } - - // address - if (!src[FPSTR(S_ADDRESS)].isNull()) { - String value = src[FPSTR(S_ADDRESS)].as(); - - if (dst.type == Sensors::Type::DALLAS_TEMP) { - uint8_t tmp[8]; - int parsed = sscanf( - value.c_str(), - "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx", - &tmp[0], &tmp[1], &tmp[2], &tmp[3], - &tmp[4], &tmp[5], &tmp[6], &tmp[7] - ); - - if (parsed == 8) { - for (uint8_t i = 0; i < parsed; i++) { - if (dst.address[i] != tmp[i]) { - dst.address[i] = tmp[i]; - changed = true; - } - } - - } else { - // reset - for (uint8_t i = 0; i < sizeof(dst.address); i++) { - dst.address[i] = 0x00; - } - - changed = true; - } - - } else if (dst.type == Sensors::Type::BLUETOOTH) { - uint8_t tmp[6]; - int parsed = sscanf( - value.c_str(), - "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx", - &tmp[0], &tmp[1], &tmp[2], - &tmp[3], &tmp[4], &tmp[5] - ); - - if (parsed == 6) { - for (uint8_t i = 0; i < parsed; i++) { - if (dst.address[i] != tmp[i]) { - dst.address[i] = tmp[i]; - changed = true; - } - } - - } else { - // reset - for (uint8_t i = 0; i < sizeof(dst.address); i++) { - dst.address[i] = 0x00; - } - - changed = true; - } - } - } - - // offset - if (!src[FPSTR(S_OFFSET)].isNull()) { - float value = src[FPSTR(S_OFFSET)].as(); - - if (value >= -20.0f && value <= 20.0f && fabsf(value - dst.offset) > 0.0001f) { - dst.offset = roundf(value, 2); - changed = true; - } - } - - // factor - if (!src[FPSTR(S_FACTOR)].isNull()) { - float value = src[FPSTR(S_FACTOR)].as(); - - if (value > 0.09f && value <= 100.0f && fabsf(value - dst.factor) > 0.0001f) { - dst.factor = roundf(value, 3); - changed = true; - } - } - - // filtering - if (src[FPSTR(S_FILTERING)].is()) { - auto value = src[FPSTR(S_FILTERING)].as(); - - if (value != dst.filtering) { - dst.filtering = value; - changed = true; - } - } - - // filtering factor - if (!src[FPSTR(S_FILTERING_FACTOR)].isNull()) { - float value = src[FPSTR(S_FILTERING_FACTOR)].as(); - - if (value > 0 && value <= 1 && fabsf(value - dst.filteringFactor) > 0.0001f) { - dst.filteringFactor = roundf(value, 3); - changed = true; - } - } - - return changed; -} - -void sensorResultToJson(const uint8_t sensorId, JsonVariant dst) { - if (!Sensors::isValidSensorId(sensorId)) { - return; - } - - auto& sSensor = Sensors::settings[sensorId]; - auto& rSensor = Sensors::results[sensorId]; - - //dst[FPSTR(S_ID)] = sensorId; - dst[FPSTR(S_CONNECTED)] = rSensor.connected; - dst[FPSTR(S_SIGNAL_QUALITY)] = rSensor.signalQuality; - - if (sSensor.type == Sensors::Type::BLUETOOTH) { - dst[FPSTR(S_TEMPERATURE)] = roundf(rSensor.values[static_cast(Sensors::ValueType::TEMPERATURE)], 3); - dst[FPSTR(S_HUMIDITY)] = roundf(rSensor.values[static_cast(Sensors::ValueType::HUMIDITY)], 3); - dst[FPSTR(S_BATTERY)] = roundf(rSensor.values[static_cast(Sensors::ValueType::BATTERY)], 1); - dst[FPSTR(S_RSSI)] = roundf(rSensor.values[static_cast(Sensors::ValueType::RSSI)], 0); - - } else { - dst[FPSTR(S_VALUE)] = roundf(rSensor.values[static_cast(Sensors::ValueType::PRIMARY)], 3); - } -} - -bool jsonToSensorResult(const uint8_t sensorId, const JsonVariantConst src) { - if (!Sensors::isValidSensorId(sensorId)) { - return false; - } - - auto& sSensor = Sensors::settings[sensorId]; - if (!sSensor.enabled || sSensor.type != Sensors::Type::MANUAL) { - return false; - } - - // value - if (!src[FPSTR(S_VALUE)].isNull()) { - return Sensors::setValueById( - sensorId, - src[FPSTR(S_VALUE)].as(), - Sensors::ValueType::PRIMARY, - true, - true - ); - } - - return false; -} - -void varsToJson(const Variables& src, JsonVariant dst) { - auto slave = dst[FPSTR(S_SLAVE)].to(); - slave[FPSTR(S_MEMBER_ID)] = src.slave.memberId; - slave[FPSTR(S_FLAGS)] = src.slave.flags; - slave[FPSTR(S_TYPE)] = src.slave.type; - slave[FPSTR(S_APP_VERSION)] = src.slave.appVersion; - slave[FPSTR(S_PROTOCOL_VERSION)] = src.slave.protocolVersion; - slave[FPSTR(S_CONNECTED)] = src.slave.connected; - slave[FPSTR(S_FLAME)] = src.slave.flame; - - auto sCooling = slave[FPSTR(S_COOLING)].to(); - sCooling[FPSTR(S_ACTIVE)] = src.slave.cooling.active; - sCooling[FPSTR(S_SETPOINT)] = src.slave.cooling.setpoint; - - auto sModulation = slave[FPSTR(S_MODULATION)].to(); - sModulation[FPSTR(S_MIN)] = src.slave.modulation.min; - sModulation[FPSTR(S_MAX)] = src.slave.modulation.max; - - auto sPower = slave[FPSTR(S_POWER)].to(); - sPower[FPSTR(S_MIN)] = roundf(src.slave.power.min, 2); - sPower[FPSTR(S_MAX)] = roundf(src.slave.power.max, 2); - - auto sHeating = slave[FPSTR(S_HEATING)].to(); - sHeating[FPSTR(S_ACTIVE)] = src.slave.heating.active; - sHeating[FPSTR(S_MIN_TEMP)] = src.slave.heating.minTemp; - sHeating[FPSTR(S_MAX_TEMP)] = src.slave.heating.maxTemp; - - auto sDhw = slave[FPSTR(S_DHW)].to(); - sDhw[FPSTR(S_ACTIVE)] = src.slave.dhw.active; - sDhw[FPSTR(S_MIN_TEMP)] = src.slave.dhw.minTemp; - sDhw[FPSTR(S_MAX_TEMP)] = src.slave.dhw.maxTemp; - - auto sFault = slave[FPSTR(S_FAULT)].to(); - sFault[FPSTR(S_ACTIVE)] = src.slave.fault.active; - sFault[FPSTR(S_CODE)] = src.slave.fault.code; - - auto sDiag = slave[FPSTR(S_DIAG)].to(); - sDiag[FPSTR(S_ACTIVE)] = src.slave.diag.active; - sDiag[FPSTR(S_CODE)] = src.slave.diag.code; - - - auto master = dst[FPSTR(S_MASTER)].to(); - auto mHeating = master[FPSTR(S_HEATING)].to(); - mHeating[FPSTR(S_ENABLED)] = src.master.heating.enabled; - mHeating[FPSTR(S_BLOCKING)] = src.master.heating.blocking; - mHeating[FPSTR(S_INDOOR_TEMP_CONTROL)] = src.master.heating.indoorTempControl; - mHeating[FPSTR(S_OVERHEAT)] = src.master.heating.overheat; - mHeating[FPSTR(S_FREEZING)] = src.master.heating.freezing; - mHeating[FPSTR(S_SETPOINT_TEMP)] = roundf(src.master.heating.setpointTemp, 2); - mHeating[FPSTR(S_TARGET_TEMP)] = roundf(src.master.heating.targetTemp, 2); - mHeating[FPSTR(S_CURRENT_TEMP)] = roundf(src.master.heating.currentTemp, 2); - mHeating[FPSTR(S_RETURN_TEMP)] = roundf(src.master.heating.returnTemp, 2); - mHeating[FPSTR(S_INDOOR_TEMP)] = roundf(src.master.heating.indoorTemp, 2); - mHeating[FPSTR(S_OUTDOOR_TEMP)] = roundf(src.master.heating.outdoorTemp, 2); - mHeating[FPSTR(S_MIN_TEMP)] = roundf(src.master.heating.minTemp, 2); - mHeating[FPSTR(S_MAX_TEMP)] = roundf(src.master.heating.maxTemp, 2); - - auto mDhw = master[FPSTR(S_DHW)].to(); - mDhw[FPSTR(S_ENABLED)] = src.master.dhw.enabled; - mDhw[FPSTR(S_OVERHEAT)] = src.master.dhw.overheat; - mDhw[FPSTR(S_TARGET_TEMP)] = roundf(src.master.dhw.targetTemp, 2); - mDhw[FPSTR(S_CURRENT_TEMP)] = roundf(src.master.dhw.currentTemp, 2); - mDhw[FPSTR(S_RETURN_TEMP)] = roundf(src.master.dhw.returnTemp, 2); - mDhw[FPSTR(S_MIN_TEMP)] = settings.dhw.minTemp; - mDhw[FPSTR(S_MAX_TEMP)] = settings.dhw.maxTemp; - - master[FPSTR(S_NETWORK)][FPSTR(S_CONNECTED)] = src.network.connected; - master[FPSTR(S_NETWORK)][FPSTR(S_RSSI)] = src.network.rssi; - master[FPSTR(S_NETWORK)][FPSTR(S_CONNECTION_TYPE)] = NetworkUtils::NetworkMgr::uplinkName(src.network.connectionType); - master[FPSTR(S_MQTT)][FPSTR(S_CONNECTED)] = src.mqtt.connected; - master[FPSTR(S_EMERGENCY)][FPSTR(S_STATE)] = src.emergency.state; - master[FPSTR(S_EXTERNAL_PUMP)][FPSTR(S_STATE)] = src.externalPump.state; - - auto mCascadeControl = master[FPSTR(S_CASCADE_CONTROL)].to(); - mCascadeControl[FPSTR(S_INPUT)] = src.cascadeControl.input; - mCascadeControl[FPSTR(S_OUTPUT)] = src.cascadeControl.output; - - master[FPSTR(S_UPTIME)] = millis() / 1000; -} - -bool jsonToVars(const JsonVariantConst src, Variables& dst) { - bool changed = false; - - // actions - if (src[FPSTR(S_ACTIONS)][FPSTR(S_RESTART)].is() && src[FPSTR(S_ACTIONS)][FPSTR(S_RESTART)].as()) { - dst.actions.restart = true; - } - - if (src[FPSTR(S_ACTIONS)][FPSTR(S_RESET_FAULT)].is() && src[FPSTR(S_ACTIONS)][FPSTR(S_RESET_FAULT)].as()) { - dst.actions.resetFault = true; - } - - if (src[FPSTR(S_ACTIONS)][FPSTR(S_RESET_DIAGNOSTIC)].is() && src[FPSTR(S_ACTIONS)][FPSTR(S_RESET_DIAGNOSTIC)].as()) { - dst.actions.resetDiagnostic = true; - } - - return changed; -} \ No newline at end of file diff --git a/src_data/locales/cn.json b/src_data/locales/cn.json index 961d724..116a442 100644 --- a/src_data/locales/cn.json +++ b/src_data/locales/cn.json @@ -8,15 +8,21 @@ "issues": "问题与反馈", "releases": "发行版" }, - "dbm": "dBm", - "kw": "kW", - "time": { + "units": { "days": "天", "hours": "小时", "min": "分", - "sec": "秒" + "sec": "秒", + "dbm": "dBm", + "mhz": "MHz", + "kw": "kW", + "rpm": "RPM", + "ppm": "ppm", + "byte": "byte", + "mbyte": "MB", + "liter": "升", + "gallon": "加仑" }, - "button": { "upgrade": "固件升级", "restart": "重启", @@ -31,26 +37,25 @@ "success": "成功", "error": "错误" }, - "index": { "title": "OpenTherm Gateway", - "section": { "network": "网络", "system": "系统" }, - "system": { "build": { "title": "Build", "version": "固件版本", + "commit": "Commit", "date": "日期", "core": "内核版本", "sdk": "SDK" }, "uptime": "运行时间", "memory": { - "title": "可用内存", + "heap": "内存 (heap)", + "psram": "内存 (PSRAM)", "maxFreeBlock": "max free block", "min": "min" }, @@ -61,32 +66,28 @@ "freq": "频率" }, "flash": { - "size": "闪存容量", - "realSize": "实际容量" + "size": "闪存容量" }, - "lastResetReason": "上次重置原因" + "lastResetReason": "上次重置原因", + "coreDump": "内存转储" } }, - "dashboard": { "name": "仪表盘", "title": "仪表盘 - OpenTherm Gateway", - "section": { "control": "调节", "states": "状态", "sensors": "传感器", "diag": "OpenTherm 诊断" }, - "thermostat": { "heating": "供暖", "dhw": "生活热水", - "temp.current": "当前温度", + "currentTemp": "当前温度", "enable": "启用", "turbo": "Turbo 模式" }, - "notify": { "fault": { "title": "锅炉报警状态已激活!", @@ -98,7 +99,6 @@ }, "reset": "点击复位" }, - "states": { "mNetworkConnected": "网络连接状态", "mMqttConnected": "MQTT服务器连接状态", @@ -106,7 +106,6 @@ "mExtPumpState": "外置循环泵", "mCascadeControlInput": "Cascade 控制 (input)", "mCascadeControlOutput": "Cascade 控制 (output)", - "sConnected": "OpenTherm 通讯状态", "sFlame": "火焰", "sCoolingActive": "制冷", @@ -115,10 +114,10 @@ "sFaultCode": "报警代码", "sDiagActive": "诊断状态", "sDiagCode": "诊断代码", - "mHeatEnabled": "供暖功能已启用", "mHeatBlocking": "供暖", "mHeatOverheat": "供暖超热保护", + "mHeatFreezing": "防冻保护", "sHeatActive": "供暖激活状态", "mHeatSetpointTemp": "供暖供水设定温度", "mHeatTargetTemp": "供暖供水目标温度", @@ -126,7 +125,6 @@ "mHeatRetTemp": "供暖回水温度", "mHeatIndoorTemp": "供暖,室内温度", "mHeatOutdoorTemp": "供暖,室外温度", - "mDhwEnabled": "生活热水功能已启用", "mDhwOverheat": "生活热水超热保护", "sDhwActive": "生活热水激活", @@ -134,7 +132,6 @@ "mDhwCurrTemp": "生活热水当前出水温度", "mDhwRetTemp": "生活热水回水温度" }, - "sensors": { "values": { "temp": "温度", @@ -144,28 +141,30 @@ } } }, - "network": { "title": "网络 - OpenTherm Gateway", "name": "网络设置", - + "type": { + "title": "连接方式", + "wifi": "Wi-Fi", + "ethernet": "Ethernet" + }, "section": { "static": "静态设置", "ethernet": "以太网", + "wifi": "Wi-Fi", "availableNetworks": "可用网络", "staSettings": "WiFi 设置", "apSettings": "AP 设置" }, - "scan": { "pos": "#", "info": "Info", - "unavailable": "请启用 WiFi 以扫描网络" + "unavailable": "仅在 Wi-Fi 模式下可扫描网络。" }, "ethernet": { - "enable": "启用以太网", - "notConfigured": "填写全部六个 GPIO 引脚后才能启用以太网。", + "notConfigured": "配置全部六个 GPIO 引脚以使用以太网。", "clk": "SPI 时钟 GPIO", "mosi": "SPI MOSI GPIO", "miso": "SPI MISO GPIO", @@ -174,7 +173,6 @@ "rst": "复位 GPIO", "note": "W5500 SPI 接线" }, - "wifi": { "ssid": "SSID", "password": "密码", @@ -182,7 +180,6 @@ "signal": "信号强度", "connected": "已连接" }, - "params": { "hostname": "Hostname", "dhcp": "自动 (DHCP)", @@ -199,16 +196,15 @@ "none": "无" } }, - "sta": { - "channel.note": "自动选择设置为0" + "channel": { + "note": "自动选择设置为0" + } } }, - "sensors": { "title": "传感器设置 - OpenTherm Gateway", "name": "传感器设置", - "enabled": "启用", "sensorName": { "title": "传感器名称", @@ -265,10 +261,11 @@ "otHeatingPumpHours": "OpenTherm, number of pump operating hours (heating)", "otDhwPumpHours": "OpenTherm, number of pump operating hours (DHW)", "otCoolingHours": "OpenTherm, number of cooling hours", - "ntcTemp": "NTC 传感器", "dallasTemp": "DALLAS 传感器", "bluetooth": "BLE 传感器", + "dht11": "DHT11 传感器", + "dht22": "DHT22 传感器", "heatSetpointTemp": "Heating, setpoint temp", "manual": "通过 MQTT/API 手动配置", "notConfigured": "未配置" @@ -295,11 +292,9 @@ } } }, - "settings": { "title": "设置 - OpenTherm Gateway", "name": "设置", - "section": { "portal": "Portal 设置", "system": "系统设置", @@ -314,18 +309,21 @@ "extPump": "外置循环泵设置", "cascadeControl": "Cascade 级联控制设置" }, - "enable": "启用", "note": { "restart": "更改这些设置后,必须重启设备以使变更生效", "blankNotUse": "空白 - 未使用", "bleDevice": "BLE设备仅支持搭载BLE功能的特定ESP32开发板使用!" }, - "temp": { "min": "最低温度", "max": "最高温度" }, + "avgType": { + "mean": "平均温度", + "min": "最低温度", + "max": "最高温度" + }, "maxModulation": "最大调制范围", "ohProtection": { "title": "超温保护", @@ -351,14 +349,12 @@ "note": "强制开启加热的阈值" } }, - "portal": { "login": "登录", "password": "密码", "auth": "需身份验证", "mdns": "使用 mDNS" }, - "system": { "unit": "单位", "metric": "公制 (摄氏度、升、巴)", @@ -369,12 +365,8 @@ "enable": "启用串口", "baud": "串口波特率" }, - "telnet": { - "enable": "启用 Telnet", - "port": { - "title": "Telnet 端口", - "note": "默认值:23" - } + "webSerial": { + "enable": "启用 WebSerial" }, "ntp": { "server": "NTP服务器", @@ -382,31 +374,30 @@ "timezonePresets": "选择预设配置..." } }, - "heating": { "hyst": { "title": "滞回", "desc": "滞回有助于维持设定的室内温度(在使用«Equitherm»和/或«PID»时)。强制禁用加热当current indoor > target + value,启用加热当current indoor < (target - value)。", - "value": "值 (以度为单位)", - "action": { - "title": "行动", - "disableHeating": "禁用加热", - "set0target": "设置空目标" - } + "value": "值 (以度为单位)" }, - "turboFactor": "Turbo 模式系数" + "turboFactor": "Turbo 模式系数", + "indoorTempAvgType": { + "title": "室内温度平均类型", + "desc": "使用两个或更多室内温度传感器时可能有用(使用 «Equitherm» 和/或 «PID» 时)。" + }, + "outdoorTempAvgType": { + "title": "室外温度平均类型", + "desc": "使用两个或更多室外温度传感器时可能有用(使用 «Equitherm» 时)。" + } }, - "emergency": { - "desc": "紧急模式会在以下情况自动激活(当PID或气候补偿无法计算热媒设定值时):
启用气候补偿但室外温度传感器断开连接;
启用PID或 OpenTherm 选项中启用原生供暖控制但室内温度传感器断开连接。
注意: 网络故障或MQTT 服务器连接故障时,类型为通过MQTT/API手动控制的传感器将显示为断开连接状态。", - + "desc": "紧急模式会在以下情况自动激活(当PID或气候补偿无法计算热媒设定值时):
启用气候补偿但室外温度传感器断开连接;
启用PID或 OpenTherm 选项中启用原生供暖控制但室内温度传感器断开连接。
注意: 网络故障或MQTT 服务器连接故障时,类型为通过MQTT/API手动控制的传感器将显示为断开连接状态。", "target": { - "title": "目标温度", - "note": "重要提示: 若启用OpenTherm选项 «原生供暖控制»,此处设定值为目标室内温度;
其他所有情况下,此处设定值为 目标热媒出水温度." + "title": "目标温度" }, - "treshold": "阈值时间 (秒)" + "thresholdTime": "状态变化延时 (秒)", + "note": "重要提示: 若启用OpenTherm选项 «原生供暖控制»,此处设定值为目标室内温度;
其他所有情况下,此处设定值为 目标热媒出水温度." }, - "equitherm": { "slope": { "title": "斜率", @@ -430,7 +421,6 @@ "outdoorTemp": "室外温度" } }, - "pid": { "p": "P 系数", "i": "I 系数", @@ -450,8 +440,17 @@ "thresholdLow": "Threshold low" } }, - "ot": { + "disablingAction": { + "title": "回路关闭方式", + "desc": "无论因何原因关闭回路,包括过热,均采用所选的关闭方式。
某些锅炉会在关闭回路时停止循环泵,此时可尝试将目标温度设为 0,以使循环泵的延时运转功能正常工作。", + "heating": "采暖回路", + "dhw": "生活热水回路", + "ch2": "回路 2", + "off": "仅关闭回路", + "zeroSetpoint": "将目标温度设为 0", + "offAndZeroSetpoint": "关闭回路并将目标温度设为 0" + }, "advanced": "高级设置", "inGpio": "In GPIO", "outGpio": "Out GPIO", @@ -464,9 +463,8 @@ }, "maxPower": { "title": "最大锅炉功率 (kW)", - "note": "0 - 自动检测,通常在锅炉参数设置中的\"最大有效热输出\"。 " + "note": "0 - 自动检测,通常在锅炉参数设置中的\"最大有效热输出\"。" }, - "options": { "title": "选项(附加设置)", "desc": "附加设置选项可调整锅炉的运行逻辑。由于协议未完整记录所有选项,同一选项在不同锅炉上可能产生不同效果。
注意:若系统运行正常,无需修改设置。", @@ -488,23 +486,27 @@ "immergasFix": "针对Immergas锅炉的兼容性修复", "alwaysSendIndoorTemp": "向锅炉发送当前室内温度" }, - "nativeOTC": { "title": "原生热载体温度计算模式", "note": "仅在锅炉处于 OTC 模式时才工作:需要并接受目标室内温度,并基于内置曲线模式自行调节热载体温度。与 PID 和 Equitherm 不兼容。" } }, - "mqtt": { - "homeAssistantDiscovery": "Home Assistant 自动发现", + "haDiscovery": "HomeAssistant 自动发现", + "haDiscoveryPrefix": "HomeAssistant 自动发现前缀", "server": "服务器地址", "port": "端口", "user": "用户名", "password": "密码", - "prefix": "Prefix 前缀", - "interval": "发布间隔 (秒)" + "prefix": { + "title": "设备前缀", + "note": "设备 MQTT 主题的前缀,每台设备必须唯一" + }, + "interval": { + "title": "发布间隔", + "note": "强制发布数值的周期,即使数值未发生变化也会发布(秒)" + } }, - "extPump": { "use": "使用外置循环泵", "gpio": "继电器 GPIO引脚", @@ -513,21 +515,20 @@ "antiStuckInterval": "防卡死间隔时间(天)", "antiStuckTime": "防卡死运行时长(分钟)" }, - "cascadeControl": { "input": { "desc": "仅当另一台锅炉发生故障时启用本锅炉加热。另一台锅炉的控制器需在故障发生时切换GPIO输入状态以触发本功能。", "enable": "启用 input", "gpio": "GPIO", "invertState": "切换 GPIO 状态", - "thresholdTime": "状态变化阈值时间(秒)" + "thresholdTime": "状态变化延时 (秒)" }, "output": { "desc": "可通过继电器控制另一台锅炉的启停。", "enable": "启用 output", "gpio": "GPIO", "invertState": "切换 GPIO 状态", - "thresholdTime": "状态变化阈值时间 (秒)", + "thresholdTime": "状态变化延时 (秒)", "events": { "desc": "事件", "onFault": "当故障状态激活时", @@ -537,23 +538,49 @@ } } }, - + "logs": { + "title": "日志 - OpenTherm Gateway", + "name": "日志", + "desc": "实时设备日志。", + "status": { + "connecting": "正在连接...", + "connected": "已连接", + "disconnected": "已断开连接" + }, + "autoscroll": "自动滚动", + "limitHistory": "最多保留 1000 条日志", + "historyNote": "不限制历史记录会占用更多浏览器内存。下载包含所有保留的日志,包括被筛选器隐藏的日志。", + "filter": "筛选", + "search": { + "title": "搜索", + "previous": "上一个", + "next": "下一个" + }, + "level": { + "note": "此级别适用于设备日志(Serial 和 WebSerial)。下方的筛选器仅影响显示。", + "loadError": "无法加载日志级别,请重试。", + "saveError": "无法保存日志级别,请检查连接后重试。" + }, + "clear": "清空", + "download": "下载日志" + }, "upgrade": { "title": "固件升级 - OpenTherm Gateway", "name": "固件升级", - "section": { - "backupAndRestore": "备份与恢复", - "backupAndRestore.desc": "本功能支持备份和恢复全部设置", - "upgrade": "升级", - "upgrade.desc": "本模块支持升级设备的固件与系统文件。
可从以下地址下载最新版本 Releases page 。" + "backupAndRestore": { + "title": "备份与恢复", + "desc": "本功能支持备份和恢复全部设置" + }, + "upgrade": { + "title": "升级", + "desc": "本模块支持升级设备的固件与系统文件。
可从以下地址下载最新版本 Releases page 。" + } }, - "note": { "disclaimer1": "升级系统文件成功后,所有设置将恢复为默认值!升级前请务必备份配置。", "disclaimer2": "升级成功后,设备将在15秒后自动重启。" }, - "settingsFile": "设置文件", "fw": "Firmware", "fs": "Filesystem" diff --git a/src_data/locales/en.json b/src_data/locales/en.json index 905552e..80b5f71 100644 --- a/src_data/locales/en.json +++ b/src_data/locales/en.json @@ -8,15 +8,21 @@ "issues": "Issues & questions", "releases": "Releases" }, - "dbm": "dBm", - "kw": "kW", - "time": { + "units": { "days": "d.", "hours": "h.", "min": "min.", - "sec": "sec." + "sec": "sec.", + "dbm": "dBm", + "mhz": "MHz", + "kw": "kW", + "rpm": "RPM", + "ppm": "ppm", + "byte": "byte", + "mbyte": "MB", + "liter": "L", + "gallon": "gal" }, - "button": { "upgrade": "Upgrade", "restart": "Restart", @@ -31,26 +37,25 @@ "success": "Success", "error": "Error" }, - "index": { "title": "OpenTherm Gateway", - "section": { "network": "Network", "system": "System" }, - "system": { "build": { "title": "Build", "version": "Version", + "commit": "Commit", "date": "Date", "core": "Core", "sdk": "SDK" }, "uptime": "Uptime", "memory": { - "title": "Free memory", + "heap": "Memory (heap)", + "psram": "Memory (PSRAM)", "maxFreeBlock": "max free block", "min": "min" }, @@ -61,32 +66,28 @@ "freq": "frequency" }, "flash": { - "size": "Flash size", - "realSize": "real size" + "size": "Flash size" }, - "lastResetReason": "Last reset reason" + "lastResetReason": "Last reset reason", + "coreDump": "Core dump" } }, - "dashboard": { "name": "Dashboard", "title": "Dashboard - OpenTherm Gateway", - "section": { "control": "Control", "states": "States", "sensors": "Sensors", "diag": "OpenTherm diagnostic" }, - "thermostat": { "heating": "Heating", "dhw": "DHW", - "temp.current": "Current", + "currentTemp": "Current", "enable": "Enable", "turbo": "Turbo mode" }, - "notify": { "fault": { "title": "Boiler Fault state is active!", @@ -98,7 +99,6 @@ }, "reset": "Try reset" }, - "states": { "mNetworkConnected": "Network connection", "mMqttConnected": "MQTT connection", @@ -106,7 +106,6 @@ "mExtPumpState": "External pump", "mCascadeControlInput": "Cascade control (input)", "mCascadeControlOutput": "Cascade control (output)", - "sConnected": "OpenTherm connection", "sFlame": "Flame", "sCoolingActive": "Cooling", @@ -115,7 +114,6 @@ "sFaultCode": "Fault code", "sDiagActive": "Diagnostic", "sDiagCode": "Diagnostic code", - "mHeatEnabled": "Heating enabled", "mHeatBlocking": "Heating blocked", "mHeatOverheat": "Heating overheat", @@ -127,7 +125,6 @@ "mHeatRetTemp": "Heating return temp", "mHeatIndoorTemp": "Heating, indoor temp", "mHeatOutdoorTemp": "Heating, outdoor temp", - "mDhwEnabled": "DHW enabled", "mDhwOverheat": "DHW overheat", "sDhwActive": "DHW active", @@ -135,7 +132,6 @@ "mDhwCurrTemp": "DHW current temp", "mDhwRetTemp": "DHW return temp" }, - "sensors": { "values": { "temp": "Temperature", @@ -145,28 +141,30 @@ } } }, - "network": { "title": "Network - OpenTherm Gateway", "name": "Network settings", - + "type": { + "title": "Connection method", + "wifi": "Wi-Fi", + "ethernet": "Ethernet" + }, "section": { "static": "Static settings", "ethernet": "Ethernet", + "wifi": "Wi-Fi", "availableNetworks": "Available networks", "staSettings": "WiFi settings", "apSettings": "AP settings" }, - "scan": { "pos": "#", "info": "Info", - "unavailable": "Please enable WiFi to scan for networks" + "unavailable": "Network scanning is available only in Wi-Fi mode." }, "ethernet": { - "enable": "Enable ethernet", - "notConfigured": "Fill in all six GPIO pins to enable ethernet.", + "notConfigured": "Configure all six GPIOs to use Ethernet.", "clk": "SPI clock GPIO", "mosi": "SPI MOSI GPIO", "miso": "SPI MISO GPIO", @@ -175,7 +173,6 @@ "rst": "Reset GPIO", "note": "W5500 SPI wiring" }, - "wifi": { "ssid": "SSID", "password": "Password", @@ -183,7 +180,6 @@ "signal": "Signal", "connected": "Connected" }, - "params": { "hostname": "Hostname", "dhcp": "Use DHCP", @@ -200,16 +196,15 @@ "none": "None" } }, - "sta": { - "channel.note": "set 0 for auto select" + "channel": { + "note": "set 0 for auto select" + } } }, - "sensors": { "title": "Sensors settings - OpenTherm Gateway", "name": "Sensors settings", - "enabled": "Enabled", "sensorName": { "title": "Sensor name", @@ -266,10 +261,11 @@ "otHeatingPumpHours": "OpenTherm, number of pump operating hours (heating)", "otDhwPumpHours": "OpenTherm, number of pump operating hours (DHW)", "otCoolingHours": "OpenTherm, number of cooling hours", - "ntcTemp": "NTC sensor", "dallasTemp": "DALLAS sensor", "bluetooth": "BLE sensor", + "dht11": "DHT11 sensor", + "dht22": "DHT22 sensor", "heatSetpointTemp": "Heating, setpoint temp", "manual": "Manual via MQTT/API", "notConfigured": "Not configured" @@ -296,11 +292,9 @@ } } }, - "settings": { "title": "Settings - OpenTherm Gateway", "name": "Settings", - "section": { "portal": "Portal settings", "system": "System settings", @@ -315,18 +309,21 @@ "extPump": "External pump settings", "cascadeControl": "Cascade control settings" }, - "enable": "Enable", "note": { "restart": "After changing these settings, the device must be restarted for the changes to take effect.", "blankNotUse": "blank - not use", "bleDevice": "BLE device can be used only with some ESP32 boards with BLE support!" }, - "temp": { "min": "Minimum temperature", "max": "Maximum temperature" }, + "avgType": { + "mean": "Mean temperature", + "min": "Minimum temperature", + "max": "Maximum temperature" + }, "maxModulation": "Max modulation level", "ohProtection": { "title": "Overheating protection", @@ -352,14 +349,12 @@ "note": "Threshold when heating is forced to turn on" } }, - "portal": { "login": "Login", "password": "Password", "auth": "Require authentication", "mdns": "Use mDNS" }, - "system": { "unit": "Unit system", "metric": "Metric (celsius, liters, bar)", @@ -370,12 +365,8 @@ "enable": "Enabled Serial port", "baud": "Serial port baud rate" }, - "telnet": { - "enable": "Enabled Telnet", - "port": { - "title": "Telnet port", - "note": "Default: 23" - } + "webSerial": { + "enable": "Enabled WebSerial" }, "ntp": { "server": "NTP server", @@ -383,31 +374,30 @@ "timezonePresets": "Select preset..." } }, - "heating": { "hyst": { "title": "Hysteresis", "desc": "Hysteresis is useful for maintaining a set indoor temp (when using «Equitherm» and/or «PID»). Forces disable heating when current indoor > target + value and enable heating when current indoor < (target - value).", - "value": "Value (in degrees)", - "action": { - "title": "Action", - "disableHeating": "Disable heating", - "set0target": "Set null target" - } + "value": "Value (in degrees)" }, - "turboFactor": "Turbo mode coeff." + "turboFactor": "Turbo mode coeff.", + "indoorTempAvgType": { + "title": "Indoor temp. averaging type", + "desc": "May be useful when using two or more indoor temp. sensors (when using «Equitherm» and/or «PID»)." + }, + "outdoorTempAvgType": { + "title": "Outdoor temp. averaging type", + "desc": "May be useful when using two or more outdoor temp. sensors (when using «Equitherm»)." + } }, - "emergency": { "desc": "Emergency mode is activated automatically when «PID» or «Equitherm» cannot calculate the heat carrier setpoint:
- if «Equitherm» is enabled and the outdoor temperature sensor is disconnected;
- if «PID» or OT option «Native heating control» is enabled and the indoor temperature sensor is disconnected.
Note: On network fault or MQTT fault, sensors with «Manual via MQTT/API» type will be in DISCONNECTED state.", - "target": { - "title": "Target temperature", - "note": "Important: Target indoor temperature if OT option «Native heating control» is enabled.
In all other cases, the target heat carrier temperature." + "title": "Target temperature" }, - "treshold": "Treshold time (sec)" + "thresholdTime": "State change delay (sec)", + "note": "Important: Target indoor temperature if OT option «Native heating control» is enabled.
In all other cases, the target heat carrier temperature." }, - "equitherm": { "slope": { "title": "Slope", @@ -431,7 +421,6 @@ "outdoorTemp": "Outdoor temperature" } }, - "pid": { "p": "P factor", "i": "I factor", @@ -451,8 +440,17 @@ "thresholdLow": "Threshold low" } }, - "ot": { + "disablingAction": { + "title": "Circuit disabling action", + "desc": "The selected action applies whenever the circuit is disabled, including overheating.
Some boilers stop the circulation pump when the circuit is disabled. In this case, you can try setting the target temperature to 0 so that the pump overrun works correctly.", + "heating": "Heating circuit", + "dhw": "DHW circuit", + "ch2": "Circuit 2", + "off": "Disable circuit only", + "zeroSetpoint": "Set the target temperature to 0", + "offAndZeroSetpoint": "Disable circuit and set the target temperature to 0" + }, "advanced": "Advanced Settings", "inGpio": "In GPIO", "outGpio": "Out GPIO", @@ -467,7 +465,6 @@ "title": "Max boiler power (kW)", "note": "0 - try detect automatically. Typically found in the boiler specification as \"maximum useful heat output\"." }, - "options": { "title": "Options (additional settings)", "desc": "Options can change the logic of the boiler. Not all options are documented in the protocol, so the same option can have different effects on different boilers.
Note: There is no need to change anything if everything works well.", @@ -489,23 +486,27 @@ "immergasFix": "Fix for Immergas boilers", "alwaysSendIndoorTemp": "Send current indoor temp to boiler" }, - "nativeOTC": { "title": "Native OTC mode", "note": "Works ONLY if the boiler is in OTC mode: requires and accepts the target indoor temperature and self-regulates the heat carrier temperature based on the built-in curves mode. Incompatible with PID and Equitherm." } }, - "mqtt": { - "homeAssistantDiscovery": "Home Assistant Discovery", + "haDiscovery": "HomeAssistant Discovery", + "haDiscoveryPrefix": "HomeAssistant discovery prefix", "server": "Server", "port": "Port", "user": "User", "password": "Password", - "prefix": "Prefix", - "interval": "Publish interval (sec)" + "prefix": { + "title": "Device prefix", + "note": "MQTT topic prefix, unique to each device" + }, + "interval": { + "title": "Publish interval", + "note": "Interval for forced publication of values, even when unchanged (in seconds)" + } }, - "extPump": { "use": "Use external pump", "gpio": "Relay GPIO", @@ -514,21 +515,20 @@ "antiStuckInterval": "Anti stuck interval (days)", "antiStuckTime": "Anti stuck time (min)" }, - "cascadeControl": { "input": { "desc": "Can be used to turn on the heating only if another boiler is faulty. The other boiler controller must change the state of the GPIO input in the event of a fault.", "enable": "Enabled input", "gpio": "GPIO", "invertState": "Invert GPIO state", - "thresholdTime": "State change threshold time (sec)" + "thresholdTime": "State change delay (sec)" }, "output": { "desc": "Can be used to switch on another boiler via relay.", "enable": "Enabled output", "gpio": "GPIO", "invertState": "Invert GPIO state", - "thresholdTime": "State change threshold time (sec)", + "thresholdTime": "State change delay (sec)", "events": { "desc": "Events", "onFault": "If the fault state is active", @@ -538,26 +538,52 @@ } } }, - + "logs": { + "title": "Logs - OpenTherm Gateway", + "name": "Logs", + "desc": "Device logs in real time.", + "status": { + "connecting": "Connecting...", + "connected": "Connected", + "disconnected": "Disconnected" + }, + "autoscroll": "Autoscroll", + "limitHistory": "Keep at most 1000 entries", + "historyNote": "Unlimited history uses more browser memory. Downloads include all retained entries, including those hidden by the filter.", + "filter": "Filter", + "search": { + "title": "Search", + "previous": "Previous", + "next": "Next" + }, + "level": { + "note": "The level applies to device logging (Serial and WebSerial). The filter below only changes the display.", + "loadError": "Could not load the log level. Retry the request.", + "saveError": "Could not save the log level. Check the connection and try again." + }, + "clear": "Clear", + "download": "Download logs" + }, "upgrade": { "title": "Upgrade - OpenTherm Gateway", "name": "Upgrade", - "section": { - "backupAndRestore": "Backup & restore", - "backupAndRestore.desc": "In this section you can save and restore a backup of ALL settings.", - "upgrade": "Upgrade", - "upgrade.desc": "In this section you can upgrade the firmware and filesystem of your device.
Latest releases can be downloaded from the Releases page of the project repository." + "backupAndRestore": { + "title": "Backup & restore", + "desc": "In this section you can save and restore a backup of ALL settings." + }, + "upgrade": { + "title": "Upgrade", + "desc": "In this section you can upgrade the firmware and filesystem of your device.
Latest releases can be downloaded from the Releases page of the project repository." + } }, - "note": { "disclaimer1": "After a successful upgrade the filesystem, ALL settings will be reset to default values! Save backup before upgrading.", "disclaimer2": "After a successful upgrade, the device will automatically reboot after 15 seconds." }, - "settingsFile": "Settings file", "fw": "Firmware", "fs": "Filesystem" } } -} \ No newline at end of file +} diff --git a/src_data/locales/it.json b/src_data/locales/it.json index 8515c24..a7fd682 100644 --- a/src_data/locales/it.json +++ b/src_data/locales/it.json @@ -8,15 +8,21 @@ "issues": "Problemi e domande", "releases": "Versione" }, - "dbm": "dBm", - "kw": "kW", - "time": { + "units": { "days": "d.", "hours": "h.", "min": "min.", - "sec": "sec." + "sec": "sec.", + "dbm": "dBm", + "mhz": "MHz", + "kw": "kW", + "rpm": "RPM", + "ppm": "ppm", + "byte": "byte", + "mbyte": "MB", + "liter": "litro", + "gallon": "gal" }, - "button": { "upgrade": "Aggiorna", "restart": "Riavvia", @@ -31,26 +37,25 @@ "success": "Riuscito", "error": "Errore" }, - "index": { "title": "OpenTherm Gateway", - "section": { "network": "Rete", "system": "Sistema" }, - "system": { "build": { "title": "Build", "version": "Versione", + "commit": "Commit", "date": "Data", "core": "Core", "sdk": "SDK" }, "uptime": "Tempo di attività", "memory": { - "title": "Memoria libera", + "heap": "Memoria (heap)", + "psram": "Memoria (PSRAM)", "maxFreeBlock": "max free block", "min": "min" }, @@ -61,32 +66,28 @@ "freq": "frequenza" }, "flash": { - "size": "Dimensioni del flash", - "realSize": "dimensione reale" + "size": "Dimensioni del flash" }, - "lastResetReason": "Motivo ultimo Reset" + "lastResetReason": "Motivo ultimo Reset", + "coreDump": "Dump di memoria" } }, - "dashboard": { "name": "Pannello", "title": "Pannello - OpenTherm Gateway", - "section": { "control": "Controlli", "states": "Stato", "sensors": "Sensori", "diag": "Diagnostica OpenTherm" }, - "thermostat": { "heating": "Riscaldamento", "dhw": "ACS", - "temp.current": "Attuale", + "currentTemp": "Attuale", "enable": "Attiva", "turbo": "Turbo" }, - "notify": { "fault": { "title": "Rilevamento guasti caldiaia attivo!", @@ -98,7 +99,6 @@ }, "reset": "Prova a resettare" }, - "states": { "mNetworkConnected": "Connessione Rete", "mMqttConnected": "Connessione MQTT", @@ -106,7 +106,6 @@ "mExtPumpState": "Pompa esterna", "mCascadeControlInput": "Controllo a cascata (input)", "mCascadeControlOutput": "Controllo a cascata (output)", - "sConnected": "Connessione OpenTherm", "sFlame": "Fiamma", "sCoolingActive": "Raffrescamento", @@ -115,10 +114,10 @@ "sFaultCode": "Codice anomalia", "sDiagActive": "Diagnostica", "sDiagCode": "Codice Diagnostica", - "mHeatEnabled": "Riscaldamento attivato", "mHeatBlocking": "Riscaldamento bloccato", "mHeatOverheat": "Riscaldamento surriscaldamento", + "mHeatFreezing": "Protezione antigelo", "sHeatActive": "Riscaldamento attivo", "mHeatSetpointTemp": "Temp riscaldamento impostato", "mHeatTargetTemp": "Target Temp caldaia", @@ -126,7 +125,6 @@ "mHeatRetTemp": "Temp ritorno riscaldamento", "mHeatIndoorTemp": "Riscaldamento, temp interna", "mHeatOutdoorTemp": "Riscaldamento, temp esterna", - "mDhwEnabled": "ACS attivata", "mDhwOverheat": "ACS surriscaldamento", "sDhwActive": "ACS attiva", @@ -134,7 +132,6 @@ "mDhwCurrTemp": "ACS temp attuale", "mDhwRetTemp": "ACS temp ricircolo" }, - "sensors": { "values": { "temp": "Temperatura", @@ -144,28 +141,30 @@ } } }, - "network": { "title": "Rete - OpenTherm Gateway", "name": "Impostazioni rete", - + "type": { + "title": "Metodo di connessione", + "wifi": "Wi-Fi", + "ethernet": "Ethernet" + }, "section": { "static": "Impostazioni statico", "ethernet": "Ethernet", + "wifi": "Wi-Fi", "availableNetworks": "Reti disponibili", "staSettings": "Impostazioni WiFi", "apSettings": "Impostazioni AP" }, - "scan": { "pos": "#", "info": "Info", - "unavailable": "Abilita il WiFi per cercare le reti" + "unavailable": "La ricerca delle reti è disponibile solo in modalità Wi-Fi." }, "ethernet": { - "enable": "Abilita ethernet", - "notConfigured": "Compilare tutti e sei i pin GPIO per abilitare ethernet.", + "notConfigured": "Configura tutti e sei i GPIO per utilizzare Ethernet.", "clk": "GPIO clock SPI", "mosi": "GPIO MOSI SPI", "miso": "GPIO MISO SPI", @@ -174,7 +173,6 @@ "rst": "GPIO reset", "note": "Cablaggio SPI del W5500" }, - "wifi": { "ssid": "SSID", "password": "Password", @@ -182,7 +180,6 @@ "signal": "Segnale", "connected": "Connesso" }, - "params": { "hostname": "Hostname", "dhcp": "Usa DHCP", @@ -199,16 +196,15 @@ "none": "Nessuno" } }, - "sta": { - "channel.note": "Metti 0 per auto selezione" + "channel": { + "note": "Metti 0 per auto selezione" + } } }, - "sensors": { "title": "Impostazione sensori - OpenTherm Gateway", "name": "Impostazione sensori", - "enabled": "Attivato", "sensorName": { "title": "Nome sensore", @@ -265,10 +261,11 @@ "otHeatingPumpHours": "OpenTherm, numero di ore di funzionamento della pompa (riscaldamento)", "otDhwPumpHours": "OpenTherm, numero di ore di funzionamento della pompa (ACS)", "otCoolingHours": "OpenTherm, numero di ore di funzionamento della cooling", - "ntcTemp": "Sensore NTC", "dallasTemp": "Sensore DALLAS", "bluetooth": "Sensore BLE", + "dht11": "Sensore DHT11", + "dht22": "Sensore DHT22", "heatSetpointTemp": "Riscaldamento, temp impostata", "manual": "Manuale via MQTT/API", "notConfigured": "Non configurato" @@ -295,11 +292,9 @@ } } }, - "settings": { "title": "Impostazioni - OpenTherm Gateway", "name": "Impostazioni", - "section": { "portal": "Impostazioni Accesso", "system": "Impostazioni sistema", @@ -314,18 +309,21 @@ "extPump": "Impostazioni pompa esterna", "cascadeControl": "Impostazioni controllo a cascata" }, - "enable": "Attiva", "note": { "restart": "Dopo aver cambiato queste impostazioni, il sistema sarà riavviato perchè i cambiamenti abbiano effetto.", "blankNotUse": "vuoto - non usare", "bleDevice": "Dispositivi BLE possono essere usati solo con alcune schede ESP32 che supportano il bluetooth!" }, - "temp": { "min": "Temperatura minima", "max": "Temperatura massima" }, + "avgType": { + "mean": "Temperatura media", + "min": "Temperatura minima", + "max": "Temperatura massima" + }, "maxModulation": "Max livello modulazione", "ohProtection": { "title": "Protezione contro il surriscaldamento", @@ -351,14 +349,12 @@ "note": "Soglia quando il riscaldamento viene forzatamente attivato" } }, - "portal": { "login": "Login", "password": "Password", "auth": "Richiede autenticazione", "mdns": "Usa mDNS" }, - "system": { "unit": "Unità di misura", "metric": "Metrico (celsius, litri, bar)", @@ -369,12 +365,8 @@ "enable": "Porta seriale attivata", "baud": "Porta seriale baud rate" }, - "telnet": { - "enable": "Telnet attivato", - "port": { - "title": "Porta Telnet", - "note": "Default: 23" - } + "webSerial": { + "enable": "WebSerial attivato" }, "ntp": { "server": "NTP server", @@ -382,31 +374,30 @@ "timezonePresets": "Seleziona preimpostato..." } }, - "heating": { "hyst": { "title": "Isteresi", "desc": "L'isteresi è utile per mantenere una temperatura interna impostata (quando si utilizza «Equitherm» e/o «PID»). Forza la disabilitazione del riscaldamento quando current indoor > target + value e abilita il riscaldamento quando current indoor < (target - value).", - "value": "Valore (in gradi)", - "action": { - "title": "Azione", - "disableHeating": "Disabilita riscaldamento", - "set0target": "Imposta target nullo" - } + "value": "Valore (in gradi)" }, - "turboFactor": "Turbo mode coeff." + "turboFactor": "Turbo mode coeff.", + "indoorTempAvgType": { + "title": "Tipo di media temperatura interna", + "desc": "Utile con due o più sensori di temperatura interna (quando si usa «Equitherm» e/o «PID»)." + }, + "outdoorTempAvgType": { + "title": "Tipo di media temperatura esterna", + "desc": "Utile con due o più sensori di temperatura esterna (quando si usa «Equitherm»)." + } }, - "emergency": { "desc": "Il modo emergenza è attivato automaticamente quando «PID» o «Equitherm» non possono calcolare il setpoint:
- se «Equitherm» è attivato e il sensore della temperatura esternare è disconnesso;
- se «PID» o l'opzione OT «Impostazioni riscaldamento native» è attiva e il sensore di temperatura interno è disconnesso.
Nota: In mancanza di rete o MQTT, sensore di tipo «Manuale via MQTT/API» è in stato Disconnesso.", - "target": { - "title": "Temperatura impostata", - "note": "Importante: Temperatura interna impostata se l'opzione OT «Controllo riscaldamento interno» è attivato.
In tutti gli altri casi, la target heat carrier temperature." + "title": "Temperatura impostata" }, - "treshold": "Tempo di soglia (sec)" + "thresholdTime": "Ritardo del cambio di stato (sec)", + "note": "Importante: Temperatura interna impostata se l'opzione OT «Controllo riscaldamento interno» è attivato.
In tutti gli altri casi, la target heat carrier temperature." }, - "equitherm": { "slope": { "title": "Pendenza", @@ -430,7 +421,6 @@ "outdoorTemp": "Temperatura esterna" } }, - "pid": { "p": "Fattore P", "i": "Fattore I", @@ -450,8 +440,17 @@ "thresholdLow": "Soglia inferiore" } }, - "ot": { + "disablingAction": { + "title": "Azione di disattivazione dei circuiti", + "desc": "L'azione selezionata si applica a ogni disattivazione del circuito, anche in caso di surriscaldamento.
Alcune caldaie arrestano la pompa di circolazione quando il circuito viene disattivato; in questo caso si può provare a impostare la temperatura desiderata a 0, affinché la post-circolazione della pompa funzioni correttamente.", + "heating": "Circuito di riscaldamento", + "dhw": "Circuito ACS", + "ch2": "Circuito 2", + "off": "Disattiva solo il circuito", + "zeroSetpoint": "Imposta la temperatura desiderata a 0", + "offAndZeroSetpoint": "Disattiva il circuito e imposta la temperatura desiderata a 0" + }, "advanced": "Impostazioni avanzate", "inGpio": "In GPIO", "outGpio": "Out GPIO", @@ -466,7 +465,6 @@ "title": "Potenza massima caldaia (kW)", "note": "0 - prova a rilevarla automaticamente. Di solito si trova nelle specifiche delle caldaia come \"potenza massima disponibile\"." }, - "options": { "title": "Opzioni (impostazioni aggiuntive)", "desc": "Le opzioni possono modificare la logica della caldaia. Non tutte le opzioni sono documentate nel protocollo, quindi la stessa opzione può avere effetti diversi su caldaie diverse.
Nota: Non è necessario modificare nulla se tutto funziona correttamente.", @@ -488,23 +486,27 @@ "immergasFix": "Fix per caldiaie Immergas", "alwaysSendIndoorTemp": "Invia la temp attuale interna alla caldaia" }, - "nativeOTC": { "title": "Modalità nativa di calcolo della temperatura del vettore termico", "note": "Funziona SOLO se la caldaia è in modalità OTC: richiede e accetta la temperatura interna target e regola autonomamente la temperatura del vettore termico basata sulla modalità curve integrata. Incompatibile con PID e Equitherm." } }, - "mqtt": { - "homeAssistantDiscovery": "Home Assistant Discovery", + "haDiscovery": "HomeAssistant Discovery", + "haDiscoveryPrefix": "Prefisso discovery di HomeAssistant", "server": "Server", "port": "Porta", "user": "Utente", "password": "Password", - "prefix": "Prefisso", - "interval": "Intervallo invio (sec)" + "prefix": { + "title": "Prefisso dispositivo", + "note": "Prefisso dei topic MQTT, univoco per ogni dispositivo" + }, + "interval": { + "title": "Intervallo di pubblicazione", + "note": "Intervallo di pubblicazione forzata dei valori, anche se invariati (in secondi)" + } }, - "extPump": { "use": "Usa pompa/circolatore esterno", "gpio": "GPIO relè", @@ -513,21 +515,20 @@ "antiStuckInterval": "Intervallo antiblocco (days)", "antiStuckTime": "Tempo antiblocco (min)" }, - "cascadeControl": { "input": { "desc": "Può essere attivata la caldaia se un'altra ha fallito. Il controllo dell'altra caldaia cambia lo stato dell'ingresso del GPIO in caso di errore.", "enable": "Ingresso abilitato", "gpio": "GPIO", "invertState": "Inverti stato GPIO", - "thresholdTime": "Tempo soglia di modifica dello stato (sec)" + "thresholdTime": "Ritardo del cambio di stato (sec)" }, "output": { "desc": "Può essere usato per passare ad un'altra caldaia tramite relè.", "enable": "Uscita abilitata", "gpio": "GPIO", "invertState": "Invert GPIO state", - "thresholdTime": "Tempo soglia di modifica dello stato (sec)", + "thresholdTime": "Ritardo del cambio di stato (sec)", "events": { "desc": "Eventi", "onFault": "Se lo stato di errore è attivo", @@ -537,26 +538,52 @@ } } }, - + "logs": { + "title": "Registro - OpenTherm Gateway", + "name": "Registro", + "desc": "Registro del dispositivo in tempo reale.", + "status": { + "connecting": "Connessione in corso...", + "connected": "Connesso", + "disconnected": "Disconnesso" + }, + "autoscroll": "Scorrimento automatico", + "limitHistory": "Conserva al massimo 1000 voci", + "historyNote": "La cronologia illimitata usa più memoria del browser. Il download include tutte le voci conservate, anche quelle nascoste dal filtro.", + "filter": "Filtro", + "search": { + "title": "Cerca", + "previous": "Precedente", + "next": "Successivo" + }, + "level": { + "note": "Il livello si applica al registro del dispositivo (Serial e WebSerial). Il filtro sottostante cambia solo la visualizzazione.", + "loadError": "Impossibile caricare il livello del registro. Riprovare la richiesta.", + "saveError": "Impossibile salvare il livello del registro. Controllare la connessione e riprovare." + }, + "clear": "Cancella", + "download": "Scarica il registro" + }, "upgrade": { "title": "Aggiornamenti - OpenTherm Gateway", "name": "Aggiornamenti", - "section": { - "backupAndRestore": "Backup & restore", - "backupAndRestore.desc": "In questa sezione puoi salvare e recuperare un backup di tutte le impostazioni.", - "upgrade": "Aggiorna", - "upgrade.desc": "In questa sezione puoi aggiornare il firmware il filesystem del tuo dispositivo.
L'ultimo aggiornamento può essere scaricato da Releases page del progetto." + "backupAndRestore": { + "title": "Backup & restore", + "desc": "In questa sezione puoi salvare e recuperare un backup di tutte le impostazioni." + }, + "upgrade": { + "title": "Aggiorna", + "desc": "In questa sezione puoi aggiornare il firmware il filesystem del tuo dispositivo.
L'ultimo aggiornamento può essere scaricato da Releases page del progetto." + } }, - "note": { "disclaimer1": "Dopo un aggiornamento riuscito del filesystem, tutte le impostazioni sono impostate di default! Salva un backup prima di aggiornare.", "disclaimer2": "Dopo un aggiornamento riuscito, il sistema viene automaticamente riavviato dopo 15 secondi." }, - "settingsFile": "Settings file", "fw": "Firmware", "fs": "Filesystem" } } -} \ No newline at end of file +} diff --git a/src_data/locales/nl.json b/src_data/locales/nl.json index 7a3e8ba..4d58b12 100644 --- a/src_data/locales/nl.json +++ b/src_data/locales/nl.json @@ -8,13 +8,20 @@ "issues": "Problemen & vragen", "releases": "Releases" }, - "dbm": "dBm", - "kw": "kW", - "time": { + "units": { "days": "d.", "hours": "u.", "min": "min.", - "sec": "sec." + "sec": "sec.", + "dbm": "dBm", + "mhz": "MHz", + "kw": "kW", + "rpm": "RPM", + "ppm": "ppm", + "byte": "byte", + "mbyte": "MB", + "liter": "L", + "gallon": "gal" }, "button": { "upgrade": "Upgraden", @@ -40,13 +47,15 @@ "build": { "title": "Build", "version": "Versie", + "commit": "Commit", "date": "Datum", "core": "Core", "sdk": "SDK" }, "uptime": "Uptime", "memory": { - "title": "Vrij geheugen", + "heap": "Geheugen (heap)", + "psram": "Geheugen (PSRAM)", "maxFreeBlock": "max. vrij blok", "min": "min" }, @@ -57,10 +66,10 @@ "freq": "frequentie" }, "flash": { - "size": "Flash-grootte", - "realSize": "werkelijke grootte" + "size": "Flash-grootte" }, - "lastResetReason": "Reden laatste herstart" + "lastResetReason": "Reden laatste herstart", + "coreDump": "Geheugendump" } }, "dashboard": { @@ -75,7 +84,7 @@ "thermostat": { "heating": "Verwarming", "dhw": "Warm water", - "temp.current": "Huidig", + "currentTemp": "Huidig", "enable": "Inschakelen", "turbo": "Turbomodus" }, @@ -108,6 +117,7 @@ "mHeatEnabled": "Verwarming ingeschakeld", "mHeatBlocking": "Verwarming geblokkeerd", "mHeatOverheat": "Verwarming oververhit", + "mHeatFreezing": "Verwarming vorstbescherming", "sHeatActive": "Verwarming actief", "mHeatSetpointTemp": "Insteltemperatuur verwarming", "mHeatTargetTemp": "Doeltemperatuur verwarming", @@ -134,9 +144,15 @@ "network": { "title": "Netwerk - OpenTherm Gateway", "name": "Netwerkinstellingen", + "type": { + "title": "Verbindingsmethode", + "wifi": "Wi-Fi", + "ethernet": "Ethernet" + }, "section": { "static": "Statische instellingen", "ethernet": "Ethernet", + "wifi": "Wi-Fi", "availableNetworks": "Beschikbare netwerken", "staSettings": "WiFi-instellingen", "apSettings": "AP-instellingen" @@ -144,12 +160,11 @@ "scan": { "pos": "#", "info": "Info", - "unavailable": "Schakel WiFi in om naar netwerken te zoeken" + "unavailable": "Netwerken zoeken is alleen beschikbaar in de Wi-Fi-modus." }, "ethernet": { - "enable": "Ethernet inschakelen", - "notConfigured": "Vul alle zes GPIO-pinnen in om ethernet in te schakelen.", + "notConfigured": "Configureer alle zes GPIO's om Ethernet te gebruiken.", "clk": "SPI-klok GPIO", "mosi": "SPI MOSI GPIO", "miso": "SPI MISO GPIO", @@ -182,7 +197,9 @@ } }, "sta": { - "channel.note": "zet op 0 voor automatische selectie" + "channel": { + "note": "zet op 0 voor automatische selectie" + } } }, "sensors": { @@ -244,10 +261,11 @@ "otHeatingPumpHours": "OpenTherm, aantal pompuren (verwarming)", "otDhwPumpHours": "OpenTherm, aantal pompuren (warm water)", "otCoolingHours": "OpenTherm, aantal cooling", - "ntcTemp": "NTC-sensor", "dallasTemp": "DALLAS-sensor", "bluetooth": "BLE-sensor", + "dht11": "DHT11-sensor", + "dht22": "DHT22-sensor", "heatSetpointTemp": "Verwarming, insteltemperatuur", "manual": "Handmatig via MQTT/API", "notConfigured": "Niet geconfigureerd" @@ -301,6 +319,11 @@ "min": "Minimumtemperatuur", "max": "Maximumtemperatuur" }, + "avgType": { + "mean": "Gemiddelde temperatuur", + "min": "Minimum temperatuur", + "max": "Maximum temperatuur" + }, "maxModulation": "Max. modulatieniveau", "ohProtection": { "title": "Oververhittingsbeveiliging", @@ -326,7 +349,6 @@ "note": "Drempel wanneer de verwarming geforceerd wordt ingeschakeld" } }, - "portal": { "login": "Gebruikersnaam", "password": "Wachtwoord", @@ -343,12 +365,8 @@ "enable": "Seriële poort ingeschakeld", "baud": "Baudrate seriële poort" }, - "telnet": { - "enable": "Telnet ingeschakeld", - "port": { - "title": "Telnet-poort", - "note": "Standaard: 23" - } + "webSerial": { + "enable": "WebSerial ingeschakeld" }, "ntp": { "server": "NTP-server", @@ -360,22 +378,25 @@ "hyst": { "title": "Hysterese", "desc": "Hysterese is nuttig voor het handhaven van een ingestelde binnentemperatuur (bij gebruik van «Equitherm» en/of «PID»). Forceert uitschakelen van verwarming wanneer current indoor > target + value en inschakelen van verwarming wanneer current indoor < (target - value).", - "value": "Waarde (in graden)", - "action": { - "title": "Actie", - "disableHeating": "Verwarming uitschakelen", - "set0target": "Stel null target in" - } + "value": "Waarde (in graden)" }, - "turboFactor": "Turbomodus coëff." + "turboFactor": "Turbomodus coëff.", + "indoorTempAvgType": { + "title": "Binnentemperatuur gemiddelde type", + "desc": "Nuttig bij twee of meer binnentemperatuursensoren (bij gebruik van «Equitherm» en/of «PID»)." + }, + "outdoorTempAvgType": { + "title": "Buitentemperatuur gemiddelde type", + "desc": "Nuttig bij twee of meer buitensensoren (bij gebruik van «Equitherm»)." + } }, "emergency": { "desc": "Noodmodus wordt automatisch geactiveerd wanneer «PID» of «Equitherm» het instelpunt van de warmtedrager niet kan berekenen:
- als «Equitherm» is ingeschakeld en de buitentemperatuursensor is losgekoppeld;
- als «PID» of OT-optie «Natuurlijke verwarmingsregeling» is ingeschakeld en de binnentemperatuursensor is losgekoppeld.
Let op: Bij een netwerk- of MQTT-storing krijgen sensoren van het type «Handmatig via MQTT/API» de status ONVERBONDEN.", "target": { - "title": "Doeltemperatuur", - "note": "Belangrijk: Doel binnentemperatuur als OT-optie «Natuurlijke verwarmingsregeling» is ingeschakeld.
In alle andere gevallen, de doel warmtedragertemperatuur." + "title": "Doeltemperatuur" }, - "treshold": "Drempeltijd (sec)" + "thresholdTime": "Vertraging bij statuswijziging (sec)", + "note": "Belangrijk: Doel binnentemperatuur als OT-optie «Natuurlijke verwarmingsregeling» is ingeschakeld.
In alle andere gevallen, de doel warmtedragertemperatuur." }, "equitherm": { "slope": { @@ -420,6 +441,16 @@ } }, "ot": { + "disablingAction": { + "title": "Actie bij uitschakelen van circuits", + "desc": "De gekozen actie geldt bij elke uitschakeling van het circuit, ook bij oververhitting.
Sommige ketels schakelen de circulatiepomp uit wanneer het circuit wordt uitgeschakeld. In dat geval kunt u proberen de doeltemperatuur op 0 in te stellen, zodat de pompnaloop correct werkt.", + "heating": "Verwarmingscircuit", + "dhw": "Warmtapwatercircuit", + "ch2": "Circuit 2", + "off": "Alleen het circuit uitschakelen", + "zeroSetpoint": "Doeltemperatuur op 0 instellen", + "offAndZeroSetpoint": "Circuit uitschakelen en doeltemperatuur op 0 instellen" + }, "advanced": "Geavanceerde instellingen", "inGpio": "In GPIO", "outGpio": "Uit GPIO", @@ -455,20 +486,26 @@ "immergasFix": "Fix voor Immergas-ketels", "alwaysSendIndoorTemp": "Stuur huidige binnentemp naar ketel" }, - "nativeOTC": { "title": "Native warmtedrager temperatuur berekeningsmodus", "note": "Werkt ALLEEN als de ketel in OTC-modus is: vereist en accepteert de doel binnentemperatuur en regelt zelf de warmtedrager temperatuur op basis van de ingebouwde curves modus. Incompatibel met PID en Equitherm." } }, "mqtt": { - "homeAssistantDiscovery": "Home Assistant Discovery", + "haDiscovery": "HomeAssistant Discovery", + "haDiscoveryPrefix": "Prefix voor HomeAssistant Discovery", "server": "Server", "port": "Poort", "user": "Gebruiker", "password": "Wachtwoord", - "prefix": "Prefix", - "interval": "Publicatie-interval (sec)" + "prefix": { + "title": "Apparaatvoorvoegsel", + "note": "MQTT-topicvoorvoegsel, uniek voor elk apparaat" + }, + "interval": { + "title": "Publicatie-interval", + "note": "Interval voor het geforceerd publiceren van waarden, ook als ze ongewijzigd zijn (in seconden)" + } }, "extPump": { "use": "Gebruik externe pomp", @@ -484,14 +521,14 @@ "enable": "Ingang ingeschakeld", "gpio": "GPIO", "invertState": "Inverteer GPIO-status", - "thresholdTime": "Drempeltijd statuswijziging (sec)" + "thresholdTime": "Vertraging bij statuswijziging (sec)" }, "output": { "desc": "Kan worden gebruikt om een andere ketel in te schakelen via een relais.", "enable": "Uitgang ingeschakeld", "gpio": "GPIO", "invertState": "Inverteer GPIO-status", - "thresholdTime": "Drempeltijd statuswijziging (sec)", + "thresholdTime": "Vertraging bij statuswijziging (sec)", "events": { "desc": "Gebeurtenissen", "onFault": "Als de storingsstatus actief is", @@ -501,14 +538,44 @@ } } }, + "logs": { + "title": "Logboek - OpenTherm Gateway", + "name": "Logboek", + "desc": "Apparaatlogboek in realtime.", + "status": { + "connecting": "Verbinden...", + "connected": "Verbonden", + "disconnected": "Verbinding verbroken" + }, + "autoscroll": "Automatisch scrollen", + "limitHistory": "Bewaar maximaal 1000 regels", + "historyNote": "Onbeperkte geschiedenis gebruikt meer browsergeheugen. Downloads bevatten alle bewaarde regels, ook de regels die door het filter zijn verborgen.", + "filter": "Filter", + "search": { + "title": "Zoeken", + "previous": "Vorige", + "next": "Volgende" + }, + "level": { + "note": "Het niveau geldt voor het apparaatlogboek (Serial en WebSerial). Het onderstaande filter wijzigt alleen de weergave.", + "loadError": "Het logniveau kon niet worden geladen. Probeer opnieuw.", + "saveError": "Het logniveau kon niet worden opgeslagen. Controleer de verbinding en probeer opnieuw." + }, + "clear": "Wissen", + "download": "Logboek downloaden" + }, "upgrade": { "title": "Upgrade - OpenTherm Gateway", "name": "Upgrade", "section": { - "backupAndRestore": "Back-up & herstel", - "backupAndRestore.desc": "In deze sectie kunt u een back-up van ALLE instellingen opslaan en herstellen.", - "upgrade": "Upgrade", - "upgrade.desc": "In deze sectie kunt u de firmware en het bestandssysteem van uw apparaat upgraden.
De nieuwste releases kunnen worden gedownload van de Releases-pagina van de projectrepository." + "backupAndRestore": { + "title": "Back-up & herstel", + "desc": "In deze sectie kunt u een back-up van ALLE instellingen opslaan en herstellen." + }, + "upgrade": { + "title": "Upgrade", + "desc": "In deze sectie kunt u de firmware en het bestandssysteem van uw apparaat upgraden.
De nieuwste releases kunnen worden gedownload van de Releases-pagina van de projectrepository." + } }, "note": { "disclaimer1": "Na een succesvolle upgrade van het bestandssysteem worden ALLE instellingen teruggezet naar de standaardwaarden! Sla een back-up op voordat u gaat upgraden.", diff --git a/src_data/locales/ru.json b/src_data/locales/ru.json index 90b6695..1fb38c9 100644 --- a/src_data/locales/ru.json +++ b/src_data/locales/ru.json @@ -8,15 +8,21 @@ "issues": "Проблемы и вопросы", "releases": "Релизы" }, - "dbm": "дБм", - "kw": "кВт", - "time": { + "units": { "days": "д.", "hours": "ч.", "min": "мин.", - "sec": "сек." + "sec": "сек.", + "dbm": "дБм", + "mhz": "МГц", + "kw": "кВт", + "rpm": "RPM", + "ppm": "ppm", + "byte": "байт", + "mbyte": "мбайт", + "liter": "Л.", + "gallon": "гал." }, - "button": { "upgrade": "Обновить", "restart": "Перезагрузка", @@ -31,26 +37,25 @@ "success": "Успешно", "error": "Ошибка" }, - "index": { "title": "OpenTherm Gateway", - "section": { "network": "Сеть", "system": "Система" }, - "system": { "build": { "title": "Билд", "version": "Версия", + "commit": "Коммит", "date": "Дата", "core": "Ядро", "sdk": "SDK" }, "uptime": "Аптайм", "memory": { - "title": "ОЗУ", + "heap": "Память (heap)", + "psram": "Память (PSRAM)", "maxFreeBlock": "макс. блок", "min": "мин." }, @@ -61,32 +66,28 @@ "freq": "частота" }, "flash": { - "size": "Размер ПЗУ", - "realSize": "реальный размер" + "size": "Размер ПЗУ" }, - "lastResetReason": "Причина перезагрузки" + "lastResetReason": "Причина перезагрузки", + "coreDump": "Дамп памяти" } }, - "dashboard": { "name": "Дашборд", "title": "Дашборд - OpenTherm Gateway", - "section": { "control": "Управление", "states": "Состояние", "sensors": "Сенсоры", "diag": "Диагностика OpenTherm" }, - "thermostat": { "heating": "Отопление", "dhw": "ГВС", - "temp.current": "Текущая", + "currentTemp": "Текущая", "enable": "Вкл", "turbo": "Турбо" }, - "notify": { "fault": { "title": "Состояние неисправности котла активно!", @@ -98,7 +99,6 @@ }, "reset": "Сбросить" }, - "states": { "mNetworkConnected": "Подключение к сети", "mMqttConnected": "Подключение к MQTT", @@ -106,7 +106,6 @@ "mExtPumpState": "Внешний насос", "mCascadeControlInput": "Каскадное управление (вход)", "mCascadeControlOutput": "Каскадное управление (выход)", - "sConnected": "Подключение к OpenTherm", "sFlame": "Пламя", "sCoolingActive": "Охлаждение", @@ -115,10 +114,10 @@ "sFaultCode": "Код ошибки", "sDiagActive": "Диагностика", "sDiagCode": "Диагностический код", - "mHeatEnabled": "Отопление", "mHeatBlocking": "Блокировка отопления", "mHeatOverheat": "Отопление, перегрев", + "mHeatFreezing": "Отопление, защита от замерзания", "sHeatActive": "Активность отопления", "mHeatSetpointTemp": "Отопление, уставка", "mHeatTargetTemp": "Отопление, целевая температура", @@ -126,7 +125,6 @@ "mHeatRetTemp": "Отопление, температура обратки", "mHeatIndoorTemp": "Отопление, внутренняя темп.", "mHeatOutdoorTemp": "Отопление, наружная темп.", - "mDhwEnabled": "ГВС", "mDhwOverheat": "ГВС, перегрев", "sDhwActive": "Активность ГВС", @@ -134,7 +132,6 @@ "mDhwCurrTemp": "ГВС, текущая температура", "mDhwRetTemp": "ГВС, температура обратки" }, - "sensors": { "values": { "temp": "Температура", @@ -144,28 +141,30 @@ } } }, - "network": { "title": "Сеть - OpenTherm Gateway", "name": "Настройки сети", - + "type": { + "title": "Способ подключения", + "wifi": "Wi-Fi", + "ethernet": "Ethernet" + }, "section": { "static": "Статические параметры", "ethernet": "Ethernet", + "wifi": "Wi-Fi", "availableNetworks": "Доступные сети", "staSettings": "Настройки подключения", "apSettings": "Настройки точки доступа" }, - "scan": { "pos": "#", "info": "Инфо", - "unavailable": "Включите WiFi, чтобы искать сети" + "unavailable": "Поиск сетей доступен только в режиме Wi-Fi." }, "ethernet": { - "enable": "Включить ethernet", - "notConfigured": "Заполните все шесть выводов GPIO, чтобы включить ethernet.", + "notConfigured": "Для подключения через Ethernet настройте все шесть GPIO.", "clk": "GPIO тактирования SPI", "mosi": "GPIO MOSI SPI", "miso": "GPIO MISO SPI", @@ -174,7 +173,6 @@ "rst": "GPIO сброса", "note": "Подключение W5500 по SPI" }, - "wifi": { "ssid": "Имя сети", "password": "Пароль", @@ -182,7 +180,6 @@ "signal": "Сигнал", "connected": "Подключено" }, - "params": { "hostname": "Имя хоста", "dhcp": "Использовать DHCP", @@ -199,16 +196,15 @@ "none": "Нет" } }, - "sta": { - "channel.note": "установите 0 для автоматического выбора" + "channel": { + "note": "установите 0 для автоматического выбора" + } } }, - "sensors": { "title": "Настройки сенсоров - OpenTherm Gateway", "name": "Настройки сенсоров", - "enabled": "Включить и использовать", "sensorName": { "title": "Имя сенсора", @@ -265,10 +261,11 @@ "otHeatingPumpHours": "OpenTherm, кол-во часов работы насоса (отопление)", "otDhwPumpHours": "OpenTherm, кол-во часов работы насоса (ГВС)", "otCoolingHours": "OpenTherm, кол-во часов работы охлаждения", - "ntcTemp": "NTC датчик", "dallasTemp": "DALLAS датчик", "bluetooth": "BLE датчик", + "dht11": "DHT11 датчик", + "dht22": "DHT22 датчик", "heatSetpointTemp": "Отопление, температура уставки", "manual": "Вручную через MQTT/API", "notConfigured": "Не сконфигурировано" @@ -295,11 +292,9 @@ } } }, - "settings": { "title": "Настройки - OpenTherm Gateway", "name": "Настройки", - "section": { "portal": "Настройки портала", "system": "Системные настройки", @@ -314,18 +309,21 @@ "extPump": "Настройки дополнительного насоса", "cascadeControl": "Настройки каскадного управления" }, - "enable": "Вкл", "note": { "restart": "После изменения этих настроек устройство необходимо перезагрузить, чтобы изменения вступили в силу.", "blankNotUse": "пусто - не использовать", "bleDevice": "BLE устройство можно использовать только с некоторыми платами ESP32, которые поддерживают BLE!" }, - "temp": { "min": "Мин. температура", "max": "Макс. температура" }, + "avgType": { + "mean": "Средняя температура", + "min": "Минимальная температура", + "max": "Максимальная температура" + }, "maxModulation": "Макс. уровень модуляции", "ohProtection": { "title": "Защита от перегрева", @@ -351,14 +349,12 @@ "note": "Порог, при котором отопление будет принудительно включено" } }, - "portal": { "login": "Логин", "password": "Пароль", "auth": "Требовать аутентификацию", "mdns": "Использовать mDNS" }, - "system": { "unit": "Система единиц", "metric": "Метрическая (цельсии, литры, бары)", @@ -369,12 +365,8 @@ "enable": "Вкл. Serial порт", "baud": "Скорость Serial порта" }, - "telnet": { - "enable": "Вкл. Telnet", - "port": { - "title": "Telnet порт", - "note": "По умолчанию: 23" - } + "webSerial": { + "enable": "Вкл. WebSerial" }, "ntp": { "server": "NTP сервер", @@ -382,31 +374,30 @@ "timezonePresets": "Выберите пресет..." } }, - "heating": { "hyst": { "title": "Гистерезис", "desc": "Гистерезис полезен для поддержания заданной внутр. темп. (при использовании «ПЗА» и/или «ПИД»). Принудительно откл. отопление, когда current indoor > target + value, и вкл. отопление, когда current indoor < (target - value).", - "value": "Значение (в градусах)", - "action": { - "title": "Действие", - "disableHeating": "Отключить отопление", - "set0target": "Установить 0 в качестве целевой темп." - } + "value": "Значение (в градусах)" }, - "turboFactor": "Коэфф. турбо режима" + "turboFactor": "Коэфф. турбо режима", + "indoorTempAvgType": { + "title": "Тип усреднения внутренней темп.", + "desc": "Полезно при использовании двух и более датчиков внутренней температуры (при использовании «Equitherm» и/или «PID»)." + }, + "outdoorTempAvgType": { + "title": "Тип усреднения наружнной темп.", + "desc": "Полезно при использовании двух и более датчиков наружной температуры (при использовании «Equitherm»)." + } }, - "emergency": { "desc": "Аварийный режим активируется автоматически, если «ПИД» или «ПЗА» не могут рассчитать уставку теплоносителя:
- если «ПЗА» включен и датчик наружной температуры отключен;
- если включен «ПИД» или OT опция «Передать управление отоплением котлу» и датчик внутренней температуры отключен.
Примечание: При сбое сети или MQTT датчики с типом «Вручную через MQTT/API» будут находиться в состоянии ОТКЛЮЧЕН.", - "target": { - "title": "Целевая температура", - "note": "Важно: Целевая температура в помещении, если включена ОТ опция «Передать управление отоплением котлу».
Во всех остальных случаях целевая температура теплоносителя." + "title": "Целевая температура" }, - "treshold": "Пороговое время включения (сек)" + "thresholdTime": "Задержка изменения состояния (сек)", + "note": "Важно: Целевая температура в помещении, если включена ОТ опция «Передать управление отоплением котлу».
Во всех остальных случаях целевая температура теплоносителя." }, - "equitherm": { "slope": { "title": "Наклон", @@ -430,7 +421,6 @@ "outdoorTemp": "Наружная температура" } }, - "pid": { "p": "Коэффициент P", "i": "Коэффициент I", @@ -450,8 +440,17 @@ "thresholdLow": "Нижний порог" } }, - "ot": { + "disablingAction": { + "title": "Действие отключения контуров", + "desc": "Выбранное действие применяется при любой причине отключения, включая перегрев.
Некоторые котлы отключают циркуляционный насос при отключении контура, в этом случае можно попробовать установить 0 в качестве целевой температуры, чтобы выбег насоса работал корректно.", + "heating": "Контур отопления", + "dhw": "Контур ГВС", + "ch2": "Контур 2", + "off": "Только отключить контур", + "zeroSetpoint": "Установить 0 в качестве целевой температуры", + "offAndZeroSetpoint": "Отключить контур и установить 0 в качестве целевой температуры" + }, "advanced": "Дополнительные настройки", "inGpio": "Вход GPIO", "outGpio": "Выход GPIO", @@ -466,7 +465,6 @@ "title": "Макс. мощность котла (кВт)", "note": "0 - попробовать определить автоматически. Обычно можно найти в спецификации котла как \"максимальная полезная тепловая мощность\"." }, - "options": { "title": "Опции (дополнительные настройки)", "desc": "Опции могут менять логику работы котла. Не все опции задокументированы в протоколе, поэтому одна и та же опция может иметь разный эффект на разных котлах.
Примечание: Нет необходимости что-то менять, если всё работает хорошо.", @@ -488,23 +486,27 @@ "immergasFix": "Фикс для котлов Immergas", "alwaysSendIndoorTemp": "Передавать текущую темп. в помещении котлу" }, - "nativeOTC": { "title": "Нативный режим OTC (расчёт температуры теплоносителя)", "note": "Работает ТОЛЬКО если котел в режиме OTC: требует и принимает целевую температуру в помещении и сам регулирует температуру теплоносителя на основе встроенного режима кривых. Несовместимо с ПИД и ПЗА." } }, - "mqtt": { - "homeAssistantDiscovery": "Home Assistant Discovery", + "haDiscovery": "HomeAssistant Discovery", + "haDiscoveryPrefix": "HomeAssistant Discovery префикс", "server": "Адрес сервера", "port": "Порт", "user": "Имя пользователя", "password": "Пароль", - "prefix": "Префикс", - "interval": "Интервал публикации (сек)" + "prefix": { + "title": "Префикс устройства", + "note": "Префикс MQTT-топиков, уникальный для каждого устройства" + }, + "interval": { + "title": "Интервал публикации", + "note": "Период принудительной публикации значений, включая неизменившиеся (в секундах)" + } }, - "extPump": { "use": "Использовать доп. насос", "gpio": "GPIO реле", @@ -513,21 +515,20 @@ "antiStuckInterval": "Интервал защиты от блокировки (в днях)", "antiStuckTime": "Время работы насоса (в минутах)" }, - "cascadeControl": { "input": { "desc": "Может использоваться для включения отопления только при неисправности другого котла. Контроллер другого котла должен изменить состояние входа GPIO в случае неисправности.", "enable": "Включить вход", "gpio": "GPIO", "invertState": "Инвертировать состояние GPIO", - "thresholdTime": "Пороговое время изменения состояния (сек)" + "thresholdTime": "Задержка изменения состояния (сек)" }, "output": { "desc": "Может использоваться для включения другого котла через реле.", "enable": "Включить выход", "gpio": "GPIO", "invertState": "Инвертировать состояние GPIO", - "thresholdTime": "Пороговое время изменения состояния (сек)", + "thresholdTime": "Задержка изменения состояния (сек)", "events": { "desc": "События", "onFault": "Если состояние fault (ошибки) активно", @@ -537,26 +538,52 @@ } } }, - + "logs": { + "title": "Журнал - OpenTherm Gateway", + "name": "Журнал", + "desc": "Журнал устройства в реальном времени.", + "status": { + "connecting": "Подключение...", + "connected": "Подключено", + "disconnected": "Нет подключения" + }, + "autoscroll": "Автопрокрутка", + "limitHistory": "Хранить не более 1000 записей", + "historyNote": "Без ограничения журнал использует больше памяти браузера. Скачиваются все сохранённые записи, включая скрытые фильтром.", + "filter": "Фильтр", + "search": { + "title": "Поиск", + "previous": "Назад", + "next": "Вперёд" + }, + "level": { + "note": "Уровень применяется к журналу устройства (Serial и WebSerial). Фильтр ниже меняет только отображение.", + "loadError": "Не удалось загрузить уровень журнала. Повторите запрос.", + "saveError": "Не удалось сохранить уровень журнала. Проверьте соединение и повторите попытку." + }, + "clear": "Очистить", + "download": "Скачать журнал" + }, "upgrade": { "title": "Обновление - OpenTherm Gateway", "name": "Обновление", - "section": { - "backupAndRestore": "Резервное копирование и восстановление", - "backupAndRestore.desc": "В этом разделе вы можете сохранить и восстановить резервную копию ВСЕХ настроек.", - "upgrade": "Обновление", - "upgrade.desc": "В этом разделе вы можете обновить прошивку и файловую систему вашего устройства.
Последнюю версию можно загрузить со страницы Релизы в репозитории проекта." + "backupAndRestore": { + "title": "Резервное копирование и восстановление", + "desc": "В этом разделе вы можете сохранить и восстановить резервную копию ВСЕХ настроек." + }, + "upgrade": { + "title": "Обновление", + "desc": "В этом разделе вы можете обновить прошивку и файловую систему вашего устройства.
Последнюю версию можно загрузить со страницы Релизы в репозитории проекта." + } }, - "note": { "disclaimer1": "После успешного обновления файловой системы ВСЕ настройки будут сброшены на стандартные! Создайте резервную копию ПЕРЕД обновлением.", "disclaimer2": "После успешного обновления устройство автоматически перезагрузится через 15 секунд." }, - "settingsFile": "Файл настроек", "fw": "Прошивка", "fs": "Файловая система" } } -} \ No newline at end of file +} diff --git a/src_data/pages/dashboard.html b/src_data/pages/dashboard.html index ad5ae18..6b2a844 100644 --- a/src_data/pages/dashboard.html +++ b/src_data/pages/dashboard.html @@ -47,7 +47,7 @@
dashboard.thermostat.heating
-
dashboard.thermostat.temp.current:
+
dashboard.thermostat.currentTemp:
@@ -68,7 +68,7 @@
dashboard.thermostat.dhw
-
dashboard.thermostat.temp.current:
+
dashboard.thermostat.currentTemp:
@@ -312,12 +312,12 @@ let prevSettings; let newSettings = { heating: { - enable: false, + enabled: false, turbo: false, target: 0 }, dhw: { - enable: false, + enabled: false, target: 0 } }; @@ -326,84 +326,119 @@ const lang = new Lang(document.getElementById('lang')); await lang.build(); - let actionTimer = null; - let actionLongPress = false; + let activePress = null; + const stopPress = () => { + if (!activePress) { + return; + } + + const press = activePress; + activePress = null; + clearInterval(press.timer); + if (press.button.hasPointerCapture(press.pointerId)) { + press.button.releasePointerCapture(press.pointerId); + } + }; + document.querySelectorAll('.tAction').forEach((item) => { const action = item.dataset.action; const tContainer = item.parentNode.parentNode; + const changeTarget = (step, minTemp, maxTemp) => { + const purpose = tContainer.dataset.purpose; + let value = 0; + if (action == 'increment') { + value = step; - for (const eName of ['pointerup', 'pointercancel']) { - item.addEventListener(eName, (event) => { - clearInterval(actionTimer); + } else if (action == 'decrement') { + value = -(step); + } - const purpose = tContainer.dataset.purpose; - const minTemp = parseFloat(tContainer.dataset.min); - const maxTemp = parseFloat(tContainer.dataset.max); - const step = parseFloat(tContainer.dataset.step); - const bigStep = parseFloat(tContainer.dataset.bigStep); + const newValue = parseFloat(constrain(newSettings[purpose].target + value, minTemp, maxTemp).toFixed(2)); + if (newSettings[purpose].target != newValue) { + newSettings[purpose].target = newValue; + modifiedTime = Date.now(); - if (!actionLongPress && prevSettings) { - let value = 0; - if (action == 'increment') { - value = step; - - } else if (action == 'decrement') { - value = -(step); - } - - newSettings[purpose].target = parseFloat(constrain(newSettings[purpose].target + value, minTemp, maxTemp).toFixed(2)); - modifiedTime = Date.now(); - setValue('.targetTemp', newSettings[purpose].target, tContainer); - } - }); - } + setValue('.targetTemp', newValue, tContainer); + tContainer.querySelector('.thermostat-header').setAttribute("aria-busy", "true"); + } + }; item.addEventListener('pointerdown', (event) => { - if (!prevSettings) { + if (!prevSettings || activePress || event.button !== 0) { return; } - const purpose = tContainer.dataset.purpose; const minTemp = parseFloat(tContainer.dataset.min); const maxTemp = parseFloat(tContainer.dataset.max); - const step = parseFloat(tContainer.dataset.step); const bigStep = parseFloat(tContainer.dataset.bigStep); - - actionLongPress = false; - actionTimer = setInterval(() => { - if (!actionLongPress) { - actionLongPress = true; - } - - let value = 0; - if (action == 'increment') { - value = bigStep; - - } else if (action == 'decrement') { - value = -(bigStep); - } - - newSettings[purpose].target = parseFloat(constrain(newSettings[purpose].target + value, minTemp, maxTemp).toFixed(2)); - modifiedTime = Date.now(); - - setValue('.targetTemp', newSettings[purpose].target, tContainer); + const press = {button: item, pointerId: event.pointerId, timer: null, longPress: false}; + activePress = press; + item.setPointerCapture(event.pointerId); + press.timer = setInterval(() => { + press.longPress = true; + changeTarget(bigStep, minTemp, maxTemp); }, 500); }); + + item.addEventListener('pointerup', (event) => { + if (!activePress || activePress.button !== item || activePress.pointerId !== event.pointerId) { + return; + } + + const longPress = activePress.longPress; + stopPress(); + if (!longPress) { + changeTarget( + parseFloat(tContainer.dataset.step), + parseFloat(tContainer.dataset.min), parseFloat(tContainer.dataset.max) + ); + } + }); + + for (const eName of ['pointercancel', 'lostpointercapture']) { + item.addEventListener(eName, (event) => { + if (activePress && activePress.button === item && activePress.pointerId === event.pointerId) { + stopPress(); + } + }); + } + }); + + window.addEventListener('blur', stopPress); + document.addEventListener('visibilitychange', () => { + if (document.hidden) { + stopPress(); + } }); document.querySelector('#tHeatEnabled').addEventListener('change', (event) => { + if (newSettings.heating.enabled == event.currentTarget.checked) { + return; + } + modifiedTime = Date.now(); newSettings.heating.enabled = event.currentTarget.checked; + document.querySelector('.tHeat .thermostat-header').setAttribute("aria-busy", "true"); }); document.querySelector('#tHeatTurbo').addEventListener('change', (event) => { + if (newSettings.heating.turbo == event.currentTarget.checked) { + return; + } + modifiedTime = Date.now(); newSettings.heating.turbo = event.currentTarget.checked; + document.querySelector('.tHeat .thermostat-header').setAttribute("aria-busy", "true"); }); document.querySelector('#tDhwEnabled').addEventListener('change', (event) => { + if (newSettings.dhw.enabled == event.currentTarget.checked) { + return; + } + modifiedTime = Date.now(); newSettings.dhw.enabled = event.currentTarget.checked; + document.querySelector('.tDhw .thermostat-header').setAttribute("aria-busy", "true"); }); document.querySelector('.notify-fault .reset').addEventListener('click', async (event) => { @@ -421,7 +456,7 @@ }, body: JSON.stringify({ "actions": { - "resetFault": true + "reset_fault": true } }) }); @@ -448,7 +483,7 @@ }, body: JSON.stringify({ "actions": { - "resetDiagnostic": true + "reset_diagnostic": true } }) }); @@ -460,6 +495,27 @@ }, 10000); }); + const requestSettingsSection = async (section, values = null) => { + const parameters = { + method: "GET", + cache: "no-cache", + credentials: "include" + }; + + if (values !== null) { + parameters.method = "POST"; + parameters.headers = {"Content-Type": "application/json"}; + parameters.body = JSON.stringify(values); + } + + const response = await fetch(`/api/settings/${section}`, parameters); + if (!response.ok) { + throw new Error('Response not valid'); + } + + return response.json(); + }; + setTimeout(async function onLoadPage() { let unitSystem = null; @@ -474,60 +530,56 @@ // settings try { - let modified = prevSettings && ( - (prevSettings.heating.enabled != newSettings.heating.enabled) - || (prevSettings.heating.turbo != newSettings.heating.turbo) - || (prevSettings.heating.target != newSettings.heating.target) - || (prevSettings.opentherm.options.dhwSupport && prevSettings.dhw.enabled != newSettings.dhw.enabled) - || (prevSettings.opentherm.options.dhwSupport && prevSettings.dhw.target != newSettings.dhw.target) + const heatingSettings = {...newSettings.heating}; + const dhwSettings = {...newSettings.dhw}; + const heatingModified = prevSettings && ( + (prevSettings.heating.enabled != heatingSettings.enabled) + || (prevSettings.heating.turbo != heatingSettings.turbo) + || (prevSettings.heating.target != heatingSettings.target) + ); + const dhwModified = prevSettings && prevSettings.opentherm.options.dhw_support && ( + (prevSettings.dhw.enabled != dhwSettings.enabled) + || (prevSettings.dhw.target != dhwSettings.target) ); - if (modified) { - console.log(newSettings); - } - - let parameters = { - method: "GET", - cache: "no-cache", - credentials: "include" - }; - - if (modified) { - parameters.method = "POST"; - parameters.body = JSON.stringify(newSettings); - } - - const response = await fetch("/api/settings", parameters); - if (!response.ok) { - throw new Error('Response not valid'); - } - - const result = await response.json(); + const system = await requestSettingsSection('system'); + const opentherm = await requestSettingsSection('opentherm'); + const heating = await requestSettingsSection('heating', heatingModified ? heatingSettings : null); + const dhw = await requestSettingsSection('dhw', dhwModified ? dhwSettings : null); + const result = {system, opentherm, heating, dhw}; prevSettings = result; - unitSystem = result.system.unitSystem; - newSettings.heating.enabled = result.heating.enabled; - newSettings.heating.turbo = result.heating.turbo; - newSettings.heating.target = result.heating.target; - newSettings.dhw.enabled = result.dhw.enabled; - newSettings.dhw.target = result.dhw.target; + unitSystem = result.system.unit_system; - if (result.opentherm.options.dhwSupport) { + if (result.opentherm.options.dhw_support) { show('.tDhw'); } else { hide('.tDhw'); } - setCheckboxValue('#tHeatEnabled', result.heating.enabled); - setCheckboxValue('#tHeatTurbo', result.heating.turbo); - setValue('.tHeat .targetTemp', result.heating.target); - - setCheckboxValue('#tDhwEnabled', result.dhw.enabled); - setValue('.tDhw .targetTemp', result.dhw.target); - setValue('.tempUnit', temperatureUnit(unitSystem)); setValue('.pressureUnit', pressureUnit(unitSystem)); setValue('.volumeUnit', volumeUnit(unitSystem)); + // An edit made while these requests were in flight is still waiting to be sent. + if (modifiedTime === null) { + newSettings.heating.enabled = result.heating.enabled; + newSettings.heating.turbo = result.heating.turbo; + newSettings.heating.target = result.heating.target; + newSettings.dhw.enabled = result.dhw.enabled; + newSettings.dhw.target = result.dhw.target; + + setCheckboxValue('#tHeatEnabled', result.heating.enabled); + setCheckboxValue('#tHeatTurbo', result.heating.turbo); + setValue('.tHeat .targetTemp', result.heating.target); + + setCheckboxValue('#tDhwEnabled', result.dhw.enabled); + setValue('.tDhw .targetTemp', result.dhw.target); + + document.querySelectorAll('.thermostat-header').forEach((item) => { + item.setAttribute("aria-busy", "false"); + }); + } + } catch (error) { console.log(error); } @@ -546,20 +598,20 @@ const result = await response.json(); // Graph - setValue('#tHeatCurrentTemp', result.master.heating.indoorTempControl - ? result.master.heating.indoorTemp - : result.master.heating.currentTemp + setValue('#tHeatCurrentTemp', result.master.heating.smart_control + ? result.master.heating.indoor_temp + : result.master.heating.current_temp ); - setValue('#tDhwCurrentTemp', result.master.dhw.currentTemp); + setValue('#tDhwCurrentTemp', result.master.dhw.current_temp); // SLAVE - setValue('.sMemberId', result.slave.memberId); - setValue('.sVendor', memberIdToVendor(result.slave.memberId)); + setValue('.sMemberId', result.slave.member_id); + setValue('.sVendor', memberIdToVendor(result.slave.member_id)); setValue('.sFlags', result.slave.flags); setValue('.sType', result.slave.type); - setValue('.sAppVersion', result.slave.appVersion); - setValue('.sProtocolVersion', result.slave.protocolVersion); + setValue('.sAppVersion', result.slave.app_version); + setValue('.sProtocolVersion', result.slave.protocol_version); setStatus( '.sConnected', @@ -578,12 +630,12 @@ setValue('.sPowerMax', result.slave.power.max); setState('.sHeatActive', result.slave.heating.active); - setValue('.sHeatMinTemp', result.slave.heating.minTemp); - setValue('.sHeatMaxTemp', result.slave.heating.maxTemp); + setValue('.sHeatMinTemp', result.slave.heating.min_temp); + setValue('.sHeatMaxTemp', result.slave.heating.max_temp); setState('.sDhwActive', result.slave.dhw.active); - setValue('.sDhwMinTemp', result.slave.dhw.minTemp); - setValue('.sDhwMaxTemp', result.slave.dhw.maxTemp); + setValue('.sDhwMinTemp', result.slave.dhw.min_temp); + setValue('.sDhwMaxTemp', result.slave.dhw.max_temp); setStatus( '.sFaultActive', @@ -631,7 +683,7 @@ result.master.heating.blocking ? "success" : "error", result.master.heating.blocking ? "red" : "green" ); - setState('.mHeatIndoorTempControl', result.master.heating.indoorTempControl); + setState('.mHeatSmartControl', result.master.heating.smart_control); setStatus( '.mHeatOverheat', result.master.heating.overheat ? "success" : "error", @@ -642,14 +694,14 @@ result.master.heating.freezing ? "success" : "error", result.master.heating.freezing ? "red" : "green" ); - setValue('.mHeatSetpointTemp', result.master.heating.setpointTemp); - setValue('.mHeatTargetTemp', result.master.heating.targetTemp); - setValue('.mHeatCurrTemp', result.master.heating.currentTemp); - setValue('.mHeatRetTemp', result.master.heating.returnTemp); - setValue('.mHeatIndoorTemp', result.master.heating.indoorTemp); - setValue('.mHeatOutdoorTemp', result.master.heating.outdoorTemp); - setValue('.mHeatMinTemp', result.master.heating.minTemp); - setValue('.mHeatMaxTemp', result.master.heating.maxTemp); + setValue('.mHeatSetpointTemp', result.master.heating.setpoint_temp); + setValue('.mHeatTargetTemp', result.master.heating.target_temp); + setValue('.mHeatCurrTemp', result.master.heating.current_temp); + setValue('.mHeatRetTemp', result.master.heating.return_temp); + setValue('.mHeatIndoorTemp', result.master.heating.indoor_temp); + setValue('.mHeatOutdoorTemp', result.master.heating.outdoor_temp); + setValue('.mHeatMinTemp', result.master.heating.min_temp); + setValue('.mHeatMaxTemp', result.master.heating.max_temp); setState('.mDhwEnabled', result.master.dhw.enabled); setStatus( @@ -657,11 +709,11 @@ result.master.dhw.overheat ? "success" : "error", result.master.dhw.overheat ? "red" : "green" ); - setValue('.mDhwTargetTemp', result.master.dhw.targetTemp); - setValue('.mDhwCurrTemp', result.master.dhw.currentTemp); - setValue('.mDhwRetTemp', result.master.dhw.returnTemp); - setValue('.mDhwMinTemp', result.master.dhw.minTemp); - setValue('.mDhwMaxTemp', result.master.dhw.maxTemp); + setValue('.mDhwTargetTemp', result.master.dhw.target_temp); + setValue('.mDhwCurrTemp', result.master.dhw.current_temp); + setValue('.mDhwRetTemp', result.master.dhw.return_temp); + setValue('.mDhwMinTemp', result.master.dhw.min_temp); + setValue('.mDhwMaxTemp', result.master.dhw.max_temp); setStatus( '.mNetworkConnected', @@ -674,17 +726,17 @@ result.master.emergency.state ? "success" : "error", result.master.emergency.state ? "red" : "green" ); - setState('.mExtPumpState', result.master.externalPump.state); - setState('.mCascadeControlInput', result.master.cascadeControl.input); - setState('.mCascadeControlOutput', result.master.cascadeControl.output); + setState('.mExtPumpState', result.master.ext_pump.state); + setState('.mCascadeControlInput', result.master.cascade_control.input); + setState('.mCascadeControlOutput', result.master.cascade_control.output); const tHeat = document.querySelector('.tHeat'); - tHeat.dataset.min = result.master.heating.minTemp; - tHeat.dataset.max = result.master.heating.maxTemp; + tHeat.dataset.min = result.master.heating.min_temp; + tHeat.dataset.max = result.master.heating.max_temp; const tDhw = document.querySelector('.tDhw'); - tDhw.dataset.min = result.master.dhw.minTemp; - tDhw.dataset.max = result.master.dhw.maxTemp; + tDhw.dataset.min = result.master.dhw.min_temp; + tDhw.dataset.max = result.master.dhw.max_temp; setBusy('#dashboard-busy', '#dashboard-container', false); @@ -739,12 +791,12 @@ sData.connected ? "green" : "red", sensorNode ); - setValue(".sName", sData.name, sensorNode); + setTextValue(".sName", sData.name, sensorNode); setValue(".sValue", "", sensorNode); const statusNode = sensorNode.querySelector(`.sStatusContainer`); if (statusNode) { - statusNode.dataset.tooltip = `${sData.signalQuality}%`; + statusNode.dataset.tooltip = `${sData.signal_quality}%`; } if (sData.value !== undefined) { @@ -766,7 +818,7 @@ } if (sData.rssi !== undefined) { - appendValue(".sValue", `${i18n('dashboard.sensors.values.rssi')}: ${sData.rssi.toFixed(0)} ${i18n('dbm')}`, `
`, sensorNode); + appendValue(".sValue", `${i18n('dashboard.sensors.values.rssi')}: ${sData.rssi.toFixed(0)} ${i18n('units.dbm')}`, `
`, sensorNode); } } @@ -779,4 +831,4 @@ }); - \ No newline at end of file + diff --git a/src_data/pages/index.html b/src_data/pages/index.html index b9cefaf..8cf9870 100644 --- a/src_data/pages/index.html +++ b/src_data/pages/index.html @@ -108,6 +108,7 @@ index.system.build.title Env:
+ index.system.build.commit:
index.system.build.date:
index.system.build.core:
index.system.build.sdk: @@ -116,32 +117,39 @@ index.system.uptime - time.days, - time.hours, - time.min, - time.sec + units.days, + units.hours, + units.min, + units.sec - index.system.memory.title + index.system.memory.heap - of bytes (index.system.memory.min: bytes)
- index.system.memory.maxFreeBlock: bytes (index.system.memory.min: bytes) + of units.byte (index.system.memory.min: units.byte)
+ index.system.memory.maxFreeBlock: units.byte (index.system.memory.min: units.byte) + + + + index.system.memory.psram + + of units.byte (index.system.memory.min: units.byte)
+ index.system.memory.maxFreeBlock: units.byte index.system.board index.system.chip.model: (rev. )
- index.system.chip.cores: , index.system.chip.freq: mHz
- index.system.flash.size: MB (index.system.flash.realSize: MB) + index.system.chip.cores: , index.system.chip.freq: units.mhz
+ index.system.flash.size: units.mbyte index.system.lastResetReason
- Save debug data + index.system.coreDump @@ -151,8 +159,9 @@ dashboard.name settings.name sensors.name + logs.name upgrade.name - button.restart + button.restart
@@ -175,6 +184,44 @@ const lang = new Lang(document.getElementById('lang')); await lang.build(); + const restartButton = document.querySelector('.restart'); + restartButton.addEventListener('click', async (event) => { + event.preventDefault(); + if (restartButton.disabled) { + return; + } + + restartButton.disabled = true; + restartButton.setAttribute('aria-busy', true); + restartButton.textContent = i18n('button.wait'); + + try { + const response = await fetch('/api/restart', { + method: 'POST', + cache: 'no-cache', + credentials: 'include' + }); + if (response.status !== 202) { + throw new Error('Restart request failed'); + } + + restartButton.textContent = i18n('button.restart'); + restartButton.classList.add('success'); + + } catch { + restartButton.textContent = i18n('button.error'); + restartButton.classList.add('failed'); + restartButton.removeAttribute('aria-busy'); + } + + setTimeout(() => { + restartButton.disabled = false; + restartButton.classList.remove('success', 'failed'); + restartButton.removeAttribute('aria-busy'); + restartButton.textContent = i18n('button.restart'); + }, 15000); + }); + setTimeout(async function onLoadPage() { try { const response = await fetch("/api/info", { @@ -187,55 +234,57 @@ } const result = await response.json(); - setValue('#reset-reason', result.system.resetReason); + setTextValue('#reset-reason', result.system.reset_reason); setValue('#uptime', result.system.uptime); setValue('#uptime-days', Math.floor(result.system.uptime / 86400)); setValue('#uptime-hours', Math.floor(result.system.uptime % 86400 / 3600)); setValue('#uptime-min', Math.floor(result.system.uptime % 3600 / 60)); setValue('#uptime-sec', Math.floor(result.system.uptime % 60)); - setValue('#network-hostname', result.network.hostname); - setValue('#network-mac', result.network.mac); - setValue('#network-connection', i18n(`network.params.connectionType.${result.network.connectionType}`)); + setTextValue('#network-hostname', result.network.hostname); + setTextValue('#network-mac', result.network.mac); + setTextValue('#network-connection', i18n(`network.params.connectionType.${result.network.connection_type}`)); setStatus( '#network-connected', result.network.connected ? "success" : "error", result.network.connected ? "green" : "red" ); - setValue('#network-ssid', result.network.ssid); - setValue('#network-signal', result.network.signalQuality); - - // SSID and signal strength only describe the uplink when WiFi carries it; with - // ethernet up the radio is parked and both values are meaningless - const wifiUplink = result.network.connectionType === "wifi"; - + setTextValue('#network-ssid', result.network.ssid); + setValue('#network-signal', result.network.signal_quality); + // SSID and signal strength describe only the Wi-Fi uplink. + const wifiUplink = result.network.connection_type === "wifi"; document.getElementById("network-ssid-row")?.classList.toggle("hidden", !wifiUplink); document.getElementById("network-signal-row")?.classList.toggle("hidden", !wifiUplink); - setValue('#network-ip', result.network.ip); - setValue('#network-subnet', result.network.subnet); - setValue('#network-gateway', result.network.gateway); - setValue('#network-dns', result.network.dns); + setTextValue('#network-ip', result.network.ip); + setTextValue('#network-subnet', result.network.subnet); + setTextValue('#network-gateway', result.network.gateway); + setTextValue('#network-dns', result.network.dns); setBusy('#main-busy', '#main-table', false); - setValue('#build-version', result.build.version); - setValue('#build-date', result.build.date); - setValue('#build-env', result.build.env); - setValue('#build-core', result.build.core); - setValue('#build-sdk', result.build.sdk); + setTextValue('#build-version', result.build.version); + setTextValue('#build-commit', result.build.commit); + setTextValue('#build-date', result.build.date); + setTextValue('#build-env', result.build.env); + setTextValue('#build-core', result.build.core); + setTextValue('#build-sdk', result.build.sdk); setValue('#heap-total', result.heap.total); setValue('#heap-free', result.heap.free); - setValue('#heap-min-free', result.heap.minFree); - setValue('#heap-max-free-block', result.heap.maxFreeBlock); - setValue('#heap-min-max-free-block', result.heap.minMaxFreeBlock); + setValue('#heap-min-free', result.heap.min_free); + setValue('#heap-max-free-block', result.heap.max_free_block); + setValue('#heap-min-max-free-block', result.heap.min_max_free_block); - setValue('#chip-model', result.chip.model); + setValue('#psram-total', result.psram.total); + setValue('#psram-free', result.psram.free); + setValue('#psram-min-free', result.psram.min_free); + setValue('#psram-max-free-block', result.psram.max_free_block); + + setTextValue('#chip-model', result.chip.model); setValue('#chip-rev', result.chip.rev); setValue('#chip-cores', result.chip.cores); setValue('#chip-freq', result.chip.freq); setValue('#flash-size', result.flash.size / 1024 / 1024); - setValue('#flash-real-size', result.flash.realSize / 1024 / 1024); setBusy('#system-busy', '#system-table', false); @@ -248,4 +297,4 @@ }); - \ No newline at end of file + diff --git a/src_data/pages/logs.html b/src_data/pages/logs.html new file mode 100644 index 0000000..76a6a14 --- /dev/null +++ b/src_data/pages/logs.html @@ -0,0 +1,664 @@ + + + + + + logs.title + + + + + +
+ +
+ +
+
+
+

logs.name

+

logs.desc

+
+ +
+ +
+ + +
+ logs.level.note + +
+ +
+ +
+ + +
+ logs.historyNote + +
+ +
+ +
+ + + +
+
+
+ +
+
+ 0 / 0 + + + +
+
+
+ +
+ + +
+
+
+ + + + + + + diff --git a/src_data/pages/network.html b/src_data/pages/network.html index a2b80f5..9945a25 100644 --- a/src_data/pages/network.html +++ b/src_data/pages/network.html @@ -47,7 +47,15 @@ + +
@@ -56,22 +64,22 @@ @@ -80,35 +88,42 @@ -
+
+
+

network.section.wifi

+

+
+

network.section.availableNetworks

-
- - - - - - - - - -
network.scan.posnetwork.wifi.ssidnetwork.scan.info
-
+
+
+ + + + + + + + + +
network.scan.posnetwork.wifi.ssidnetwork.scan.info
+
- - + + +

-

network.section.staSettings

+

network.section.staSettings

@@ -116,52 +131,51 @@
-
-
-
-
-
-

network.section.apSettings

-

-
+
+
+
+

network.section.apSettings

+

+
-
- + + +
@@ -174,43 +188,39 @@
@@ -208,38 +208,16 @@ const container = document.querySelector("article"); const templateNode = container.querySelector("#template"); - let bleSupported = false; - - const applyCapabilities = (info, root) => { - // pages and firmware ship together: BLE stays disabled unless the build says it has the stack - bleSupported = info?.features?.ble === true; - - root.querySelectorAll('[data-requires="ble"]').forEach((option) => { - option.disabled = !bleSupported; - }); - - document.getElementById("ble-not-supported")?.classList.toggle("hidden", bleSupported); - }; - try { - const [response, infoResponse] = await Promise.all([ - fetch("/api/sensors", { - cache: "no-cache", - credentials: "include" - }), - fetch("/api/info", { - cache: "no-cache", - credentials: "include" - }) - ]); + const response = await fetch("/api/sensors", { + cache: "no-cache", + credentials: "include" + }); if (!response.ok) { throw new Error("Response not valid"); } - const info = infoResponse.ok ? await infoResponse.json() : null; - applyCapabilities(info, templateNode); - const result = await response.json(); for (const sensorId in result) { const sensorNode = templateNode.cloneNode(true); @@ -248,7 +226,7 @@ sensorNode.dataset.id = sensorId; setValue(".id", sensorId, sensorNode); setValue(".pos", parseInt(sensorId) + 1, sensorNode); - setValue(".name", result[sensorId], sensorNode); + setTextValue(".name", result[sensorId], sensorNode); container.appendChild(sensorNode); container.appendChild(document.createElement("hr")); @@ -264,7 +242,7 @@ setInputValue("[name='offset']", data.offset, {}, sensorForm); setInputValue("[name='factor']", data.factor, {}, sensorForm); setCheckboxValue("[name='filtering']", data.filtering, sensorForm); - setInputValue("[name='filteringFactor']", data.filteringFactor, {}, sensorForm); + setInputValue("[name='filtering_factor']", data.filtering_factor, {}, sensorForm); setTimeout(() => { sensorForm.querySelector("[name='type']").dispatchEvent(new Event("change")); @@ -295,33 +273,35 @@ } switch(parseInt(event.target.value)) { - // ntc + // NTC10K case 50: parentGpio.classList.remove("hidden"); parentAddress.classList.add("hidden"); address.removeAttribute("pattern"); break; - // dallas + // OneWire case 51: parentGpio.classList.remove("hidden"); parentAddress.classList.remove("hidden"); address.setAttribute("pattern", "([A-Fa-f0-9]{2}:){7}[A-Fa-f0-9]{2}"); break; - // ble + // Bluetooth case 52: - if (!bleSupported) { - parentGpio.classList.add("hidden"); - parentAddress.classList.add("hidden"); - break; - } - parentGpio.classList.add("hidden"); parentAddress.classList.remove("hidden"); address.setAttribute("pattern", "([A-Fa-f0-9]{2}:){5}[A-Fa-f0-9]{2}"); break; + // DHT + case 53: + case 54: + parentGpio.classList.remove("hidden"); + parentAddress.classList.add("hidden"); + address.removeAttribute("pattern"); + break; + // other default: parentGpio.classList.add("hidden"); @@ -355,7 +335,7 @@ } }); - setupForm(`.sensor[data-id='${sensorId}'] form`, fillData, ['address']); + setupForm(`.sensor[data-id='${sensorId}'] form`, fillData, ['name', 'address']); } } catch (error) { @@ -364,4 +344,4 @@ }); - \ No newline at end of file + diff --git a/src_data/pages/settings.html b/src_data/pages/settings.html index b6c0e89..ac77a70 100644 --- a/src_data/pages/settings.html +++ b/src_data/pages/settings.html @@ -42,26 +42,26 @@ settings.section.portal
- +

@@ -77,17 +77,17 @@ settings.section.system
- +
settings.system.unit
@@ -95,13 +95,13 @@