Compare commits

..
7 Commits
Author SHA1 Message Date
Yurii 05acc8162f Delete CNAME 2025-01-09 06:30:36 +03:00
Yurii 26d10fe02a Update CNAME 2025-01-09 06:28:42 +03:00
Yurii bcf2192d8a Create CNAME 2025-01-09 06:23:41 +03:00
Yurii f2db7cd529 refactor: corsproxy replaced 2025-01-09 04:26:44 +03:00
Yurii de7c178bf1 refactor: added `no-cache` 2025-01-07 07:36:57 +03:00
Yurii 4c42c148f8 Added web flasher 2025-01-07 06:50:06 +03:00
Yurii ee15abe429 Initial commit 2025-01-07 06:47:54 +03:00
102 changed files with 446 additions and 45570 deletions

No files matched your search

-11
View File
@@ -1,11 +0,0 @@
version: 2
updates:
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "daily"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"
-175
View File
@@ -1,175 +0,0 @@
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 }}
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Python
uses: actions/setup-python@v6
with:
python-version: ${{ env.PYTHON_VERSION }}
- 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: |
ENVS=$(
pio project config --json-output \
| jq -c '
.[]
| select(type == "array")
| .[0]
| select(startswith("env:"))
| sub("^env:"; "")
' | jq -s -c '.'
)
echo "envs=$ENVS" >> "$GITHUB_OUTPUT"
echo "$ENVS"
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: 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: Upload artifacts
uses: actions/upload-artifact@v7
with:
name: ${{ matrix.env }}
if-no-files-found: error
path: |
build/*.bin
build/*.elf
release:
name: Release Dev
runs-on: ubuntu-latest
needs: build
permissions:
contents: write
if: ${{ github.repository_owner == 'Laxilef' && github.ref == 'refs/heads/async' }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Move dev tag
run: |
git fetch --tags
git tag -f dev
git push origin refs/tags/dev --force
- name: Download artifacts
uses: actions/download-artifact@v5
with:
path: artifacts
merge-multiple: true
- name: Delete old release assets
uses: mknejp/delete-release-assets@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
tag: dev
fail-if-no-assets: false
fail-if-no-release: false
assets: |
*.bin
*.elf
- name: Clear release body
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
gh release edit dev --notes ""
- name: Publish Dev release
uses: softprops/action-gh-release@v3
with:
tag_name: dev
target_commitish: async
name: Dev (unstable)
prerelease: true
make_latest: false
generate_release_notes: true
files: |
artifacts/*.bin
artifacts/*.elf
-117
View File
@@ -1,117 +0,0 @@
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
-20
View File
@@ -1,20 +0,0 @@
name: "Close stale issues and PR"
on:
schedule:
- cron: "0 * * * *"
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v11
with:
stale-issue-message: >
This issue is stale because it has been open 15 days with no activity. Remove stale label or comment or this will be closed in 5 days.
close-issue-message: >
This issue was closed because it has been stalled for 5 days with no activity.
days-before-stale: 15
days-before-close: 5
days-before-pr-stale: -1
days-before-pr-close: -1
exempt-issue-labels: "documentation,bug,enhancement"
+2 -9
View File
@@ -1,15 +1,8 @@
.pio .pio
.dummy
.vscode .vscode
.PVS-Studio build/*.bin
build/*
data/* data/*
managed_components/*
node_modules/*
agent-notes/*
secrets.ini secrets.ini
node_modules
package-lock.json package-lock.json
*.lock
sdkconfig.*
CMakeLists.txt
!.gitkeep !.gitkeep
-191
View File
@@ -1,191 +0,0 @@
# Инструкции для агентов
## Роль и цели
Ты — инженерный 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 должны оставаться общие правила. Планы, текущий статус и выводы
отдельных исследований храни в заметках, а не в инструкциях.
-344
View File
@@ -1,344 +0,0 @@
# Стиль кода 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);
```
Не считай это общим требованием переносить имя объекта перед любой цепочкой.
В многострочных условиях сохраняй принятую рядом расстановку `&&` и `||`:
в проекте встречаются оба варианта переноса. Группируй связанные условия
скобками и не меняй их порядок или приоритет ради выравнивания.
## Имена и структура файлов
| Элемент | Принятый вид |
| --- | --- |
| Функции, методы, переменные, поля | `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 и рабочие заметки проекта могут быть
на русском.
## Перед завершением правки
- Сверь изменённый участок с окружающим кодом и последними указаниями пользователя.
- Проверь отступы, пустые строки, переносы цепочек, комментарии и окончания строк.
- Убери случайное переформатирование посторонних участков.
- Убедись, что сокращение кода не изменило порядок действий и обязательные ветки.
- Не добавляй правила, абстракции и исключения, не нужные для решаемой задачи.
-674
View File
@@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
-89
View File
@@ -1,89 +0,0 @@
<div align="center">
[![GitHub version](https://img.shields.io/github/release/Laxilef/OTGateway.svg?include_prereleases)](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)
</div>
<hr />
![Dashboard](/assets/poster-1.png)
![Configuration](/assets/poster-2.png)
![Integration with HomeAssistant](/assets/poster-3.png)
## Features
- DHW temperature control
- Heating temperature control
- Smart heating temperature control modes:
- 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.
- 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:
- Displaying gateway status
- Displaying the connection status to the boiler via OpenTherm
- Displaying the fault status and fault code
- Displaying the diagnostic status & diagnostic code
- Display of the process of heating: works/does not work
- Display of burner (flame) status: on/off
- Display of burner modulation level in percent
- Display of pressure in the heating system
- Display of current temperature of the heat carrier
- Display of return temperature of the heat carrier
- Display of setpoint heat carrier temperature (useful when using PID or Equitherm)
- Display of the process of DHW: working/not working
- Display of current DHW temperature
- _And other information..._
- [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)
## Translations
The project uses [Weblate](https://hosted.weblate.org/new-lang/otgateway/) to manage translations of the interface.<br />
Anyone is welcome to add their native language as a [new localization](https://hosted.weblate.org/new-lang/otgateway/portal/). All contributions are welcome!
<a href="https://hosted.weblate.org/engage/otgateway/">
<img src="https://hosted.weblate.org/widget/otgateway/multi-auto.svg" alt="Translation status" />
</a>
## Gratitude
* 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), [GyverPID](https://github.com/GyverLibs/GyverPID), [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!
View File
Whitespace-only changes.
-1
View File
@@ -1 +0,0 @@
/*.priv.*
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
1 Designator Device Footprint Mid X Mid Y Ref X Ref Y Pad X Pad Y Pins Layer Rotation SMD Comment
2 PCB_B1 D2MG_PCB_B_WITHOUT_TERMINALS D2MG_PCB_B_WITHOUT_TERMINALS 51.475mm -42.746mm 35.285mm -13.632mm 36.555mm -22.776mm 16 T 0 No D2MG_PCB_B_WITHOUT_TERMINALS
3 C2 100nF C0805 7.778mm -43.871mm 7.778mm -43.871mm 6.778mm -43.871mm 2 T 0 Yes 100nF
4 U3 AMS1117-3.3 SOT-223-3_L6.4-W3.5-P2.30-LS7.0-BR 5.873mm -49.078mm 5.873mm -49.078mm 8.843mm -51.378mm 4 T 0 Yes AMS1117-3.3
5 R2 0805W8F4701T5E R0805 10.668mm -63.881mm 10.668mm -63.881mm 10.668mm -64.881mm 2 T 90 Yes 4.7kΩ
6 R3 0805W8F3300T5E R0805 45.679mm -68.448mm 45.679mm -68.448mm 45.679mm -69.448mm 2 T 90 Yes 330Ω
7 R4 0805W8F2200T5E R0805 54.188mm -67.686mm 54.188mm -67.686mm 54.188mm -68.686mm 2 T 90 Yes 220Ω
8 R5 0805W8F1000T5E_C17408 R0805 56.855mm -67.686mm 56.855mm -67.686mm 56.855mm -66.686mm 2 T 270 Yes 100Ω
9 R6 0805W8F3300T5E R0805 46.822mm -59.558mm 46.822mm -59.558mm 45.822mm -59.558mm 2 T 0 Yes 330Ω
10 R7 0805W8F1501T5E R0805 56.347mm -59.558mm 56.347mm -59.558mm 57.347mm -59.558mm 2 T 180 Yes 1.5kΩ
11 R10 0805W8F4701T5E R0805 14.605mm -63.881mm 14.605mm -63.881mm 14.605mm -62.881mm 2 T 270 Yes 4.7kΩ
12 U2 HLK-PM01 PWRM-TH_HLK-PM01 22.383mm -42.728mm 22.383mm -42.728mm 24.883mm -28.028mm 4 T 270 No HLK-PM01
13 Q1 BC858A_C8583 SOT-23-3_L2.9-W1.6-P1.90-LS2.8-BR 49.743mm -68.067mm 49.743mm -68.067mm 48.508mm -67.117mm 3 T 180 Yes BC858A
14 ZD1 BZV55C4V7 SOD-80_L3.5-W1.5-RD 55.534mm -62.987mm 55.534mm -62.987mm 53.769mm -62.987mm 2 T 0 Yes BZV55C4V7
15 ZD2 BZV55C15 SOD-80_L3.5-W1.5-RD 47.457mm -64.572mm 47.457mm -64.572mm 45.692mm -64.572mm 2 T 0 Yes BZV55C15
16 ZD3 BZV55C4V3 SOD-80_L3.5-W1.5-RD 47.457mm -61.844mm 47.457mm -61.844mm 45.692mm -61.844mm 2 T 0 Yes BZV55C4V3
17 C4 100nF C0805 62.103mm -19.558mm 62.103mm -19.558mm 61.103mm -19.558mm 2 T 0 Yes 100nF
18 C5 GRM21BR61C106KE15L C0805 64.868mm -45.759mm 64.868mm -45.759mm 64.868mm -46.759mm 2 T 90 Yes 10uF
19 C6 100nF C0805 62.481mm -45.763mm 62.481mm -45.763mm 62.481mm -44.763mm 2 T 270 Yes 100nF
20 R11 0805W8F5101T5E R0805 57.887mm -19.558mm 57.887mm -19.558mm 58.887mm -19.558mm 2 T 180 Yes 5.1kΩ
21 R12 0805W8F5101T5E R0805 39.954mm -16.612mm 39.954mm -16.612mm 39.954mm -15.612mm 2 T 270 Yes 5.1kΩ
22 R13 0805W8F5101T5E R0805 51.943mm -16.637mm 51.943mm -16.637mm 51.943mm -17.637mm 2 T 90 Yes 5.1kΩ
23 SW1 TS-1088R-02026 SW-SMD_L3.9-W3.0-P4.45 59.944mm -16.383mm 59.944mm -16.383mm 57.759mm -16.383mm 2 T 0 Yes TS-1088R-02026
24 R1 0805W8F1000T5E_C17408 R0805 61.562mm -51.237mm 61.562mm -51.237mm 61.562mm -50.237mm 2 T 270 Yes 100Ω
25 R8 0805W8F1000T5E_C17408 R0805 52.342mm -51.237mm 52.342mm -51.237mm 52.342mm -50.237mm 2 T 270 Yes 100Ω
26 R9 0805W8F1000T5E_C17408 R0805 41.25mm -51.237mm 41.25mm -51.237mm 41.25mm -50.237mm 2 T 270 Yes 100Ω
27 PCB_A1 D2MG_PCB_A_WITHOUT_TERMINALS D2MG_PCB_A_WITHOUT_TERMINALS 16.458mm -42.746mm 16.458mm -43.406mm 1.538mm -22.776mm 16 T 0 No D2MG_PCB_A_WITHOUT_TERMINALS
28 F1 S6125-M2-0.5A FUSE-SMD_L6.1-W2.5 14.986mm -17.78mm 14.986mm -17.78mm 14.986mm -15.28mm 2 T 270 Yes S6125-M2-0.5A
29 VAR1 VDR-10D391K RES-TH_L12.5-W5.1-P7.50-D1.2-S2.20 20.955mm -18.796mm 20.955mm -18.796mm 22.055mm -15.047mm 2 T 270 No VDR-10D391K
30 D5 BAV99S,115 SOT-363_L2.0-W1.3-P0.65-LS2.1-TL 51.613mm -58.674mm 51.613mm -58.674mm 50.963mm -59.594mm 6 T 90 Yes BAV99S,115
31 U5 PC817 SMD-4(6.5X4.58) 61.681mm -64.511mm 61.681mm -64.511mm 60.411mm -69.511mm 4 T 90 Yes PC817
32 U4 PC817 SMD-4(6.5X4.58) 41.488mm -64.511mm 41.488mm -64.511mm 42.758mm -59.511mm 4 T 270 Yes PC817
33 U10 ESP32-S3-WROOM-1U-N4 WIRELM-SMD_ESP32-S3-WROOM-1U 51.943mm -31.75mm 51.943mm -31.75mm 60.693mm -40.645mm 49 T 180 Yes ESP32-S3-WROOM-1U-N4
34 U1 WEMOS_D1_MINI DIP-16_WEMOS_D1_MINI_PRO4 51.943mm -31.623mm 51.943mm -31.623mm 40.513mm -40.513mm 16 T 180 No WEMOS_D1_MINI
35 R14 0805W8F2200T5E R0805 24.952mm -63.881mm 24.952mm -63.881mm 24.952mm -62.881mm 2 T 270 Yes 220Ω
36 R15 0805W8F2200T5E R0805 20.955mm -63.881mm 20.955mm -63.881mm 20.955mm -62.881mm 2 T 270 Yes 220Ω
37 R16 0805W8F5101T5E R0805 18.542mm -63.881mm 18.542mm -63.881mm 18.542mm -62.881mm 2 T 270 Yes 5.1kΩ
38 SW2 TS-1088R-02026 SW-SMD_L3.9-W3.0-P4.45 37.211mm -28.575mm 37.211mm -28.575mm 37.211mm -26.39mm 2 T 270 Yes TS-1088R-02026
39 U7 XY126V-5.0-3P KLS2-300-5.00-03P-2S 23.994mm -4.267mm 28.994mm -4.267mm 28.994mm -4.267mm 3 T 180 No XY126V-5.0-3P
40 U6 XY126V-5.0-3P KLS2-300-5.00-03P-2S 8.97mm -4.267mm 13.97mm -4.267mm 13.97mm -4.267mm 3 T 180 No XY126V-5.0-3P
41 U9 XY126V-5.0-3P KLS2-300-5.00-03P-2S 8.988mm -81.242mm 3.988mm -81.242mm 3.988mm -81.242mm 3 T 0 No XY126V-5.0-3P
42 U8 XY126V-5.0-3P KLS2-300-5.00-03P-2S 23.986mm -81.242mm 18.987mm -81.242mm 18.987mm -81.242mm 3 T 0 No XY126V-5.0-3P
43 U11 TYPE-C 14PLC-H10.0 USB-C-TH_SHOUHAN_TYPE-C-14PLC-H10.0 45.949mm -16.815mm 45.949mm -16.815mm 47.948mm -14.885mm 18 T 0 No TYPE-C 14PLC-H10.0
44 C1 100uF CAP-SMD_BD6.3-L6.6-W6.6-LS7.2-FD 6.127mm -38.537mm 6.127mm -38.537mm 8.797mm -38.537mm 2 T 180 Yes 100uF
45 C3 22uF CAP-SMD_BD5.0-L5.3-W5.3-LS6.3-FD 6.934mm -56.007mm 6.934mm -56.007mm 9.08mm -56.007mm 2 T 180 Yes 22uF
46 F2 MF-MSMF110/16-2 F1812 5.207mm -30.226mm 5.207mm -30.226mm 7.06mm -30.226mm 2 T 180 Yes MF-MSMF110/16-2
47 L1 SZYY0805YG LED0805-R-RD_GREEN 64.19mm -51.174mm 64.19mm -51.174mm 64.19mm -50.123mm 2 T 90 Yes SZYY0805YG
48 L2 SZYY0805YG LED0805-R-RD_GREEN 43.87mm -51.174mm 43.87mm -51.174mm 43.87mm -50.123mm 2 T 90 Yes SZYY0805YG
49 L3 SZYY0805YG LED0805-R-RD_GREEN 54.97mm -51.174mm 54.97mm -51.174mm 54.97mm -50.123mm 2 T 90 Yes SZYY0805YG
-18957
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
BIN
View File
Binary file not shown.
-19
View File
@@ -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"
-51
View File
@@ -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 }}"
@@ -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 }}"
-17
View File
@@ -1,17 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="880" height="300" viewBox="0 0 880 300">
<g stroke="none" stroke-width="1" fill="none" fill-rule="oddeven">
<g transform="translate(440, 145)">
<text font-family="Helvetica Nue,Helvetica,Arial,sans-serif" font-size="25" font-weight="300" letter-spacing="1" text-anchor="end" fill="#444444">
<tspan x="-12" y="12">OPENTHERM GATEWAY</tspan>
</text>
<line x1="0" y1="-12" x2="0" y2="18" stroke-width="1" stroke="#e1e1e1"/>
<text font-family="Helvetica Nue,Helvetica,Arial,sans-serif" font-size="15" font-weight="300" fill="#7e7e7e">
<tspan x="12" y="10">SMART CONTROLLER FOR BOILERS</tspan>
</text>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 803 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 973 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 283 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 386 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 849 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.5 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 242 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

-12
View File
@@ -1,12 +0,0 @@
<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" height="40" aria-label="Import blueprint to My Home Assistant" style="border-radius:24px;width:auto" viewBox="0 0 592 96">
<rect width="592" height="96" fill="#18BCF2" rx="48"/>
<path fill="#fff" d="M42.55 60.2h4.59V36.75h-4.59Zm10.35 0h4.59V43.99l7.23 10.58 7.24-10.62V60.2h4.56V36.75h-4.56v.03l-.4-.03-6.84 10.12-6.83-10.12-.4.03v-.03H52.9Zm29.38 0h4.59v-7.77h4.49c4.72 0 8.07-3.29 8.07-7.87 0-4.59-3.48-7.88-8.44-7.84l-4.66.03h-4.05Zm8.61-19.26c2.27-.04 3.88 1.47 3.88 3.62 0 2.14-1.47 3.65-3.51 3.65h-4.39v-7.27Zm22.98 19.66c6.97 0 11.92-5.02 11.92-12.09 0-7.1-4.95-12.13-12.02-12.13-7.04 0-12 4.99-12 12.13 0 7.07 5 12.09 12.1 12.09m0-4.19c-4.36 0-7.41-3.28-7.41-7.9 0-4.66 3.02-7.94 7.31-7.94 4.32 0 7.33 3.28 7.33 7.94 0 4.62-2.98 7.9-7.23 7.9m16.31 3.79h4.59v-8.31h3.52l4.79 8.31h5.19l-5.42-9.11c2.71-1.21 4.48-3.69 4.48-6.77 0-4.45-3.48-7.64-8.44-7.6l-4.65.03h-4.06Zm8.51-19.26c2.28 0 3.89 1.37 3.89 3.38 0 1.98-1.61 3.38-3.65 3.38h-4.16v-6.76Zm18.33 19.26h4.59V40.94h7v-4.19h-18.63v4.19h7.04Zm23.91 0h9.02c4.69 0 7.77-2.41 7.77-6.7 0-2.65-1.24-4.42-3.42-5.53 1.64-1.17 2.61-2.78 2.61-4.55 0-4.43-3.21-6.7-8.04-6.7l-3.45.03h-4.49Zm7.68-19.8c2.21-.03 3.61 1.07 3.61 2.95s-1.27 2.95-3.25 2.95h-3.55v-5.9Zm.53 9.65c2.41-.03 3.89 1.17 3.89 3.08 0 1.81-1.34 3.02-3.52 3.02h-4.09v-6.1h.24Zm12.97 10.15h14.9v-4.19H206.7V36.75h-4.59Zm18.32-8.74c0 5.62 3.69 9.21 9.51 9.21 5.9 0 9.65-3.59 9.65-9.21V36.75H235v14.71c0 3.01-1.97 4.95-4.99 4.95-3.01 0-4.99-1.94-4.99-4.95V36.75h-4.59Zm24.59 8.74h14.97v-4.19h-10.38v-5.66h8.84v-4.09h-8.84v-5.32h10.25v-4.19h-14.84Zm20.4 0h4.59v-7.77h4.49c4.72 0 8.07-3.29 8.07-7.87 0-4.59-3.48-7.88-8.44-7.84l-4.66.03h-4.05Zm8.61-19.26c2.28-.04 3.89 1.47 3.89 3.62 0 2.14-1.48 3.65-3.52 3.65h-4.39v-7.27Zm12.26 19.26h4.59v-8.31h3.52l4.79 8.31h5.19l-5.43-9.11c2.72-1.21 4.49-3.69 4.49-6.77 0-4.45-3.48-7.64-8.44-7.6l-4.65.03h-4.06Zm8.51-19.26c2.28 0 3.89 1.37 3.89 3.38 0 1.98-1.61 3.38-3.65 3.38h-4.16v-6.76Zm13.77 19.26h4.59V36.75h-4.59Zm10.35 0 4.59.03V44.12l11.66 16.08h4.55V36.75h-4.55v15.81l-11.46-15.81h-4.79Zm31.52 0h4.59V40.94h7.01v-4.19h-18.63v4.19h7.03Zm28.88 0h4.59V40.94h7v-4.19h-18.62v4.19h7.03Zm26 .4c6.97 0 11.92-5.02 11.92-12.09 0-7.1-4.95-12.13-12.02-12.13-7.04 0-12 4.99-12 12.13 0 7.07 5 12.09 12.1 12.09m0-4.19c-4.36 0-7.41-3.28-7.41-7.9 0-4.66 3.02-7.94 7.31-7.94 4.32 0 7.33 3.28 7.33 7.94 0 4.62-2.98 7.9-7.23 7.9"/>
<g style="transform:translate(95px,0)">
<rect width="137" height="64" x="344" y="16" fill="#F2F4F9" rx="32"/>
<path fill="#18BCF2" d="M394.419 37.047V60.5h-4.297V46.797L384.716 60.5h-4.157l-5.343-13.594V60.5h-4.188V37.047h4.188l7.422 18.36 7.484-18.36zm9.365 0 5.344 9.89 5.344-9.89h4.766l-7.969 14.14V60.5h-4.391v-9.312l-8.031-14.141zM457 60c0 1.65-1.35 3-3 3h-24c-1.65 0-3-1.35-3-3v-9c0-1.65.95-3.95 2.12-5.12l10.76-10.76a3 3 0 0 1 4.24 0l10.76 10.76c1.17 1.17 2.12 3.47 2.12 5.12z"/>
<path fill="#F2F4F9" stroke="#F2F4F9" d="M442 45.5a2 2 0 1 0 0-4 2 2 0 0 0 0 4Z"/>
<path fill="#F2F4F9" stroke="#F2F4F9" stroke-miterlimit="10" d="M449.5 53.5a2 2 0 1 0 0-4 2 2 0 0 0 0 4ZM434.5 57.5a2 2 0 1 0 0-4 2 2 0 0 0 0 4Z"/>
<path fill="none" stroke="#F2F4F9" stroke-miterlimit="10" stroke-width="2.25" d="M442 43.48V63l-7.5-7.5M449.5 51.46l-7.41 7.41"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

View File
Whitespace-only changes.
View File
Whitespace-only changes.
View File
Whitespace-only changes.
-7
View File
@@ -1,7 +0,0 @@
# Name, Type, SubType, Offset, Size, Flags
nvs, data, nvs, 0x9000, 0x5000,
otadata, data, ota, 0xE000, 0x2000,
app0, app, ota_0, 0x10000, 0x1B0000,
app1, app, ota_1, 0x1C0000, 0x1B0000,
spiffs, data, spiffs, 0x370000, 0x80000,
coredump, data, coredump, 0x3F0000, 0x10000,
1 # Name Type SubType Offset Size Flags
2 nvs data nvs 0x9000 0x5000
3 otadata data ota 0xE000 0x2000
4 app0 app ota_0 0x10000 0x1B0000
5 app1 app ota_1 0x1C0000 0x1B0000
6 spiffs data spiffs 0x370000 0x80000
7 coredump data coredump 0x3F0000 0x10000
-149
View File
@@ -1,149 +0,0 @@
const { src, dest, parallel } = require('gulp');
const concat = require('gulp-concat');
const gzip = require('gulp-gzip');
const postcss = require('gulp-postcss');
const cssnano = require('cssnano');
const terser = require('gulp-terser');
const jsonminify = require('gulp-jsonminify');
const htmlmin = require('gulp-html-minifier-terser');
const replace = require('gulp-replace');
// Paths for tasks
let paths = {
styles: {
dest: 'data/static/',
bundles: {
'app.css': [
'src_data/styles/pico.min.css',
'src_data/styles/iconly.css',
'src_data/styles/app.css'
]
}
},
scripts: {
dest: 'data/static/',
bundles: {
'app.js': [
'src_data/scripts/i18n.min.js',
'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'
]
}
},
json: [
{
src: 'src_data/locales/*.json',
dest: 'data/static/locales/'
},
{
src: 'src_data/*.json',
dest: 'data/static/'
}
],
static: [
{
src: 'src_data/fonts/*.*',
dest: 'data/static/fonts/'
},
{
src: 'src_data/images/*.*',
dest: 'data/static/images/'
},
{
src: 'src_data/*.txt',
dest: 'data/static/'
}
],
pages: {
src: 'src_data/pages/*.html',
dest: 'data/pages/'
}
};
// Tasks
const styles = parallel(...Object.entries(paths.styles.bundles).map(([name, items]) => {
return () => 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]) => {
return () => 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));
}));
const jsonFiles = parallel(...paths.json.map((item) => {
return () => src(item.src)
.pipe(replace(
"{BUILD_TIME}",
Math.floor(Date.now() / 1000)
))
.pipe(jsonminify())
.pipe(gzip({
append: true
}))
.pipe(dest(item.dest));
}));
const staticFiles = parallel(...paths.static.map((item) => {
return () => src(item.src, { encoding: false })
.pipe(gzip({
append: true
}))
.pipe(dest(item.dest));
}));
const pages = () => {
return src(paths.pages.src)
.pipe(replace(
"{BUILD_TIME}",
Math.floor(Date.now() / 1000)
))
.pipe(htmlmin({
html5: true,
caseSensitive: true,
collapseWhitespace: true,
collapseInlineTagWhitespace: true,
conservativeCollapse: true,
removeComments: true,
minifyJS: true
}))
.pipe(gzip({
append: true
}))
.pipe(dest(paths.pages.dest));
}
exports.build_styles = styles;
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);
-771
View File
@@ -1,771 +0,0 @@
#pragma once
#include <Arduino.h>
#include <errno.h>
#include <esp_log.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <cmath>
#include <functional>
#include <mutex>
#include <optional>
#include <string>
#include <string_view>
#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<Settings> getSettings(uint8_t sensorId) {
std::lock_guard<std::mutex> lock(mutex);
if (settings == nullptr || !isValidSensorId(sensorId)) {
return std::nullopt;
}
return settings[sensorId];
}
static std::optional<Snapshot> getSnapshot(uint8_t sensorId) {
std::lock_guard<std::mutex> 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 <class T>
static bool isValidSensorId(const T id) {
return id >= 0 && id <= getMaxSensorId();
}
static std::optional<uint8_t> 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<uint8_t>(parsed);
}
static inline bool isValidValueId(const uint8_t id) {
return id >= (uint8_t) ValueType::TEMPERATURE && id <= (uint8_t) ValueType::RSSI;
}
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
|| memcmp(previous.address, current.address, sizeof(previous.address)) != 0
|| 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<std::mutex> 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<std::mutex> 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<uint8_t> getIdByName(const char* name) {
std::lock_guard<std::mutex> 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<uint8_t> getIdBySlug(const char* slug) {
if (slug == nullptr || !slug[0]) {
return std::nullopt;
}
std::lock_guard<std::mutex> 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<uint8_t>(valueType);
char name[sizeof(Settings::name)];
float compensatedValue = value;
float loggedValue;
bool connectedChanged;
{
std::lock_guard<std::mutex> 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<std::mutex> 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<uint8_t>(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<uint8_t>(ValueType::PRIMARY), value, value, value
);
return true;
}
static std::optional<uint8_t> setManualValueBySlug(std::string_view slug, float value, const UnitSystem srcUnit) {
if (slug.empty()) {
return std::nullopt;
}
std::optional<uint8_t> sensorId;
char name[sizeof(Settings::name)];
bool connectedChanged = false;
{
std::lock_guard<std::mutex> 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<uint8_t>(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<uint8_t>(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<std::mutex> 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<std::mutex> 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<std::mutex> 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<uint8_t>(value);
results[sensorId].updatedAt = millis();
}
return true;
}
static bool setAddressById(uint8_t sensorId, const uint8_t* address, const std::function<void()>& onUpdated = nullptr) {
{
std::lock_guard<std::mutex> lock(mutex);
if (settings == nullptr || address == nullptr || !isValidSensorId(sensorId)) {
return false;
}
if (memcmp(settings[sensorId].address, address, sizeof(Settings::address)) == 0) {
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<std::mutex> 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<std::mutex> 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) {
float sum = 0.0f;
for (uint8_t id = 0; id <= getMaxSensorId(); id++) {
auto& sSensor = settings[id];
auto& rSensor = results[id];
if (sSensor.purpose == purpose && (!onlyConnected || rSensor.connected)) {
sum += rSensor.values[valueId];
amount++;
}
}
value = amount == 1 ? sum : (sum / 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<std::mutex> 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;
-390
View File
@@ -1,390 +0,0 @@
#pragma once
#include <esp_log.h>
#include <atomic>
#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 {
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 SystemSettings {
esp_log_level_t logLevel = static_cast<esp_log_level_t>(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 = 5;
bool homeAssistantDiscovery = true;
};
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;
} 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;
struct {
std::atomic<bool> upgrading{false};
} states;
};
-150
View File
@@ -1,150 +0,0 @@
#pragma once
#include <Arduino.h>
#include <ArduinoJson.h>
#include <MycilaHADiscovery.h>
#include <MycilaTaskManager.h>
#include <esp_log.h>
#include <functional>
#include <initializer_list>
#include <mutex>
#include <string>
#include <string_view>
#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
extern Variables vars;
extern TaskManager coreTaskManager;
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.
extern 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<Sensors::Settings> previousSettings = std::nullopt);
void requestPublishMqttSensor(uint8_t sensorId);
std::string mqttTopic(std::initializer_list<std::string_view> parts);
template <typename... Parts>
std::string mqttTopic(const Parts&... parts) {
return mqttTopic({std::string_view(parts)...});
}
// Home Assistant discovery
extern HA::Discovery haDiscovery;
void 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();
bool isNetworkInterfaceStarted(NetworkMode mode);
// Last state published by the system worker, including during event callbacks.
bool isNetworkConnected();
void reconnectNetwork();
-5
View File
@@ -1,5 +0,0 @@
#pragma once
// Preserve C6 size optimizations through SDK metadata and shell parsing.
#define _GLIBCXX20_CONSTEXPR __attribute__((cold)) constexpr
#define _GLIBCXX23_CONSTEXPR __attribute__((cold)) constexpr
-170
View File
@@ -1,170 +0,0 @@
#pragma once
#include <Arduino.h>
#include <driver/gpio.h>
#define PROJECT_NAME "OpenTherm Gateway"
#define PROJECT_REPO "https://github.com/Laxilef/OTGateway"
#define MQTT_RECONNECT_INTERVAL 15000
#define MQTT_SENSOR_REPUBLISH_INTERVAL 300000u
#define SETTINGS_VALID_VALUE "stvalid" // only 8 chars!
#define GPIO_IS_NOT_CONFIGURED 0xff
#define DEFAULT_HEATING_TARGET_TEMP 40
#define DEFAULT_HEATING_MIN_TEMP 20
#define DEFAULT_HEATING_MAX_TEMP 90
#define DEFAULT_DHW_TARGET_TEMP 40
#define DEFAULT_DHW_MIN_TEMP 30
#define DEFAULT_DHW_MAX_TEMP 60
#define THERMOSTAT_INDOOR_DEFAULT_TEMP 20
#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_THRESHOLD 25.0f
#define DEFAULT_NTC_VHIGH_THRESHOLD 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
#ifndef DEFAULT_SERIAL_BAUD
#define DEFAULT_SERIAL_BAUD 115200
#endif
#ifndef DEFAULT_WEBSERIAL_ENABLED
#define DEFAULT_WEBSERIAL_ENABLED true
#endif
#ifndef USE_BLE
#define USE_BLE false
#endif
#ifndef DEFAULT_HOSTNAME
#define DEFAULT_HOSTNAME ""
#endif
#ifndef DEFAULT_AP_SSID
#define DEFAULT_AP_SSID "OpenTherm Gateway"
#endif
#ifndef DEFAULT_AP_PASSWORD
#define DEFAULT_AP_PASSWORD "otgateway123456"
#endif
#ifndef DEFAULT_STA_SSID
#define DEFAULT_STA_SSID ""
#endif
#ifndef DEFAULT_STA_PASSWORD
#define DEFAULT_STA_PASSWORD ""
#endif
#ifndef DEFAULT_LOG_LEVEL
#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_PORTAL_LOGIN
#define DEFAULT_PORTAL_LOGIN ""
#endif
#ifndef DEFAULT_PORTAL_PASSWORD
#define DEFAULT_PORTAL_PASSWORD ""
#endif
#ifndef DEFAULT_MQTT_ENABLED
#define DEFAULT_MQTT_ENABLED false
#endif
#ifndef DEFAULT_MQTT_SERVER
#define DEFAULT_MQTT_SERVER ""
#endif
#ifndef DEFAULT_MQTT_PORT
#define DEFAULT_MQTT_PORT 1883
#endif
#ifndef DEFAULT_MQTT_USER
#define DEFAULT_MQTT_USER ""
#endif
#ifndef DEFAULT_MQTT_PASSWORD
#define DEFAULT_MQTT_PASSWORD ""
#endif
#ifndef DEFAULT_MQTT_PREFIX
#define DEFAULT_MQTT_PREFIX ""
#endif
#ifndef DEFAULT_OT_IN_GPIO
#define DEFAULT_OT_IN_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef DEFAULT_OT_OUT_GPIO
#define DEFAULT_OT_OUT_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef DEFAULT_OT_RX_LED_GPIO
#define DEFAULT_OT_RX_LED_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef DEFAULT_OT_FAULT_STATE_GPIO
#define DEFAULT_OT_FAULT_STATE_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef DEFAULT_SENSOR_OUTDOOR_GPIO
#define DEFAULT_SENSOR_OUTDOOR_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef DEFAULT_SENSOR_INDOOR_GPIO
#define DEFAULT_SENSOR_INDOOR_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef SENSORS_AMOUNT
#define SENSORS_AMOUNT 20
#endif
#ifndef DEFAULT_EXT_PUMP_GPIO
#define DEFAULT_EXT_PUMP_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#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
#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))
#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))
-105
View File
@@ -1,105 +0,0 @@
#pragma once
#include <Arduino.h>
#include <esp_arduino_version.h>
#include <esp_heap_caps.h>
#include <esp_timer.h>
#include <stdint.h>
#include <mutex>
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<std::mutex> 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);
}
-220
View File
@@ -1,220 +0,0 @@
#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_CODE[] = "code";
inline const char S_COMMIT[] = "commit";
inline const char S_CONNECTED[] = "connected";
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_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_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_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_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_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_MODEL[] = "model";
inline const char S_MODULATION[] = "modulation";
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_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";
-117
View File
@@ -1,117 +0,0 @@
#pragma once
#include <stdint.h>
#include <functional>
enum class UnitSystem : uint8_t {
METRIC = 0,
IMPERIAL = 1
};
enum class ChannelDisablingAction : uint8_t {
OFF = 0,
ZERO_SETPOINT = 1,
OFF_AND_ZERO_SETPOINT = 2
};
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 NetworkEvent : uint8_t {
CONNECTED,
DISCONNECTED,
STA_STARTED,
STA_STOPPED,
STA_CONNECTED,
STA_DISCONNECTED,
STA_GOT_IP,
STA_LOST_IP,
STA_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<void(NetworkMode mode, NetworkState previous, NetworkState state)>;
-124
View File
@@ -1,124 +0,0 @@
#pragma once
#include <Arduino.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <cmath>
#include <string>
#include "types.h"
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<unsigned long>(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) {
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);
}
+327
View File
@@ -0,0 +1,327 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>OTGateway Web Flasher</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css" />
<link rel="stylesheet" href="./styles.css" />
</head>
<body>
<header class="container">
<nav>
<ul>
<li>
<a href="#">
<div class="logo">OpenTherm Gateway</div>
</a>
</li>
</ul>
<ul>
<li>
<a href="https://github.com/Laxilef/OTGateway/wiki" role="button" class="secondary" target="_blank">Wiki</a>
</li>
</ul>
</nav>
</header>
<main class="container">
<article>
<div>
<hgroup>
<h2>Web Flasher</h2>
<p></p>
</hgroup>
<div>
<label>
<span>Choose version</span>
<select name="fwVersion" disabled required>
<option selected value="0">Choose version...</option>
</select>
</label>
<label class="fwBoardContainer hidden">
<span>Board</span>
<select name="fwBoard" required>
<option selected value="0">Choose board...</option>
</select>
</label>
<div class="toolContainer hidden">
<hr />
<div>
<b>Status:</b> <span class="status">Not connected</span>
<br /><br />
</div>
<div class="progress hidden">
<progress value="0" max="100"></progress>
<br /><br />
</div>
<div class="grid">
<button class="connect">💡 1. Connect</button>
<button class="flash" disabled>🚀 2. Flash</button>
</div>
</div>
</div>
<div class="powered-by">
<small>
Powered by <a href="https://github.com/espressif/esptool-js/" target="_blank" class="secondary">espressif/esptool-js</a>
</small>
</div>
</div>
</article>
</main>
<footer class="container">
<small>
<b>Made by Laxilef</b>
• <a href="https://github.com/Laxilef/OTGateway/blob/master/LICENSE" target="_blank" class="secondary">License</a>
• <a href="https://github.com/Laxilef/OTGateway/blob/master/" target="_blank" class="secondary">Source code</a>
• <a href="https://github.com/Laxilef/OTGateway/wiki" target="_blank" class="secondary">Help</a>
• <a href="https://github.com/Laxilef/OTGateway/issues" target="_blank" class="secondary">Issues & questions</a>
• <a href="https://github.com/Laxilef/OTGateway/releases" target="_blank" class="secondary">Releases</a>
</small>
</footer>
<script type="module">
import { ESPLoader, Transport } from "https://unpkg.com/esptool-js/bundle.js";
let esploader = null;
const corsProxy = "https://corsproxy.laxilef.workers.dev/?";
const fwVersion = document.querySelector("[name='fwVersion']");
const fwBoardContainer = document.querySelector(".fwBoardContainer");
const fwBoard = document.querySelector("[name='fwBoard']");
const toolContainer = document.querySelector(".toolContainer");
const statusContainer = document.querySelector(".status");
const connectBtn = document.querySelector(".connect");
const flashBtn = document.querySelector(".flash");
const progressContainer = document.querySelector(".progress");
async function loadFwVersions() {
try {
fwVersion.disabled = true;
const response = await fetch("https://api.github.com/repos/Laxilef/OTGateway/releases", {
cache: "no-cache"
});
const data = await response.json();
for (let release of data) {
const releaseDate = new Date(release.published_at).toLocaleDateString();
const option = document.createElement("option");
option.textContent = `${release.name} (${releaseDate})`;
option.value = release.id;
fwVersion.appendChild(option);
}
} catch (error) {
console.error("Error fetching releases:", error);
alert("Error fetching releases");
return false;
}
fwVersion.disabled = false;
return true;
}
async function loadFwBoards(releaseId) {
let configUrl = null;
let files = [];
try {
const response = await fetch(`https://api.github.com/repos/Laxilef/OTGateway/releases/${releaseId}/assets`, {
cache: "no-cache"
});
const assets = await response.json();
for (const file of assets) {
if (file.name == "webflasher.json") {
configUrl = file.browser_download_url;
} else {
files.push({
"name": file.name,
"url": file.browser_download_url
});
}
}
} catch (error) {
console.error("Error fetching release:", error);
alert("Error fetching release");
return false;
}
if (!configUrl) {
return false;
}
try {
while (fwBoard.length > 1) {
fwBoard.remove(1);
}
const response = await fetch(`${corsProxy}${configUrl}`, {
cache: "no-cache"
});
const boards = await response.json();
for (let board of boards) {
let value = [];
for (let file of board.files) {
for (let sFile of files) {
if (file.name == sFile.name) {
value.push({
"address": file.address,
"name": file.name,
"url": sFile.url
});
}
}
}
const option = document.createElement("option");
option.textContent = board.name;
option.value = JSON.stringify(value);
fwBoard.appendChild(option);
}
} catch (error) {
console.error("Error fetching release config:", error);
alert("Error fetching release config");
return false;
}
return true;
}
fwVersion.addEventListener("change", async (element) => {
fwBoardContainer.classList.toggle("hidden", true);
toolContainer.classList.toggle("hidden", true);
if (element.target.value == 0) {
return;
}
if (await loadFwBoards(element.target.value)) {
fwBoardContainer.classList.toggle("hidden", false);
} else {
alert("This version is not supported by web flasher");
}
});
fwBoard.addEventListener("change", async (element) => {
if (element.target.value == 0) {
toolContainer.classList.toggle("hidden", true);
return;
}
toolContainer.classList.toggle("hidden", false);
});
connectBtn.addEventListener("click", async () => {
connectBtn.disabled = true;
flashBtn.disabled = true;
try {
statusContainer.textContent = "Connecting...";
const device = await navigator.serial.requestPort({});
const transport = new Transport(device);
esploader = new ESPLoader({
transport: transport,
baudrate: parseInt(115200),
debugLogging: false,
});
const model = await esploader.main();
flashBtn.disabled = false;
statusContainer.textContent = `Connected to ${model}`;
} catch (error) {
statusContainer.textContent = "Failed to connect to device! Maybe this browser is not supported?";
} finally {
connectBtn.disabled = false;
}
});
flashBtn.addEventListener("click", async () => {
connectBtn.disabled = true;
flashBtn.disabled = true;
progressContainer.classList.toggle("hidden", false);
const progressBar = progressContainer.querySelector("progress");
progressBar.removeAttribute("value");
progressBar.removeAttribute("max");
let files = JSON.parse(fwBoard[fwBoard.selectedIndex].value);
try {
statusContainer.textContent = "Downloading files...";
for (let file of files) {
const response = await fetch(`${corsProxy}${file.url}`, {
cache: "no-cache"
});
const firmwareArrayBuffer = await response.arrayBuffer();
const uint8Array = new Uint8Array(firmwareArrayBuffer);
file.data = "";
for (let i = 0; i < uint8Array.length; i++) {
file.data += String.fromCharCode(uint8Array[i]);
}
}
} catch (error) {
statusContainer.textContent = "Failed to download files";
connectBtn.disabled = false;
flashBtn.disabled = false;
progressContainer.classList.toggle("hidden", true);
return;
}
try {
statusContainer.textContent = "Erasing flash...";
await esploader.writeFlash({
fileArray: files,
flashSize: "keep",
eraseAll: true,
compress: true,
reportProgress: (fIndex, written, total) => {
progressBar.setAttribute("value", (written / total) * 100);
progressBar.setAttribute("max", 100);
statusContainer.textContent = `Flashing '${files[fIndex].name}'...`;
}
});
statusContainer.textContent = "Flashed successfully!";
try {
await esploader.hardReset();
} catch (error) { }
} catch (error) {
statusContainer.textContent = `Failed to write: ${error}`;
} finally {
connectBtn.disabled = false;
//flashBtn.disabled = false;
progressContainer.classList.toggle("hidden", true);
}
});
await loadFwVersions();
</script>
</body>
</html>
-252
View File
@@ -1,252 +0,0 @@
#include <Arduino.h>
#include <esp_log.h>
#include <strings_shared.h>
class UpgradeHandler : public AsyncWebHandler {
public:
enum class UpgradeType {
FIRMWARE = 0,
FILESYSTEM = 1
};
enum class UpgradeStatus {
NONE,
NO_FILE,
SUCCESS,
PROHIBITED,
SIZE_MISMATCH,
ERROR_ON_START,
ERROR_ON_WRITE,
ERROR_ON_FINISH
};
typedef struct {
UpgradeType type;
UpgradeStatus status;
String error;
size_t progress = 0;
size_t size = 0;
} UpgradeResult;
typedef std::function<bool(AsyncWebServerRequest *request, UpgradeType)> BeforeUpgradeCallback;
// A null request reports an upload disconnected after preparation was accepted.
typedef std::function<void(AsyncWebServerRequest *request, const UpgradeResult&, const UpgradeResult&)> AfterUpgradeCallback;
explicit UpgradeHandler(AsyncURIMatcher uri) : uri(uri) {}
bool canHandle(AsyncWebServerRequest *request) const final {
if (!request->isHTTP() || request->method() != HTTP_POST) {
return false;
}
return this->uri.matches(request);
}
UpgradeHandler* setBeforeUpgradeCallback(BeforeUpgradeCallback callback = nullptr) {
this->beforeUpgradeCallback = callback;
return this;
}
UpgradeHandler* setAfterUpgradeCallback(AfterUpgradeCallback callback = nullptr) {
this->afterUpgradeCallback = callback;
return this;
}
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(request, result->type)) {
result->status = UpgradeStatus::PROHIBITED;
return;
}
this->preparationAccepted = true;
if (!fileName.length()) {
result->status = UpgradeStatus::NO_FILE;
return;
}
if (!index) {
// reset
if (Update.isRunning()) {
Update.end(false);
Update.clearError();
}
// try begin
bool begin = false;
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);
}
if (!begin || Update.hasError()) {
result->status = UpgradeStatus::ERROR_ON_START;
result->error = Update.errorString();
ESP_LOGE(L_PORTAL_OTA, "File '%s', on start: %s", fileName.c_str(), result->error.c_str());
return;
}
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;
result->error = Update.errorString();
ESP_LOGE(
L_PORTAL_OTA, "File '%s', on write %d bytes, %d of %d bytes",
fileName.c_str(),
dataLength,
result->progress + dataLength,
result->size
);
return;
}
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
);
}
if (result->size > 0) {
if (result->progress > result->size || (isFinal && result->progress < result->size)) {
Update.end(false);
result->status = UpgradeStatus::SIZE_MISMATCH;
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;
result->error = Update.errorString();
ESP_LOGE(L_PORTAL_OTA, "File '%s', on finish: %s", fileName.c_str(), result->error.c_str());
return;
}
result->status = UpgradeStatus::SUCCESS;
ESP_LOGI(L_PORTAL_OTA, "File '%s': finish", fileName.c_str());
}
}
bool isRequestHandlerTrivial() const final {
return false;
}
protected:
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;
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};
};
-18
View File
@@ -1,18 +0,0 @@
{
"name": "otgateway",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"devDependencies": {
"cssnano": "^9.3.2",
"cssnano-preset-advanced": "^9.2.2",
"gulp": "^5.0.0",
"gulp-concat": "^2.6.1",
"gulp-gzip": "^1.4.2",
"gulp-html-minifier-terser": "^8.0.0",
"gulp-jsonminify": "^1.1.0",
"gulp-postcss": "^10.0.0",
"gulp-terser": "^2.1.0",
"gulp-replace": "^1.1.4"
}
}
-313
View File
@@ -1,313 +0,0 @@
[platformio]
;extra_configs = secrets.ini
extra_configs = secrets.default.ini
;core_dir = .pio
[env]
custom_version = 2.0.0-dev
framework = arduino
lib_deps = ESP32Async/AsyncTCP@^3.5.0
ESP32Async/ESPAsyncWebServer@^3.12.1
mathieucarbou/MycilaWebSerial@^8.2.3
bblanchon/ArduinoJson@^7.4.3
;ihormelnyk/OpenTherm Library@^1.1.5
https://github.com/Laxilef/ESP32OT
https://github.com/mathieucarbou/MycilaMQTT
https://github.com/mathieucarbou/MycilaHADiscovery/
gyverlibs/FileData@^1.0.3
gyverlibs/GyverPID@^3.3.2
gyverlibs/GyverBlinker@^1.1.1
;pstolarz/OneWireNg@^0.14.1
https://github.com/pstolarz/OneWireNg.git
milesburton/DallasTemperature@^4.0.6
https://github.com/Laxilef/esp32DHT#idf5
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}"'
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
[esp32_defaults]
;platform = https://github.com/pioarduino/platform-espressif32.git#prep_IDF6
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}
https://github.com/mathieucarbou/MycilaTaskManager#main
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
; BLE callbacks format logs; System sends them to transports.
-D MYNEWT_VAL_NIMBLE_HOST_TASK_STACK_SIZE=4608
-D MYNEWT_VAL_BLE_ROLE_CENTRAL=0
-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_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'
check_tool = ${env.check_tool}
check_flags = ${env.check_flags}
; Boards
[env:s2_mini]
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=2
build_flags = ${esp32_defaults.build_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]
extends = esp32_defaults
board = lolin_s3_mini
custom_sdkconfig = ${esp32_defaults.custom_sdkconfig}
'# CONFIG_TINYUSB_ENABLED is not set'
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 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: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]
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
-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]
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
-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:d1_mini32]
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
-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]
extends = esp32_defaults
board = esp32-c6-devkitc-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
build_flags = ${esp32_defaults.build_flags}
-msave-restore
-fno-exceptions
-Oz
-include "$PROJECT_DIR/include/c6_compiler_flags.h"
-D USE_BLE=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
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'
'# 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'
; 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]
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
-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
custom_sdkconfig = ${esp32_defaults.custom_sdkconfig}
CONFIG_COMPILER_SAVE_RESTORE_LIBCALLS=y
-24
View File
@@ -1,24 +0,0 @@
[secrets]
build_type = release
serial_enabled = true
serial_baud = 115200
webserial_enabled = true
log_level = ESP_LOG_INFO
hostname =
ap_ssid = OpenTherm Gateway
ap_password = otgateway123456
sta_ssid =
sta_password =
portal_login = admin
portal_password = admin
mqtt_enabled = false
mqtt_server =
mqtt_port = 1883
mqtt_user =
mqtt_password =
mqtt_prefix =
-3513
View File
File diff suppressed because it is too large. Load diff
-455
View File
@@ -1,455 +0,0 @@
#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE
#include <app.h>
#include <algorithm>
Variables vars;
enum class PumpStartReason {NONE, HEATING, ANTISTUCK};
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<float>(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<float>(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<float>(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<float>(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<float>(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<float>(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;
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 = millis();
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 = millis();
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 = millis();
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 = millis();
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 || millis() - vars.externalPump.lastEnabledTime >= (settings.externalPump.antiStuckInterval * 1000lu))) {
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() {
freezeProtectionTask.setInterval(1000);
coreTaskManager.addTask(freezeProtectionTask);
emergencyTask.setInterval(1000);
coreTaskManager.addTask(emergencyTask);
// The OpenTherm loop previously skipped overheat control while disconnected.
overheatProtectionTask.setEnabledWhen([] {
return vars.slave.connected;
});
overheatProtectionTask.setInterval(1000);
coreTaskManager.addTask(overheatProtectionTask);
cascadeTask.setInterval(1000);
coreTaskManager.addTask(cascadeTask);
externalPumpTask.setInterval(1000);
coreTaskManager.addTask(externalPumpTask);
}
-1181
View File
File diff suppressed because it is too large. Load diff
-91
View File
@@ -1,91 +0,0 @@
#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE
#include <app.h>
#include <Blinker.h>
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() {
ledStatusTask.setInterval(100);
coreTaskManager.addTask(ledStatusTask);
}
-239
View File
@@ -1,239 +0,0 @@
#include <app.h>
#include <MycilaWebSerial.h>
#include <esp_log_color.h>
#include <esp_private/log_format.h>
#include <esp_private/log_timestamp.h>
#include <esp_rom_sys.h>
#include <freertos/ringbuf.h>
#include <algorithm>
#include <atomic>
#include <cstdio>
#include <cstdlib>
#include <cstring>
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<RingbufHandle_t> loggingQueue{nullptr};
static std::atomic<bool> activeSerial{false};
static std::atomic<bool> 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<char*>(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<uint8_t*>(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);
sendLogsTask.setInterval(10);
systemTaskManager.addTask(sendLogsTask);
return true;
}
-98
View File
@@ -1,98 +0,0 @@
#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE
#include <app.h>
#include <metrics.h>
#include <esp_system.h>
#include <cstdlib>
#if ARDUINO_USB_CDC_ON_BOOT && !ARDUINO_USB_MODE
#include <USB.h>
#endif
#ifndef ARDUINO_ARCH_ESP32
#error Only ESP32 boards are supported
#endif
#include <LittleFS.h>
// Vars
Sensors::Result sensorsResults[SENSORS_AMOUNT];
TaskManager coreTaskManager("Core");
TaskManager systemTaskManager("System");
TaskManager openthermTaskManager("OpenTherm");
TaskManager sensorsTaskManager("Sensors");
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;
LittleFS.begin();
if (!initLogging()) {
std::abort();
}
initConfig();
initNetwork();
initSensors();
initControl();
initRegulator();
initLeds();
initMqtt();
initPortal();
initSystem();
initOpenTherm();
// RMT has its own worker; this manager schedules synchronous boiler operations.
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());
// Core runs control and MQTT tasks; poll their intervals every 100 ms.
if (!coreTaskManager.asyncStart(4608, 4, tskNO_AFFINITY, 100, false)) {
esp_system_abort("Failed to start Core task manager");
}
ESP_LOGI(L_MAIN, "Started %s task manager", coreTaskManager.name());
// System keeps maintenance, networking and restart handling active during Core 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());
BaseType_t sensorsCore = tskNO_AFFINITY;
#if USE_BLE && defined(CONFIG_BT_NIMBLE_PINNED_TO_CORE)
sensorsCore = CONFIG_BT_NIMBLE_PINNED_TO_CORE;
#endif
// Keep physical sensor I/O and result processing outside the Core worker.
if (!sensorsTaskManager.asyncStart(4096, 4, sensorsCore, 1000, false)) {
esp_system_abort("Failed to start Sensors task manager");
}
ESP_LOGI(L_MAIN, "Started %s task manager", sensorsTaskManager.name());
}
-1106
View File
File diff suppressed because it is too large. Load diff
-849
View File
@@ -1,849 +0,0 @@
#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE
#include <app.h>
#include <DNSServer.h>
#include <ESPmDNS.h>
#include <ESPAsyncWebServer.h>
#include <Network.h>
#include <WiFi.h>
#include <esp_wifi.h>
#include <freertos/queue.h>
#include <atomic>
#include <cstdlib>
#include <vector>
// Requests and state shared with other workers.
static std::atomic<bool> reconnectRequested{false};
static std::atomic<bool> staStarted{false};
static std::atomic<bool> apStarted{false};
static std::atomic<NetworkState> staState{NetworkState::NETWORK_DISABLED};
static std::atomic<NetworkState> apState{NetworkState::NETWORK_DISABLED};
// Subscriptions are fixed before the worker starts.
static std::vector<NetworkEventCallback> networkCallbacks;
static std::vector<NetworkStateCallback> 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 and AP_STARTED.
NetworkEvent event;
uint8_t reason; // STA 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<bool> networkEventsOverflowed{false};
static std::atomic<bool> 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)] = {};
// 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();
}
// Ethernet initialization and routing will be implemented separately.
return NetworkState::NETWORK_DISABLED;
}
bool isNetworkConnected() {
return getNetworkState(NetworkMode::STA) == NetworkState::NETWORK_CONNECTED;
}
NetworkMode getNetworkMode() {
if (isNetworkConnected()) {
return NetworkMode::STA;
}
return apStarted.load() ? NetworkMode::AP : NetworkMode::NONE;
}
bool isNetworkInterfaceStarted(NetworkMode mode) {
if (mode == NetworkMode::STA) {
return staStarted.load();
}
return mode == NetworkMode::AP && apStarted.load();
}
// 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;
const NetworkState previous = state.load();
if (previous == next) {
return;
}
if (mode == NetworkMode::STA) {
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 (mode == NetworkMode::STA) {
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, uint8_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 handleWifiEvent(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<uint32_t>(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);
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;
default:
break;
}
}
static void postInterfaceStopped(arduino_event_id_t type) {
// onDisable() can remove the native STOP handler. 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 WiFi requested");
networkRecoveryRequested.store(true);
}
}
// WiFi interfaces
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() {
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() {
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);
if (!WiFi.AP.create(
networkSettings.ap.ssid,
networkSettings.ap.password[0] ? networkSettings.ap.password : nullptr,
networkSettings.ap.channel
)) {
stopAccessPoint();
setNetworkState(NetworkMode::AP, NetworkState::NETWORK_DISABLED);
ESP_LOGE(L_NETWORK, "Failed configure AP");
}
}
static bool resetWifi() {
const bool restoreAp = WiFi.AP.started();
connectionPending = false;
// 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) {
startAccessPoint();
}
return true;
}
static bool startNetworkConnection() {
// Ordinary retries preserve AP. Escalate only if STA cannot be stopped.
const bool wasStarted = WiFi.STA.started();
if (!WiFi.STA.end()) {
ESP_LOGW(L_NETWORK, "Failed stop STA, reset WiFi...");
if (!resetWifi()) {
return false;
}
} else if (wasStarted) {
postInterfaceStopped(ARDUINO_EVENT_WIFI_STA_STOP);
}
if (!WiFi.STA.begin()) {
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.sta.ssid,
networkSettings.sta.password[0] ? networkSettings.sta.password : nullptr,
networkSettings.sta.channel
);
}
// Station connection and recovery timeouts
static void updateConnection() {
if (!networkSettings.sta.ssid[0]) {
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.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() {
const bool ready = webServerReady;
// Serve captive DNS only while HTTP is ready and no upstream connection exists.
const bool captive = ready
&& 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");
}
}
// Advertise HTTP on either interface, including while the fallback AP is active.
const bool enableMdns = ready
&& settings.portal.mdns
&& (apStarted.load() || isNetworkConnected());
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:
// 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:
// Association alone does not confirm a usable IP address.
staAssociated = true;
break;
case NetworkEvent::STA_GOT_IP:
if (!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 (isNetworkConnected() && connectedIp != pending.value) {
disconnectReason = 0;
setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISCONNECTED);
}
staAssociated = true;
connectedIp = pending.value;
if (!isNetworkConnected()) {
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;
// Access point
case NetworkEvent::AP_STARTED:
// 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 (!isNetworkConnected()) {
stopMdns();
}
if (!started) {
return;
}
break;
}
case NetworkEvent::AP_CLIENT_CONNECTED:
if (apClients < UINT8_MAX) {
++apClients;
}
break;
case NetworkEvent::AP_CLIENT_DISCONNECTED:
if (apClients) {
--apClients;
}
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);
apStarted.store(false);
staAssociated = false;
setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISABLED);
setNetworkState(NetworkMode::AP, NetworkState::NETWORK_DISABLED);
if (overflowed) {
ESP_LOGW(L_NETWORK, "Network event queue overflow, reset WiFi 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 WiFi after network event failure...");
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 (isNetworkConnected() && 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 != NetworkMode::STA) {
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 STA connected");
});
static Task reconnectTask("Reconnect network", Task::Type::ONCE, [](void*) {
ESP_LOGI(L_NETWORK, "Reconnecting...");
const bool wasStarted = WiFi.STA.started();
if (!WiFi.STA.end()) {
ESP_LOGW(L_NETWORK, "Failed stop STA, reset WiFi...");
resetWifi();
return;
}
if (wasStarted) {
postInterfaceStopped(ARDUINO_EVENT_WIFI_STA_STOP);
}
lastConnectionAttempt = 0;
connectionPending = false;
});
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 (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(handleWifiEvent);
onNetworkStateChange(logNetworkState);
WiFi.persistent(false);
WiFi.STA.setAutoReconnect(false);
Network.setHostname(networkSettings.hostname);
networkTask.setInterval(100);
systemTaskManager.addTask(reconnectTask);
systemTaskManager.addTask(networkTask);
systemTaskManager.addTask(networkStartTask);
}
-2306
View File
File diff suppressed because it is too large. Load diff
-985
View File
@@ -1,985 +0,0 @@
#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE
#include <app.h>
#include <metrics.h>
//#define PORTAL_CACHE "max-age=86400"
#define PORTAL_CACHE nullptr
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <AsyncJson.h>
#include <ArduinoJson.h>
#include <LittleFS.h>
#include <Update.h>
#include <UpgradeHandler.h>
#include <WiFi.h>
#include <MycilaWebSerial.h>
#include <esp_core_dump.h>
#include <esp_partition.h>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <string>
WebSerial* webSerial = nullptr;
AsyncWebServer* webServer = nullptr;
enum class RequestInterface : uint8_t {
UNKNOWN,
AP,
STA,
ETH
};
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();
if (localIP == apIP && localIP == staIP) {
// Matching AP/STA addresses cannot identify the interface.
return RequestInterface::UNKNOWN;
}
if (localIP == apIP) {
return RequestInterface::AP;
}
if (localIP == staIP) {
return RequestInterface::STA;
}
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 void 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);
}
// auth middleware
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() {
// index page
webServer->on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
request->redirect("/index.html");
});
webServer->serveStatic("/index.html", LittleFS, "/pages/index.html", PORTAL_CACHE);
// dashboard page
webServer->serveStatic("/dashboard.html", LittleFS, "/pages/dashboard.html", PORTAL_CACHE)
.addMiddleware(&authMiddleware);
// network settings page
webServer->serveStatic("/network.html", LittleFS, "/pages/network.html", PORTAL_CACHE)
.addMiddleware(&authMiddleware);
// settings page
webServer->serveStatic("/settings.html", LittleFS, "/pages/settings.html", PORTAL_CACHE)
.addMiddleware(&authMiddleware);
// sensors page
webServer->serveStatic("/sensors.html", LittleFS, "/pages/sensors.html", PORTAL_CACHE)
.addMiddleware(&authMiddleware);
// upgrade page
webServer->serveStatic("/upgrade.html", LittleFS, "/pages/upgrade.html", PORTAL_CACHE)
.addMiddleware(&authMiddleware);
// logs page
webServer->serveStatic("/logs.html", LittleFS, "/pages/logs.html", PORTAL_CACHE)
.addMiddleware(&authMiddleware);
// not found
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");
}
});
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() {
// OTA
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;
}
if (restartTask.scheduled() || restartTask.active()) {
return false;
}
// UpgradeHandler invokes this callback for every upload chunk.
if (vars.states.upgrading) {
return true;
}
vars.states.upgrading = true;
coreTaskManager.pause();
// Core owns MQTT; finish its current callback before stopping the client.
if (!coreTaskManager.waitForPaused(5000)) {
vars.states.upgrading = false;
if (!restartTask.scheduled() && !restartTask.active()) {
coreTaskManager.resume();
}
ESP_LOGW(L_PORTAL_OTA, "Core task manager pause not confirmed, upgrade cancelled");
return false;
}
stopMqtt(false);
// An MQTT command already in flight may have scheduled a restart before end().
if (restartTask.scheduled() || restartTask.active()) {
vars.states.upgrading = false;
return false;
}
sensorsTaskManager.pause();
if (!sensorsTaskManager.waitForPaused(5000)) {
requestReconfigureMqtt();
vars.states.upgrading = false;
if (!restartTask.scheduled() && !restartTask.active()) {
coreTaskManager.resume();
sensorsTaskManager.resume();
}
ESP_LOGW(L_PORTAL_OTA, "Sensors task manager pause not confirmed, upgrade cancelled");
return false;
}
openthermTaskManager.pause();
if (!openthermTaskManager.waitForPaused(5000)) {
requestReconfigureMqtt();
vars.states.upgrading = false;
if (!restartTask.scheduled() && !restartTask.active()) {
coreTaskManager.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");
}
unsigned short status = 406;
if (fwResult.status == UpgradeHandler::UpgradeStatus::SUCCESS || fsResult.status == UpgradeHandler::UpgradeStatus::SUCCESS) {
status = 202;
if (!restartTask.scheduled() && !restartTask.active()) {
restartTask.resume(15000);
}
} else {
requestReconfigureMqtt();
}
vars.states.upgrading = false;
if (status != 202 && !restartTask.scheduled() && !restartTask.active()) {
coreTaskManager.resume();
sensorsTaskManager.resume();
openthermTaskManager.resume();
}
if (!request) {
return;
}
// make response
auto *response = new AsyncJsonResponse();
auto& doc = response->getRoot();
auto fwDoc = doc["firmware"].to<JsonObject>();
fwDoc["status"] = static_cast<uint8_t>(fwResult.status);
fwDoc["error"] = fwResult.error;
auto fsDoc = doc["filesystem"].to<JsonObject>();
fsDoc["status"] = static_cast<uint8_t>(fsResult.status);
fsDoc["error"] = fsResult.error;
// send response
response->setLength();
response->setCode(status);
request->send(response);
});
upgradeHandler->addMiddleware(&authMiddleware);
webServer->addHandler(upgradeHandler);
// backup
webServer->on("/api/backup/save", HTTP_GET, [](AsyncWebServerRequest *request) {
// make response
auto *response = new AsyncJsonResponse();
auto& doc = response->getRoot();
// add network settings
auto networkDoc = doc[S_NETWORK].to<JsonObject>();
toJson(networkSettings, networkDoc);
// add main settings
auto settingsDoc = doc[S_SETTINGS].to<JsonObject>();
toJson(settings.system, settingsDoc[S_SYSTEM].to<JsonObject>());
toJson(settings.portal, settingsDoc[S_PORTAL].to<JsonObject>());
toJson(settings.opentherm, settingsDoc[S_OPENTHERM].to<JsonObject>());
toJson(settings.mqtt, settingsDoc[S_MQTT].to<JsonObject>());
toJson(settings.emergency, settingsDoc[S_EMERGENCY].to<JsonObject>());
toJson(settings.heating, settingsDoc[S_HEATING].to<JsonObject>());
toJson(settings.dhw, settingsDoc[S_DHW].to<JsonObject>());
toJson(settings.equitherm, settingsDoc[S_EQUITHERM].to<JsonObject>());
toJson(settings.pid, settingsDoc[S_PID].to<JsonObject>());
toJson(settings.externalPump, settingsDoc[S_EXTERNAL_PUMP].to<JsonObject>());
toJson(settings.cascadeControl, settingsDoc[S_CASCADE_CONTROL].to<JsonObject>());
// add sensors settings
for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) {
if (const auto sensor = Sensors::getSettings(sensorId)) {
auto sensorsettingsDoc = doc[S_SENSORS][sensorId].to<JsonObject>();
toJson(sensorId, *sensor, sensorsettingsDoc);
}
}
// send response
setDownloadFilename(response, "backup", "json");
response->setLength();
request->send(response);
}).addMiddleware(&authMiddleware);
// restart
webServer->on("/api/restart", HTTP_POST, [](AsyncWebServerRequest *request) {
if (vars.states.upgrading || restartTask.scheduled() || restartTask.active()) {
return request->send(503);
}
restartTask.resume(15000);
request->send(202);
}).addMiddleware(&authMiddleware);
// network
webServer->on("/api/network/settings", HTTP_GET, [](AsyncWebServerRequest *request) {
// make response
auto *response = new AsyncJsonResponse();
auto& doc = response->getRoot();
toJson(networkSettings, doc);
// send response
response->setLength();
request->send(response);
}).addMiddleware(&authMiddleware);
auto& nsHandler = webServer->on("/api/network/settings", HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) {
if (vars.states.upgrading || restartTask.scheduled() || restartTask.active()) {
return request->send(503);
}
if (requestDoc.isNull() || !requestDoc.size()) {
return request->send(400);
}
// prepare request
const auto result = fromJson(requestDoc, networkSettings);
if (result.changed) {
requestSaveNetworkSettings();
}
requestDoc.clear();
if (request->hasParam("noresponse")) {
request->send(result.changed ? 201 : 200);
} else {
// make response
auto *response = new AsyncJsonResponse();
auto& responseDoc = response->getRoot();
toJson(networkSettings, responseDoc);
// send response
response->setLength();
response->setCode(result.changed ? 201 : 200);
request->send(response);
}
if (result.changed && !request->hasParam("noreconnect")) {
// Queue the response before a network reset can disconnect this request.
reconnectNetwork();
}
});
nsHandler.setMaxContentLength(512);
nsHandler.addMiddleware(&authMiddleware);
webServer->on("/api/network/scan", HTTP_GET, [](AsyncWebServerRequest *request) {
auto apCount = WiFi.scanComplete();
switch (apCount) {
case WIFI_SCAN_FAILED:
WiFi.scanNetworks(true, true, true);
request->send(404);
break;
case WIFI_SCAN_RUNNING:
request->send(202);
break;
default:
// make respponse
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);
// clear
WiFi.scanDelete();
}
}).addMiddleware(&authMiddleware);
// settings
webServer->on(AsyncURIMatcher::prefix("/api/settings/"), HTTP_GET, [](AsyncWebServerRequest *request) {
const auto& url = request->url();
const auto section = std::string_view(url.c_str(), url.length())
.substr(sizeof("/api/settings/") - 1);
auto *response = new AsyncJsonResponse();
auto& doc = response->getRoot();
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);
}
response->setLength();
request->send(response);
}).addMiddleware(&authMiddleware);
auto& settingsHandler = webServer->on(AsyncURIMatcher::prefix("/api/settings/"), HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) {
if (vars.states.upgrading || restartTask.scheduled() || restartTask.active()) {
request->send(503);
return;
}
if (!requestDoc.is<JsonObjectConst>() || !requestDoc.size()) {
request->send(400);
return;
}
const auto& url = request->url();
const auto section = std::string_view(url.c_str(), url.length())
.substr(sizeof("/api/settings/") - 1);
SettingResult result;
bool mqttChanged = false;
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);
}
result.changed = normalizeSettings(settings) || result.changed;
if (result.changed) {
requestSaveSettings();
configureLoggingTask.resume();
if (mqttChanged) {
requestReconfigureMqtt();
}
// If busy, the periodic task will publish the current settings.
std::unique_lock<std::mutex> lock(mqttMutex, std::try_to_lock);
if (lock.owns_lock() && mqttPublishSettingsTask) {
mqttPublishSettingsTask->requestEarlyRun();
}
}
requestDoc.clear();
if (request->hasParam("noresponse")) {
return request->send(result.changed ? 201 : 200);
}
auto *response = new AsyncJsonResponse();
auto& responseDoc = response->getRoot();
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);
}
response->setLength();
response->setCode(result.changed ? 201 : 200);
request->send(response);
});
settingsHandler.setMaxContentLength(3072);
settingsHandler.addMiddleware(&authMiddleware);
// sensors list
webServer->on("/api/sensors", HTTP_GET, [](AsyncWebServerRequest *request) {
// make response
bool detailed = request->hasParam("detailed");
auto *response = new AsyncJsonResponse(true);
auto& responseDoc = response->getRoot();
// add sensors
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<const char*>(snapshot->settings.name);
responseDoc[sensorId][S_SLUG] = static_cast<const char*>(snapshot->settings.slug);
responseDoc[sensorId][S_PURPOSE] = static_cast<uint8_t>(snapshot->settings.purpose);
toJson(snapshot->settings, snapshot->result, responseDoc[sensorId]);
}
} else if (const auto sensor = Sensors::getSettings(sensorId)) {
responseDoc[sensorId] = static_cast<const char*>(sensor->name);
}
}
// send response
response->setLength();
request->send(response);
}).addMiddleware(&authMiddleware);
// sensor settings
webServer->on(AsyncURIMatcher::exact("/api/sensor"), HTTP_GET, [](AsyncWebServerRequest *request) {
if (!request->hasParam("id")) {
return request->send(400);
}
const auto& id = request->getParam("id")->value();
const auto sensorId = Sensors::parseId(id.c_str());
if (!sensorId) {
return request->send(404);
}
const auto sensor = Sensors::getSettings(*sensorId);
if (!sensor) {
return request->send(404);
}
auto *response = new AsyncJsonResponse();
auto& doc = response->getRoot();
toJson(*sensorId, *sensor, doc);
response->setLength();
request->send(response);
}).addMiddleware(&authMiddleware);
auto& ssHandler = webServer->on(AsyncURIMatcher::exact("/api/sensor"), HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) {
if (vars.states.upgrading || restartTask.scheduled() || restartTask.active()) {
return request->send(503);
}
if (requestDoc.isNull() || !requestDoc.size()) {
return request->send(400);
}
if (!request->hasParam("id")) {
return request->send(400);
}
auto& id = request->getParam("id")->value();
const auto sensorId = Sensors::parseId(id.c_str());
if (!sensorId) {
return request->send(404);
}
const auto previousSettings = Sensors::getSettings(*sensorId);
if (!previousSettings) {
return request->send(404);
}
bool isDifferent = false;
SettingResult result;
{
std::lock_guard<std::mutex> lock(Sensors::mutex);
auto& sensor = Sensors::settings[*sensorId];
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;
}
}
if (result.changed) {
if (isDifferent) {
requestReconfigureMqttSensor(*sensorId, *previousSettings);
}
requestSaveSensorsSettings();
}
requestDoc.clear();
if (request->hasParam("noresponse")) {
return request->send(result.changed ? 201 : 200);
}
// make 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);
});
ssHandler.setMaxContentLength(1024);
ssHandler.addMiddleware(&authMiddleware);
// sensor measurements
webServer->on(AsyncURIMatcher::exact("/api/sensor/value"), HTTP_GET, [](AsyncWebServerRequest *request) {
if (!request->hasParam("id")) {
return request->send(400);
}
const auto& id = request->getParam("id")->value();
const auto sensorId = Sensors::parseId(id.c_str());
if (!sensorId) {
return request->send(404);
}
const auto sensor = Sensors::getSnapshot(*sensorId);
if (!sensor) {
return request->send(404);
}
auto *response = new AsyncJsonResponse();
auto& doc = response->getRoot();
toJson(sensor->settings, sensor->result, doc);
response->setLength();
request->send(response);
}).addMiddleware(&authMiddleware);
auto& sensorValueHandler = webServer->on(AsyncURIMatcher::exact("/api/sensor/value"), HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) {
if (vars.states.upgrading || restartTask.scheduled() || restartTask.active()) {
return request->send(503);
}
if (!requestDoc.is<JsonObjectConst>() || !requestDoc.size()) {
return request->send(400);
}
if (!request->hasParam("id")) {
return request->send(400);
}
const auto& id = request->getParam("id")->value();
const auto sensorId = Sensors::parseId(id.c_str());
if (!sensorId) {
return request->send(404);
}
if (!requestDoc[S_VALUE].is<float>()) {
return request->send(400);
}
const auto value = requestDoc[S_VALUE].as<float>();
requestDoc.clear();
if (!Sensors::setManualValueById(*sensorId, value, settings.system.unitSystem)) {
return request->send(400);
}
requestPublishMqttSensor(*sensorId);
if (request->hasParam("noresponse")) {
return request->send(201);
}
const auto sensor = Sensors::getSnapshot(*sensorId);
if (!sensor) {
return request->send(404);
}
auto *response = new AsyncJsonResponse();
auto& responseDoc = response->getRoot();
toJson(sensor->settings, sensor->result, responseDoc);
response->setLength();
response->setCode(201);
request->send(response);
});
sensorValueHandler.setMaxContentLength(1024);
sensorValueHandler.addMiddleware(&authMiddleware);
// vars
webServer->on("/api/vars", HTTP_GET, [](AsyncWebServerRequest *request) {
// make response
auto *response = new AsyncJsonResponse();
auto& doc = response->getRoot();
toJson(vars, doc);
// send response
response->setLength();
request->send(response);
});
auto& vHandler = webServer->on("/api/vars", HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) {
if (vars.states.upgrading || restartTask.scheduled() || restartTask.active()) {
return request->send(503);
}
if (requestDoc.isNull() || !requestDoc.size()) {
return request->send(400);
}
// prepare request
const auto result = fromJson(requestDoc, vars);
requestDoc.clear();
// make 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) {
// If busy, the periodic task will publish the current state.
std::unique_lock<std::mutex> lock(mqttMutex, std::try_to_lock);
if (lock.owns_lock() && mqttPublishStateTask) {
mqttPublishStateTask->requestEarlyRun();
}
}
});
vHandler.setMaxContentLength(1536);
vHandler.addMiddleware(&authMiddleware);
webServer->on("/api/info", HTTP_GET, [](AsyncWebServerRequest *request) {
// make response
auto *response = new AsyncJsonResponse();
auto& doc = response->getRoot();
auto docSystem = doc[S_SYSTEM].to<JsonObject>();
docSystem[S_RESET_REASON] = getResetReason();
docSystem[S_UPTIME] = millis() / 1000;
bool isConnected = isNetworkConnected();
auto docNetwork = doc[S_NETWORK].to<JsonObject>();
docNetwork[S_HOSTNAME] = networkSettings.hostname;
docNetwork[S_MAC] = WiFi.STA.macAddress();
docNetwork[S_CONNECTED] = isConnected;
docNetwork[S_SSID] = strlen(networkSettings.sta.ssid) ? networkSettings.sta.ssid : nullptr;
docNetwork[S_SIGNAL_QUALITY] = isConnected ? rssiToSignalQuality(WiFi.STA.RSSI()) : 0;
docNetwork[S_CHANNEL] = isConnected ? networkSettings.sta.channel : 0;
docNetwork[S_IP] = isConnected ? WiFi.STA.localIP().toString() : "";
docNetwork[S_SUBNET] = isConnected ? WiFi.STA.subnetMask().toString() : "";
docNetwork[S_GATEWAY] = isConnected ? WiFi.STA.gatewayIP().toString() : "";
docNetwork[S_DNS] = isConnected ? WiFi.STA.dnsIP().toString() : "";
auto docBuild = doc[S_BUILD].to<JsonObject>();
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();
const auto memory = getMemoryMetrics();
auto docHeap = doc[S_HEAP].to<JsonObject>();
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<JsonObject>();
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;
auto docChip = doc[S_CHIP].to<JsonObject>();
docChip[S_MODEL] = ESP.getChipModel();
docChip[S_REV] = ESP.getChipRevision();
docChip[S_CORES] = ESP.getChipCores();
docChip[S_FREQ] = ESP.getCpuFreqMHz();
auto docFlash = doc[S_FLASH].to<JsonObject>();
docFlash[S_SIZE] = ESP.getFlashChipSize();
// send response
response->setLength();
request->send(response);
});
webServer->on("/api/coredump", HTTP_GET, [](AsyncWebServerRequest* request) {
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;
}
if (esp_core_dump_image_check() != ESP_OK) {
request->send(500);
return;
}
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;
}
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;
}
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;
});
setDownloadFilename(response, "coredump", "bin");
request->send(response);
}).addMiddleware(&authMiddleware);
}
// Initialization
void initPortal() {
webServer = new AsyncWebServer(80);
initWebSerial();
routes();
restApi();
}
-242
View File
@@ -1,242 +0,0 @@
#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE
#include <app.h>
#include <cmath>
#include <GyverPID.h>
static GyverPID pidRegulator(0, 0, 0);
static float prevHeatingTarget = 0.0f;
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.09f)) {
equithermResult = etResult;
ESP_LOGI(L_REGULATOR_EQUITHERM, "New result: %.2f", etResult);
}
});
static Task pidTask("PID", Task::Type::FOREVER, [](void*) {
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);
// Use the same period for scheduling and the integral/derivative terms.
pidRegulator.setDt(pidTask.interval());
pidRegulator.input = vars.master.heating.indoorTemp;
pidRegulator.setpoint = settings.heating.target;
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 result = pidRegulator.getResult();
if (isFloatDifferent(pidResult, result, 0.09f)) {
pidResult = result;
ESP_LOGI(L_REGULATOR_PID, "New result: %.2f", result);
ESP_LOGD(L_REGULATOR_PID, "Integral: %.2f", pidRegulator.integral);
}
});
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(prevHeatingTarget, settings.heating.target, 0.0001f)) {
prevHeatingTarget = 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<float>(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;
}
// This must still run when the PID calculation task is disabled.
if (!settings.pid.enabled && fabsf(pidRegulator.integral) > 0.01f) {
pidRegulator.integral = 0.0f;
ESP_LOGI(L_REGULATOR_PID, "Integral sum has been reset");
}
turbo();
hysteresis();
vars.master.heating.targetTemp = settings.heating.target;
const float setpointTemp = getHeatingSetpointTemp();
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() {
regulatorTask.setInterval(10000);
// Sensor availability is refreshed by the regulator before checking PID eligibility.
pidTask.setEnabledWhen([] {
return settings.pid.enabled && settings.heating.enabled
&& !vars.emergency.state && !settings.opentherm.options.nativeOTC
&& indoorSensorsConnected;
});
pidTask.setInterval(10000);
pidTask.resume(pidTask.interval());
// Apply mode changes and turbo auto-disable before a PID calculation due on the same pass.
coreTaskManager.addTask(regulatorTask);
coreTaskManager.addTask(pidTask);
coreTaskManager.addTask(equithermTask);
equithermTask.pause();
}
-991
View File
@@ -1,991 +0,0 @@
#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE
#include <app.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <esp32DHT.h>
#include <math.h>
#include <string.h>
#include <atomic>
#include <optional>
#include <unordered_map>
#if USE_BLE
#include <NimBLEDevice.h>
#endif
#if USE_BLE
class BluetoothScanCallbacks : public NimBLEScanCallbacks {
public:
void onDiscovered(const NimBLEAdvertisedDevice* device) override {
auto& deviceAddress = device->getAddress();
bool found = false;
uint8_t sensorId;
std::optional<Sensors::Settings> 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<uint16_t>(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<int16_t>(
(static_cast<uint8_t>(serviceData[6]) << 8) |
static_cast<uint8_t>(serviceData[7])
) * 0.1f;
Sensors::setValueById(
sensorId, temperature,
Sensors::ValueType::TEMPERATURE, true, true
);
// Humidity (1 byte)
float humidity = static_cast<uint8_t>(serviceData[8]);
Sensors::setValueById(sensorId, humidity, Sensors::ValueType::HUMIDITY, true, true);
// Battery level (1 byte)
uint8_t batteryLevel = static_cast<uint8_t>(serviceData[9]);
Sensors::setValueById(sensorId, batteryLevel, Sensors::ValueType::BATTERY, true, true);
// Battery mV (2 bytes, big-endian)
uint16_t batteryMv = (static_cast<uint8_t>(serviceData[10]) << 8) | static_cast<uint8_t>(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<uint16_t>(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<int16_t>(
(static_cast<uint8_t>(serviceData[7]) << 8) |
static_cast<uint8_t>(serviceData[6])
) * 0.01f;
Sensors::setValueById(
sensorId, temperature,
Sensors::ValueType::TEMPERATURE, true, true
);
// Humidity (2 bytes, little-endian)
float humidity = (
(static_cast<uint8_t>(serviceData[9]) << 8) | static_cast<uint8_t>(serviceData[8])
) * 0.01f;
Sensors::setValueById(sensorId, humidity, Sensors::ValueType::HUMIDITY, true, true);
// Battery level (1 byte)
uint8_t batteryLevel = static_cast<uint8_t>(serviceData[12]);
Sensors::setValueById(sensorId, batteryLevel, Sensors::ValueType::BATTERY, true, true);
// Battery mV (2 bytes, little-endian)
uint16_t batteryMv = (static_cast<uint8_t>(serviceData[11]) << 8) | static_cast<uint8_t>(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<uint16_t>(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<uint8_t>(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<uint8_t>(serviceData[serviceDataPos + 1]) << 8)
| static_cast<uint8_t>(serviceData[serviceDataPos]);
float temperature = static_cast<float>(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<uint16_t>(serviceData[serviceDataPos + 1]) << 8)
| static_cast<uint8_t>(serviceData[serviceDataPos]);
float humidity = static_cast<float>(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<uint16_t>(serviceData[serviceDataPos + 1]) << 8)
| static_cast<uint8_t>(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;
}
};
static BluetoothScanCallbacks bluetoothScanCallbacks;
#endif
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<uint8_t, OneWire> owInstances;
static std::unordered_map<uint8_t, DallasTemperature> dallasInstances;
static std::unordered_map<uint8_t, unsigned long> dallasSearchTime;
static std::unordered_map<uint8_t, unsigned long> dallasLastPollingTime;
static std::unordered_map<uint8_t, bool> dallasPolling;
#if USE_BLE
static NimBLEScan* pBLEScan = nullptr;
static bool activeScanBle = false;
#endif
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;
}
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) {
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 (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");
}
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 !vars.states.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<uint8_t, unsigned long> 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<gpio_num_t>(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(instance.getStatus())
);
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<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;
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)
);
})
.resume(15000);
sensorsTaskManager.addTask(scanBleSensorsTask);
#endif
updateSensorsTask.setInterval(1000)
.setEnabledWhen(canRunSensors);
sensorsTaskManager.addTask(updateSensorsTask);
}
-140
View File
@@ -1,140 +0,0 @@
#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE
#include <app.h>
#include <metrics.h>
#include <esp_system.h>
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");
coreTaskManager.pause();
sensorsTaskManager.pause();
openthermTaskManager.pause();
// Finish application callbacks and onDone before saving, including with critical heap.
coreTaskManager.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 core 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 (!vars.states.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);
maintenanceTask.setInterval(100);
systemTaskManager.addTask(maintenanceTask);
heapTask.setInterval(100);
systemTaskManager.addTask(heapTask);
}
Binary file not shown.
-96
View File
@@ -1,96 +0,0 @@
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" >
<svg xmlns="http://www.w3.org/2000/svg">
<defs>
<font id="iconly" horiz-adv-x="1024">
<font-face font-family="iconly"
units-per-em="1024" ascent="896"
descent="128" />
<missing-glyph horiz-adv-x="0" />
<glyph glyph-name="plus"
unicode="&#xE000;"
horiz-adv-x="895.5537099041368" d="M831.585587768127 479.8473854289214H543.729038156083V767.7039350409655C543.729038156083 803.0263324829433 515.0833134620511 831.6720571769752 479.7609160200732 831.6720571769752H415.7927938840635C380.4703964420856 831.6720571769752 351.8246717480538 803.0263324829433 351.8246717480538 767.7039350409655V479.8473854289214H63.9681221360098C28.6457246940319 479.8473854289214 0 451.2016607348895 0 415.8792632929117V351.9111411569019C0 316.588743714924 28.6457246940319 287.9430190208922 63.9681221360098 287.9430190208922H351.8246717480538V0.0864694088482C351.8246717480538 -35.2359280331298 380.4703964420857 -63.8816527271616 415.7927938840635 -63.8816527271616H479.7609160200732C515.0833134620511 -63.8816527271616 543.729038156083 -35.2359280331298 543.729038156083 0.0864694088482V287.9430190208922H831.585587768127C866.9079852101049 287.9430190208922 895.5537099041368 316.588743714924 895.5537099041368 351.9111411569019V415.8792632929117C895.5537099041368 451.2016607348896 866.9079852101049 479.8473854289214 831.585587768127 479.8473854289214z" />
<glyph glyph-name="plus-1"
unicode="&#x70;&#x6C;&#x75;&#x73;"
horiz-adv-x="895.5537099041368" d="M831.585587768127 479.8473854289214H543.729038156083V767.7039350409655C543.729038156083 803.0263324829433 515.0833134620511 831.6720571769752 479.7609160200732 831.6720571769752H415.7927938840635C380.4703964420856 831.6720571769752 351.8246717480538 803.0263324829433 351.8246717480538 767.7039350409655V479.8473854289214H63.9681221360098C28.6457246940319 479.8473854289214 0 451.2016607348895 0 415.8792632929117V351.9111411569019C0 316.588743714924 28.6457246940319 287.9430190208922 63.9681221360098 287.9430190208922H351.8246717480538V0.0864694088482C351.8246717480538 -35.2359280331298 380.4703964420857 -63.8816527271616 415.7927938840635 -63.8816527271616H479.7609160200732C515.0833134620511 -63.8816527271616 543.729038156083 -35.2359280331298 543.729038156083 0.0864694088482V287.9430190208922H831.585587768127C866.9079852101049 287.9430190208922 895.5537099041368 316.588743714924 895.5537099041368 351.9111411569019V415.8792632929117C895.5537099041368 451.2016607348896 866.9079852101049 479.8473854289214 831.585587768127 479.8473854289214z" />
<glyph glyph-name="minus"
unicode="&#xE001;"
horiz-adv-x="893.7641930109211" d="M829.9238935101409 480.448527979227H63.8402995007801C28.5884841201931 480.4465329698676 0 451.8580488496745 0 416.6062334690875V352.7659339683073C0 317.5141185877203 28.5884841201931 288.9256344675273 63.8402995007801 288.9256344675273H829.9238935101409C865.1757088907281 288.9256344675273 893.7641930109211 317.5141185877203 893.7641930109211 352.7659339683073V416.6062334690875C893.7641930109211 451.8580488496744 865.1757088907281 480.4465329698675 829.9238935101409 480.4465329698675z" />
<glyph glyph-name="minus-1"
unicode="&#x6D;&#x69;&#x6E;&#x75;&#x73;"
horiz-adv-x="893.7641930109211" d="M829.9238935101409 480.448527979227H63.8402995007801C28.5884841201931 480.4465329698676 0 451.8580488496745 0 416.6062334690875V352.7659339683073C0 317.5141185877203 28.5884841201931 288.9256344675273 63.8402995007801 288.9256344675273H829.9238935101409C865.1757088907281 288.9256344675273 893.7641930109211 317.5141185877203 893.7641930109211 352.7659339683073V416.6062334690875C893.7641930109211 451.8580488496744 865.1757088907281 480.4465329698675 829.9238935101409 480.4465329698675z" />
<glyph glyph-name="unlocked"
unicode="&#xE002;"
horiz-adv-x="1024" d="M426.667 341.333C473.6 341.333 512 303.36 512 256S474.027 170.667 426.6670000000001 170.667S341.3330000000001 208.64 341.3330000000001 256S379.733 341.333 426.6670000000001 341.333M768 853.333C650.24 853.333 554.667 757.76 554.667 640V554.667H170.667C123.733 554.667 85.333 516.267 85.333 469.333V42.667C85.333 -4.2669999999999 123.733 -42.6669999999999 170.667 -42.6669999999999H682.667C729.6 -42.6669999999999 768 -4.2669999999999 768 42.6670000000001V469.333C768 516.267 729.6 554.667 682.667 554.667H640V640C640 710.827 697.173 768 768 768S896 710.827 896 640V554.667H981.333V640C981.333 757.76 885.76 853.333 768 853.333M682.667 469.333V42.6669999999999H170.667V469.333H682.667z" />
<glyph glyph-name="unlocked-1"
unicode="&#x75;&#x6E;&#x6C;&#x6F;&#x63;&#x6B;&#x65;&#x64;"
horiz-adv-x="1024" d="M426.667 341.333C473.6 341.333 512 303.36 512 256S474.027 170.667 426.6670000000001 170.667S341.3330000000001 208.64 341.3330000000001 256S379.733 341.333 426.6670000000001 341.333M768 853.333C650.24 853.333 554.667 757.76 554.667 640V554.667H170.667C123.733 554.667 85.333 516.267 85.333 469.333V42.667C85.333 -4.2669999999999 123.733 -42.6669999999999 170.667 -42.6669999999999H682.667C729.6 -42.6669999999999 768 -4.2669999999999 768 42.6670000000001V469.333C768 516.267 729.6 554.667 682.667 554.667H640V640C640 710.827 697.173 768 768 768S896 710.827 896 640V554.667H981.333V640C981.333 757.76 885.76 853.333 768 853.333M682.667 469.333V42.6669999999999H170.667V469.333H682.667z" />
<glyph glyph-name="locked"
unicode="&#xE003;"
horiz-adv-x="1024" d="M512 170.667C464.64 170.667 426.6670000000001 209.067 426.6670000000001 256C426.6670000000001 303.36 464.64 341.333 512 341.333A85.333 85.333 0 0 0 597.333 256A85.333 85.333 0 0 0 512 170.667M768 42.667V469.333H256V42.667H768M768 554.667A85.333 85.333 0 0 0 853.333 469.333V42.667A85.333 85.333 0 0 0 768 -42.667H256C208.64 -42.667 170.667 -4.2670000000001 170.667 42.6669999999999V469.333C170.667 516.693 208.64 554.667 256 554.667H298.6670000000001V640A213.333 213.333 0 0 0 512 853.333A213.333 213.333 0 0 0 725.333 640V554.667H768M512 768A128 128 0 0 1 384 640V554.667H640V640A128 128 0 0 1 512 768z" />
<glyph glyph-name="locked-1"
unicode="&#x6C;&#x6F;&#x63;&#x6B;&#x65;&#x64;"
horiz-adv-x="1024" d="M512 170.667C464.64 170.667 426.6670000000001 209.067 426.6670000000001 256C426.6670000000001 303.36 464.64 341.333 512 341.333A85.333 85.333 0 0 0 597.333 256A85.333 85.333 0 0 0 512 170.667M768 42.667V469.333H256V42.667H768M768 554.667A85.333 85.333 0 0 0 853.333 469.333V42.667A85.333 85.333 0 0 0 768 -42.667H256C208.64 -42.667 170.667 -4.2670000000001 170.667 42.6669999999999V469.333C170.667 516.693 208.64 554.667 256 554.667H298.6670000000001V640A213.333 213.333 0 0 0 512 853.333A213.333 213.333 0 0 0 725.333 640V554.667H768M512 768A128 128 0 0 1 384 640V554.667H640V640A128 128 0 0 1 512 768z" />
<glyph glyph-name="wifi-strength-1"
unicode="&#xE004;"
horiz-adv-x="1022.9733303792667" d="M511.4866651896334 768.1283337025917C332.0397604864727 768.1283337025917 157.7087214326013 708.0286505428097 16.1967447318741 597.6324456402496C187.9713494571903 381.9559014844185 336.3024823621839 198.2472739029395 511.4866651896334 -20.4132754656288C685.3921313541088 196.1154134663874 862.7071756207173 416.9078232715078 1008.0553023103668 597.6324456402497C866.1177527202434 708.0286505428097 691.3591427821901 768.1283337025917 511.4866651896334 768.1283337025917M511.4866651896334 682.8808891701171C642.3423366997788 682.8808891701171 771.0661477733722 646.2236788332648 882.7410693389065 578.4516956956384L665.3592366333123 307.3637631451326C618.0467201032712 329.95509018927 564.7661931477559 341.8891130454328 511.4866651896333 341.8891130454328C458.2071372315108 341.8891130454328 404.9266102759954 329.9550901892699 357.6140937459543 307.7903350319215L139.3801162641751 578.8782675824273C251.9071826058945 646.6502507200537 380.6309936794878 682.8808891701171 511.4866651896334 682.8808891701171z" />
<glyph glyph-name="wifi-strength-1-1"
unicode="&#x77;&#x69;&#x66;&#x69;&#x5F;&#x73;&#x74;&#x72;&#x65;&#x6E;&#x67;&#x74;&#x68;&#x5F;&#x31;"
horiz-adv-x="1022.9733303792667" d="M511.4866651896334 768.1283337025917C332.0397604864727 768.1283337025917 157.7087214326013 708.0286505428097 16.1967447318741 597.6324456402496C187.9713494571903 381.9559014844185 336.3024823621839 198.2472739029395 511.4866651896334 -20.4132754656288C685.3921313541088 196.1154134663874 862.7071756207173 416.9078232715078 1008.0553023103668 597.6324456402497C866.1177527202434 708.0286505428097 691.3591427821901 768.1283337025917 511.4866651896334 768.1283337025917M511.4866651896334 682.8808891701171C642.3423366997788 682.8808891701171 771.0661477733722 646.2236788332648 882.7410693389065 578.4516956956384L665.3592366333123 307.3637631451326C618.0467201032712 329.95509018927 564.7661931477559 341.8891130454328 511.4866651896333 341.8891130454328C458.2071372315108 341.8891130454328 404.9266102759954 329.9550901892699 357.6140937459543 307.7903350319215L139.3801162641751 578.8782675824273C251.9071826058945 646.6502507200537 380.6309936794878 682.8808891701171 511.4866651896334 682.8808891701171z" />
<glyph glyph-name="wifi-strength-0"
unicode="&#xE005;"
horiz-adv-x="1022.9733303792667" d="M511.4866651896334 768.1283337025917C332.4663323732617 768.1283337025917 157.7087214326013 708.4552224295987 17.0498885054521 597.6324456402496C183.283054692083 393.0377795643962 349.5162208787138 184.1813906102245 511.4866651896334 -20.4132754656289C609.5212763518488 103.1956689560682 711.8186093897755 226.8046133777654 809.8542195493837 350.4145567968553V486.8106678482933L511.4866651896334 115.9828355858092L140.6588329271492 580.5835561321903C251.4806107191054 648.7811121592129 379.3522770165138 682.8808891701171 511.4866651896334 682.8808891701171S771.4927196601614 644.5193892808945 882.3144974521176 580.5835561321903L865.2646089466655 555.0092228727087H976.0873857360147C988.8745523657554 567.7963895024495 997.398997119785 584.8452790105086 1010.186163749526 597.6324456402496C865.2646089466655 708.4552224295987 690.5069980060051 768.1283337025917 511.4866651896334 768.1283337025917M895.1016640818584 469.7607793428413V214.0174467480247H980.349108614333V469.7607793428413M895.1016640818584 128.77000221555V43.5225576830754H980.349108614333V128.77000221555" />
<glyph glyph-name="wifi-strength-0-1"
unicode="&#x77;&#x69;&#x66;&#x69;&#x5F;&#x73;&#x74;&#x72;&#x65;&#x6E;&#x67;&#x74;&#x68;&#x5F;&#x30;"
horiz-adv-x="1022.9733303792667" d="M511.4866651896334 768.1283337025917C332.4663323732617 768.1283337025917 157.7087214326013 708.4552224295987 17.0498885054521 597.6324456402496C183.283054692083 393.0377795643962 349.5162208787138 184.1813906102245 511.4866651896334 -20.4132754656289C609.5212763518488 103.1956689560682 711.8186093897755 226.8046133777654 809.8542195493837 350.4145567968553V486.8106678482933L511.4866651896334 115.9828355858092L140.6588329271492 580.5835561321903C251.4806107191054 648.7811121592129 379.3522770165138 682.8808891701171 511.4866651896334 682.8808891701171S771.4927196601614 644.5193892808945 882.3144974521176 580.5835561321903L865.2646089466655 555.0092228727087H976.0873857360147C988.8745523657554 567.7963895024495 997.398997119785 584.8452790105086 1010.186163749526 597.6324456402496C865.2646089466655 708.4552224295987 690.5069980060051 768.1283337025917 511.4866651896334 768.1283337025917M895.1016640818584 469.7607793428413V214.0174467480247H980.349108614333V469.7607793428413M895.1016640818584 128.77000221555V43.5225576830754H980.349108614333V128.77000221555" />
<glyph glyph-name="wifi-strength-2"
unicode="&#xE006;"
horiz-adv-x="1022.9733303792667" d="M511.4866651896334 768.1283337025917C332.0397604864727 768.1283337025917 157.7087214326013 708.0286505428097 16.1967447318741 597.6324456402496C187.9713494571903 381.9559014844185 336.3024823621839 198.2472739029395 511.4866651896334 -20.4132754656288C685.3921313541088 196.1154134663874 862.7071756207173 416.9078232715078 1008.0553023103668 597.6324456402497C866.1177527202434 708.0286505428097 691.3591427821901 768.1283337025917 511.4866651896334 768.1283337025917M511.4866651896334 682.8808891701171C642.3423366997788 682.8808891701171 771.0661477733722 646.2236788332648 882.7410693389065 578.4516956956384L745.9183864006797 408.8089514068742C693.0644313319532 438.2194346552781 612.505281564586 469.7607793428413 511.4866651896334 469.7607793428413C410.0414769278917 469.7607793428413 329.9088990473136 437.7928627684892 277.0549439785871 408.8089514068743L139.3801162641751 578.8782675824273C251.9071826058945 646.6502507200537 380.6309936794878 682.8808891701171 511.4866651896334 682.8808891701171z" />
<glyph glyph-name="wifi-strength-2-1"
unicode="&#x77;&#x69;&#x66;&#x69;&#x5F;&#x73;&#x74;&#x72;&#x65;&#x6E;&#x67;&#x74;&#x68;&#x5F;&#x32;"
horiz-adv-x="1022.9733303792667" d="M511.4866651896334 768.1283337025917C332.0397604864727 768.1283337025917 157.7087214326013 708.0286505428097 16.1967447318741 597.6324456402496C187.9713494571903 381.9559014844185 336.3024823621839 198.2472739029395 511.4866651896334 -20.4132754656288C685.3921313541088 196.1154134663874 862.7071756207173 416.9078232715078 1008.0553023103668 597.6324456402497C866.1177527202434 708.0286505428097 691.3591427821901 768.1283337025917 511.4866651896334 768.1283337025917M511.4866651896334 682.8808891701171C642.3423366997788 682.8808891701171 771.0661477733722 646.2236788332648 882.7410693389065 578.4516956956384L745.9183864006797 408.8089514068742C693.0644313319532 438.2194346552781 612.505281564586 469.7607793428413 511.4866651896334 469.7607793428413C410.0414769278917 469.7607793428413 329.9088990473136 437.7928627684892 277.0549439785871 408.8089514068743L139.3801162641751 578.8782675824273C251.9071826058945 646.6502507200537 380.6309936794878 682.8808891701171 511.4866651896334 682.8808891701171z" />
<glyph glyph-name="error"
unicode="&#xE007;"
horiz-adv-x="1024" d="M512 810.667C747.605 810.667 938.667 619.605 938.667 384C938.667 148.395 747.6049999999999 -42.6669999999999 511.9999999999999 -42.6669999999999C276.395 -42.6669999999999 85.333 148.3950000000001 85.333 384.0000000000001C85.333 619.605 276.395 810.667 512 810.667zM512 725.333C323.7970000000001 725.333 170.667 572.203 170.667 384C170.667 195.797 323.797 42.6669999999999 512 42.6669999999999C700.203 42.6669999999999 853.3330000000001 195.7969999999999 853.3330000000001 384C853.3330000000001 572.203 700.2030000000001 725.3330000000001 512 725.3330000000001zM609.835 542.165L670.1650000000001 481.835L572.33 384L670.1650000000001 286.165L609.835 225.8349999999999L512 323.67L414.165 225.8349999999999L353.8350000000001 286.165L451.67 384L353.8350000000001 481.835L414.165 542.165L512 444.33L609.835 542.165z" />
<glyph glyph-name="error-1"
unicode="&#x65;&#x72;&#x72;&#x6F;&#x72;"
horiz-adv-x="1024" d="M512 810.667C747.605 810.667 938.667 619.605 938.667 384C938.667 148.395 747.6049999999999 -42.6669999999999 511.9999999999999 -42.6669999999999C276.395 -42.6669999999999 85.333 148.3950000000001 85.333 384.0000000000001C85.333 619.605 276.395 810.667 512 810.667zM512 725.333C323.7970000000001 725.333 170.667 572.203 170.667 384C170.667 195.797 323.797 42.6669999999999 512 42.6669999999999C700.203 42.6669999999999 853.3330000000001 195.7969999999999 853.3330000000001 384C853.3330000000001 572.203 700.2030000000001 725.3330000000001 512 725.3330000000001zM609.835 542.165L670.1650000000001 481.835L572.33 384L670.1650000000001 286.165L609.835 225.8349999999999L512 323.67L414.165 225.8349999999999L353.8350000000001 286.165L451.67 384L353.8350000000001 481.835L414.165 542.165L512 444.33L609.835 542.165z" />
<glyph glyph-name="wifi-strength-3"
unicode="&#xE008;"
horiz-adv-x="1022.9733303792667" d="M511.4866651896334 768.1283337025917C332.0397604864727 768.1283337025917 157.7087214326013 708.0286505428097 16.1967447318741 597.6324456402496C187.9713494571903 381.9559014844185 336.3024823621839 198.2472739029395 511.4866651896334 -20.4132754656288C685.3921313541088 196.1154134663874 862.7071756207173 416.9078232715078 1008.0553023103668 597.6324456402497C866.1177527202434 708.0286505428097 691.3591427821901 768.1283337025917 511.4866651896334 768.1283337025917M511.4866651896334 682.8808891701171C642.3423366997788 682.8808891701171 771.0661477733722 646.2236788332648 882.7410693389065 578.4516956956384L800.0500591349871 474.8756459947375C735.688653096887 512.385001107775 634.2434648351453 555.0092228727087 511.4866651896334 555.0092228727087C383.614998892225 555.0092228727087 284.7272439564316 512.385001107775 222.0701274707015 476.5809345445006L139.3801162641751 578.8782675824273C251.9071826058945 646.6502507200537 380.6309936794878 682.8808891701171 511.4866651896334 682.8808891701171z" />
<glyph glyph-name="wifi-strength-3-1"
unicode="&#x77;&#x69;&#x66;&#x69;&#x5F;&#x73;&#x74;&#x72;&#x65;&#x6E;&#x67;&#x74;&#x68;&#x5F;&#x33;"
horiz-adv-x="1022.9733303792667" d="M511.4866651896334 768.1283337025917C332.0397604864727 768.1283337025917 157.7087214326013 708.0286505428097 16.1967447318741 597.6324456402496C187.9713494571903 381.9559014844185 336.3024823621839 198.2472739029395 511.4866651896334 -20.4132754656288C685.3921313541088 196.1154134663874 862.7071756207173 416.9078232715078 1008.0553023103668 597.6324456402497C866.1177527202434 708.0286505428097 691.3591427821901 768.1283337025917 511.4866651896334 768.1283337025917M511.4866651896334 682.8808891701171C642.3423366997788 682.8808891701171 771.0661477733722 646.2236788332648 882.7410693389065 578.4516956956384L800.0500591349871 474.8756459947375C735.688653096887 512.385001107775 634.2434648351453 555.0092228727087 511.4866651896334 555.0092228727087C383.614998892225 555.0092228727087 284.7272439564316 512.385001107775 222.0701274707015 476.5809345445006L139.3801162641751 578.8782675824273C251.9071826058945 646.6502507200537 380.6309936794878 682.8808891701171 511.4866651896334 682.8808891701171z" />
<glyph glyph-name="down"
unicode="&#xE009;"
horiz-adv-x="893.7641930109211" d="M824.1383663678829 451.520892267936L868.427574146549 407.2306869845902C887.180662124903 388.477599006236 887.180662124903 358.1514617340061 868.427574146549 339.5978746915919L480.79725561525 -48.2279547569284C462.0441676368958 -66.9810427352825 431.7200253740253 -66.9810427352825 413.1664383316111 -48.2279547569284L25.3366188643721 339.6018647103107C6.5835308860179 358.3549526886648 6.5835308860179 388.6790949515354 25.3366188643721 407.2326819939496L69.6258266430383 451.5218897726157C88.5784155573323 470.4744786869098 119.5010606280227 470.07547681503 138.0546476704369 450.723886028856L367.0817221294855 210.325258221231V783.690948112612C367.0817221294855 810.2245725926238 388.4283222750588 831.5711727381971 414.9619467550705 831.5711727381971H478.8022462558506C505.3358707358623 831.5711727381971 526.6824708814356 810.2245725926238 526.6824708814356 783.690948112612V210.325258221231L755.7095453404842 450.723886028856C774.2631323828984 470.2749777509699 805.1857774535888 470.6739796228497 824.1383663678829 451.5218897726157z" />
<glyph glyph-name="down-1"
unicode="&#x64;&#x6F;&#x77;&#x6E;"
horiz-adv-x="893.7641930109211" d="M824.1383663678829 451.520892267936L868.427574146549 407.2306869845902C887.180662124903 388.477599006236 887.180662124903 358.1514617340061 868.427574146549 339.5978746915919L480.79725561525 -48.2279547569284C462.0441676368958 -66.9810427352825 431.7200253740253 -66.9810427352825 413.1664383316111 -48.2279547569284L25.3366188643721 339.6018647103107C6.5835308860179 358.3549526886648 6.5835308860179 388.6790949515354 25.3366188643721 407.2326819939496L69.6258266430383 451.5218897726157C88.5784155573323 470.4744786869098 119.5010606280227 470.07547681503 138.0546476704369 450.723886028856L367.0817221294855 210.325258221231V783.690948112612C367.0817221294855 810.2245725926238 388.4283222750588 831.5711727381971 414.9619467550705 831.5711727381971H478.8022462558506C505.3358707358623 831.5711727381971 526.6824708814356 810.2245725926238 526.6824708814356 783.690948112612V210.325258221231L755.7095453404842 450.723886028856C774.2631323828984 470.2749777509699 805.1857774535888 470.6739796228497 824.1383663678829 451.5218897726157z" />
<glyph glyph-name="wifi-strength-4"
unicode="&#xE00A;"
horiz-adv-x="1022.9733303792667" d="M511.4866651896334 768.1283337025917C332.0397604864727 768.1283337025917 157.7087214326013 708.0286505428097 16.1967447318741 597.6324456402496C187.9713494571903 381.9559014844185 336.3024823621839 198.2472739029395 511.4866651896334 -20.4132754656288C685.3921313541088 196.1154134663874 862.7071756207173 416.9078232715078 1008.0553023103668 597.6324456402497C866.1177527202434 708.0286505428097 691.3591427821901 768.1283337025917 511.4866651896334 768.1283337025917z" />
<glyph glyph-name="wifi-strength-4-1"
unicode="&#x77;&#x69;&#x66;&#x69;&#x5F;&#x73;&#x74;&#x72;&#x65;&#x6E;&#x67;&#x74;&#x68;&#x5F;&#x34;"
horiz-adv-x="1022.9733303792667" d="M511.4866651896334 768.1283337025917C332.0397604864727 768.1283337025917 157.7087214326013 708.0286505428097 16.1967447318741 597.6324456402496C187.9713494571903 381.9559014844185 336.3024823621839 198.2472739029395 511.4866651896334 -20.4132754656288C685.3921313541088 196.1154134663874 862.7071756207173 416.9078232715078 1008.0553023103668 597.6324456402497C866.1177527202434 708.0286505428097 691.3591427821901 768.1283337025917 511.4866651896334 768.1283337025917z" />
<glyph glyph-name="success"
unicode="&#xE00B;"
horiz-adv-x="1024" d="M512 810.667C276.36 810.667 85.333 619.64 85.333 384C85.333 148.36 276.3590000000001 -42.6669999999999 512 -42.6669999999999C747.64 -42.6669999999999 938.667 148.3590000000002 938.667 384.0000000000001C938.667 619.64 747.64 810.667 512 810.667zM512 42.667C323.79 42.667 170.667 195.789 170.667 384.0000000000001C170.667 572.21 323.789 725.3330000000001 512 725.3330000000001C700.21 725.3330000000001 853.3330000000001 572.211 853.3330000000001 384.0000000000001C853.3330000000001 195.7900000000001 700.211 42.667 512 42.667zM672.672 536.437L733.005 476.104L469.333 211.328L311.167 369.495L371.5 429.828L469.333 331.995L672.673 536.438z" />
<glyph glyph-name="success-1"
unicode="&#x73;&#x75;&#x63;&#x63;&#x65;&#x73;&#x73;"
horiz-adv-x="1024" d="M512 810.667C276.36 810.667 85.333 619.64 85.333 384C85.333 148.36 276.3590000000001 -42.6669999999999 512 -42.6669999999999C747.64 -42.6669999999999 938.667 148.3590000000002 938.667 384.0000000000001C938.667 619.64 747.64 810.667 512 810.667zM512 42.667C323.79 42.667 170.667 195.789 170.667 384.0000000000001C170.667 572.21 323.789 725.3330000000001 512 725.3330000000001C700.21 725.3330000000001 853.3330000000001 572.211 853.3330000000001 384.0000000000001C853.3330000000001 195.7900000000001 700.211 42.667 512 42.667zM672.672 536.437L733.005 476.104L469.333 211.328L311.167 369.495L371.5 429.828L469.333 331.995L672.673 536.438z" />
<glyph glyph-name="up"
unicode="&#xE00C;"
horiz-adv-x="893.7641930109211" d="M69.6258266430383 317.8562626928574L25.3366188643721 362.1454704715236C6.5835308860179 380.8985584498777 6.5835308860179 411.2227007127483 25.3366188643721 429.7762877551625L412.9669373956711 817.6021172036826C431.7200253740253 836.3552051820368 462.0441676368958 836.3552051820368 480.59775467931 817.6021172036826L868.2280732106092 429.9717986723836C886.9811611889633 411.2187106940295 886.9811611889633 380.894568431159 868.2280732106092 362.3409813887447L823.938865431943 318.0517736100786C804.9862765176489 299.0991846957845 774.0636314469585 299.4981865676644 755.5100444045443 318.8497773538383L526.6824708814356 559.0528942442421V-14.3127956471388C526.6824708814356 -40.8464201271506 505.3358707358623 -62.1930202727239 478.8022462558506 -62.1930202727239H414.9619467550705C388.4283222750588 -62.1930202727239 367.0817221294855 -40.8464201271506 367.0817221294855 -14.3127956471388V559.0528942442422L138.0546476704369 318.6542664366173C119.5010606280227 299.1031747145034 88.5784155573324 298.7041728426234 69.6258266430383 317.8562626928575z" />
<glyph glyph-name="up-1"
unicode="&#x75;&#x70;"
horiz-adv-x="893.7641930109211" d="M69.6258266430383 317.8562626928574L25.3366188643721 362.1454704715236C6.5835308860179 380.8985584498777 6.5835308860179 411.2227007127483 25.3366188643721 429.7762877551625L412.9669373956711 817.6021172036826C431.7200253740253 836.3552051820368 462.0441676368958 836.3552051820368 480.59775467931 817.6021172036826L868.2280732106092 429.9717986723836C886.9811611889633 411.2187106940295 886.9811611889633 380.894568431159 868.2280732106092 362.3409813887447L823.938865431943 318.0517736100786C804.9862765176489 299.0991846957845 774.0636314469585 299.4981865676644 755.5100444045443 318.8497773538383L526.6824708814356 559.0528942442421V-14.3127956471388C526.6824708814356 -40.8464201271506 505.3358707358623 -62.1930202727239 478.8022462558506 -62.1930202727239H414.9619467550705C388.4283222750588 -62.1930202727239 367.0817221294855 -40.8464201271506 367.0817221294855 -14.3127956471388V559.0528942442422L138.0546476704369 318.6542664366173C119.5010606280227 299.1031747145034 88.5784155573324 298.7041728426234 69.6258266430383 317.8562626928575z" />
<glyph glyph-name="alarm"
unicode="&#xE00D;"
horiz-adv-x="1024" d="M512 810.667C747.22 810.667 938.667 619.22 938.667 384C938.667 148.78 747.2199999999999 -42.6669999999999 511.9999999999999 -42.6669999999999C276.78 -42.667 85.333 148.78 85.333 384C85.333 619.22 276.78 810.667 512 810.667zM512 725.333C323.082 725.333 170.667 572.918 170.667 384C170.667 195.082 323.082 42.6669999999999 512 42.6669999999999C700.918 42.6669999999999 853.3330000000001 195.0819999999999 853.3330000000001 384C853.3330000000001 572.918 700.9180000000001 725.3330000000001 512 725.3330000000001zM512 266.581C542.476 266.581 565.333 244.054 565.333 213.3340000000001S542.476 160.085 512 160.085C480.83 160.085 458.667 182.6130000000001 458.667 214.015C458.667 244.053 481.524 266.581 512 266.581zM554.667 640V341.3330000000001H469.333V640H554.667z" />
<glyph glyph-name="alarm-1"
unicode="&#x61;&#x6C;&#x61;&#x72;&#x6D;"
horiz-adv-x="1024" d="M512 810.667C747.22 810.667 938.667 619.22 938.667 384C938.667 148.78 747.2199999999999 -42.6669999999999 511.9999999999999 -42.6669999999999C276.78 -42.667 85.333 148.78 85.333 384C85.333 619.22 276.78 810.667 512 810.667zM512 725.333C323.082 725.333 170.667 572.918 170.667 384C170.667 195.082 323.082 42.6669999999999 512 42.6669999999999C700.918 42.6669999999999 853.3330000000001 195.0819999999999 853.3330000000001 384C853.3330000000001 572.918 700.9180000000001 725.3330000000001 512 725.3330000000001zM512 266.581C542.476 266.581 565.333 244.054 565.333 213.3340000000001S542.476 160.085 512 160.085C480.83 160.085 458.667 182.6130000000001 458.667 214.015C458.667 244.053 481.524 266.581 512 266.581zM554.667 640V341.3330000000001H469.333V640H554.667z" />
</font>
</defs>
</svg>

Before

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

-556
View File
@@ -1,556 +0,0 @@
{
"values": {
"logo": "OpenTherm Gateway",
"nav": {
"license": "授权许可",
"source": "源代码",
"help": "帮助",
"issues": "问题与反馈",
"releases": "发行版"
},
"units": {
"days": "天",
"hours": "小时",
"min": "分",
"sec": "秒",
"dbm": "dBm",
"mhz": "MHz",
"kw": "kW",
"rpm": "RPM",
"ppm": "ppm",
"byte": "byte",
"mbyte": "MB",
"liter": "升",
"gallon": "加仑"
},
"button": {
"upgrade": "固件升级",
"restart": "重启",
"save": "保存",
"saved": "已保存",
"refresh": "刷新",
"restore": "恢复",
"restored": "已恢复",
"backup": "备份",
"wait": "请等待...",
"uploading": "上传中...",
"success": "成功",
"error": "错误"
},
"index": {
"title": "OpenTherm Gateway",
"section": {
"network": "网络",
"system": "系统"
},
"system": {
"build": {
"title": "Build",
"version": "固件版本",
"commit": "Commit",
"date": "日期",
"core": "内核版本",
"sdk": "SDK"
},
"uptime": "运行时间",
"memory": {
"heap": "内存 (heap)",
"psram": "内存 (PSRAM)",
"maxFreeBlock": "max free block",
"min": "min"
},
"board": "开发板",
"chip": {
"model": "芯片",
"cores": "核心数",
"freq": "频率"
},
"flash": {
"size": "闪存容量"
},
"lastResetReason": "上次重置原因",
"coreDump": "内存转储"
}
},
"dashboard": {
"name": "仪表盘",
"title": "仪表盘 - OpenTherm Gateway",
"section": {
"control": "调节",
"states": "状态",
"sensors": "传感器",
"diag": "OpenTherm 诊断"
},
"thermostat": {
"heating": "供暖",
"dhw": "生活热水",
"currentTemp": "当前温度",
"enable": "启用",
"turbo": "Turbo 模式"
},
"notify": {
"fault": {
"title": "锅炉报警状态已激活!",
"note": "建议检查锅炉并查看说明书对应的报警代码:"
},
"diag": {
"title": "锅炉诊断状态已激活!",
"note": "锅炉可能需要检查,建议查看说明书对应的诊断代码:"
},
"reset": "点击复位"
},
"states": {
"mNetworkConnected": "网络连接状态",
"mMqttConnected": "MQTT服务器连接状态",
"mEmergencyState": "应急模式",
"mExtPumpState": "外置循环泵",
"mCascadeControlInput": "Cascade 控制 (input)",
"mCascadeControlOutput": "Cascade 控制 (output)",
"sConnected": "OpenTherm 通讯状态",
"sFlame": "火焰",
"sCoolingActive": "制冷",
"sCoolingSetpoint": "冷却设定点",
"sFaultActive": "报警状态",
"sFaultCode": "报警代码",
"sDiagActive": "诊断状态",
"sDiagCode": "诊断代码",
"mHeatEnabled": "供暖功能已启用",
"mHeatBlocking": "供暖",
"mHeatOverheat": "供暖超热保护",
"mHeatFreezing": "防冻保护",
"sHeatActive": "供暖激活状态",
"mHeatSetpointTemp": "供暖供水设定温度",
"mHeatTargetTemp": "供暖供水目标温度",
"mHeatCurrTemp": "供暖当前供水温度",
"mHeatRetTemp": "供暖回水温度",
"mHeatIndoorTemp": "供暖,室内温度",
"mHeatOutdoorTemp": "供暖,室外温度",
"mDhwEnabled": "生活热水功能已启用",
"mDhwOverheat": "生活热水超热保护",
"sDhwActive": "生活热水激活",
"mDhwTargetTemp": "生活热水目标温度",
"mDhwCurrTemp": "生活热水当前出水温度",
"mDhwRetTemp": "生活热水回水温度"
},
"sensors": {
"values": {
"temp": "温度",
"humidity": "湿度",
"battery": "电量",
"rssi": "RSSI"
}
}
},
"network": {
"title": "网络 - OpenTherm Gateway",
"name": "网络设置",
"section": {
"static": "静态设置",
"availableNetworks": "可用网络",
"staSettings": "WiFi 设置",
"apSettings": "AP 设置"
},
"scan": {
"pos": "#",
"info": "Info"
},
"wifi": {
"ssid": "SSID",
"password": "密码",
"channel": "频道",
"signal": "信号强度",
"connected": "已连接"
},
"params": {
"hostname": "Hostname",
"dhcp": "自动 (DHCP)",
"mac": "物理地址 (MAC)",
"ip": "IP",
"subnet": "子网掩码",
"gateway": "网关",
"dns": "DNS 服务器"
},
"sta": {
"channel": {
"note": "自动选择设置为0"
}
}
},
"sensors": {
"title": "传感器设置 - OpenTherm Gateway",
"name": "传感器设置",
"enabled": "启用",
"sensorName": {
"title": "传感器名称",
"note": "只能包含:a-z、A-Z、0-9、下划线和空格"
},
"purpose": "用途",
"purposes": {
"outdoorTemp": "室外温度",
"indoorTemp": "室内温度",
"heatTemp": "供暖,温度",
"heatRetTemp": "供暖回水温度",
"dhwTemp": "生活热水温度",
"dhwRetTemp": "生活热水回水温度",
"dhwFlowRate": "生活热水水流量",
"exhaustTemp": "烟气温度",
"modLevel": "Modulation level (%)",
"number": "Number (raw)",
"powerFactor": "功率 (%)",
"power": "功率(kW)",
"fanSpeed": "风机转速",
"co2": "CO2",
"pressure": "压力",
"humidity": "湿度",
"temperature": "温度",
"notConfigured": "未配置"
},
"type": "类型/来源",
"types": {
"otOutdoorTemp": "OpenTherm, outdoor temp",
"otHeatTemp": "OpenTherm, heating, temp",
"otHeatRetTemp": "OpenTherm, heating, return temp",
"otDhwTemp": "OpenTherm, DHW, temperature",
"otDhwTemp2": "OpenTherm, DHW, temperature 2",
"otDhwFlowRate": "OpenTherm, DHW, flow rate",
"otCh2Temp": "OpenTherm, channel 2, temp",
"otExhaustTemp": "OpenTherm, exhaust temp",
"otHeatExchangerTemp": "OpenTherm, heat exchanger temp",
"otPressure": "OpenTherm, pressure",
"otModLevel": "OpenTherm, modulation level",
"otCurrentPower": "OpenTherm, current power",
"otExhaustCo2": "OpenTherm, exhaust CO2",
"otExhaustFanSpeed": "OpenTherm, exhaust fan speed",
"otSupplyFanSpeed": "OpenTherm, supply fan speed",
"otSolarStorageTemp": "OpenTherm, solar storage temp",
"otSolarCollectorTemp": "OpenTherm, solar collector temp",
"otFanSpeedSetpoint": "OpenTherm, setpoint fan speed",
"otFanSpeedCurrent": "OpenTherm, current fan speed",
"otBurnerStarts": "OpenTherm, number of burner starts",
"otDhwBurnerStarts": "OpenTherm, number of burner starts (DHW)",
"otHeatingPumpStarts": "OpenTherm, number of pump starts (heating)",
"otDhwPumpStarts": "OpenTherm, number of pump starts (DHW)",
"otBurnerHours": "OpenTherm, number of burner operating hours",
"otDhwBurnerHours": "OpenTherm, number of burner operating hours (DHW)",
"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": "未配置"
},
"gpio": "GPIO",
"address": {
"title": "传感器地址",
"note": "如需自动检测DALLAS传感器,请保持默认设置;如需连接BLE设备,则需提供MAC地址"
},
"correction": {
"desc": "数值校正",
"offset": "补偿值(偏移量)",
"factor": "Multiplier"
},
"filtering": {
"desc": "数值滤波",
"enabled": {
"title": "启用滤波",
"note": "如果图表中有大量尖锐的噪声,此功能会很有用。使用的滤波器是 \"滑动平均滤波器\"."
},
"factor": {
"title": "滤波系数",
"note": "数值越低,数值变化越平滑且响应越滞后"
}
}
},
"settings": {
"title": "设置 - OpenTherm Gateway",
"name": "设置",
"section": {
"portal": "Portal 设置",
"system": "系统设置",
"diag": "诊断",
"heating": "供热设置",
"dhw": "生活热水设置",
"emergency": "应急模式设置",
"equitherm": "气候补偿设置",
"pid": "PID 参数设置",
"ot": "OpenTherm协议设置",
"mqtt": "MQTT 服务器设置",
"extPump": "外置循环泵设置",
"cascadeControl": "Cascade 级联控制设置"
},
"enable": "启用",
"note": {
"restart": "更改这些设置后,必须重启设备以使变更生效",
"blankNotUse": "空白 - 未使用",
"bleDevice": "BLE设备仅支持搭载BLE功能的特定ESP32开发板使用!"
},
"temp": {
"min": "最低温度",
"max": "最高温度"
},
"avgType": {
"mean": "平均温度",
"min": "最低温度",
"max": "最高温度"
},
"maxModulation": "最大调制范围",
"ohProtection": {
"title": "超温保护",
"desc": "<b>注意:</b> 当锅炉内置过热保护失效或工作异常导致系统超温时,此功能可提供额外保护。如需禁用,请将<b>最高温度</b>和<b>最低温度</b>均设为0。",
"highTemp": {
"title": "高温阈值",
"note": "触发燃烧器强制关闭的阈值温度"
},
"lowTemp": {
"title": "低温阈值",
"note": "燃烧器重新启动的阈值温度"
}
},
"freezeProtection": {
"title": "防冻保护",
"desc": "如果热载体或室内温度低于 <b>低温</b>,加热将被强制开启。",
"highTemp": {
"title": "高温阈值",
"note": "防冻保护激活后系统恢复正常模式的阈值"
},
"lowTemp": {
"title": "低温阈值",
"note": "强制开启加热的阈值"
}
},
"portal": {
"login": "登录",
"password": "密码",
"auth": "需身份验证",
"mdns": "使用 mDNS"
},
"system": {
"unit": "单位",
"metric": "公制 <small>(摄氏度、升、巴)</small>",
"imperial": "英制 <small>(华氏度、加仑、psi)</small>",
"statusLedGpio": "状态指示灯GPIO引脚",
"logLevel": "日志级别",
"serial": {
"enable": "启用串口",
"baud": "串口波特率"
},
"webSerial": {
"enable": "启用 WebSerial"
},
"ntp": {
"server": "NTP服务器",
"timezone": "时区",
"timezonePresets": "选择预设配置..."
}
},
"heating": {
"hyst": {
"title": "滞回",
"desc": "滞回有助于维持设定的室内温度(在使用«Equitherm»和/或«PID»时)。强制禁用加热当<code>current indoor > target + value</code>,启用加热当<code>current indoor < (target - value)</code>。",
"value": "值 <small>(以度为单位)</small>"
},
"turboFactor": "Turbo 模式系数",
"indoorTempAvgType": {
"title": "室内温度平均类型",
"desc": "使用两个或更多室内温度传感器时可能有用(使用 «Equitherm» 和/或 «PID» 时)。"
},
"outdoorTempAvgType": {
"title": "室外温度平均类型",
"desc": "使用两个或更多室外温度传感器时可能有用(使用 «Equitherm» 时)。"
}
},
"emergency": {
"desc": "紧急模式会在以下情况自动激活(当PID或气候补偿无法计算热媒设定值时):<br />启用气候补偿但室外温度传感器断开连接;<br />启用PID或 OpenTherm 选项中启用<i>原生供暖控制</i>但室内温度传感器断开连接。<br /><b>注意:</b> 网络故障或MQTT 服务器连接故障时,类型为<i>通过MQTT/API手动控制</i>的传感器将显示为断开连接状态。",
"target": {
"title": "目标温度",
"note": "<b>重要提示:</b> 若启用OpenTherm选项 <i>«原生供暖控制»</i>,此处设定值为<u>目标室内温度</u>;<br />其他所有情况下,此处设定值为 <u>目标热媒出水温度</u>."
},
"thresholdTime": "进入或退出应急模式的延时 <small>(秒)</small>"
},
"equitherm": {
"slope": {
"title": "斜率",
"note": "热损失补偿。主要调谐参数。"
},
"exponent": {
"title": "指数",
"note": "散热器效率。典型值:<code>1.1</code> - 地板采暖,<code>1.2</code> - 铸铁,<code>1.3</code> - 面板散热器,<code>1.4</code> - 对流器。"
},
"shift": {
"title": "偏移",
"note": "补偿额外热损失(例如,在管道中)或额外热源。"
},
"targetDiffFactor": {
"title": "T 因子",
"note": "如果启用 PID,则不使用。将目标和当前室内温度之间的差值添加到设定点:<code>setpoint = setpoint + ((target - indoor) * T)</code>。"
},
"chart": {
"targetTemp": "目标室内温度",
"setpointTemp": "热载体温度",
"outdoorTemp": "室外温度"
}
},
"pid": {
"p": "P 系数",
"i": "I 系数",
"d": "D 系数",
"dt": "DT <small>以秒为单位</small>",
"limits": {
"title": "Limits",
"note": "<b>重要提示:</b> When using «Equitherm» and «PID» at the same time, the min and max temperatures limit the influence on the «Equitherm» result temperature.<br />Thus, if the min temperature is set to -15 and the max temperature is set to 15, then the final heat carrier setpoint will be from <code>equitherm_result - 15</code> to <code>equitherm_result + 15</code>."
},
"deadband": {
"title": "Deadband",
"note": "Deadband is a range around the target temperature where PID regulation becomes less active. Within this range, the algorithm can reduce intensity or pause adjustments to avoid overreacting to small fluctuations.<br /><br />For instance, with a target temperature of 22°, a lower threshold of 1.0, and an upper threshold of 0.5, the deadband operates between 21° and 22.5°. If the I coefficient is 0.0005 and the I multiplier is 0.05, then within the deadband, the I coefficient becomes: <code>0.0005 * 0.05 = 0.000025</code>",
"p_multiplier": "Multiplier for P factor",
"i_multiplier": "Multiplier for I factor",
"d_multiplier": "Multiplier for D factor",
"thresholdHigh": "Threshold high",
"thresholdLow": "Threshold low"
}
},
"ot": {
"disablingAction": {
"title": "回路关闭方式",
"desc": "无论因何原因关闭回路,包括过热,均采用所选的关闭方式。<br />某些锅炉会在关闭回路时停止循环泵,此时可尝试将目标温度设为 <b>0</b>,以使循环泵的延时运转功能正常工作。",
"heating": "采暖回路",
"dhw": "生活热水回路",
"ch2": "回路 2",
"off": "仅关闭回路",
"zeroSetpoint": "将目标温度设为 <b>0</b>",
"offAndZeroSetpoint": "关闭回路并将目标温度设为 <b>0</b>"
},
"advanced": "高级设置",
"inGpio": "In GPIO",
"outGpio": "Out GPIO",
"ledGpio": "RX LED GPIO",
"memberId": "主设备成员 ID",
"flags": "主设备标志",
"minPower": {
"title": "最小锅炉功率 <small>(kW)</small>",
"note": "该值对应锅炉0-1%的调制水平,通常在锅炉参数设置中的\"最小有效热输出\"。"
},
"maxPower": {
"title": "最大锅炉功率 <small>(kW)</small>",
"note": "<b>0</b> - 自动检测,通常在锅炉参数设置中的\"最大有效热输出\"。"
},
"options": {
"title": "选项(附加设置)",
"desc": "附加设置选项可调整锅炉的运行逻辑。由于协议未完整记录所有选项,同一选项在不同锅炉上可能产生不同效果。<br /><b>注意:</b>若系统运行正常,无需修改设置。",
"dhwSupport": "生活热水支持",
"coolingSupport": "制冷支持",
"summerWinterMode": "夏季/冬季模式",
"heatingStateToSummerWinterMode": "以供暖状态作为夏季/冬季模式",
"ch2AlwaysEnabled": "CH2 始终启用",
"heatingToCh2": "将供暖同步至 CH2",
"dhwToCh2": "将生活热水同步至 CH2",
"dhwBlocking": "生活热水锁定",
"dhwStateAsDhwBlocking": "以生活热水状态作为生活热水锁定依据",
"maxTempSyncWithTargetTemp": "将最高供暖温度与目标温度同步",
"getMinMaxTemp": "从锅炉获取最小/最大温度参数",
"ignoreDiagState": "忽略诊断状态",
"autoFaultReset": "自动报警复位 <small>(不推荐!)</small>",
"autoDiagReset": "自动诊断复位 <small>(不推荐!)</small>",
"setDateAndTime": "同步设置锅炉日期与时间",
"immergasFix": "针对Immergas锅炉的兼容性修复",
"alwaysSendIndoorTemp": "向锅炉发送当前室内温度"
},
"nativeOTC": {
"title": "原生热载体温度计算模式",
"note": "仅在锅炉处于 OTC 模式时<u>才</u>工作:需要并接受目标室内温度,并基于内置曲线模式自行调节热载体温度。与 PID 和 Equitherm 不兼容。"
}
},
"mqtt": {
"homeAssistantDiscovery": "Home Assistant 自动发现",
"server": "服务器地址",
"port": "端口",
"user": "用户名",
"password": "密码",
"prefix": "Prefix 前缀",
"interval": "发布间隔 <small>(秒)</small>"
},
"extPump": {
"use": "使用外置循环泵",
"gpio": "继电器 GPIO引脚",
"invertState": "切换 GPIO 状态",
"postCirculationTime": "后循环时间 <small>(分钟)</small>",
"antiStuckInterval": "防卡死间隔时间<small>(天)</small>",
"antiStuckTime": "防卡死运行时长<small>(分钟)</small>"
},
"cascadeControl": {
"input": {
"desc": "仅当另一台锅炉发生故障时启用本锅炉加热。另一台锅炉的控制器需在故障发生时切换GPIO输入状态以触发本功能。",
"enable": "启用 input",
"gpio": "GPIO",
"invertState": "切换 GPIO 状态",
"thresholdTime": "状态变化阈值时间<small>(秒)</small>"
},
"output": {
"desc": "可通过<u>继电器</u>控制另一台锅炉的启停。",
"enable": "启用 output",
"gpio": "GPIO",
"invertState": "切换 GPIO 状态",
"thresholdTime": "状态变化阈值时间 <small>(秒)</small>",
"events": {
"desc": "事件",
"onFault": "当故障状态激活时",
"onLossConnection": "当OpenTherm连接中断时",
"onEnabledHeating": "当供暖功能启用时"
}
}
}
},
"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": {
"title": "备份与恢复",
"desc": "本功能支持备份和恢复全部设置"
},
"upgrade": {
"title": "升级",
"desc": "本模块支持升级设备的固件与系统文件。<br />可从以下地址下载最新版本 <a href=\"https://github.com/Laxilef/OTGateway/releases\" target=\"_blank\">Releases page</a> 。"
}
},
"note": {
"disclaimer1": "升级系统文件成功后,所有设置将恢复为默认值!升级前请务必备份配置。",
"disclaimer2": "升级成功后,设备将在15秒后自动重启。"
},
"settingsFile": "设置文件",
"fw": "Firmware",
"fs": "Filesystem"
}
}
}
-556
View File
@@ -1,556 +0,0 @@
{
"values": {
"logo": "OpenTherm Gateway",
"nav": {
"license": "License",
"source": "Source code",
"help": "Help",
"issues": "Issues & questions",
"releases": "Releases"
},
"units": {
"days": "d.",
"hours": "h.",
"min": "min.",
"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",
"save": "Save",
"saved": "Saved",
"refresh": "Refresh",
"restore": "Restore",
"restored": "Restored",
"backup": "Backup",
"wait": "Please wait...",
"uploading": "Uploading...",
"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": {
"heap": "Memory (heap)",
"psram": "Memory (PSRAM)",
"maxFreeBlock": "max free block",
"min": "min"
},
"board": "Board",
"chip": {
"model": "Chip",
"cores": "Cores",
"freq": "frequency"
},
"flash": {
"size": "Flash size"
},
"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",
"currentTemp": "Current",
"enable": "Enable",
"turbo": "Turbo mode"
},
"notify": {
"fault": {
"title": "Boiler Fault state is active!",
"note": "It is recommended to inspect the boiler and study the documentation to interpret the fault code:"
},
"diag": {
"title": "Boiler Diagnostic state is active!",
"note": "Perhaps your boiler needs inspection? It is recommended study the documentation to interpret the diag code:"
},
"reset": "Try reset"
},
"states": {
"mNetworkConnected": "Network connection",
"mMqttConnected": "MQTT connection",
"mEmergencyState": "Emergency mode",
"mExtPumpState": "External pump",
"mCascadeControlInput": "Cascade control (input)",
"mCascadeControlOutput": "Cascade control (output)",
"sConnected": "OpenTherm connection",
"sFlame": "Flame",
"sCoolingActive": "Cooling",
"sCoolingSetpoint": "Cooling setpoint",
"sFaultActive": "Fault",
"sFaultCode": "Fault code",
"sDiagActive": "Diagnostic",
"sDiagCode": "Diagnostic code",
"mHeatEnabled": "Heating enabled",
"mHeatBlocking": "Heating blocked",
"mHeatOverheat": "Heating overheat",
"mHeatFreezing": "Heating freezing",
"sHeatActive": "Heating active",
"mHeatSetpointTemp": "Heating setpoint temp",
"mHeatTargetTemp": "Heating target temp",
"mHeatCurrTemp": "Heating current temp",
"mHeatRetTemp": "Heating return temp",
"mHeatIndoorTemp": "Heating, indoor temp",
"mHeatOutdoorTemp": "Heating, outdoor temp",
"mDhwEnabled": "DHW enabled",
"mDhwOverheat": "DHW overheat",
"sDhwActive": "DHW active",
"mDhwTargetTemp": "DHW target temp",
"mDhwCurrTemp": "DHW current temp",
"mDhwRetTemp": "DHW return temp"
},
"sensors": {
"values": {
"temp": "Temperature",
"humidity": "Humidity",
"battery": "Battery",
"rssi": "RSSI"
}
}
},
"network": {
"title": "Network - OpenTherm Gateway",
"name": "Network settings",
"section": {
"static": "Static settings",
"availableNetworks": "Available networks",
"staSettings": "WiFi settings",
"apSettings": "AP settings"
},
"scan": {
"pos": "#",
"info": "Info"
},
"wifi": {
"ssid": "SSID",
"password": "Password",
"channel": "Channel",
"signal": "Signal",
"connected": "Connected"
},
"params": {
"hostname": "Hostname",
"dhcp": "Use DHCP",
"mac": "MAC",
"ip": "IP",
"subnet": "Subnet",
"gateway": "Gateway",
"dns": "DNS"
},
"sta": {
"channel": {
"note": "set 0 for auto select"
}
}
},
"sensors": {
"title": "Sensors settings - OpenTherm Gateway",
"name": "Sensors settings",
"enabled": "Enabled",
"sensorName": {
"title": "Sensor name",
"note": "May only contain: a-z, A-Z, 0-9, _ and space"
},
"purpose": "Purpose",
"purposes": {
"outdoorTemp": "Outdoor temperature",
"indoorTemp": "Indoor temperature",
"heatTemp": "Heating, temperature",
"heatRetTemp": "Heating, return temperature",
"dhwTemp": "DHW, temperature",
"dhwRetTemp": "DHW, return temperature",
"dhwFlowRate": "DHW, flow rate",
"exhaustTemp": "Exhaust temperature",
"modLevel": "Modulation level (in percents)",
"number": "Number (raw)",
"powerFactor": "Power (in percent)",
"power": "Power (in kWt)",
"fanSpeed": "Fan speed",
"co2": "CO2",
"pressure": "Pressure",
"humidity": "Humidity",
"temperature": "Temperature",
"notConfigured": "Not configured"
},
"type": "Type/source",
"types": {
"otOutdoorTemp": "OpenTherm, outdoor temp",
"otHeatTemp": "OpenTherm, heating, temp",
"otHeatRetTemp": "OpenTherm, heating, return temp",
"otDhwTemp": "OpenTherm, DHW, temperature",
"otDhwTemp2": "OpenTherm, DHW, temperature 2",
"otDhwFlowRate": "OpenTherm, DHW, flow rate",
"otCh2Temp": "OpenTherm, channel 2, temp",
"otExhaustTemp": "OpenTherm, exhaust temp",
"otHeatExchangerTemp": "OpenTherm, heat exchanger temp",
"otPressure": "OpenTherm, pressure",
"otModLevel": "OpenTherm, modulation level",
"otCurrentPower": "OpenTherm, current power",
"otExhaustCo2": "OpenTherm, exhaust CO2",
"otExhaustFanSpeed": "OpenTherm, exhaust fan speed",
"otSupplyFanSpeed": "OpenTherm, supply fan speed",
"otSolarStorageTemp": "OpenTherm, solar storage temp",
"otSolarCollectorTemp": "OpenTherm, solar collector temp",
"otFanSpeedSetpoint": "OpenTherm, setpoint fan speed",
"otFanSpeedCurrent": "OpenTherm, current fan speed",
"otBurnerStarts": "OpenTherm, number of burner starts",
"otDhwBurnerStarts": "OpenTherm, number of burner starts (DHW)",
"otHeatingPumpStarts": "OpenTherm, number of pump starts (heating)",
"otDhwPumpStarts": "OpenTherm, number of pump starts (DHW)",
"otBurnerHours": "OpenTherm, number of burner operating hours",
"otDhwBurnerHours": "OpenTherm, number of burner operating hours (DHW)",
"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"
},
"gpio": "GPIO",
"address": {
"title": "Sensor address",
"note": "For auto detection of DALLAS sensors leave it at default, for BLE devices need a MAC address"
},
"correction": {
"desc": "Correction of values",
"offset": "Compensation (offset)",
"factor": "Multiplier"
},
"filtering": {
"desc": "Filtering values",
"enabled": {
"title": "Enabled filtering",
"note": "It can be useful if there is a lot of sharp noise on the charts. The filter used is \"Running Average\"."
},
"factor": {
"title": "Filtration factor",
"note": "The lower the value, the smoother and <u>longer</u> the change in numeric values."
}
}
},
"settings": {
"title": "Settings - OpenTherm Gateway",
"name": "Settings",
"section": {
"portal": "Portal settings",
"system": "System settings",
"diag": "Diagnostic",
"heating": "Heating settings",
"dhw": "DHW settings",
"emergency": "Emergency mode settings",
"equitherm": "Equitherm settings",
"pid": "PID settings",
"ot": "OpenTherm settings",
"mqtt": "MQTT settings",
"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 <u>only</u> 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",
"desc": "<b>Note:</b> This feature can be useful if the built-in boiler overheating protection does not work or does not work correctly and the heat carrier boils. To disable, set 0 as <b>high</b> and <b>low</b> temperature.",
"highTemp": {
"title": "High temperature threshold",
"note": "Threshold at which the burner will be forcibly switched off"
},
"lowTemp": {
"title": "Low temperature threshold",
"note": "Threshold at which the burner can be turned on again"
}
},
"freezeProtection": {
"title": "Freeze protection",
"desc": "Heating will be forced to turn on if the heat carrier or indoor temperature drops below <b>Low temperature</b>.",
"highTemp": {
"title": "High temperature threshold",
"note": "Threshold when the system returns to normal mode after freeze protection activation"
},
"lowTemp": {
"title": "Low temperature threshold",
"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 <small>(celsius, liters, bar)</small>",
"imperial": "Imperial <small>(fahrenheit, gallons, psi)</small>",
"statusLedGpio": "Status LED GPIO",
"logLevel": "Log level",
"serial": {
"enable": "Enabled Serial port",
"baud": "Serial port baud rate"
},
"webSerial": {
"enable": "Enabled WebSerial"
},
"ntp": {
"server": "NTP server",
"timezone": "Timezone",
"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 <code>current indoor > target + value</code> and enable heating when <code>current indoor < (target - value)</code>.",
"value": "Value <small>(in degrees)</small>"
},
"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:<br />- if «Equitherm» is enabled and the outdoor temperature sensor is disconnected;<br />- if «PID» or OT option <i>«Native heating control»</i> is enabled and the indoor temperature sensor is disconnected.<br /><b>Note:</b> On network fault or MQTT fault, sensors with <i>«Manual via MQTT/API»</i> type will be in DISCONNECTED state.",
"target": {
"title": "Target temperature",
"note": "<b>Important:</b> <u>Target indoor temperature</u> if OT option <i>«Native heating control»</i> is enabled.<br />In all other cases, the <u>target heat carrier temperature</u>."
},
"thresholdTime": "Delay before entering or leaving emergency mode <small>(sec)</small>"
},
"equitherm": {
"slope": {
"title": "Slope",
"note": "Heat loss compensation. Main tuning parameter."
},
"exponent": {
"title": "Exponent",
"note": "Radiator efficiency. Typical values: <code>1.1</code> - Floor heating, <code>1.2</code> - Cast iron, <code>1.3</code> - Panel radiators, <code>1.4</code> - Convectors."
},
"shift": {
"title": "Shift",
"note": "Compensates for additional heat losses (e.g., in pipes) or extra heat sources."
},
"targetDiffFactor": {
"title": "T factor",
"note": "Not used if PID is enabled. Adds to the setpoint the difference between the target and current indoor temp: <code>setpoint = setpoint + ((target - indoor) * T)</code>."
},
"chart": {
"targetTemp": "Target indoor temperature",
"setpointTemp": "Heat carrier temperature",
"outdoorTemp": "Outdoor temperature"
}
},
"pid": {
"p": "P factor",
"i": "I factor",
"d": "D factor",
"dt": "DT <small>in seconds</small>",
"limits": {
"title": "Limits",
"note": "<b>Important:</b> When using «Equitherm» and «PID» at the same time, the min and max temperatures limit the influence on the «Equitherm» result temperature.<br />Thus, if the min temperature is set to -15 and the max temperature is set to 15, then the final heat carrier setpoint will be from <code>equitherm_result - 15</code> to <code>equitherm_result + 15</code>."
},
"deadband": {
"title": "Deadband",
"note": "Deadband is a range around the target temperature where PID regulation becomes less active. Within this range, the algorithm can reduce intensity or pause adjustments to avoid overreacting to small fluctuations.<br /><br />For instance, with a target temperature of 22°, a lower threshold of 1.0, and an upper threshold of 0.5, the deadband operates between 21° and 22.5°. If the I coefficient is 0.0005 and the I multiplier is 0.05, then within the deadband, the I coefficient becomes: <code>0.0005 * 0.05 = 0.000025</code>",
"p_multiplier": "Multiplier for P factor",
"i_multiplier": "Multiplier for I factor",
"d_multiplier": "Multiplier for D factor",
"thresholdHigh": "Threshold high",
"thresholdLow": "Threshold low"
}
},
"ot": {
"disablingAction": {
"title": "Circuit disabling action",
"desc": "The selected action applies whenever the circuit is disabled, including overheating.<br />Some boilers stop the circulation pump when the circuit is disabled. In this case, you can try setting the target temperature to <b>0</b> 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 <b>0</b>",
"offAndZeroSetpoint": "Disable circuit and set the target temperature to <b>0</b>"
},
"advanced": "Advanced Settings",
"inGpio": "In GPIO",
"outGpio": "Out GPIO",
"ledGpio": "RX LED GPIO",
"memberId": "Master member ID",
"flags": "Master flags",
"minPower": {
"title": "Min boiler power <small>(kW)</small>",
"note": "This value is at 0-1% boiler modulation level. Typically found in the boiler specification as \"minimum useful heat output\"."
},
"maxPower": {
"title": "Max boiler power <small>(kW)</small>",
"note": "<b>0</b> - 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.<br /><b>Note:</b> There is no need to change anything if everything works well.",
"dhwSupport": "DHW support",
"coolingSupport": "Cooling support",
"summerWinterMode": "Summer/winter mode",
"heatingStateToSummerWinterMode": "Heating state as summer/winter mode",
"ch2AlwaysEnabled": "CH2 always enabled",
"heatingToCh2": "Duplicate heating to CH2",
"dhwToCh2": "Duplicate DHW to CH2",
"dhwBlocking": "DHW blocking",
"dhwStateAsDhwBlocking": "DHW state as DHW blocking",
"maxTempSyncWithTargetTemp": "Sync max heating temp with target temp",
"getMinMaxTemp": "Get min/max temp from boiler",
"ignoreDiagState": "Ignore diag state",
"autoFaultReset": "Auto fault reset <small>(not recommended!)</small>",
"autoDiagReset": "Auto diag reset <small>(not recommended!)</small>",
"setDateAndTime": "Set date & time on boiler",
"immergasFix": "Fix for Immergas boilers",
"alwaysSendIndoorTemp": "Send current indoor temp to boiler"
},
"nativeOTC": {
"title": "Native OTC mode",
"note": "Works <u>ONLY</u> 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",
"server": "Server",
"port": "Port",
"user": "User",
"password": "Password",
"prefix": "Prefix",
"interval": "Publish interval <small>(sec)</small>"
},
"extPump": {
"use": "Use external pump",
"gpio": "Relay GPIO",
"invertState": "Invert GPIO state",
"postCirculationTime": "Post circulation time <small>(min)</small>",
"antiStuckInterval": "Anti stuck interval <small>(days)</small>",
"antiStuckTime": "Anti stuck time <small>(min)</small>"
},
"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 <small>(sec)</small>"
},
"output": {
"desc": "Can be used to switch on another boiler <u>via relay</u>.",
"enable": "Enabled output",
"gpio": "GPIO",
"invertState": "Invert GPIO state",
"thresholdTime": "State change threshold time <small>(sec)</small>",
"events": {
"desc": "Events",
"onFault": "If the fault state is active",
"onLossConnection": "If the connection via Opentherm is lost",
"onEnabledHeating": "If heating is enabled"
}
}
}
},
"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": {
"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.<br />Latest releases can be downloaded from the <a href=\"https://github.com/Laxilef/OTGateway/releases\" target=\"_blank\">Releases page</a> 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"
}
}
}
-556
View File
@@ -1,556 +0,0 @@
{
"values": {
"logo": "OpenTherm Gateway",
"nav": {
"license": "Licenza",
"source": "Codice",
"help": "Aiuto",
"issues": "Problemi e domande",
"releases": "Versione"
},
"units": {
"days": "d.",
"hours": "h.",
"min": "min.",
"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",
"save": "Salva",
"saved": "Salvato",
"refresh": "Ricarica",
"restore": "Recupera",
"restored": "Recuperato",
"backup": "Backup",
"wait": "Attendi...",
"uploading": "caricamento...",
"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": {
"heap": "Memoria (heap)",
"psram": "Memoria (PSRAM)",
"maxFreeBlock": "max free block",
"min": "min"
},
"board": "Scheda",
"chip": {
"model": "Chip",
"cores": "Cores",
"freq": "frequenza"
},
"flash": {
"size": "Dimensioni del flash"
},
"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",
"currentTemp": "Attuale",
"enable": "Attiva",
"turbo": "Turbo"
},
"notify": {
"fault": {
"title": "Rilevamento guasti caldiaia attivo!",
"note": "Si consiglia di ispezionare la caldaia e studiare la documentazione per interpretare il codice di errore:"
},
"diag": {
"title": "Stato diagnostica Caldaia attivo!",
"note": "Forse la tua caldaia ha bisogno di un'ispezione? Si consiglia di studiare la documentazione per interpretare il codice diagnostico:"
},
"reset": "Prova a resettare"
},
"states": {
"mNetworkConnected": "Connessione Rete",
"mMqttConnected": "Connessione MQTT",
"mEmergencyState": "Modo Emergenza",
"mExtPumpState": "Pompa esterna",
"mCascadeControlInput": "Controllo a cascata (input)",
"mCascadeControlOutput": "Controllo a cascata (output)",
"sConnected": "Connessione OpenTherm",
"sFlame": "Fiamma",
"sCoolingActive": "Raffrescamento",
"sCoolingSetpoint": "Raffrescamento setpoint",
"sFaultActive": "Anomalia",
"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",
"mHeatCurrTemp": "Temp attuale riscaldamento",
"mHeatRetTemp": "Temp ritorno riscaldamento",
"mHeatIndoorTemp": "Riscaldamento, temp interna",
"mHeatOutdoorTemp": "Riscaldamento, temp esterna",
"mDhwEnabled": "ACS attivata",
"mDhwOverheat": "ACS surriscaldamento",
"sDhwActive": "ACS attiva",
"mDhwTargetTemp": "ACS temp impostata",
"mDhwCurrTemp": "ACS temp attuale",
"mDhwRetTemp": "ACS temp ricircolo"
},
"sensors": {
"values": {
"temp": "Temperatura",
"humidity": "Umidità",
"battery": "Batteria",
"rssi": "RSSI"
}
}
},
"network": {
"title": "Rete - OpenTherm Gateway",
"name": "Impostazioni rete",
"section": {
"static": "Impostazioni statico",
"availableNetworks": "Reti disponibili",
"staSettings": "Impostazioni WiFi",
"apSettings": "Impostazioni AP"
},
"scan": {
"pos": "#",
"info": "Info"
},
"wifi": {
"ssid": "SSID",
"password": "Password",
"channel": "Canale",
"signal": "Segnale",
"connected": "Connesso"
},
"params": {
"hostname": "Hostname",
"dhcp": "Usa DHCP",
"mac": "MAC",
"ip": "IP",
"subnet": "Subnet",
"gateway": "Gateway",
"dns": "DNS"
},
"sta": {
"channel": {
"note": "Metti 0 per auto selezione"
}
}
},
"sensors": {
"title": "Impostazione sensori - OpenTherm Gateway",
"name": "Impostazione sensori",
"enabled": "Attivato",
"sensorName": {
"title": "Nome sensore",
"note": "Può contenere solo: a-z, A-Z, 0-9, _ e spazi"
},
"purpose": "Funzione",
"purposes": {
"outdoorTemp": "Temperatura esterna",
"indoorTemp": "Temperatura interna",
"heatTemp": "Riscaldamento, temperatura mandata",
"heatRetTemp": "Riscaldamento, temperatura ritorno",
"dhwTemp": "ACS, temperatura",
"dhwRetTemp": "ACS, temperatura ritorno",
"dhwFlowRate": "ACS, prelievo",
"exhaustTemp": "Temperatura fumi",
"modLevel": "Livello Modulazione (%)",
"number": "Numero (raw)",
"powerFactor": "Potenza (%)",
"power": "Potenza (in kW)",
"fanSpeed": "Velocità ventilatore",
"co2": "CO2",
"pressure": "Pressione",
"humidity": "Umidità",
"temperature": "Temperatura",
"notConfigured": "Non configurato"
},
"type": "Tipo/sorgente",
"types": {
"otOutdoorTemp": "OpenTherm, temp esterna",
"otHeatTemp": "OpenTherm, riscaldamento, temp",
"otHeatRetTemp": "OpenTherm, riscaldamento, temp ritorno",
"otDhwTemp": "OpenTherm, ACS, temperatura",
"otDhwTemp2": "OpenTherm, ACS, temperatura 2",
"otDhwFlowRate": "OpenTherm, ACS, prelievo",
"otCh2Temp": "OpenTherm, canale 2, temp",
"otExhaustTemp": "OpenTherm, temp fumi",
"otHeatExchangerTemp": "OpenTherm, temp scambiatore",
"otPressure": "OpenTherm, pressione",
"otModLevel": "OpenTherm, livello modulazione",
"otCurrentPower": "OpenTherm, potenza attuale",
"otExhaustCo2": "OpenTherm, CO2 fumi",
"otExhaustFanSpeed": "OpenTherm, velocità ventola fumi",
"otSupplyFanSpeed": "OpenTherm, velocità ventola supporto",
"otSolarStorageTemp": "OpenTherm, temp accumulo solare",
"otSolarCollectorTemp": "OpenTherm, temp collettore solare",
"otFanSpeedSetpoint": "OpenTherm, velocità ventola impostata",
"otFanSpeedCurrent": "OpenTherm, velocità ventola attuale",
"otBurnerStarts": "OpenTherm, numero di avviamenti del bruciatore",
"otDhwBurnerStarts": "OpenTherm, numero di avviamenti del bruciatore (ACS)",
"otHeatingPumpStarts": "OpenTherm, numero di avviamenti della pompa (riscaldamento)",
"otDhwPumpStarts": "OpenTherm, numero di avviamenti della pompa (ACS)",
"otBurnerHours": "OpenTherm, numero di ore di funzionamento del bruciatore",
"otDhwBurnerHours": "OpenTherm, numero di ore di funzionamento del bruciatore (ACS)",
"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"
},
"gpio": "GPIO",
"address": {
"title": "Indirizzo sensore",
"note": "Per l'autoriconoscimento del sensore DALLAS lasciare quello di default, per sensore BLE richiede indirizzo MAC"
},
"correction": {
"desc": "Correzione del valore",
"offset": "Compensazione (offset)",
"factor": "Moltiplicatore"
},
"filtering": {
"desc": "Filtraggio valore",
"enabled": {
"title": "Filtraggio attivo",
"note": "Può servire in caso vi siano molti sbalzi nel grafico. Il filtro usato è \"Running Average\"."
},
"factor": {
"title": "Fattore di filtrazione",
"note": "Quanto più basso è il valore, tanto più graduale e prolungata sarà la variazione dei valori numerici."
}
}
},
"settings": {
"title": "Impostazioni - OpenTherm Gateway",
"name": "Impostazioni",
"section": {
"portal": "Impostazioni Accesso",
"system": "Impostazioni sistema",
"diag": "Diagnostica",
"heating": "Impostazioni riscaldamento",
"dhw": "Impostazioni ACS",
"emergency": "Impostazioni modo Emergenza",
"equitherm": "Impostazioni Equitherm",
"pid": "Impostazioni PID",
"ot": "Impostazioni OpenTherm",
"mqtt": "Impostazioni MQTT",
"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 <u>solo</u> 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",
"desc": "<b>Nota:</b> questa funzione può essere utile se la protezione contro il surriscaldamento integrata nella caldaia non funziona o non funziona correttamente e il fluido termovettore bolle. Per disattivarla, impostare 0 come temperatura <b>alta</b> e <b>bassa</b>.",
"highTemp": {
"title": "Soglia di temperatura alta",
"note": "Soglia alla quale il bruciatore verrà spento forzatamente"
},
"lowTemp": {
"title": "Soglia di temperatura bassa",
"note": "Soglia alla quale il bruciatore può essere riacceso"
}
},
"freezeProtection": {
"title": "Protezione antigelo",
"desc": "Il riscaldamento verrà forzatamente attivato se la temperatura del vettore termico o la temperatura interna scende al di sotto della <b>Soglia di temperatura bassa</b>.",
"highTemp": {
"title": "Soglia di temperatura alta",
"note": "Soglia quando il sistema ritorna alla modalità normale dopo l'attivazione della protezione antigelo"
},
"lowTemp": {
"title": "Soglia di temperatura bassa",
"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 <small>(celsius, litri, bar)</small>",
"imperial": "Imperiale <small>(fahrenheit, galloni, psi)</small>",
"statusLedGpio": "LED di stato GPIO",
"logLevel": "Log livello",
"serial": {
"enable": "Porta seriale attivata",
"baud": "Porta seriale baud rate"
},
"webSerial": {
"enable": "WebSerial attivato"
},
"ntp": {
"server": "NTP server",
"timezone": "Zona oraria",
"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 <code>current indoor > target + value</code> e abilita il riscaldamento quando <code>current indoor < (target - value)</code>.",
"value": "Valore <small>(in gradi)</small>"
},
"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:<br />- se «Equitherm» è attivato e il sensore della temperatura esternare è disconnesso;<br />- se «PID» o l'opzione OT <i>«Impostazioni riscaldamento native»</i> è attiva e il sensore di temperatura interno è disconnesso.<br /><b>Nota:</b> In mancanza di rete o MQTT, sensore di tipo <i>«Manuale via MQTT/API»</i> è in stato Disconnesso.",
"target": {
"title": "Temperatura impostata",
"note": "<b>Importante:</b> <u>Temperatura interna impostata</u> se l'opzione OT <i>«Controllo riscaldamento interno»</i> è attivato.<br />In tutti gli altri casi, la <u>target heat carrier temperature</u>."
},
"thresholdTime": "Ritardo di entrata e uscita dalla modalità di emergenza <small>(sec)</small>"
},
"equitherm": {
"slope": {
"title": "Pendenza",
"note": "Compensazione della perdita di calore. Parametro di regolazione principale."
},
"exponent": {
"title": "Esponente",
"note": "Efficienza del radiatore. Valori tipici: <code>1.1</code> - Riscaldamento a pavimento, <code>1.2</code> - Ghisa, <code>1.3</code> - Radiatori a pannello, <code>1.4</code> - Convettori."
},
"shift": {
"title": "Spostamento",
"note": "Compensa perdite di calore aggiuntive (ad es., nelle tubature) o fonti di calore extra."
},
"targetDiffFactor": {
"title": "Fattore T",
"note": "Non utilizzato se PID è abilitato. Aggiunge al setpoint la differenza tra la temperatura target e quella interna attuale: <code>setpoint = setpoint + ((target - indoor) * T)</code>."
},
"chart": {
"targetTemp": "Temperatura interna target",
"setpointTemp": "Temperatura del vettore termico",
"outdoorTemp": "Temperatura esterna"
}
},
"pid": {
"p": "Fattore P",
"i": "Fattore I",
"d": "Fattore D",
"dt": "DT <small>in secondi</small>",
"limits": {
"title": "Limiti",
"note": "<b>Importante:</b> Quando usi «Equitherm» e «PID» allo stesso tempo, i limiti della temperatura min e max influenzano il risultato della temperatura «Equitherm».<br />Thus, se la temperatura minima è impostata a -15 e la massima a 15, il riscaldamento finale sarà impostato fra <code>equitherm_result - 15</code> a <code>equitherm_result + 15</code>."
},
"deadband": {
"title": "Zona morta (Deadband)",
"note": "La zona morta è un intervallo intorno alla temperatura target in cui la regolazione PID diventa meno attiva. In questo intervallo, l'algoritmo può ridurre l'intensità o interrompere gli aggiustamenti per evitare di reagire eccessivamente a piccole fluttuazioni.<br /><br />Ad esempio, con una temperatura target di 22°, una soglia inferiore di 1.0 e una soglia superiore di 0.5, la zona morta opera tra 21° e 22.5°. Se il coefficiente I è 0.0005 e il moltiplicatore I è 0.05, allora nella zona morta, il coefficiente I diventa: <code>0.0005 * 0.05 = 0.000025</code>",
"p_multiplier": "Moltiplicatore P",
"i_multiplier": "Moltiplicatore I",
"d_multiplier": "Moltiplicatore D",
"thresholdHigh": "Soglia superiore",
"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.<br />Alcune caldaie arrestano la pompa di circolazione quando il circuito viene disattivato; in questo caso si può provare a impostare la temperatura desiderata a <b>0</b>, 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 <b>0</b>",
"offAndZeroSetpoint": "Disattiva il circuito e imposta la temperatura desiderata a <b>0</b>"
},
"advanced": "Impostazioni avanzate",
"inGpio": "In GPIO",
"outGpio": "Out GPIO",
"ledGpio": "RX LED GPIO",
"memberId": "Master member ID",
"flags": "Master flags",
"minPower": {
"title": "Potenza minima caldaia <small>(kW)</small>",
"note": "Questo valore corrisponde allo livello 0-1% di modulazione della caldaia. Di solito si trova nelle specifiche delle caldaia come \"potenza minima disponibile\"."
},
"maxPower": {
"title": "Potenza massima caldaia <small>(kW)</small>",
"note": "<b>0</b> - 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.<br /><b>Nota:</b> Non è necessario modificare nulla se tutto funziona correttamente.",
"dhwSupport": "Supporto ACS",
"coolingSupport": "Supporto rafferscamento",
"summerWinterMode": "Modalità Estate/inverno",
"heatingStateToSummerWinterMode": "Stato di riscaldamento come modalità estate/inverno",
"ch2AlwaysEnabled": "CH2 sempre abilitato",
"heatingToCh2": "Riproduci riscaldamento su CH2",
"dhwToCh2": "Riproduci ACS su CH2",
"dhwBlocking": "Bloccare ACS",
"dhwStateAsDhwBlocking": "Stato ACS come bloccare ACS",
"maxTempSyncWithTargetTemp": "Sincronizza la temperatura massima di riscaldamento con la temperatura target",
"getMinMaxTemp": "Prendi temp min/max dalla caldaia",
"ignoreDiagState": "Ignora lo stato diagnostico",
"autoFaultReset": "Ripristino automatico degli errori <small>(sconsigliato!)</small>",
"autoDiagReset": "Ripristino diagnostico automatica <small>(sconsigliato!)</small>",
"setDateAndTime": "Imposta data e ora sulla caldaia",
"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 <u>SOLO</u> 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",
"server": "Server",
"port": "Porta",
"user": "Utente",
"password": "Password",
"prefix": "Prefisso",
"interval": "Intervallo invio <small>(sec)</small>"
},
"extPump": {
"use": "Usa pompa/circolatore esterno",
"gpio": "GPIO relè",
"invertState": "Inverti stato GPIO",
"postCirculationTime": "Tempo di post circolazione <small>(min)</small>",
"antiStuckInterval": "Intervallo antiblocco <small>(days)</small>",
"antiStuckTime": "Tempo antiblocco <small>(min)</small>"
},
"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 <small>(sec)</small>"
},
"output": {
"desc": "Può essere usato per passare ad un'altra caldaia tramite <u>relè</u>.",
"enable": "Uscita abilitata",
"gpio": "GPIO",
"invertState": "Invert GPIO state",
"thresholdTime": "Tempo soglia di modifica dello stato <small>(sec)</small>",
"events": {
"desc": "Eventi",
"onFault": "Se lo stato di errore è attivo",
"onLossConnection": "Se non c'è la connessione via Opentherm",
"onEnabledHeating": "Se il riscaldamento è attivato"
}
}
}
},
"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": {
"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.<br />L'ultimo aggiornamento può essere scaricato da <a href=\"https://github.com/Laxilef/OTGateway/releases\" target=\"_blank\">Releases page</a> 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"
}
}
}
-556
View File
@@ -1,556 +0,0 @@
{
"values": {
"logo": "OpenTherm Gateway",
"nav": {
"license": "Licentie",
"source": "Broncode",
"help": "Help",
"issues": "Problemen & vragen",
"releases": "Releases"
},
"units": {
"days": "d.",
"hours": "u.",
"min": "min.",
"sec": "sec.",
"dbm": "dBm",
"mhz": "MHz",
"kw": "kW",
"rpm": "RPM",
"ppm": "ppm",
"byte": "byte",
"mbyte": "MB",
"liter": "L",
"gallon": "gal"
},
"button": {
"upgrade": "Upgraden",
"restart": "Herstarten",
"save": "Opslaan",
"saved": "Opgeslagen",
"refresh": "Vernieuwen",
"restore": "Herstellen",
"restored": "Hersteld",
"backup": "Back-up",
"wait": "Even wachten...",
"uploading": "Uploaden...",
"success": "Succes",
"error": "Fout"
},
"index": {
"title": "OpenTherm Gateway",
"section": {
"network": "Netwerk",
"system": "Systeem"
},
"system": {
"build": {
"title": "Build",
"version": "Versie",
"commit": "Commit",
"date": "Datum",
"core": "Core",
"sdk": "SDK"
},
"uptime": "Uptime",
"memory": {
"heap": "Geheugen (heap)",
"psram": "Geheugen (PSRAM)",
"maxFreeBlock": "max. vrij blok",
"min": "min"
},
"board": "Board",
"chip": {
"model": "Chip",
"cores": "Kernen",
"freq": "frequentie"
},
"flash": {
"size": "Flash-grootte"
},
"lastResetReason": "Reden laatste herstart",
"coreDump": "Geheugendump"
}
},
"dashboard": {
"name": "Dashboard",
"title": "Dashboard - OpenTherm Gateway",
"section": {
"control": "Bediening",
"states": "Statussen",
"sensors": "Sensoren",
"diag": "OpenTherm diagnose"
},
"thermostat": {
"heating": "Verwarming",
"dhw": "Warm water",
"currentTemp": "Huidig",
"enable": "Inschakelen",
"turbo": "Turbomodus"
},
"notify": {
"fault": {
"title": "Ketelstoring is actief!",
"note": "Het wordt aanbevolen de ketel te inspecteren en de documentatie te raadplegen om de storingscode te interpreteren:"
},
"diag": {
"title": "Keteldiagnose is actief!",
"note": "Heeft uw ketel misschien een inspectie nodig? Het wordt aanbevolen de documentatie te raadplegen om de diagnosecode te interpreteren:"
},
"reset": "Probeer te resetten"
},
"states": {
"mNetworkConnected": "Netwerkverbinding",
"mMqttConnected": "MQTT-verbinding",
"mEmergencyState": "Noodmodus",
"mExtPumpState": "Externe pomp",
"mCascadeControlInput": "Cascaderegeling (ingang)",
"mCascadeControlOutput": "Cascaderegeling (uitgang)",
"sConnected": "OpenTherm-verbinding",
"sFlame": "Vlam",
"sCoolingActive": "Koeling",
"sCoolingSetpoint": "Koelinstelpunt",
"sFaultActive": "Storing",
"sFaultCode": "Storingscode",
"sDiagActive": "Diagnose",
"sDiagCode": "Diagnosecode",
"mHeatEnabled": "Verwarming ingeschakeld",
"mHeatBlocking": "Verwarming geblokkeerd",
"mHeatOverheat": "Verwarming oververhit",
"mHeatFreezing": "Verwarming vorstbescherming",
"sHeatActive": "Verwarming actief",
"mHeatSetpointTemp": "Insteltemperatuur verwarming",
"mHeatTargetTemp": "Doeltemperatuur verwarming",
"mHeatCurrTemp": "Huidige temperatuur verwarming",
"mHeatRetTemp": "Retourtemperatuur verwarming",
"mHeatIndoorTemp": "Verwarming, binnentemperatuur",
"mHeatOutdoorTemp": "Verwarming, buitentemperatuur",
"mDhwEnabled": "Warm water ingeschakeld",
"mDhwOverheat": "Warm water oververhit",
"sDhwActive": "Warm water actief",
"mDhwTargetTemp": "Doeltemperatuur warm water",
"mDhwCurrTemp": "Huidige temperatuur warm water",
"mDhwRetTemp": "Retourtemperatuur warm water"
},
"sensors": {
"values": {
"temp": "Temperatuur",
"humidity": "Luchtvochtigheid",
"battery": "Batterij",
"rssi": "RSSI"
}
}
},
"network": {
"title": "Netwerk - OpenTherm Gateway",
"name": "Netwerkinstellingen",
"section": {
"static": "Statische instellingen",
"availableNetworks": "Beschikbare netwerken",
"staSettings": "WiFi-instellingen",
"apSettings": "AP-instellingen"
},
"scan": {
"pos": "#",
"info": "Info"
},
"wifi": {
"ssid": "SSID",
"password": "Wachtwoord",
"channel": "Kanaal",
"signal": "Signaal",
"connected": "Verbonden"
},
"params": {
"hostname": "Hostnaam",
"dhcp": "Gebruik DHCP",
"mac": "MAC",
"ip": "IP",
"subnet": "Subnet",
"gateway": "Gateway",
"dns": "DNS"
},
"sta": {
"channel": {
"note": "zet op 0 voor automatische selectie"
}
}
},
"sensors": {
"title": "Sensorinstellingen - OpenTherm Gateway",
"name": "Sensorinstellingen",
"enabled": "Ingeschakeld",
"sensorName": {
"title": "Sensornaam",
"note": "Mag alleen bevatten: a-z, A-Z, 0-9, _ en spatie"
},
"purpose": "Doel",
"purposes": {
"outdoorTemp": "Buitentemperatuur",
"indoorTemp": "Binnentemperatuur",
"heatTemp": "Verwarming, temperatuur",
"heatRetTemp": "Verwarming, retourtemperatuur",
"dhwTemp": "Warm water, temperatuur",
"dhwRetTemp": "Warm water, retourtemperatuur",
"dhwFlowRate": "Warm water, doorstroomsnelheid",
"exhaustTemp": "Rookgastemperatuur",
"modLevel": "Modulatieniveau (in procenten)",
"number": "Getal (ruw)",
"powerFactor": "Vermogen (in procent)",
"power": "Vermogen (in kWt)",
"fanSpeed": "Ventilatorsnelheid",
"co2": "CO2",
"pressure": "Druk",
"humidity": "Luchtvochtigheid",
"temperature": "Temperatuur",
"notConfigured": "Niet geconfigureerd"
},
"type": "Type/bron",
"types": {
"otOutdoorTemp": "OpenTherm, buitentemp.",
"otHeatTemp": "OpenTherm, verwarming, temp.",
"otHeatRetTemp": "OpenTherm, verwarming, retourtemp.",
"otDhwTemp": "OpenTherm, warm water, temperatuur",
"otDhwTemp2": "OpenTherm, warm water, temperatuur 2",
"otDhwFlowRate": "OpenTherm, warm water, doorstroomsnelheid",
"otCh2Temp": "OpenTherm, kanaal 2, temp.",
"otExhaustTemp": "OpenTherm, rookgastemp.",
"otHeatExchangerTemp": "OpenTherm, warmtewisselaar temp.",
"otPressure": "OpenTherm, druk",
"otModLevel": "OpenTherm, modulatieniveau",
"otCurrentPower": "OpenTherm, huidig vermogen",
"otExhaustCo2": "OpenTherm, rookgas CO2",
"otExhaustFanSpeed": "OpenTherm, rookgasventilator snelheid",
"otSupplyFanSpeed": "OpenTherm, toevoerventilator snelheid",
"otSolarStorageTemp": "OpenTherm, zonneboiler opslagtemp.",
"otSolarCollectorTemp": "OpenTherm, zonnecollector temp.",
"otFanSpeedSetpoint": "OpenTherm, instelpunt ventilatorsnelheid",
"otFanSpeedCurrent": "OpenTherm, huidige ventilatorsnelheid",
"otBurnerStarts": "OpenTherm, aantal branderstarts",
"otDhwBurnerStarts": "OpenTherm, aantal branderstarts (warm water)",
"otHeatingPumpStarts": "OpenTherm, aantal pompstarts (verwarming)",
"otDhwPumpStarts": "OpenTherm, aantal pompstarts (warm water)",
"otBurnerHours": "OpenTherm, aantal branderuren",
"otDhwBurnerHours": "OpenTherm, aantal branderuren (warm water)",
"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"
},
"gpio": "GPIO",
"address": {
"title": "Sensoradres",
"note": "Laat leeg voor automatische detectie van DALLAS-sensoren. Voor BLE-apparaten is een MAC-adres vereist."
},
"correction": {
"desc": "Correctie van waarden",
"offset": "Compensatie (offset)",
"factor": "Vermenigvuldiger"
},
"filtering": {
"desc": "Filteren van waarden",
"enabled": {
"title": "Filteren ingeschakeld",
"note": "Kan handig zijn bij veel scherpe ruis in de grafieken. Het gebruikte filter is \"Voortschrijdend gemiddelde\"."
},
"factor": {
"title": "Filterfactor",
"note": "Hoe lager de waarde, hoe vloeiender en <u>langer</u> de verandering in numerieke waarden."
}
}
},
"settings": {
"title": "Instellingen - OpenTherm Gateway",
"name": "Instellingen",
"section": {
"portal": "Portaalinstellingen",
"system": "Systeeminstellingen",
"diag": "Diagnose",
"heating": "Verwarmingsinstellingen",
"dhw": "Warmwaterinstellingen",
"emergency": "Instellingen noodmodus",
"equitherm": "Equitherm-instellingen",
"pid": "PID-instellingen",
"ot": "OpenTherm-instellingen",
"mqtt": "MQTT-instellingen",
"extPump": "Instellingen externe pomp",
"cascadeControl": "Instellingen cascaderegeling"
},
"enable": "Inschakelen",
"note": {
"restart": "Na het wijzigen van deze instellingen moet het apparaat opnieuw worden opgestart om de wijzigingen door te voeren.",
"blankNotUse": "leeg - niet gebruiken",
"bleDevice": "BLE-apparaat kan <u>alleen</u> worden gebruikt met sommige ESP32-boards met BLE-ondersteuning!"
},
"temp": {
"min": "Minimumtemperatuur",
"max": "Maximumtemperatuur"
},
"avgType": {
"mean": "Gemiddelde temperatuur",
"min": "Minimum temperatuur",
"max": "Maximum temperatuur"
},
"maxModulation": "Max. modulatieniveau",
"ohProtection": {
"title": "Oververhittingsbeveiliging",
"desc": "<b>Let op:</b> Deze functie kan handig zijn als de ingebouwde oververhittingsbeveiliging van de ketel niet of niet correct werkt en de warmtedrager kookt. Om uit te schakelen, stel 0 in als <b>hoge</b> en <b>lage</b> temperatuur.",
"highTemp": {
"title": "Drempelwaarde hoge temperatuur",
"note": "Drempelwaarde waarbij de brander geforceerd wordt uitgeschakeld"
},
"lowTemp": {
"title": "Drempelwaarde lage temperatuur",
"note": "Drempelwaarde waarbij de brander weer ingeschakeld kan worden"
}
},
"freezeProtection": {
"title": "Vorbeveiliging",
"desc": "Verwarming zal geforceerd worden ingeschakeld als de temperatuur van de warmtedrager of de binnentemperatuur daalt onder de <b>Lage temperatuurdrempel</b>.",
"highTemp": {
"title": "Hoge temperatuurdrempel",
"note": "Drempel waarna het systeem terugkeert naar de normale modus na activering van de vorbeveiliging"
},
"lowTemp": {
"title": "Lage temperatuurdrempel",
"note": "Drempel wanneer de verwarming geforceerd wordt ingeschakeld"
}
},
"portal": {
"login": "Gebruikersnaam",
"password": "Wachtwoord",
"auth": "Authenticatie vereisen",
"mdns": "Gebruik mDNS"
},
"system": {
"unit": "Eenheidssysteem",
"metric": "Metrisch <small>(celsius, liters, bar)</small>",
"imperial": "Imperiaal <small>(fahrenheit, gallons, psi)</small>",
"statusLedGpio": "Status LED GPIO",
"logLevel": "Logniveau",
"serial": {
"enable": "Seriële poort ingeschakeld",
"baud": "Baudrate seriële poort"
},
"webSerial": {
"enable": "WebSerial ingeschakeld"
},
"ntp": {
"server": "NTP-server",
"timezone": "Tijdzone",
"timezonePresets": "Selecteer voorinstelling..."
}
},
"heating": {
"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 <code>current indoor > target + value</code> en inschakelen van verwarming wanneer <code>current indoor < (target - value)</code>.",
"value": "Waarde <small>(in graden)</small>"
},
"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:<br />- als «Equitherm» is ingeschakeld en de buitentemperatuursensor is losgekoppeld;<br />- als «PID» of OT-optie <i>«Natuurlijke verwarmingsregeling»</i> is ingeschakeld en de binnentemperatuursensor is losgekoppeld.<br /><b>Let op:</b> Bij een netwerk- of MQTT-storing krijgen sensoren van het type <i>«Handmatig via MQTT/API»</i> de status ONVERBONDEN.",
"target": {
"title": "Doeltemperatuur",
"note": "<b>Belangrijk:</b> <u>Doel binnentemperatuur</u> als OT-optie <i>«Natuurlijke verwarmingsregeling»</i> is ingeschakeld.<br />In alle andere gevallen, de <u>doel warmtedragertemperatuur</u>."
},
"thresholdTime": "Vertraging bij in- en uitschakelen van de noodmodus <small>(sec)</small>"
},
"equitherm": {
"slope": {
"title": "Helling",
"note": "Compensatie voor warmteverlies. Hoofdafstelparameter."
},
"exponent": {
"title": "Exponent",
"note": "Radiator efficiëntie. Typische waarden: <code>1.1</code> - Vloerverwarming, <code>1.2</code> - Gietijzer, <code>1.3</code> - Paneelradiatoren, <code>1.4</code> - Convectors."
},
"shift": {
"title": "Verschuiving",
"note": "Compenseert voor extra warmteverliezen (bijv. in leidingen) of extra warmtebronnen."
},
"targetDiffFactor": {
"title": "T factor",
"note": "Niet gebruikt als PID is ingeschakeld. Voegt aan de setpoint de verschil tussen de target en huidige binnentemperatuur toe: <code>setpoint = setpoint + ((target - indoor) * T)</code>."
},
"chart": {
"targetTemp": "Doel binnentemperatuur",
"setpointTemp": "Warmtedrager temperatuur",
"outdoorTemp": "Buitentemperatuur"
}
},
"pid": {
"p": "P-factor",
"i": "I-factor",
"d": "D-factor",
"dt": "DT <small>in seconden</small>",
"limits": {
"title": "Limieten",
"note": "<b>Belangrijk:</b> Bij gelijktijdig gebruik van «Equitherm» en «PID» beperken de min- en maxtemperaturen de invloed op de resulterende «Equitherm»-temperatuur.<br />Dus, als de min-temperatuur is ingesteld op -15 en de max-temperatuur op 15, zal het uiteindelijke instelpunt van de warmtedrager liggen tussen <code>equitherm_resultaat - 15</code> en <code>equitherm_resultaat + 15</code>."
},
"deadband": {
"title": "Deadband",
"note": "Deadband is een bereik rond de doeltemperatuur waarbinnen de PID-regeling minder actief wordt. Binnen dit bereik kan het algoritme de intensiteit verminderen of aanpassingen pauzeren om overreactie op kleine schommelingen te voorkomen.<br /><br />Bijvoorbeeld, met een doeltemperatuur van 22°, een onderdrempel van 1.0 en een bovendrempel van 0.5, werkt de deadband tussen 21° en 22.5°. Als de I-coëfficiënt 0.0005 is en de I-vermenigvuldiger 0.05, dan wordt de I-coëfficiënt binnen de deadband: <code>0.0005 * 0.05 = 0.000025</code>",
"p_multiplier": "Vermenigvuldiger voor P-factor",
"i_multiplier": "Vermenigvuldiger voor I-factor",
"d_multiplier": "Vermenigvuldiger voor D-factor",
"thresholdHigh": "Bovendrempel",
"thresholdLow": "Onderdrempel"
}
},
"ot": {
"disablingAction": {
"title": "Actie bij uitschakelen van circuits",
"desc": "De gekozen actie geldt bij elke uitschakeling van het circuit, ook bij oververhitting.<br />Sommige ketels schakelen de circulatiepomp uit wanneer het circuit wordt uitgeschakeld. In dat geval kunt u proberen de doeltemperatuur op <b>0</b> in te stellen, zodat de pompnaloop correct werkt.",
"heating": "Verwarmingscircuit",
"dhw": "Warmtapwatercircuit",
"ch2": "Circuit 2",
"off": "Alleen het circuit uitschakelen",
"zeroSetpoint": "Doeltemperatuur op <b>0</b> instellen",
"offAndZeroSetpoint": "Circuit uitschakelen en doeltemperatuur op <b>0</b> instellen"
},
"advanced": "Geavanceerde instellingen",
"inGpio": "In GPIO",
"outGpio": "Uit GPIO",
"ledGpio": "RX LED GPIO",
"memberId": "Master member ID",
"flags": "Master flags",
"minPower": {
"title": "Min. ketelvermogen <small>(kW)</small>",
"note": "Deze waarde is bij 0-1% modulatieniveau van de ketel. Typisch te vinden in de ketelspecificatie als \"minimum nuttig warmtevermogen\"."
},
"maxPower": {
"title": "Max. ketelvermogen <small>(kW)</small>",
"note": "<b>0</b> - probeer automatisch te detecteren. Typisch te vinden in de ketelspecificatie als \"maximum nuttig warmtevermogen\"."
},
"options": {
"title": "Opties (aanvullende instellingen)",
"desc": "Opties kunnen de logica van de ketel veranderen. Niet alle opties zijn gedocumenteerd in het protocol, dus dezelfde optie kan verschillende effecten hebben op verschillende ketels.<br /><b>Let op:</b> Het is niet nodig om iets te veranderen als alles goed werkt.",
"dhwSupport": "Warm water ondersteuning",
"coolingSupport": "Koeling ondersteuning",
"summerWinterMode": "Zomer/wintermodus",
"heatingStateToSummerWinterMode": "Verwarmingsstatus als zomer/wintermodus",
"ch2AlwaysEnabled": "CH2 altijd ingeschakeld",
"heatingToCh2": "Dupliceer verwarming naar CH2",
"dhwToCh2": "Dupliceer warm water naar CH2",
"dhwBlocking": "Blokkering warm water",
"dhwStateAsDhwBlocking": "Status warm water als blokkering warm water",
"maxTempSyncWithTargetTemp": "Synchroniseer max. verwarmingstemp. met doeltemp.",
"getMinMaxTemp": "Haal min/max temp. op van ketel",
"ignoreDiagState": "Negeer diagnosestatus",
"autoFaultReset": "Automatische storingsreset <small>(niet aanbevolen!)</small>",
"autoDiagReset": "Automatische diagnosereset <small>(niet aanbevolen!)</small>",
"setDateAndTime": "Stel datum & tijd in op ketel",
"immergasFix": "Fix voor Immergas-ketels",
"alwaysSendIndoorTemp": "Stuur huidige binnentemp naar ketel"
},
"nativeOTC": {
"title": "Native warmtedrager temperatuur berekeningsmodus",
"note": "Werkt <u>ALLEEN</u> 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",
"server": "Server",
"port": "Poort",
"user": "Gebruiker",
"password": "Wachtwoord",
"prefix": "Prefix",
"interval": "Publicatie-interval <small>(sec)</small>"
},
"extPump": {
"use": "Gebruik externe pomp",
"gpio": "Relais GPIO",
"invertState": "Inverteer GPIO-status",
"postCirculationTime": "Nacirculatietijd <small>(min)</small>",
"antiStuckInterval": "Anti-vastloopinterval <small>(dagen)</small>",
"antiStuckTime": "Anti-vastlooptijd <small>(min)</small>"
},
"cascadeControl": {
"input": {
"desc": "Kan worden gebruikt om de verwarming alleen in te schakelen als een andere ketel defect is. De besturing van de andere ketel moet de status van de GPIO-ingang wijzigen in geval van een storing.",
"enable": "Ingang ingeschakeld",
"gpio": "GPIO",
"invertState": "Inverteer GPIO-status",
"thresholdTime": "Drempeltijd statuswijziging <small>(sec)</small>"
},
"output": {
"desc": "Kan worden gebruikt om een andere ketel in te schakelen <u>via een relais</u>.",
"enable": "Uitgang ingeschakeld",
"gpio": "GPIO",
"invertState": "Inverteer GPIO-status",
"thresholdTime": "Drempeltijd statuswijziging <small>(sec)</small>",
"events": {
"desc": "Gebeurtenissen",
"onFault": "Als de storingsstatus actief is",
"onLossConnection": "Als de verbinding via Opentherm is verbroken",
"onEnabledHeating": "Als de verwarming is ingeschakeld"
}
}
}
},
"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": {
"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.<br />De nieuwste releases kunnen worden gedownload van de <a href=\"https://github.com/Laxilef/OTGateway/releases\" target=\"_blank\">Releases-pagina</a> 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.",
"disclaimer2": "Na een succesvolle upgrade zal het apparaat automatisch herstarten na 15 seconden."
},
"settingsFile": "Instellingenbestand",
"fw": "Firmware",
"fs": "Bestandssysteem"
}
}
}
-556
View File
@@ -1,556 +0,0 @@
{
"values": {
"logo": "OpenTherm Gateway",
"nav": {
"license": "Лицензия",
"source": "Исходный код",
"help": "Помощь",
"issues": "Проблемы и вопросы",
"releases": "Релизы"
},
"units": {
"days": "д.",
"hours": "ч.",
"min": "мин.",
"sec": "сек.",
"dbm": "дБм",
"mhz": "МГц",
"kw": "кВт",
"rpm": "RPM",
"ppm": "ppm",
"byte": "байт",
"mbyte": "мбайт",
"liter": "Л.",
"gallon": "гал."
},
"button": {
"upgrade": "Обновить",
"restart": "Перезагрузка",
"save": "Сохранить",
"saved": "Сохранено",
"refresh": "Обновить",
"restore": "Восстановить настройки",
"restored": "Восстановлено",
"backup": "Сохранить настройки",
"wait": "Пожалуйста, подождите...",
"uploading": "Загрузка...",
"success": "Успешно",
"error": "Ошибка"
},
"index": {
"title": "OpenTherm Gateway",
"section": {
"network": "Сеть",
"system": "Система"
},
"system": {
"build": {
"title": "Билд",
"version": "Версия",
"commit": "Коммит",
"date": "Дата",
"core": "Ядро",
"sdk": "SDK"
},
"uptime": "Аптайм",
"memory": {
"heap": "Память (heap)",
"psram": "Память (PSRAM)",
"maxFreeBlock": "макс. блок",
"min": "мин."
},
"board": "Плата",
"chip": {
"model": "Чип",
"cores": "Кол-во ядер",
"freq": "частота"
},
"flash": {
"size": "Размер ПЗУ"
},
"lastResetReason": "Причина перезагрузки",
"coreDump": "Дамп памяти"
}
},
"dashboard": {
"name": "Дашборд",
"title": "Дашборд - OpenTherm Gateway",
"section": {
"control": "Управление",
"states": "Состояние",
"sensors": "Сенсоры",
"diag": "Диагностика OpenTherm"
},
"thermostat": {
"heating": "Отопление",
"dhw": "ГВС",
"currentTemp": "Текущая",
"enable": "Вкл",
"turbo": "Турбо"
},
"notify": {
"fault": {
"title": "Состояние неисправности котла активно!",
"note": "Рекомендуется осмотреть котел и изучить документацию котла для расшифровки кода неисправности:"
},
"diag": {
"title": "Состояние диагностики котла активно!",
"note": "Возможно, вашему котлу требуется проверка? Рекомендуется изучить документацию котла для расшифровки кода диагностики:"
},
"reset": "Сбросить"
},
"states": {
"mNetworkConnected": "Подключение к сети",
"mMqttConnected": "Подключение к MQTT",
"mEmergencyState": "Аварийный режим",
"mExtPumpState": "Внешний насос",
"mCascadeControlInput": "Каскадное управление (вход)",
"mCascadeControlOutput": "Каскадное управление (выход)",
"sConnected": "Подключение к OpenTherm",
"sFlame": "Пламя",
"sCoolingActive": "Охлаждение",
"sCoolingSetpoint": "Охлаждение, уставка",
"sFaultActive": "Ошибка",
"sFaultCode": "Код ошибки",
"sDiagActive": "Диагностика",
"sDiagCode": "Диагностический код",
"mHeatEnabled": "Отопление",
"mHeatBlocking": "Блокировка отопления",
"mHeatOverheat": "Отопление, перегрев",
"mHeatFreezing": "Отопление, защита от замерзания",
"sHeatActive": "Активность отопления",
"mHeatSetpointTemp": "Отопление, уставка",
"mHeatTargetTemp": "Отопление, целевая температура",
"mHeatCurrTemp": "Отопление, текущая температура",
"mHeatRetTemp": "Отопление, температура обратки",
"mHeatIndoorTemp": "Отопление, внутренняя темп.",
"mHeatOutdoorTemp": "Отопление, наружная темп.",
"mDhwEnabled": "ГВС",
"mDhwOverheat": "ГВС, перегрев",
"sDhwActive": "Активность ГВС",
"mDhwTargetTemp": "ГВС, целевая температура",
"mDhwCurrTemp": "ГВС, текущая температура",
"mDhwRetTemp": "ГВС, температура обратки"
},
"sensors": {
"values": {
"temp": "Температура",
"humidity": "Влажность",
"battery": "Уровень заряда",
"rssi": "RSSI"
}
}
},
"network": {
"title": "Сеть - OpenTherm Gateway",
"name": "Настройки сети",
"section": {
"static": "Статические параметры",
"availableNetworks": "Доступные сети",
"staSettings": "Настройки подключения",
"apSettings": "Настройки точки доступа"
},
"scan": {
"pos": "#",
"info": "Инфо"
},
"wifi": {
"ssid": "Имя сети",
"password": "Пароль",
"channel": "Канал",
"signal": "Сигнал",
"connected": "Подключено"
},
"params": {
"hostname": "Имя хоста",
"dhcp": "Использовать DHCP",
"mac": "MAC адрес",
"ip": "IP адрес",
"subnet": "Адрес подсети",
"gateway": "Адрес шлюза",
"dns": "DNS адрес"
},
"sta": {
"channel": {
"note": "установите 0 для автоматического выбора"
}
}
},
"sensors": {
"title": "Настройки сенсоров - OpenTherm Gateway",
"name": "Настройки сенсоров",
"enabled": "Включить и использовать",
"sensorName": {
"title": "Имя сенсора",
"note": "Может содержать только: a-z, A-Z, 0-9, _ и пробел"
},
"purpose": "Назначение",
"purposes": {
"outdoorTemp": "Внешняя температура",
"indoorTemp": "Внутренняя температура",
"heatTemp": "Отопление, температура",
"heatRetTemp": "Отопление, температура обратки",
"dhwTemp": "ГВС, температура",
"dhwRetTemp": "ГВС, температура обратки",
"dhwFlowRate": "ГВС, расход/скорость потока",
"exhaustTemp": "Температура выхлопных газов",
"modLevel": "Уровень модуляции (в процентах)",
"number": "Число (raw)",
"powerFactor": "Мощность (в процентах)",
"power": "Мощность (в кВт)",
"fanSpeed": "Скорость вентилятора",
"co2": "CO2",
"pressure": "Давление",
"humidity": "Влажность",
"temperature": "Температура",
"notConfigured": "Не сконфигурировано"
},
"type": "Тип/источник",
"types": {
"otOutdoorTemp": "OpenTherm, внешняя температура",
"otHeatTemp": "OpenTherm, отопление, температура",
"otHeatRetTemp": "OpenTherm, отопление, температура обратки",
"otDhwTemp": "OpenTherm, ГВС, температура",
"otDhwTemp2": "OpenTherm, ГВС, температура 2",
"otDhwFlowRate": "OpenTherm, ГВС, расход/скорость потока",
"otCh2Temp": "OpenTherm, канал 2, температура",
"otExhaustTemp": "OpenTherm, температура выхлопных газов",
"otHeatExchangerTemp": "OpenTherm, температура теплообменника",
"otPressure": "OpenTherm, давление",
"otModLevel": "OpenTherm, уровень модуляции",
"otCurrentPower": "OpenTherm, текущая мощность",
"otExhaustCo2": "OpenTherm, CO2 вытяжного воздуха",
"otExhaustFanSpeed": "OpenTherm, скорость вытяжного вентилятора",
"otSupplyFanSpeed": "OpenTherm, скорость приточного вентилятора",
"otSolarStorageTemp": "OpenTherm, темп. бойлера солн. коллектора",
"otSolarCollectorTemp": "OpenTherm, темп. солн. коллектора",
"otFanSpeedSetpoint": "OpenTherm, установленная мощн. вентилятора",
"otFanSpeedCurrent": "OpenTherm, текущая мощн. вентилятора",
"otBurnerStarts": "OpenTherm, кол-во запусков горелки",
"otDhwBurnerStarts": "OpenTherm, кол-во запусков горелки (ГВС)",
"otHeatingPumpStarts": "OpenTherm, кол-во запусков насоса (отопление)",
"otDhwPumpStarts": "OpenTherm, кол-во запусков насоса (ГВС)",
"otBurnerHours": "OpenTherm, кол-во часов работы горелки",
"otDhwBurnerHours": "OpenTherm, кол-во часов работы горелки (ГВС)",
"otHeatingPumpHours": "OpenTherm, кол-во часов работы насоса (отопление)",
"otDhwPumpHours": "OpenTherm, кол-во часов работы насоса (ГВС)",
"otCoolingHours": "OpenTherm, кол-во часов работы охлаждения",
"ntcTemp": "NTC датчик",
"dallasTemp": "DALLAS датчик",
"bluetooth": "BLE датчик",
"dht11": "DHT11 датчик",
"dht22": "DHT22 датчик",
"heatSetpointTemp": "Отопление, температура уставки",
"manual": "Вручную через MQTT/API",
"notConfigured": "Не сконфигурировано"
},
"gpio": "GPIO датчика",
"address": {
"title": "Адрес датчика",
"note": "Для DALLAS датчиков оставьте по умолчанию для автоопределения, для BLE устройств необходимо указать MAC адрес"
},
"correction": {
"desc": "Коррекция показаний",
"offset": "Компенсация (смещение)",
"factor": "Множитель"
},
"filtering": {
"desc": "Фильтрация показаний",
"enabled": {
"title": "Включить фильтрацию",
"note": "Может быть полезно, если на графиках много резкого шума. В качестве фильтра используется \"бегущее среднее\"."
},
"factor": {
"title": "Коэфф. фильтрации",
"note": "Чем меньше коэф., тем плавнее и <u>дольше</u> изменение числовых значений."
}
}
},
"settings": {
"title": "Настройки - OpenTherm Gateway",
"name": "Настройки",
"section": {
"portal": "Настройки портала",
"system": "Системные настройки",
"diag": "Диагностика",
"heating": "Настройки отопления",
"dhw": "Настройки ГВС",
"emergency": "Настройки аварийного режима",
"equitherm": "Настройки ПЗА",
"pid": "Настройки ПИД",
"ot": "Настройки OpenTherm",
"mqtt": "Настройки MQTT",
"extPump": "Настройки дополнительного насоса",
"cascadeControl": "Настройки каскадного управления"
},
"enable": "Вкл",
"note": {
"restart": "После изменения этих настроек устройство необходимо перезагрузить, чтобы изменения вступили в силу.",
"blankNotUse": "пусто - не использовать",
"bleDevice": "BLE устройство можно использовать <u>только</u> с некоторыми платами ESP32, которые поддерживают BLE!"
},
"temp": {
"min": "Мин. температура",
"max": "Макс. температура"
},
"avgType": {
"mean": "Средняя температура",
"min": "Минимальная температура",
"max": "Максимальная температура"
},
"maxModulation": "Макс. уровень модуляции",
"ohProtection": {
"title": "Защита от перегрева",
"desc": "<b>Примечание:</b> Эта функция может быть полезна, если встроенная защита от перегрева котла не срабатывает или срабатывает некорректно и теплоноситель закипает. Для отключения установите 0 в качестве <b>верхнего</b> и <b>нижнего</b> порога температуры.",
"highTemp": {
"title": "Верхний порог температуры",
"note": "Порог, при котором горелка будет принудительно отключена"
},
"lowTemp": {
"title": "Нижний порог температуры",
"note": "Порог, при котором горелка может быть включена снова"
}
},
"freezeProtection": {
"title": "Защита от замерзания",
"desc": "Отопление будет принудительно включено, если темп. теплоносителя или внутренняя темп. опустится ниже <b>нижнего порога</b>.",
"highTemp": {
"title": "Верхний порог температуры",
"note": "Порог, при котором система вернется в нормальное состояние после активации защиты от замерзания"
},
"lowTemp": {
"title": "Нижний порог температуры",
"note": "Порог, при котором отопление будет принудительно включено"
}
},
"portal": {
"login": "Логин",
"password": "Пароль",
"auth": "Требовать аутентификацию",
"mdns": "Использовать mDNS"
},
"system": {
"unit": "Система единиц",
"metric": "Метрическая <small>(цельсии, литры, бары)</small>",
"imperial": "Imperial <small>(фаренгейты, галлоны, psi)</small>",
"statusLedGpio": "Статус LED GPIO",
"logLevel": "Уровень логирования",
"serial": {
"enable": "Вкл. Serial порт",
"baud": "Скорость Serial порта"
},
"webSerial": {
"enable": "Вкл. WebSerial"
},
"ntp": {
"server": "NTP сервер",
"timezone": "Часовой пояс",
"timezonePresets": "Выберите пресет..."
}
},
"heating": {
"hyst": {
"title": "Гистерезис",
"desc": "Гистерезис полезен для поддержания заданной внутр. темп. (при использовании «ПЗА» и/или «ПИД»). Принудительно откл. отопление, когда <code>current indoor > target + value</code>, и вкл. отопление, когда <code>current indoor < (target - value)</code>.",
"value": "Значение <small>(в градусах)</small>"
},
"turboFactor": "Коэфф. турбо режима",
"indoorTempAvgType": {
"title": "Тип усреднения внутренней темп.",
"desc": "Полезно при использовании двух и более датчиков внутренней температуры (при использовании «Equitherm» и/или «PID»)."
},
"outdoorTempAvgType": {
"title": "Тип усреднения наружнной темп.",
"desc": "Полезно при использовании двух и более датчиков наружной температуры (при использовании «Equitherm»)."
}
},
"emergency": {
"desc": "Аварийный режим активируется автоматически, если «ПИД» или «ПЗА» не могут рассчитать уставку теплоносителя:<br />- если «ПЗА» включен и датчик наружной температуры отключен;<br />- если включен «ПИД» или OT опция <i>«Передать управление отоплением котлу»</i> и датчик внутренней температуры отключен.<br /><b>Примечание:</b> При сбое сети или MQTT датчики с типом <i>«Вручную через MQTT/API»</i> будут находиться в состоянии ОТКЛЮЧЕН.",
"target": {
"title": "Целевая температура",
"note": "<b>Важно:</b> <u>Целевая температура в помещении</u>, если включена ОТ опция <i>«Передать управление отоплением котлу»</i>.<br />Во всех остальных случаях <u>целевая температура теплоносителя</u>."
},
"thresholdTime": "Задержка входа в аварийный режим и выхода из него <small>(сек)</small>"
},
"equitherm": {
"slope": {
"title": "Наклон",
"note": "Компенсация теплопотерь. Основной параметр настройки."
},
"exponent": {
"title": "Экспонента",
"note": "Эффективность радиатора. Типичные значения: <code>1.1</code> - Тёплый пол, <code>1.2</code> - Чугунные радиаторы, <code>1.3</code> - Панельные радиаторы, <code>1.4</code> - Конвекторы."
},
"shift": {
"title": "Смещение",
"note": "Компенсирует дополнительные теплопотери (например, в трубах) или дополнительные источники тепла."
},
"targetDiffFactor": {
"title": "Коэффициент T",
"note": "Не используется, если ПИД включен. Добавляет разницу между целевой и текущей температурой в помещении: <code>setpoint = setpoint + ((target - indoor) * T)</code>."
},
"chart": {
"targetTemp": "Целевая внутренняя температура",
"setpointTemp": "Температура теплоносителя",
"outdoorTemp": "Наружная температура"
}
},
"pid": {
"p": "Коэффициент P",
"i": "Коэффициент I",
"d": "Коэффициент D",
"dt": "DT <small>(сек)</small>",
"limits": {
"title": "Лимиты",
"note": "<b>Важно:</b> При использовании «ПЗА» и «ПИД» одновременно, мин. и макс. температура ограничивает влияние на расчётную температуру «ПЗА».<br />Таким образом, если мин. температура задана как -15, а макс. как 15, то конечная температура теплоносителя будет от <code>equitherm_result - 15</code> до <code>equitherm_result + 15</code>."
},
"deadband": {
"title": "Зона нечувствительности (Deadband)",
"note": "Deadband - это зона нечувствительности вокруг целевой температуры, в которой PID-регулирование становится менее активным. В этом диапазоне алгоритм может снижать интенсивность или полностью прекращать корректировку температуры, чтобы избежать излишней чувствительности к небольшим колебаниям.<br /><br />Например, при целевой температуре 22°, нижнем пороге 1.0 и верхнем 0.5, deadband активен в диапазоне от 21° до 22.5°. Если коэфф. I=0.0005, а множитель I=0.05, то при включении зоны нечувствительности коэфф. I будет равен: <code>0.0005 * 0.05 = 0.000025</code>",
"p_multiplier": "Множитель для коэф. P",
"i_multiplier": "Множитель для коэф. I",
"d_multiplier": "Множитель для коэф. D",
"thresholdHigh": "Верхний порог",
"thresholdLow": "Нижний порог"
}
},
"ot": {
"disablingAction": {
"title": "Действие отключения контуров",
"desc": "Выбранное действие применяется при любой причине отключения, включая перегрев.<br />Некоторые котлы отключают циркуляционный насос при отключении контура, в этом случае можно попробовать установить <b>0</b> в качестве целевой температуры, чтобы выбег насоса работал корректно.",
"heating": "Контур отопления",
"dhw": "Контур ГВС",
"ch2": "Контур 2",
"off": "Только отключить контур",
"zeroSetpoint": "Установить <b>0</b> в качестве целевой температуры",
"offAndZeroSetpoint": "Отключить контур и установить <b>0</b> в качестве целевой температуры"
},
"advanced": "Дополнительные настройки",
"inGpio": "Вход GPIO",
"outGpio": "Выход GPIO",
"ledGpio": "RX LED GPIO",
"memberId": "Master member ID",
"flags": "Master flags",
"minPower": {
"title": "Мин. мощность котла <small>(кВт)</small>",
"note": "Это значение соответствует уровню модуляции котла 0–1%. Обычно можно найти в спецификации котла как \"минимальная полезная тепловая мощность\"."
},
"maxPower": {
"title": "Макс. мощность котла <small>(кВт)</small>",
"note": "<b>0</b> - попробовать определить автоматически. Обычно можно найти в спецификации котла как \"максимальная полезная тепловая мощность\"."
},
"options": {
"title": "Опции (дополнительные настройки)",
"desc": "Опции могут менять логику работы котла. Не все опции задокументированы в протоколе, поэтому одна и та же опция может иметь разный эффект на разных котлах.<br /><b>Примечание:</b> Нет необходимости что-то менять, если всё работает хорошо.",
"dhwSupport": "Поддержка ГВС",
"coolingSupport": "Поддержка охлаждения",
"summerWinterMode": "Летний/зимний режим",
"heatingStateToSummerWinterMode": "Летний/зимний режим в качестве состояния отопления",
"ch2AlwaysEnabled": "Канал 2 всегда вкл.",
"heatingToCh2": "Дублировать параметры отопления в канал 2",
"dhwToCh2": "Дублировать параметры ГВС в канал 2",
"dhwBlocking": "DHW blocking",
"dhwStateAsDhwBlocking": "DHW blocking в качестве состояния ГВС",
"maxTempSyncWithTargetTemp": "Синхронизировать макс. темп. отопления с целевой темп.",
"getMinMaxTemp": "Получать мин. и макс. температуру от котла",
"ignoreDiagState": "Игнорировать состояние диагностики",
"autoFaultReset": "Автоматический сброс ошибок <small>(не рекомендуется!)</small>",
"autoDiagReset": "Автоматический сброс диагностики <small>(не рекомендуется!)</small>",
"setDateAndTime": "Устанавливать время и дату на котле",
"immergasFix": "Фикс для котлов Immergas",
"alwaysSendIndoorTemp": "Передавать текущую темп. в помещении котлу"
},
"nativeOTC": {
"title": "Нативный режим OTC (расчёт температуры теплоносителя)",
"note": "Работает <u>ТОЛЬКО</u> если котел в режиме OTC: требует и принимает целевую температуру в помещении и сам регулирует температуру теплоносителя на основе встроенного режима кривых. Несовместимо с ПИД и ПЗА."
}
},
"mqtt": {
"homeAssistantDiscovery": "Home Assistant Discovery",
"server": "Адрес сервера",
"port": "Порт",
"user": "Имя пользователя",
"password": "Пароль",
"prefix": "Префикс",
"interval": "Интервал публикации <small>(сек)</small>"
},
"extPump": {
"use": "Использовать доп. насос",
"gpio": "GPIO реле",
"invertState": "Инвертировать состояние GPIO",
"postCirculationTime": "Время постциркуляции <small>(в минутах)</small>",
"antiStuckInterval": "Интервал защиты от блокировки <small>(в днях)</small>",
"antiStuckTime": "Время работы насоса <small>(в минутах)</small>"
},
"cascadeControl": {
"input": {
"desc": "Может использоваться для включения отопления только при неисправности другого котла. Контроллер другого котла должен изменить состояние входа GPIO в случае неисправности.",
"enable": "Включить вход",
"gpio": "GPIO",
"invertState": "Инвертировать состояние GPIO",
"thresholdTime": "Пороговое время изменения состояния <small>(сек)</small>"
},
"output": {
"desc": "Может использоваться для включения другого котла <u>через реле</u>.",
"enable": "Включить выход",
"gpio": "GPIO",
"invertState": "Инвертировать состояние GPIO",
"thresholdTime": "Пороговое время изменения состояния <small>(сек)</small>",
"events": {
"desc": "События",
"onFault": "Если состояние fault (ошибки) активно",
"onLossConnection": "Если соединение по OpenTherm потеряно",
"onEnabledHeating": "Если отопление включено"
}
}
}
},
"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": {
"title": "Резервное копирование и восстановление",
"desc": "В этом разделе вы можете сохранить и восстановить резервную копию ВСЕХ настроек."
},
"upgrade": {
"title": "Обновление",
"desc": "В этом разделе вы можете обновить прошивку и файловую систему вашего устройства.<br />Последнюю версию можно загрузить со страницы <a href=\"https://github.com/Laxilef/OTGateway/releases\" target=\"_blank\">Релизы</a> в репозитории проекта."
}
},
"note": {
"disclaimer1": "После успешного обновления файловой системы ВСЕ настройки будут сброшены на стандартные! Создайте резервную копию ПЕРЕД обновлением.",
"disclaimer2": "После успешного обновления устройство автоматически перезагрузится через 15 секунд."
},
"settingsFile": "Файл настроек",
"fw": "Прошивка",
"fs": "Файловая система"
}
}
}
-834
View File
@@ -1,834 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title data-i18n>dashboard.title</title>
<link rel="stylesheet" href="/static/app.css?{BUILD_TIME}" />
</head>
<body>
<header class="container">
<nav>
<ul>
<li>
<a href="/">
<div class="logo" data-i18n>logo</div>
</a>
</li>
</ul>
<ul>
<li>
<select id="lang" aria-label="Lang">
<option value="en" selected>EN</option>
<option value="cn">CN</option>
<option value="it">IT</option>
<option value="nl">NL</option>
<option value="ru">RU</option>
</select>
</li>
</ul>
</nav>
</header>
<main class="container">
<article>
<hgroup>
<h2 data-i18n>dashboard.name</h2>
<p></p>
</hgroup>
<div id="dashboard-busy" aria-busy="true"></div>
<div id="dashboard-container" class="hidden">
<details open>
<summary><b data-i18n>dashboard.section.control</b></summary>
<div class="grid">
<div class="thermostat tHeat" data-purpose="heating" data-min="0" data-max="100" data-step="0.1" data-big-step="1">
<div class="thermostat-header" data-i18n>dashboard.thermostat.heating</div>
<div class="thermostat-temp">
<div class="thermostat-temp-target"><span class="targetTemp"></span> <span class="tempUnit"></span></div>
<div class="thermostat-temp-current"><span data-i18n>dashboard.thermostat.currentTemp</span>: <span id="tHeatCurrentTemp"></span> <span class="tempUnit"></span></div>
</div>
<div class="thermostat-minus">
<button class="tAction outline" data-action="decrement"><i class="icons-down"></i></button>
</div>
<div class="thermostat-plus">
<button class="tAction outline" data-action="increment"><i class="icons-up"></i></button>
</div>
<div class="thermostat-control">
<input type="checkbox" role="switch" id="tHeatEnabled" value="true">
<label htmlFor="tHeatEnabled" data-i18n>dashboard.thermostat.enable</label>
<input type="checkbox" role="switch" id="tHeatTurbo" value="true">
<label htmlFor="tHeatTurbo" data-i18n>dashboard.thermostat.turbo</label>
</div>
</div>
<div class="thermostat tDhw" data-purpose="dhw" data-min="0" data-max="100" data-step="1" data-big-step="5">
<div class="thermostat-header" data-i18n>dashboard.thermostat.dhw</div>
<div class="thermostat-temp">
<div class="thermostat-temp-target"><span class="targetTemp"></span> <span class="tempUnit"></span></div>
<div class="thermostat-temp-current"><span data-i18n>dashboard.thermostat.currentTemp</span>: <span id="tDhwCurrentTemp"></span> <span class="tempUnit"></span></div>
</div>
<div class="thermostat-minus">
<button class="tAction outline" data-action="decrement"><i class="icons-down"></i></button>
</div>
<div class="thermostat-plus">
<button class="tAction outline" data-action="increment"><i class="icons-up"></i></button>
</div>
<div class="thermostat-control">
<input type="checkbox" role="switch" id="tDhwEnabled" value="true">
<label htmlFor="tDhwEnabled" data-i18n>dashboard.thermostat.enable</label>
</div>
</div>
</div>
<div class="notify notify-error notify-fault hidden">
<div class="notify-icon">
<i class="icons-error"></i>
</div>
<div class="notify-content">
<b data-i18n>dashboard.notify.fault.title</b><br />
<small>
<span data-i18n>dashboard.notify.fault.note</span> <b class="sFaultCode"></b>
</small>
</div>
<div class="notify-actions">
<button class="reset" data-i18n>dashboard.notify.reset</button>
</div>
</div>
<div class="notify notify-alarm notify-diag hidden">
<div class="notify-icon">
<i class="icons-alarm"></i>
</div>
<div class="notify-content">
<b data-i18n>dashboard.notify.diag.title</b><br />
<small>
<span data-i18n>dashboard.notify.diag.note</span> <b class="sDiagCode"></b>
</small>
</div>
<div class="notify-actions">
<button class="reset" data-i18n>dashboard.notify.reset</button>
</div>
</div>
</details>
<hr />
<details>
<summary><b data-i18n>dashboard.section.states</b></summary>
<table>
<tbody>
<tr>
<th scope="row" data-i18n>dashboard.states.mNetworkConnected</th>
<td><i class="mNetworkConnected"></i></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.mMqttConnected</th>
<td><i class="mMqttConnected"></i></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.mEmergencyState</th>
<td><i class="mEmergencyState"></i></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.mExtPumpState</th>
<td><i class="mExtPumpState"></i></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.mCascadeControlInput</th>
<td><i class="mCascadeControlInput"></i></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.mCascadeControlOutput</th>
<td><i class="mCascadeControlOutput"></i></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.sConnected</th>
<td><i class="sConnected"></i></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.sFlame</th>
<td><i class="sFlame"></i></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.sCoolingActive</th>
<td><i class="sCoolingActive"></i></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.sCoolingSetpoint</th>
<td><b class="sCoolingSetpoint"></b> %</td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.sFaultActive</th>
<td><i class="sFaultActive"></i></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.sFaultCode</th>
<td><b class="sFaultCode"></b></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.sDiagActive</th>
<td><i class="sDiagActive"></i></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.sDiagCode</th>
<td><b class="sDiagCode"></b></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.mHeatEnabled</th>
<td><i class="mHeatEnabled"></i></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.mHeatBlocking</th>
<td><i class="mHeatBlocking"></i></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.mHeatOverheat</th>
<td><i class="mHeatOverheat"></i></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.mHeatFreezing</th>
<td><i class="mHeatFreezing"></i></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.sHeatActive</th>
<td><i class="sHeatActive"></i></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.mHeatTargetTemp</th>
<td><b class="mHeatTargetTemp"></b> <span class="tempUnit"></span></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.mHeatSetpointTemp</th>
<td><b class="mHeatSetpointTemp"></b> <span class="tempUnit"></span></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.mHeatCurrTemp</th>
<td><b class="mHeatCurrTemp"></b> <span class="tempUnit"></span></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.mHeatRetTemp</th>
<td><b class="mHeatRetTemp"></b> <span class="tempUnit"></span></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.mHeatIndoorTemp</th>
<td><b class="mHeatIndoorTemp"></b> <span class="tempUnit"></span></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.mHeatOutdoorTemp</th>
<td><b class="mHeatOutdoorTemp"></b> <span class="tempUnit"></span></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.mDhwEnabled</th>
<td><i class="mDhwEnabled"></i></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.mDhwOverheat</th>
<td><i class="mDhwOverheat"></i></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.sDhwActive</th>
<td><i class="sDhwActive"></i></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.mDhwTargetTemp</th>
<td><b class="mDhwTargetTemp"></b> <span class="tempUnit"></span></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.mDhwCurrTemp</th>
<td><b class="mDhwCurrTemp"></b> <span class="tempUnit"></span></td>
</tr>
<tr>
<th scope="row" data-i18n>dashboard.states.mDhwRetTemp</th>
<td><b class="mDhwRetTemp"></b> <span class="tempUnit"></span></td>
</tr>
</tbody>
</table>
</details>
<hr />
<details>
<summary><b data-i18n>dashboard.section.sensors</b></summary>
<table>
<tbody class="sensors">
<tr class="sensor template hidden">
<td style="width: 1.35rem">
<span class="sStatusContainer">
<i class="sStatus"></i>
</span>
</td>
<th scope="row" class="sName"></th>
<td class="sValue"></td>
</tr>
</tbody>
</table>
</details>
<hr />
<details>
<summary><b data-i18n>dashboard.section.diag</b></summary>
<pre><b>Vendor:</b> <span class="sVendor"></span>
<b>Member ID:</b> <span class="sMemberId"></span>
<b>Flags:</b> <span class="sFlags"></span>
<b>Type:</b> <span class="sType"></span>
<b>AppVersion:</b> <span class="sAppVersion"></span>
<b>OT version:</b> <span class="sProtocolVersion"></span>
<b>Modulation:</b> min: <span class="sModMin"></span> %, curr. max: <span class="sModMax"></span> %
<b>Power limits:</b> <span class="sPowerMin"></span>...<span class="sPowerMax"></span> kW
<b>Heating limits:</b> <span class="sHeatMinTemp"></span>...<span class="sHeatMaxTemp"></span> <span class="tempUnit"></span>
<b>DHW limits:</b> <span class="sDhwMinTemp"></span>...<span class="sDhwMaxTemp"></span> <span class="tempUnit"></span></pre>
</details>
</div>
</article>
</main>
<footer class="container">
<small>
<b>Made by Laxilef</b>
• <a href="https://github.com/Laxilef/OTGateway/blob/master/LICENSE" target="_blank" class="secondary" data-i18n>nav.license</a>
• <a href="https://github.com/Laxilef/OTGateway/blob/master/" target="_blank" class="secondary" data-i18n>nav.source</a>
• <a href="https://github.com/Laxilef/OTGateway/wiki" target="_blank" class="secondary" data-i18n>nav.help</a>
• <a href="https://github.com/Laxilef/OTGateway/issues" target="_blank" class="secondary" data-i18n>nav.issues</a>
• <a href="https://github.com/Laxilef/OTGateway/releases" target="_blank" class="secondary" data-i18n>nav.releases</a>
</small>
</footer>
<script src="/static/app.js?{BUILD_TIME}"></script>
<script>
let modifiedTime = null;
let prevSettings;
let newSettings = {
heating: {
enabled: false,
turbo: false,
target: 0
},
dhw: {
enabled: false,
target: 0
}
};
document.addEventListener('DOMContentLoaded', async () => {
const lang = new Lang(document.getElementById('lang'));
await lang.build();
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;
} else if (action == 'decrement') {
value = -(step);
}
const newValue = parseFloat(constrain(newSettings[purpose].target + value, minTemp, maxTemp).toFixed(2));
if (newSettings[purpose].target != newValue) {
newSettings[purpose].target = newValue;
modifiedTime = Date.now();
setValue('.targetTemp', newValue, tContainer);
tContainer.querySelector('.thermostat-header').setAttribute("aria-busy", "true");
}
};
item.addEventListener('pointerdown', (event) => {
if (!prevSettings || activePress || event.button !== 0) {
return;
}
const minTemp = parseFloat(tContainer.dataset.min);
const maxTemp = parseFloat(tContainer.dataset.max);
const bigStep = parseFloat(tContainer.dataset.bigStep);
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) => {
const resetBtn = document.querySelector(".notify-fault .reset");
if (!resetBtn.disabled) {
resetBtn.disabled = true;
}
let response = await fetch("/api/vars", {
method: "POST",
cache: "no-cache",
credentials: "include",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
"actions": {
"reset_fault": true
}
})
});
setTimeout(() => {
if (resetBtn.disabled) {
resetBtn.disabled = false;
}
}, 10000);
});
document.querySelector('.notify-diag .reset').addEventListener('click', async (event) => {
const resetBtn = document.querySelector(".notify-diag .reset");
if (!resetBtn.disabled) {
resetBtn.disabled = true;
}
let response = await fetch("/api/vars", {
method: "POST",
cache: "no-cache",
credentials: "include",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
"actions": {
"reset_diagnostic": true
}
})
});
setTimeout(() => {
if (resetBtn.disabled) {
resetBtn.disabled = false;
}
}, 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;
if (modifiedTime) {
if ((Date.now() - modifiedTime) < 5000) {
setTimeout(onLoadPage, 1000);
return;
}
modifiedTime = null;
}
// settings
try {
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)
);
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.unit_system;
if (result.opentherm.options.dhw_support) {
show('.tDhw');
} else {
hide('.tDhw');
}
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);
}
// vars
try {
const response = await fetch("/api/vars", {
cache: "no-cache",
credentials: "include"
});
if (!response.ok) {
throw new Error('Response not valid');
}
const result = await response.json();
// Graph
setValue('#tHeatCurrentTemp', result.master.heating.smart_control
? result.master.heating.indoor_temp
: result.master.heating.current_temp
);
setValue('#tDhwCurrentTemp', result.master.dhw.current_temp);
// SLAVE
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.app_version);
setValue('.sProtocolVersion', result.slave.protocol_version);
setStatus(
'.sConnected',
result.slave.connected ? "success" : "error",
result.slave.connected ? "green" : "red"
);
setState('.sFlame', result.slave.flame);
setState('.sCoolingActive', result.slave.cooling.active);
setValue('.sCoolingSetpoint', result.slave.cooling.setpoint);
setValue('.sModMin', result.slave.modulation.min);
setValue('.sModMax', result.slave.modulation.max);
setValue('.sPowerMin', result.slave.power.min);
setValue('.sPowerMax', result.slave.power.max);
setState('.sHeatActive', result.slave.heating.active);
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.min_temp);
setValue('.sDhwMaxTemp', result.slave.dhw.max_temp);
setStatus(
'.sFaultActive',
result.slave.fault.active ? "success" : "error",
result.slave.fault.active ? "red" : "green"
);
setValue(
'.sFaultCode',
result.slave.fault.active
? `${result.slave.fault.code} (0x${dec2hex(result.slave.fault.code)})`
: "-"
);
if (result.slave.fault.active) {
show(".notify-fault");
} else {
hide('.notify-fault');
}
setStatus(
'.sDiagActive',
result.slave.diag.active ? "success" : "error",
result.slave.diag.active ? "red" : "green"
);
setValue(
'.sDiagCode',
result.slave.diag.active
? `${result.slave.diag.code} (0x${dec2hex(result.slave.diag.code)})`
: "-"
);
if (result.slave.diag.active) {
show(".notify-diag");
} else {
hide('.notify-diag');
}
// MASTER
setState('.mHeatEnabled', result.master.heating.enabled);
setStatus(
'.mHeatBlocking',
result.master.heating.blocking ? "success" : "error",
result.master.heating.blocking ? "red" : "green"
);
setState('.mHeatSmartControl', result.master.heating.smart_control);
setStatus(
'.mHeatOverheat',
result.master.heating.overheat ? "success" : "error",
result.master.heating.overheat ? "red" : "green"
);
setStatus(
'.mHeatFreezing',
result.master.heating.freezing ? "success" : "error",
result.master.heating.freezing ? "red" : "green"
);
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(
'.mDhwOverheat',
result.master.dhw.overheat ? "success" : "error",
result.master.dhw.overheat ? "red" : "green"
);
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',
result.master.network.connected ? "success" : "error",
result.master.network.connected ? "green" : "red"
);
setState('.mMqttConnected', result.master.mqtt.connected);
setStatus(
'.mEmergencyState',
result.master.emergency.state ? "success" : "error",
result.master.emergency.state ? "red" : "green"
);
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.min_temp;
tHeat.dataset.max = result.master.heating.max_temp;
const tDhw = document.querySelector('.tDhw');
tDhw.dataset.min = result.master.dhw.min_temp;
tDhw.dataset.max = result.master.dhw.max_temp;
setBusy('#dashboard-busy', '#dashboard-container', false);
} catch (error) {
console.log(error);
}
// sensors
try {
const response = await fetch("/api/sensors?detailed=1", {
cache: "no-cache",
credentials: "include"
});
if (!response.ok) {
throw new Error("Response not valid");
}
const container = document.querySelector(".sensors");
const templateNode = container.querySelector(".template");
const result = await response.json();
for (const sensorId in result) {
let sensorNode = container.querySelector(`.sensor[data-id='${sensorId}']`);
if (sensorNode) {
continue;
}
sensorNode = templateNode.cloneNode(true);
sensorNode.dataset.id = sensorId;
sensorNode.classList.remove("template");
container.appendChild(sensorNode);
}
for (const sensorId in result) {
const sensorNode = container.querySelector(`.sensor[data-id='${sensorId}']`);
if (!sensorNode) {
continue;
}
const sData = result[sensorId];
if (!sData.enabled || sData.purpose == 255) {
sensorNode.classList.toggle("hidden", true);
continue;
}
sensorNode.classList.toggle("hidden", false);
setStatus(
".sStatus",
sData.connected ? "success" : "error",
sData.connected ? "green" : "red",
sensorNode
);
setTextValue(".sName", sData.name, sensorNode);
setValue(".sValue", "", sensorNode);
const statusNode = sensorNode.querySelector(`.sStatusContainer`);
if (statusNode) {
statusNode.dataset.tooltip = `${sData.signal_quality}%`;
}
if (sData.value !== undefined) {
const sUnit = purposeUnit(sData.purpose, unitSystem);
appendValue(".sValue", `<b>${sData.value.toFixed(2)}</b> ${sUnit !== null ? sUnit : ``}`, `<br />`, sensorNode);
}
if (sData.temperature !== undefined) {
const sUnit = temperatureUnit(unitSystem);
appendValue(".sValue", `${i18n('dashboard.sensors.values.temp')}: <b>${sData.temperature.toFixed(2)}</b> ${sUnit !== null ? sUnit : ``}`, `<br />`, sensorNode);
}
if (sData.humidity !== undefined) {
appendValue(".sValue", `${i18n('dashboard.sensors.values.humidity')}: <b>${sData.humidity.toFixed(2)}</b> %`, `<br />`, sensorNode);
}
if (sData.battery !== undefined) {
appendValue(".sValue", `${i18n('dashboard.sensors.values.battery')}: <b>${sData.battery.toFixed(2)}</b> %`, `<br />`, sensorNode);
}
if (sData.rssi !== undefined) {
appendValue(".sValue", `${i18n('dashboard.sensors.values.rssi')}: <b>${sData.rssi.toFixed(0)}</b> ${i18n('units.dbm')}`, `<br />`, sensorNode);
}
}
} catch (error) {
console.log(error);
}
setTimeout(onLoadPage, 10000);
}, 1000);
});
</script>
</body>
</html>
-290
View File
@@ -1,290 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title data-i18n>index.title</title>
<link rel="stylesheet" href="/static/app.css?{BUILD_TIME}" />
</head>
<body>
<header class="container">
<nav>
<ul>
<li>
<a href="/">
<div class="logo" data-i18n>logo</div>
</a>
</li>
</ul>
<ul>
<li>
<select id="lang" aria-label="Lang">
<option value="en" selected>EN</option>
<option value="cn">CN</option>
<option value="it">IT</option>
<option value="nl">NL</option>
<option value="ru">RU</option>
</select>
</li>
</ul>
</nav>
</header>
<main class="container">
<article>
<div>
<hgroup>
<h2 data-i18n>index.section.network</h2>
<p></p>
</hgroup>
<div id="main-busy" aria-busy="true"></div>
<table id="main-table" class="hidden">
<tbody>
<tr>
<th scope="row" data-i18n>network.params.hostname</th>
<td><b id="network-hostname"></b></td>
</tr>
<tr>
<th scope="row" data-i18n>network.params.mac</th>
<td><b id="network-mac"></b></td>
</tr>
<tr>
<th scope="row" data-i18n>network.wifi.connected</th>
<td><i id="network-connected"></i></td>
</tr>
<tr>
<th scope="row" data-i18n>network.wifi.ssid</th>
<td><b id="network-ssid"></b></td>
</tr>
<tr>
<th scope="row" data-i18n>network.wifi.signal</th>
<td><b id="network-signal"></b> %</td>
</tr>
<tr>
<th scope="row" data-i18n>network.params.ip</th>
<td><b id="network-ip"></b></td>
</tr>
<tr>
<th scope="row" data-i18n>network.params.subnet</th>
<td><b id="network-subnet"></b></td>
</tr>
<tr>
<th scope="row" data-i18n>network.params.gateway</th>
<td><b id="network-gateway"></b></td>
</tr>
<tr>
<th scope="row" data-i18n>network.params.dns</th>
<td><b id="network-dns"></b></td>
</tr>
</tbody>
</table>
<div class="grid">
<a href="/network.html" role="button" data-i18n>network.name</a>
</div>
</div>
</article>
<article>
<div>
<hgroup>
<h2 data-i18n>index.section.system</h2>
<p></p>
</hgroup>
<div id="system-busy" aria-busy="true"></div>
<table id="system-table" class="hidden">
<tbody>
<tr>
<th scope="row" data-i18n>index.system.build.version</th>
<td><b id="build-version"></b></td>
</tr>
<tr>
<th scope="row" data-i18n>index.system.build.title</th>
<td>
Env: <b id="build-env"></b><br />
<span data-i18n>index.system.build.commit</span>: <b id="build-commit"></b><br />
<span data-i18n>index.system.build.date</span>: <b id="build-date"></b><br />
<span data-i18n>index.system.build.core</span>: <b id="build-core"></b><br />
<span data-i18n>index.system.build.sdk</span>: <b id="build-sdk"></b>
</td>
</tr>
<tr>
<th scope="row" data-i18n>index.system.uptime</th>
<td>
<b id="uptime-days"></b> <span data-i18n>units.days</span>,
<b id="uptime-hours"></b> <span data-i18n>units.hours</span>,
<b id="uptime-min"></b> <span data-i18n>units.min</span>,
<b id="uptime-sec"></b> <span data-i18n>units.sec</span>
</td>
</tr>
<tr>
<th scope="row" data-i18n>index.system.memory.heap</th>
<td>
<b id="heap-free"></b> of <b id="heap-total"></b> <span data-i18n>units.byte</span> (<span data-i18n>index.system.memory.min</span>: <b id="heap-min-free"></b> <span data-i18n>units.byte</span>)<br />
<span data-i18n>index.system.memory.maxFreeBlock</span>: <b id="heap-max-free-block"></b> <span data-i18n>units.byte</span> (<span data-i18n>index.system.memory.min</span>: <b id="heap-min-max-free-block"></b> <span data-i18n>units.byte</span>)
</td>
</tr>
<tr>
<th scope="row" data-i18n>index.system.memory.psram</th>
<td>
<b id="psram-free"></b> of <b id="psram-total"></b> <span data-i18n>units.byte</span> (<span data-i18n>index.system.memory.min</span>: <b id="psram-min-free"></b> <span data-i18n>units.byte</span>)<br />
<span data-i18n>index.system.memory.maxFreeBlock</span>: <b id="psram-max-free-block"></b> <span data-i18n>units.byte</span>
</td>
</tr>
<tr>
<th scope="row" data-i18n>index.system.board</th>
<td>
<span data-i18n>index.system.chip.model</span>: <b id="chip-model"></b> (rev. <span id="chip-rev"></span>)<br />
<span data-i18n>index.system.chip.cores</span>: <b id="chip-cores"></b>, <span data-i18n>index.system.chip.freq</span>: <b id="chip-freq"></b> <span data-i18n>units.mhz</span><br />
<span data-i18n>index.system.flash.size</span>: <b id="flash-size"></b> <span data-i18n>units.mbyte</span>
</td>
</tr>
<tr>
<th scope="row" data-i18n>index.system.lastResetReason</th>
<td>
<b id="reset-reason"></b><br />
<a href="/api/coredump" target="_blank"><small data-i18n>index.system.coreDump</small></a>
</td>
</tr>
</tbody>
</table>
<div class="grid" style="grid-template-columns: repeat(auto-fit,minmax(12rem,1fr)) !important;">
<a href="/dashboard.html" role="button" data-i18n>dashboard.name</a>
<a href="/settings.html" role="button" data-i18n>settings.name</a>
<a href="/sensors.html" role="button" data-i18n>sensors.name</a>
<a href="/logs.html" role="button" data-i18n>logs.name</a>
<a href="/upgrade.html" role="button" data-i18n>upgrade.name</a>
<a href="#" role="button" class="secondary restart" data-i18n>button.restart</a>
</div>
</div>
</article>
</main>
<footer class="container">
<small>
<b>Made by Laxilef</b>
• <a href="https://github.com/Laxilef/OTGateway/blob/master/LICENSE" target="_blank" class="secondary" data-i18n>nav.license</a>
• <a href="https://github.com/Laxilef/OTGateway/blob/master/" target="_blank" class="secondary" data-i18n>nav.source</a>
• <a href="https://github.com/Laxilef/OTGateway/wiki" target="_blank" class="secondary" data-i18n>nav.help</a>
• <a href="https://github.com/Laxilef/OTGateway/issues" target="_blank" class="secondary" data-i18n>nav.issues</a>
• <a href="https://github.com/Laxilef/OTGateway/releases" target="_blank" class="secondary" data-i18n>nav.releases</a>
</small>
</footer>
<script src="/static/app.js?{BUILD_TIME}"></script>
<script>
document.addEventListener('DOMContentLoaded', async () => {
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", {
cache: "no-cache",
credentials: "include"
});
if (!response.ok) {
throw new Error('Response not valid');
}
const result = await response.json();
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));
setTextValue('#network-hostname', result.network.hostname);
setTextValue('#network-mac', result.network.mac);
setStatus(
'#network-connected',
result.network.connected ? "success" : "error",
result.network.connected ? "green" : "red"
);
setTextValue('#network-ssid', result.network.ssid);
setValue('#network-signal', result.network.signal_quality);
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);
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.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('#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);
setBusy('#system-busy', '#system-table', false);
} catch (error) {
console.log(error);
}
setTimeout(onLoadPage, 10000);
}, 1000);
});
</script>
</body>
</html>
-664
View File
@@ -1,664 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title data-i18n>logs.title</title>
<link rel="stylesheet" href="/static/app.css?{BUILD_TIME}" />
<style>
#log-console {
background: #15191e;
color: #e5e7eb;
border-radius: var(--pico-border-radius);
margin-bottom: 1rem;
}
#log-console-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.5rem;
border-bottom: 1px solid var(--pico-muted-border-color);
}
#connection-status {
display: inline-block;
width: 0.65rem;
height: 0.65rem;
border: 0;
border-radius: 50%;
background: var(--pico-form-element-invalid-border-color);
}
#connection-status[data-state="connected"] {
background: var(--pico-form-element-valid-border-color);
}
#log-output {
position: relative;
height: 55vh;
min-height: 10rem;
resize: vertical;
overflow: auto;
padding: 0.5rem;
font: 0.6rem/1.4 monospace;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
#log-output > .search-match {
background: var(--pico-primary-focus);
outline: 1px solid var(--pico-primary);
outline-offset: -1px;
}
#log-output > div {
min-height: 1.4em;
}
#search-count {
white-space: nowrap;
}
#search-logs {
min-width: 0;
}
#log-controls label {
margin-bottom: 0.5rem;
}
#log-search-controls > button {
flex: 0 0 auto;
width: auto;
padding-inline: 0.75rem;
}
</style>
</head>
<body>
<header class="container">
<nav>
<ul>
<li>
<a href="/">
<div class="logo" data-i18n>logo</div>
</a>
</li>
</ul>
<ul>
<li>
<select id="lang" aria-label="Lang">
<option value="en" selected>EN</option>
<option value="cn">CN</option>
<option value="it">IT</option>
<option value="nl">NL</option>
<option value="ru">RU</option>
</select>
</li>
</ul>
</nav>
</header>
<main class="container">
<article>
<hgroup>
<h2 data-i18n>logs.name</h2>
<p data-i18n>logs.desc</p>
</hgroup>
<form action="/api/settings/system" method="post" id="log-level-form">
<label for="log-level" data-i18n>settings.system.logLevel</label>
<div role="group">
<select name="loglevel" id="log-level" disabled>
<option value="0">NONE</option>
<option value="1">ERROR</option>
<option value="2">WARN</option>
<option value="3">INFO</option>
<option value="4">DEBUG</option>
<option value="5">VERBOSE</option>
</select>
<button type="submit" disabled data-i18n>button.save</button>
</div>
<small data-i18n>logs.level.note</small>
<div id="log-level-load-error" hidden>
<small id="log-level-error" data-i18n="logs.level.loadError"></small>
<button type="button" id="retry-log-level" class="secondary" data-i18n>button.refresh</button>
</div>
</form>
<hr />
<div id="log-controls" class="grid">
<label>
<input type="checkbox" id="autoscroll" checked />
<span data-i18n>logs.autoscroll</span>
</label>
<label>
<input type="checkbox" id="limit-history" checked />
<span data-i18n>logs.limitHistory</span>
</label>
</div>
<small data-i18n>logs.historyNote</small>
<div class="grid">
<label for="filter-logs">
<span data-i18n>logs.filter</span>
<input type="search" id="filter-logs" />
</label>
<div>
<label for="search-logs" data-i18n>logs.search.title</label>
<div role="group" id="log-search-controls">
<input type="search" id="search-logs" />
<button type="button" id="search-prev" class="secondary" disabled>
<span aria-hidden="true">↑</span>
<span hidden data-i18n>logs.search.previous</span>
</button>
<button type="button" id="search-next" class="secondary" disabled>
<span aria-hidden="true">↓</span>
<span hidden data-i18n>logs.search.next</span>
</button>
</div>
</div>
</div>
<div id="log-console">
<div id="log-console-header">
<small id="search-count" aria-live="polite">0 / 0</small>
<span id="connection-status" role="img" tabindex="0" data-state="connecting" data-placement="left">
<span id="connection-text" hidden data-i18n="logs.status.connecting"></span>
</span>
</div>
<div id="log-output" role="log" aria-live="off" tabindex="0"></div>
</div>
<div role="group" id="log-actions">
<button type="button" id="clear-logs" class="secondary" data-i18n>logs.clear</button>
<button type="button" id="download-logs" data-i18n>logs.download</button>
</div>
</article>
</main>
<footer class="container">
<small>
<b>Made by Laxilef</b>
• <a href="https://github.com/Laxilef/OTGateway/blob/master/LICENSE" target="_blank" class="secondary" data-i18n>nav.license</a>
• <a href="https://github.com/Laxilef/OTGateway/blob/master/" target="_blank" class="secondary" data-i18n>nav.source</a>
• <a href="https://github.com/Laxilef/OTGateway/wiki" target="_blank" class="secondary" data-i18n>nav.help</a>
• <a href="https://github.com/Laxilef/OTGateway/issues" target="_blank" class="secondary" data-i18n>nav.issues</a>
• <a href="https://github.com/Laxilef/OTGateway/releases" target="_blank" class="secondary" data-i18n>nav.releases</a>
</small>
</footer>
<script src="/static/app.js?{BUILD_TIME}"></script>
<script>
document.addEventListener('DOMContentLoaded', async () => {
const lang = new Lang(document.getElementById('lang'));
await lang.build();
const output = document.getElementById('log-output');
const autoscroll = document.getElementById('autoscroll');
const limitHistory = document.getElementById('limit-history');
const filterInput = document.getElementById('filter-logs');
const searchInput = document.getElementById('search-logs');
const searchPrevious = document.getElementById('search-prev');
const searchNext = document.getElementById('search-next');
const searchCount = document.getElementById('search-count');
const status = document.getElementById('connection-status');
const statusText = document.getElementById('connection-text');
const colors = [
'#000000', '#cd3131', '#0dbc79', '#e5e510',
'#2472c8', '#bc3fbc', '#11a8cd', '#e5e5e5',
'#666666', '#f14c4c', '#23d18b', '#f5f543',
'#3b8eea', '#d670d6', '#29b8db', '#ffffff'
];
let escapeState = 'text';
let escapeParams = '';
let foreground = null;
let background = null;
let bold = false;
let socket = null;
let reconnectTimer = null;
let heartbeatTimer = null;
let waitingForPong = false;
let active = true;
let viewTimer = null;
let filterText = '';
let searchText = '';
let matches = [];
let selectedIndex = -1;
let selectedRecord = null;
const updateLabels = () => {
status.setAttribute('data-tooltip', statusText.textContent);
status.setAttribute('aria-label', statusText.textContent);
for (const button of [searchPrevious, searchNext]) {
const text = button.querySelector('[data-i18n]').textContent;
button.setAttribute('data-tooltip', text);
button.setAttribute('aria-label', text);
}
};
const labelObserver = new MutationObserver(updateLabels);
for (const label of [statusText, ...document.querySelectorAll('#log-search-controls [data-i18n]')]) {
labelObserver.observe(label, {childList: true, subtree: true, characterData: true});
}
const setConnectionStatus = (state) => {
status.dataset.state = state;
statusText.setAttribute('data-i18n', `logs.status.${state}`);
lang.translateElement(statusText);
updateLabels();
};
const updateSelection = (scroll = false) => {
const nextRecord = matches[selectedIndex] || null;
if (selectedRecord !== nextRecord) {
if (selectedRecord) {
selectedRecord.classList.remove('search-match');
}
selectedRecord = nextRecord;
if (selectedRecord) {
selectedRecord.classList.add('search-match');
}
}
searchCount.textContent = `${selectedRecord ? selectedIndex + 1 : 0} / ${matches.length}`;
searchPrevious.disabled = matches.length === 0;
searchNext.disabled = matches.length === 0;
if (scroll && selectedRecord) {
autoscroll.checked = false;
output.scrollTop = selectedRecord.offsetTop - (output.clientHeight - selectedRecord.offsetHeight) / 2;
}
};
const pruneHistory = () => {
let removedMatches = 0;
while (limitHistory.checked && output.childElementCount > 1000) {
const record = output.firstElementChild;
if (matches[removedMatches] === record) {
removedMatches++;
}
record.remove();
}
if (removedMatches) {
matches.splice(0, removedMatches);
selectedIndex = matches.length ? Math.max(0, selectedIndex - removedMatches) : -1;
}
};
const applyView = (scrollToSelection = false) => {
clearTimeout(viewTimer);
viewTimer = null;
filterText = filterInput.value.toLowerCase();
searchText = searchInput.value.toLowerCase();
matches = [];
for (const record of output.children) {
const text = record.textContent.toLowerCase();
record.hidden = !text.includes(filterText);
if (!record.hidden && searchText && text.includes(searchText)) {
matches.push(record);
}
}
selectedIndex = matches.indexOf(selectedRecord);
if (selectedIndex < 0 && matches.length) {
selectedIndex = 0;
}
updateSelection(scrollToSelection);
if (autoscroll.checked) {
output.scrollTop = output.scrollHeight;
}
};
const scheduleView = (event) => {
clearTimeout(viewTimer);
const scrollToSelection = event.target === searchInput;
viewTimer = setTimeout(() => applyView(scrollToSelection), 150);
};
filterInput.addEventListener('input', scheduleView);
searchInput.addEventListener('input', scheduleView);
const moveSearch = (direction) => {
if (viewTimer !== null) {
applyView(true);
return;
}
if (!matches.length) {
return;
}
selectedIndex = (selectedIndex + direction + matches.length) % matches.length;
updateSelection(true);
};
searchPrevious.addEventListener('click', () => moveSearch(-1));
searchNext.addEventListener('click', () => moveSearch(1));
searchInput.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
event.preventDefault();
moveSearch(event.shiftKey ? -1 : 1);
}
});
limitHistory.addEventListener('change', () => {
pruneHistory();
updateSelection();
});
const levelForm = document.getElementById('log-level-form');
const levelSelect = document.getElementById('log-level');
const levelSave = levelForm.querySelector('button[type="submit"]');
const levelError = document.getElementById('log-level-load-error');
const levelErrorText = document.getElementById('log-level-error');
const levelRetry = document.getElementById('retry-log-level');
let confirmedLevel = null;
let levelBusy = false;
const setSaveLabel = (key) => {
levelSave.setAttribute('data-i18n', key);
lang.translateElement(levelSave);
};
const updateLevelControls = () => {
levelSelect.disabled = levelBusy || confirmedLevel === null;
levelSave.disabled = levelSelect.disabled;
levelRetry.disabled = levelBusy;
if (levelBusy) {
levelSave.setAttribute('aria-busy', 'true');
} else {
levelSave.removeAttribute('aria-busy');
}
};
const updateLogLevel = async (save = false) => {
if (levelBusy) {
return;
}
const level = Number(levelSelect.value);
if (save && (!Number.isInteger(level) || level < 0 || level > 5)) {
return;
}
levelBusy = true;
levelError.hidden = true;
setSaveLabel(save ? 'button.wait' : 'button.save');
updateLevelControls();
try {
const options = {cache: 'no-cache', credentials: 'include'};
if (save) {
options.method = 'POST';
options.headers = {'Content-Type': 'application/json'};
options.body = JSON.stringify({loglevel: level});
}
const response = await fetch(levelForm.action, options);
if (!response.ok) {
throw new Error('Response not valid');
}
const result = await response.json();
const value = result.loglevel;
if (!Number.isInteger(value) || value < 0 || value > 5) {
throw new Error('Invalid log level');
}
confirmedLevel = value;
levelSelect.value = String(value);
setSaveLabel(save ? 'button.saved' : 'button.save');
} catch (err) {
if (confirmedLevel !== null) {
levelSelect.value = String(confirmedLevel);
}
levelErrorText.setAttribute('data-i18n', save ? 'logs.level.saveError' : 'logs.level.loadError');
lang.translateElement(levelErrorText);
levelError.hidden = false;
setSaveLabel('button.save');
} finally {
levelBusy = false;
updateLevelControls();
}
};
levelForm.addEventListener('submit', (event) => {
event.preventDefault();
updateLogLevel(true);
});
levelRetry.addEventListener('click', () => updateLogLevel());
levelSelect.addEventListener('change', () => setSaveLabel('button.save'));
updateLogLevel();
const resetFormatting = () => {
escapeState = 'text';
escapeParams = '';
foreground = null;
background = null;
bold = false;
};
const applyFormatting = () => {
const codes = escapeParams.split(';').map(Number);
for (let i = 0; i < codes.length; i++) {
const code = codes[i];
if (code === 0) {
foreground = null;
background = null;
bold = false;
} else if (code === 1) {
bold = true;
} else if (code === 22) {
bold = false;
} else if (code === 39) {
foreground = null;
} else if (code === 49) {
background = null;
} else if (code >= 30 && code <= 37) {
foreground = colors[code - 30];
} else if (code >= 90 && code <= 97) {
foreground = colors[code - 90 + 8];
} else if (code >= 40 && code <= 47) {
background = colors[code - 40];
} else if (code >= 100 && code <= 107) {
background = colors[code - 100 + 8];
} else if (code === 38 || code === 48) {
// Skip unsupported extended colors, including their parameters.
if (codes[i + 1] === 5) {
i += 2;
} else if (codes[i + 1] === 2) {
i += 4;
}
}
}
};
const appendLog = (message) => {
const record = document.createElement('div');
let text = '';
const flushText = () => {
if (!text) {
return;
}
if (bold || foreground || background) {
const span = document.createElement('span');
span.textContent = text;
if (bold) {
span.style.fontWeight = 'bold';
}
if (foreground) {
span.style.color = foreground;
}
if (background) {
span.style.backgroundColor = background;
}
record.appendChild(span);
} else {
record.appendChild(document.createTextNode(text));
}
text = '';
};
// Retain parser state when an escape sequence crosses frame boundaries.
for (const symbol of message) {
const code = symbol.charCodeAt(0);
if (escapeState === 'string' || escapeState === 'stringEscape') {
if (symbol === '\x07' || (escapeState === 'stringEscape' && symbol === '\\')) {
escapeState = 'text';
} else {
escapeState = symbol === '\x1b' ? 'stringEscape' : 'string';
}
continue;
}
if (symbol === '\x1b') {
flushText();
escapeState = 'escape';
continue;
}
if (escapeState === 'escape') {
if (symbol === '[') {
escapeState = 'csi';
escapeParams = '';
} else if (']P^_'.includes(symbol)) {
escapeState = 'string';
} else {
escapeState = code >= 0x20 && code <= 0x2f ? 'intermediate' : 'text';
}
continue;
}
if (escapeState === 'intermediate') {
if (code >= 0x30 && code <= 0x7e) {
escapeState = 'text';
}
continue;
}
if (escapeState === 'csi') {
if (code >= 0x40 && code <= 0x7e) {
if (symbol === 'm') {
applyFormatting();
}
escapeState = 'text';
} else if (escapeParams.length < 128) {
escapeParams += symbol;
}
continue;
}
if (symbol === '\n' || symbol === '\t' || (code >= 0x20 && (code < 0x7f || code > 0x9f))) {
text += symbol;
}
}
flushText();
const plainText = record.textContent.toLowerCase();
record.hidden = !plainText.includes(filterText);
output.appendChild(record);
if (!record.hidden && searchText && plainText.includes(searchText)) {
matches.push(record);
if (selectedIndex < 0) {
selectedIndex = 0;
}
}
pruneHistory();
updateSelection();
if (autoscroll.checked) {
output.scrollTop = output.scrollHeight;
}
};
const scheduleReconnect = () => {
setConnectionStatus('disconnected');
if (active && reconnectTimer === null) {
reconnectTimer = setTimeout(() => {
reconnectTimer = null;
connect();
}, 3000);
}
};
const connect = () => {
if (!active || socket) {
return;
}
setConnectionStatus('connecting');
resetFormatting();
try {
socket = new WebSocket(`${location.protocol === 'https:' ? 'wss:' : 'ws:'}//${location.host}/webserial`);
} catch (err) {
scheduleReconnect();
return;
}
socket.onopen = () => {
setConnectionStatus('connected');
waitingForPong = false;
heartbeatTimer = setInterval(() => {
if (socket.readyState !== WebSocket.OPEN) {
return;
}
if (waitingForPong) {
socket.close();
return;
}
waitingForPong = true;
socket.send('ping');
}, 10000);
};
socket.onmessage = (event) => {
if (event.data === 'pong') {
waitingForPong = false;
} else if (typeof event.data === 'string') {
appendLog(event.data);
}
};
socket.onerror = () => socket.close();
socket.onclose = () => {
clearInterval(heartbeatTimer);
heartbeatTimer = null;
socket = null;
scheduleReconnect();
};
};
document.getElementById('clear-logs').addEventListener('click', () => {
output.replaceChildren();
applyView();
resetFormatting();
});
document.getElementById('download-logs').addEventListener('click', () => {
const text = Array.from(output.children, (record) => record.textContent).join('\n');
const url = URL.createObjectURL(new Blob([text], {type: 'text/plain;charset=utf-8'}));
const link = document.createElement('a');
link.href = url;
link.download = `otgateway-logs-${new Date().toISOString().replace(/[:.]/g, '-')}.txt`;
document.body.appendChild(link);
link.click();
link.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
});
autoscroll.addEventListener('change', () => {
if (autoscroll.checked) {
output.scrollTop = output.scrollHeight;
}
});
window.addEventListener('pagehide', () => {
active = false;
clearTimeout(reconnectTimer);
clearInterval(heartbeatTimer);
clearTimeout(viewTimer);
reconnectTimer = null;
heartbeatTimer = null;
viewTimer = null;
if (socket) {
socket.onopen = null;
socket.onmessage = null;
socket.onerror = null;
socket.onclose = null;
socket.close();
socket = null;
}
});
window.addEventListener('pageshow', (event) => {
if (event.persisted) {
active = true;
applyView();
connect();
}
});
connect();
});
</script>
</body>
</html>
-228
View File
@@ -1,228 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title data-i18n>network.title</title>
<link rel="stylesheet" href="/static/app.css?{BUILD_TIME}" />
</head>
<body>
<header class="container">
<nav>
<ul>
<li>
<a href="/">
<div class="logo" data-i18n>logo</div>
</a>
</li>
</ul>
<ul>
<li>
<select id="lang" aria-label="Lang">
<option value="en" selected>EN</option>
<option value="cn">CN</option>
<option value="it">IT</option>
<option value="nl">NL</option>
<option value="ru">RU</option>
</select>
</li>
</ul>
</nav>
</header>
<main class="container">
<article>
<div>
<hgroup>
<h2 data-i18n>network.name</h2>
<p></p>
</hgroup>
<div id="network-settings-busy" aria-busy="true"></div>
<form action="/api/network/settings" id="network-settings" class="hidden">
<label>
<span data-i18n>network.params.hostname</span>
<input type="text" name="hostname" maxlength="24" pattern="[A-Za-z0-9]+[A-Za-z0-9\-]+[A-Za-z0-9]+" required>
</label>
<label>
<input type="checkbox" name="use_dhcp" value="true">
<span data-i18n>network.params.dhcp</span>
</label>
<br />
<hr />
<h4 data-i18n>network.section.static</h4>
<label>
<span data-i18n>network.params.ip</span>
<input type="text" name="static_config[ip]" value="true" maxlength="16" pattern="\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" required>
</label>
<label>
<span data-i18n>network.params.gateway</span>
<input type="text" name="static_config[gateway]" maxlength="16" pattern="\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" required>
</label>
<label>
<span data-i18n>network.params.subnet</span>
<input type="text" name="static_config[subnet]" maxlength="16" pattern="\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" required>
</label>
<label>
<span data-i18n>network.params.dns</span>
<input type="text" name="static_config[dns]" maxlength="16" pattern="\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" required>
</label>
<button type="submit" data-i18n>button.save</button>
</form>
</div>
</article>
<article>
<div>
<hgroup>
<h3 data-i18n>network.section.availableNetworks</h3>
<p></p>
</hgroup>
<form action="/api/network/scan" id="network-scan">
<div style="max-height: 25rem;" class="overflow-auto">
<table id="networks" role="grid">
<thead>
<tr>
<th scope="col" data-i18n>network.scan.pos</th>
<th scope="col" data-i18n>network.wifi.ssid</th>
<th scope="col" data-i18n>network.scan.info</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<button type="submit" data-i18n>button.refresh</button>
</form>
<hr />
<div>
<hgroup>
<h2 data-i18n>network.section.staSettings</h2>
<p></p>
</hgroup>
<div id="sta-settings-busy" aria-busy="true"></div>
<form action="/api/network/settings" id="sta-settings" class="hidden">
<label>
<span data-i18n>network.wifi.ssid</span>
<input type="text" name="sta[ssid]" maxlength="32" required>
</label>
<label>
<span data-i18n>network.wifi.password</span>
<input type="password" name="sta[password]" maxlength="64" required>
</label>
<label>
<span data-i18n>network.wifi.channel</span>
<input type="number" inputmode="numeric" name="sta[channel]" min="0" max="12" step="1" required>
<small data-i18n>network.sta.channel.note</small>
</label>
<button type="submit" data-i18n>button.save</button>
</form>
</div>
</div>
</article>
<article>
<div>
<hgroup>
<h2 data-i18n>network.section.apSettings</h2>
<p></p>
</hgroup>
<div id="ap-settings-busy" aria-busy="true"></div>
<form action="/api/network/settings" id="ap-settings" class="hidden">
<label>
<span data-i18n>network.wifi.ssid</span>
<input type="text" name="ap[ssid]" maxlength="32" required>
</label>
<label>
<span data-i18n>network.wifi.password</span>
<input type="text" name="ap[password]" maxlength="64" required>
</label>
<label>
<span data-i18n>network.wifi.channel</span>
<input type="number" inputmode="numeric" name="ap[channel]" min="1" max="12" step="1" required>
</label>
<button type="submit" data-i18n>button.save</button>
</form>
</div>
</article>
</main>
<footer class="container">
<small>
<b>Made by Laxilef</b>
• <a href="https://github.com/Laxilef/OTGateway/blob/master/LICENSE" target="_blank" class="secondary" data-i18n>nav.license</a>
• <a href="https://github.com/Laxilef/OTGateway/blob/master/" target="_blank" class="secondary" data-i18n>nav.source</a>
• <a href="https://github.com/Laxilef/OTGateway/wiki" target="_blank" class="secondary" data-i18n>nav.help</a>
• <a href="https://github.com/Laxilef/OTGateway/issues" target="_blank" class="secondary" data-i18n>nav.issues</a>
• <a href="https://github.com/Laxilef/OTGateway/releases" target="_blank" class="secondary" data-i18n>nav.releases</a>
</small>
</footer>
<script src="/static/app.js?{BUILD_TIME}"></script>
<script>
document.addEventListener('DOMContentLoaded', async () => {
const lang = new Lang(document.getElementById('lang'));
await lang.build();
const fillData = (data) => {
setInputValue("[name='hostname']", data.hostname);
setCheckboxValue("[name='use_dhcp']", data.use_dhcp);
setInputValue("[name='static_config[ip]']", data.static_config.ip);
setInputValue("[name='static_config[gateway]']", data.static_config.gateway);
setInputValue("[name='static_config[subnet]']", data.static_config.subnet);
setInputValue("[name='static_config[dns]']", data.static_config.dns);
setBusy('#network-settings-busy', '#network-settings', false);
setInputValue("[name='sta[ssid]']", data.sta.ssid);
setInputValue("[name='sta[password]']", data.sta.password);
setInputValue("[name='sta[channel]']", data.sta.channel);
setBusy('#sta-settings-busy', '#sta-settings', false);
setInputValue("[name='ap[ssid]']", data.ap.ssid);
setInputValue("[name='ap[password]']", data.ap.password);
setInputValue("[name='ap[channel]']", data.ap.channel);
setBusy('#ap-settings-busy', '#ap-settings', false);
};
try {
const response = await fetch("/api/network/settings", {
cache: "no-cache",
credentials: "include"
});
if (!response.ok) {
throw new Error('Response not valid');
}
const result = await response.json();
fillData(result);
setupForm('#network-settings', fillData, ['hostname', 'static_config.ip', 'static_config.gateway', 'static_config.subnet', 'static_config.dns']);
setupNetworkScanForm('#network-scan', '#networks');
setupForm('#sta-settings', fillData, ['sta.ssid', 'sta.password']);
setupForm('#ap-settings', fillData, ['ap.ssid', 'ap.password']);
} catch (error) {
console.log(error);
}
});
</script>
</body>
</html>
-347
View File
@@ -1,347 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title data-i18n>sensors.title</title>
<link rel="stylesheet" href="/static/app.css?{BUILD_TIME}" />
</head>
<body>
<header class="container">
<nav>
<ul>
<li>
<a href="/">
<div class="logo" data-i18n>logo</div>
</a>
</li>
</ul>
<ul>
<li>
<select id="lang" aria-label="Lang">
<option value="en" selected>EN</option>
<option value="cn">CN</option>
<option value="it">IT</option>
<option value="nl">NL</option>
<option value="ru">RU</option>
</select>
</li>
</ul>
</nav>
</header>
<main class="container">
<article>
<hgroup>
<h2 data-i18n>sensors.name</h2>
<p></p>
</hgroup>
<details id="template" class="sensor hidden" data-id="" data-preloaded="0">
<summary><b>#<span class="pos"></span>: <span class="name"></span></b></summary>
<div>
<div class="form-busy" aria-busy="true"></div>
<form action="/api/sensor?id={id}" class="hidden">
<fieldset>
<label>
<input type="checkbox" role="switch" name="enabled" value="true">
<span data-i18n>sensors.enabled</span>
</label>
<br />
<label>
<span data-i18n>sensors.sensorName.title</span>
<input type="text" name="name" maxlength="32" required>
<small data-i18n>sensors.sensorName.note</small>
</label>
<div class="grid">
<label>
<span data-i18n>sensors.purpose</span>
<select name="purpose" required>
<option value="0" data-i18n>sensors.purposes.outdoorTemp</option>
<option value="1" data-i18n>sensors.purposes.indoorTemp</option>
<option value="2" data-i18n>sensors.purposes.heatTemp</option>
<option value="3" data-i18n>sensors.purposes.heatRetTemp</option>
<option value="4" data-i18n>sensors.purposes.dhwTemp</option>
<option value="5" data-i18n>sensors.purposes.dhwRetTemp</option>
<option value="6" data-i18n>sensors.purposes.dhwFlowRate</option>
<option value="7" data-i18n>sensors.purposes.exhaustTemp</option>
<option value="8" data-i18n>sensors.purposes.modLevel</option>
<option value="247" data-i18n>sensors.purposes.number</option>
<option value="248" data-i18n>sensors.purposes.powerFactor</option>
<option value="249" data-i18n>sensors.purposes.power</option>
<option value="250" data-i18n>sensors.purposes.fanSpeed</option>
<option value="251" data-i18n>sensors.purposes.co2</option>
<option value="252" data-i18n>sensors.purposes.pressure</option>
<option value="253" data-i18n>sensors.purposes.humidity</option>
<option value="254" data-i18n>sensors.purposes.temperature</option>
<option value="255" data-i18n>sensors.purposes.notConfigured</option>
</select>
</label>
<label>
<span data-i18n>sensors.type</span>
<select name="type" required>
<option value="0" data-i18n>sensors.types.otOutdoorTemp</option>
<option value="1" data-i18n>sensors.types.otHeatTemp</option>
<option value="2" data-i18n>sensors.types.otHeatRetTemp</option>
<option value="3" data-i18n>sensors.types.otDhwTemp</option>
<option value="4" data-i18n>sensors.types.otDhwTemp2</option>
<option value="5" data-i18n>sensors.types.otDhwFlowRate</option>
<option value="6" data-i18n>sensors.types.otCh2Temp</option>
<option value="7" data-i18n>sensors.types.otExhaustTemp</option>
<option value="8" data-i18n>sensors.types.otHeatExchangerTemp</option>
<option value="9" data-i18n>sensors.types.otPressure</option>
<option value="10" data-i18n>sensors.types.otModLevel</option>
<option value="11" data-i18n>sensors.types.otCurrentPower</option>
<option value="12" data-i18n>sensors.types.otExhaustCo2</option>
<option value="13" data-i18n>sensors.types.otExhaustFanSpeed</option>
<option value="14" data-i18n>sensors.types.otSupplyFanSpeed</option>
<option value="15" data-i18n>sensors.types.otSolarStorageTemp</option>
<option value="16" data-i18n>sensors.types.otSolarCollectorTemp</option>
<option value="17" data-i18n>sensors.types.otFanSpeedSetpoint</option>
<option value="18" data-i18n>sensors.types.otFanSpeedCurrent</option>
<option value="19" data-i18n>sensors.types.otBurnerStarts</option>
<option value="20" data-i18n>sensors.types.otDhwBurnerStarts</option>
<option value="21" data-i18n>sensors.types.otHeatingPumpStarts</option>
<option value="22" data-i18n>sensors.types.otDhwPumpStarts</option>
<option value="23" data-i18n>sensors.types.otBurnerHours</option>
<option value="24" data-i18n>sensors.types.otDhwBurnerHours</option>
<option value="25" data-i18n>sensors.types.otHeatingPumpHours</option>
<option value="26" data-i18n>sensors.types.otDhwPumpHours</option>
<option value="27" data-i18n>sensors.types.otCoolingHours</option>
<option value="50" data-i18n>sensors.types.ntcTemp</option>
<option value="51" data-i18n>sensors.types.dallasTemp</option>
<option value="52" data-i18n>sensors.types.bluetooth</option>
<option value="53" data-i18n>sensors.types.dht11</option>
<option value="54" data-i18n>sensors.types.dht22</option>
<option value="253" data-i18n>sensors.types.heatSetpointTemp</option>
<option value="254" data-i18n>sensors.types.manual</option>
<option value="255" data-i18n>sensors.types.notConfigured</option>
</select>
</label>
</div>
</fieldset>
<div class="grid">
<label>
<span data-i18n>sensors.gpio</span>
<input type="number" outputmode="numeric" name="gpio" min="0" max="254" step="1">
</label>
<label>
<span data-i18n>sensors.address.title</span>
<input type="text" name="address">
<small data-i18n>sensors.address.note</small>
</label>
</div>
<hr class="correction" />
<details class="correction">
<summary><b data-i18n>sensors.correction.desc</b></summary>
<div class="grid">
<label>
<span data-i18n>sensors.correction.offset</span>
<input type="number" inputmode="decimal" name="offset" min="-20" max="20" step="0.01" required>
</label>
<label>
<span data-i18n>sensors.correction.factor</span>
<input type="number" inputmode="decimal" name="factor" min="0.01" max="100" step="0.01" required>
</label>
</div>
</details>
<hr class="filtering" />
<details class="filtering">
<summary><b data-i18n>sensors.filtering.desc</b></summary>
<div>
<label>
<input type="checkbox" name="filtering" value="true">
<span data-i18n>sensors.filtering.enabled.title</span>
<br />
<small data-i18n>sensors.filtering.enabled.note</small>
</label>
<label>
<span data-i18n>sensors.filtering.factor.title</span>
<input type="number" inputmode="decimal" name="filtering_factor" min="0.01" max="1" step="0.01">
<small data-i18n>sensors.filtering.factor.note</small>
</label>
</div>
</details>
<br/>
<button type="submit" data-i18n>button.save</button>
</form>
</div>
</details>
</article>
</main>
<footer class="container">
<small>
<b>Made by Laxilef</b>
• <a href="https://github.com/Laxilef/OTGateway/blob/master/LICENSE" target="_blank" class="secondary" data-i18n>nav.license</a>
• <a href="https://github.com/Laxilef/OTGateway/blob/master/" target="_blank" class="secondary" data-i18n>nav.source</a>
• <a href="https://github.com/Laxilef/OTGateway/wiki" target="_blank" class="secondary" data-i18n>nav.help</a>
• <a href="https://github.com/Laxilef/OTGateway/issues" target="_blank" class="secondary" data-i18n>nav.issues</a>
• <a href="https://github.com/Laxilef/OTGateway/releases" target="_blank" class="secondary" data-i18n>nav.releases</a>
</small>
</footer>
<script src="/static/app.js?{BUILD_TIME}"></script>
<script>
document.addEventListener("DOMContentLoaded", async () => {
const lang = new Lang(document.getElementById("lang"));
await lang.build();
const container = document.querySelector("article");
const templateNode = container.querySelector("#template");
try {
const response = await fetch("/api/sensors", {
cache: "no-cache",
credentials: "include"
});
if (!response.ok) {
throw new Error("Response not valid");
}
const result = await response.json();
for (const sensorId in result) {
const sensorNode = templateNode.cloneNode(true);
sensorNode.removeAttribute("id");
sensorNode.classList.remove("hidden");
sensorNode.dataset.id = sensorId;
setValue(".id", sensorId, sensorNode);
setValue(".pos", parseInt(sensorId) + 1, sensorNode);
setTextValue(".name", result[sensorId], sensorNode);
container.appendChild(sensorNode);
container.appendChild(document.createElement("hr"));
const sensorForm = sensorNode.querySelector("form");
const fillData = (data) => {
setCheckboxValue("[name='enabled']", data.enabled, sensorForm);
setInputValue("[name='name']", data.name, {}, sensorForm);
setSelectValue("[name='purpose']", data.purpose, sensorForm);
setSelectValue("[name='type']", data.type, sensorForm);
setInputValue("[name='gpio']", data.gpio < 255 ? data.gpio : "", {}, sensorForm);
setInputValue("[name='address']", data.address, {}, sensorForm);
setInputValue("[name='offset']", data.offset, {}, sensorForm);
setInputValue("[name='factor']", data.factor, {}, sensorForm);
setCheckboxValue("[name='filtering']", data.filtering, sensorForm);
setInputValue("[name='filtering_factor']", data.filtering_factor, {}, sensorForm);
setTimeout(() => {
sensorForm.querySelector("[name='type']").dispatchEvent(new Event("change"));
}, 10);
setBusy(".form-busy", "form", false, sensorNode);
};
sensorForm.action = sensorForm.action.replace("{id}", sensorId);
sensorForm.querySelector("[name='type']").addEventListener("change", async (event) => {
const gpio = sensorForm.querySelector("[name='gpio']");
const address = sensorForm.querySelector("[name='address']");
const parentGpio = gpio.parentElement;
const parentAddress = address.parentElement;
switch(parseInt(event.target.value)) {
// heating setpoint, manual
case 253:
case 254:
hide(".correction", sensorForm);
hide(".filtering", sensorForm);
break;
// other
default:
show(".correction", sensorForm);
show(".filtering", sensorForm);
}
switch(parseInt(event.target.value)) {
// NTC10K
case 50:
parentGpio.classList.remove("hidden");
parentAddress.classList.add("hidden");
address.removeAttribute("pattern");
break;
// 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;
// Bluetooth
case 52:
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");
parentAddress.classList.add("hidden");
address.removeAttribute("pattern");
break;
}
});
sensorNode.addEventListener("click", async (event) => {
if (parseInt(sensorNode.dataset.preloaded)) {
return;
}
try {
const response = await fetch(sensorForm.action, {
cache: "no-cache",
credentials: "include"
});
if (response.status != 200) {
return;
}
const result = await response.json();
fillData(result);
sensorNode.dataset.preloaded = 1;
} catch (error) {
console.log(error);
}
});
setupForm(`.sensor[data-id='${sensorId}'] form`, fillData, ['name', 'address']);
}
} catch (error) {
console.log(error);
}
});
</script>
</body>
</html>
File diff suppressed because it is too large. Load diff
-418
View File
@@ -1,418 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title data-i18n>upgrade.title</title>
<link rel="stylesheet" href="/static/app.css?{BUILD_TIME}">
</head>
<body>
<header class="container">
<nav>
<ul>
<li>
<a href="/">
<div class="logo" data-i18n>logo</div>
</a>
</li>
</ul>
<ul>
<li>
<select id="lang" aria-label="Lang">
<option value="en" selected>EN</option>
<option value="cn">CN</option>
<option value="it">IT</option>
<option value="nl">NL</option>
<option value="ru">RU</option>
</select>
</li>
</ul>
</nav>
</header>
<main class="container">
<article>
<div>
<hgroup>
<h2 data-i18n>upgrade.section.backupAndRestore.title</h2>
<p data-i18n>upgrade.section.backupAndRestore.desc</p>
</hgroup>
<form id="restore">
<label for="restore-file">
<span data-i18n>upgrade.settingsFile</span>
<input type="file" name="settings" id="restore-file" accept=".json">
</label>
<div role="group">
<button type="submit" data-i18n>button.restore</button>
<button type="button" class="secondary" onclick="window.location='/api/backup/save';" data-i18n>button.backup</button>
</div>
</form>
</div>
</article>
<article>
<div>
<hgroup>
<h2 data-i18n>upgrade.section.upgrade.title</h2>
<p data-i18n>upgrade.section.upgrade.desc</p>
</hgroup>
<form action="/api/upgrade" id="upgrade">
<fieldset class="primary">
<label>
<span data-i18n>upgrade.fw</span>:
<div class="grid">
<input type="file" name="fw" accept=".bin">
<button type="button" class="fwResult hidden" disabled></button>
</div>
</label>
<label>
<span data-i18n>upgrade.fs</span>:
<div class="grid">
<input type="file" name="fs" accept=".bin">
<button type="button" class="fsResult hidden" disabled></button>
</div>
</label>
</fieldset>
<ul>
<li><mark data-i18n>upgrade.note.disclaimer1</mark></li>
<li><mark data-i18n>upgrade.note.disclaimer2</mark></li>
</ul>
<button type="submit" data-i18n>button.upgrade</button>
</form>
</div>
</article>
</main>
<footer class="container">
<small>
<b>Made by Laxilef</b>
• <a href="https://github.com/Laxilef/OTGateway/blob/master/LICENSE" target="_blank" class="secondary" data-i18n>nav.license</a>
• <a href="https://github.com/Laxilef/OTGateway/blob/master/" target="_blank" class="secondary" data-i18n>nav.source</a>
• <a href="https://github.com/Laxilef/OTGateway/wiki" target="_blank" class="secondary" data-i18n>nav.help</a>
• <a href="https://github.com/Laxilef/OTGateway/issues" target="_blank" class="secondary" data-i18n>nav.issues</a>
• <a href="https://github.com/Laxilef/OTGateway/releases" target="_blank" class="secondary" data-i18n>nav.releases</a>
</small>
</footer>
<script src="/static/app.js?{BUILD_TIME}"></script>
<script src="/static/settings-converter.js?{BUILD_TIME}"></script>
<script>
const setupRestoreBackupForm = (formSelector) => {
const form = document.querySelector(formSelector);
if (!form) {
return;
}
const button = form.querySelector('button[type="submit"]');
form.addEventListener('submit', (event) => {
event.preventDefault();
const defaultText = button ? button.textContent : '';
if (button) {
button.textContent = i18n('button.wait');
button.setAttribute('disabled', true);
button.setAttribute('aria-busy', true);
}
const onFinished = (success) => {
if (button) {
button.textContent = i18n(success ? 'button.restored' : 'button.error');
button.classList.add(success ? 'success' : 'failed');
button.removeAttribute('aria-busy');
setTimeout(() => {
button.removeAttribute('disabled');
button.classList.remove('success', 'failed');
button.textContent = defaultText;
}, 5000);
}
};
const files = form.querySelector('#restore-file').files;
if (files.length === 0) {
onFinished(false);
return;
}
const reader = new FileReader();
reader.onload = async (event) => {
try {
const data = convertLegacyBackup(JSON.parse(event.target.result));
const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
if (!isObject(data)) {
throw new Error('Backup not valid');
}
let hasData = false;
if (data.settings !== undefined) {
if (!isObject(data.settings)) {
throw new Error('Backup settings not valid');
}
for (const section of Object.values(data.settings)) {
if (!isObject(section) || Object.keys(section).length === 0) {
throw new Error('Backup section not valid');
}
hasData = true;
}
}
if (data.sensors !== undefined) {
if (!isObject(data.sensors) && !Array.isArray(data.sensors)) {
throw new Error('Backup sensors not valid');
}
for (const [sensorId, sensor] of Object.entries(data.sensors)) {
if (!/^\d+$/.test(sensorId) || !isObject(sensor) || Object.keys(sensor).length === 0) {
throw new Error('Backup sensor not valid');
}
hasData = true;
}
}
if (data.network !== undefined) {
if (!isObject(data.network) || Object.keys(data.network).length === 0) {
throw new Error('Backup network not valid');
}
hasData = true;
}
if (!hasData) {
throw new Error('Backup is empty');
}
const headers = {
'Content-Type': 'application/json'
};
const post = async (url, payload) => {
const response = await fetch(url, {
method: 'POST',
cache: 'no-cache',
credentials: 'include',
headers,
body: payload === undefined ? undefined : JSON.stringify(payload)
});
if (!response.ok) {
throw new Error('Restore request failed');
}
return response;
};
if (data.settings !== undefined) {
// Units and regulator modes must precede temperature limits and targets.
const prioritySections = ['system', 'opentherm', 'equitherm', 'pid'];
for (const sectionName of prioritySections) {
if (data.settings[sectionName] === undefined) {
continue;
}
await post(`/api/settings/${sectionName}?noresponse`, data.settings[sectionName]);
}
for (const [sectionName, section] of Object.entries(data.settings)) {
if (sectionName === 'portal' || prioritySections.includes(sectionName)) {
continue;
}
await post(`/api/settings/${encodeURIComponent(sectionName)}?noresponse`, section);
}
// Restore targets again after mode and limit normalization.
for (const sectionName of ['emergency', 'heating', 'dhw']) {
const target = data.settings[sectionName]?.target;
if (target !== undefined) {
await post(`/api/settings/${sectionName}?noresponse`, {target});
}
}
}
if (data.sensors !== undefined) {
for (const [sensorId, sensor] of Object.entries(data.sensors)) {
await post(`/api/sensor?id=${encodeURIComponent(sensorId)}&noresponse`, sensor);
}
}
if (data.settings?.portal !== undefined) {
const response = await post('/api/settings/portal', data.settings.portal);
const portal = await response.json();
if (!isObject(portal) || typeof portal.auth !== 'boolean'
|| typeof portal.login !== 'string' || typeof portal.password !== 'string') {
throw new Error('Portal response not valid');
}
if (portal.auth) {
// Basic authentication encodes UTF-8 bytes, not UTF-16 code units.
const bytes = new TextEncoder().encode(`${portal.login}:${portal.password}`);
let credentials = '';
for (const byte of bytes) {
credentials += String.fromCharCode(byte);
}
headers.Authorization = `Basic ${btoa(credentials)}`;
}
}
if (data.network !== undefined) {
// Network requests are limited to 512 bytes, including escaped strings.
for (const [key, value] of Object.entries(data.network)) {
if (isObject(value)) {
for (const [field, fieldValue] of Object.entries(value)) {
await post('/api/network/settings?noreconnect&noresponse', {[key]: {[field]: fieldValue}});
}
} else {
await post('/api/network/settings?noreconnect&noresponse', {[key]: value});
}
}
}
await post('/api/restart');
onFinished(true);
} catch {
onFinished(false);
}
};
reader.onerror = () => {
onFinished(false);
};
reader.onabort = () => {
onFinished(false);
};
try {
reader.readAsText(files[0]);
} catch {
onFinished(false);
}
});
};
document.addEventListener('DOMContentLoaded', async () => {
const lang = new Lang(document.getElementById('lang'));
await lang.build();
setupRestoreBackupForm('#restore');
const upgradeForm = document.querySelector('#upgrade');
if (upgradeForm) {
upgradeForm.reset();
const statusToText = (status) => {
switch (status) {
case 0:
return "None";
case 1:
return "No file";
case 2:
return "Success";
case 3:
return "Prohibited";
case 4:
return "Size mismatch";
case 5:
return "Error on start";
case 6:
return "Error on write";
case 7:
return "Error on finish";
default:
return "Unknown";
}
};
upgradeForm.addEventListener('submit', async (event) => {
event.preventDefault();
hide('.fwResult');
hide('.fsResult');
let button = upgradeForm.querySelector('button[type="submit"]');
button.textContent = i18n('button.uploading');
button.setAttribute('disabled', true);
button.setAttribute('aria-busy', true);
try {
let fd = new FormData();
const fw = upgradeForm.querySelector("[name='fw']").files;
if (fw.length > 0) {
fd.append("fw_size", fw[0].size);
fd.append("fw", fw[0]);
}
const fs = upgradeForm.querySelector("[name='fs']").files;
if (fs.length > 0) {
fd.append("fs_size", fs[0].size);
fd.append("fs", fs[0]);
}
let response = await fetch(upgradeForm.action, {
method: "POST",
cache: "no-cache",
credentials: "include",
body: fd
});
if (response.status != 202 && response.status != 406) {
throw new Error('Response not valid');
}
const result = await response.json();
let resItem = upgradeForm.querySelector('.fwResult');
if (resItem && result.firmware.status > 1) {
resItem.textContent = statusToText(result.firmware.status);
resItem.classList.remove('hidden');
if (result.firmware.status == 2) {
resItem.classList.remove('failed');
resItem.classList.add('success');
} else {
resItem.classList.remove('success');
resItem.classList.add('failed');
if (result.firmware.error != "") {
resItem.textContent += `: ${result.firmware.error}`;
}
}
}
resItem = upgradeForm.querySelector('.fsResult');
if (resItem && result.filesystem.status > 1) {
resItem.textContent = statusToText(result.filesystem.status);
resItem.classList.remove('hidden');
if (result.filesystem.status == 2) {
resItem.classList.remove('failed');
resItem.classList.add('success');
} else {
resItem.classList.remove('success');
resItem.classList.add('failed');
if (result.filesystem.error != "") {
resItem.textContent += `: ${result.filesystem.error}`;
}
}
}
} catch (err) {
console.log(err);
button.textContent = i18n('button.error');
button.classList.add('failed');
} finally {
setTimeout(() => {
button.removeAttribute('aria-busy');
button.removeAttribute('disabled');
button.classList.remove('success', 'failed');
button.textContent = i18n(button.dataset.i18n);
upgradeForm.reset();
}, 10000);
}
});
}
});
</script>
</body>
</html>
-2
View File
@@ -1,2 +0,0 @@
User-agent: *
Disallow: /
-14
View File
@@ -1,14 +0,0 @@
/*!
* Chart.js v4.5.0
* https://www.chartjs.org
* (c) 2025 Chart.js Contributors
* Released under the MIT License
*/
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).Chart=e()}(this,(function(){"use strict";var t=Object.freeze({__proto__:null,get Colors(){return Jo},get Decimation(){return ta},get Filler(){return ba},get Legend(){return Ma},get SubTitle(){return Pa},get Title(){return ka},get Tooltip(){return Na}});function e(){}const i=(()=>{let t=0;return()=>t++})();function s(t){return null==t}function n(t){if(Array.isArray&&Array.isArray(t))return!0;const e=Object.prototype.toString.call(t);return"[object"===e.slice(0,7)&&"Array]"===e.slice(-6)}function o(t){return null!==t&&"[object Object]"===Object.prototype.toString.call(t)}function a(t){return("number"==typeof t||t instanceof Number)&&isFinite(+t)}function r(t,e){return a(t)?t:e}function l(t,e){return void 0===t?e:t}const h=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100:+t/e,c=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100*e:+t;function d(t,e,i){if(t&&"function"==typeof t.call)return t.apply(i,e)}function u(t,e,i,s){let a,r,l;if(n(t))if(r=t.length,s)for(a=r-1;a>=0;a--)e.call(i,t[a],a);else for(a=0;a<r;a++)e.call(i,t[a],a);else if(o(t))for(l=Object.keys(t),r=l.length,a=0;a<r;a++)e.call(i,t[l[a]],l[a])}function f(t,e){let i,s,n,o;if(!t||!e||t.length!==e.length)return!1;for(i=0,s=t.length;i<s;++i)if(n=t[i],o=e[i],n.datasetIndex!==o.datasetIndex||n.index!==o.index)return!1;return!0}function g(t){if(n(t))return t.map(g);if(o(t)){const e=Object.create(null),i=Object.keys(t),s=i.length;let n=0;for(;n<s;++n)e[i[n]]=g(t[i[n]]);return e}return t}function p(t){return-1===["__proto__","prototype","constructor"].indexOf(t)}function m(t,e,i,s){if(!p(t))return;const n=e[t],a=i[t];o(n)&&o(a)?x(n,a,s):e[t]=g(a)}function x(t,e,i){const s=n(e)?e:[e],a=s.length;if(!o(t))return t;const r=(i=i||{}).merger||m;let l;for(let e=0;e<a;++e){if(l=s[e],!o(l))continue;const n=Object.keys(l);for(let e=0,s=n.length;e<s;++e)r(n[e],t,l,i)}return t}function b(t,e){return x(t,e,{merger:_})}function _(t,e,i){if(!p(t))return;const s=e[t],n=i[t];o(s)&&o(n)?b(s,n):Object.prototype.hasOwnProperty.call(e,t)||(e[t]=g(n))}const y={"":t=>t,x:t=>t.x,y:t=>t.y};function v(t){const e=t.split("."),i=[];let s="";for(const t of e)s+=t,s.endsWith("\\")?s=s.slice(0,-1)+".":(i.push(s),s="");return i}function M(t,e){const i=y[e]||(y[e]=function(t){const e=v(t);return t=>{for(const i of e){if(""===i)break;t=t&&t[i]}return t}}(e));return i(t)}function w(t){return t.charAt(0).toUpperCase()+t.slice(1)}const k=t=>void 0!==t,S=t=>"function"==typeof t,P=(t,e)=>{if(t.size!==e.size)return!1;for(const i of t)if(!e.has(i))return!1;return!0};function D(t){return"mouseup"===t.type||"click"===t.type||"contextmenu"===t.type}const C=Math.PI,O=2*C,A=O+C,T=Number.POSITIVE_INFINITY,L=C/180,E=C/2,R=C/4,I=2*C/3,z=Math.log10,F=Math.sign;function V(t,e,i){return Math.abs(t-e)<i}function B(t){const e=Math.round(t);t=V(t,e,t/1e3)?e:t;const i=Math.pow(10,Math.floor(z(t))),s=t/i;return(s<=1?1:s<=2?2:s<=5?5:10)*i}function W(t){const e=[],i=Math.sqrt(t);let s;for(s=1;s<i;s++)t%s==0&&(e.push(s),e.push(t/s));return i===(0|i)&&e.push(i),e.sort(((t,e)=>t-e)).pop(),e}function N(t){return!function(t){return"symbol"==typeof t||"object"==typeof t&&null!==t&&!(Symbol.toPrimitive in t||"toString"in t||"valueOf"in t)}(t)&&!isNaN(parseFloat(t))&&isFinite(t)}function H(t,e){const i=Math.round(t);return i-e<=t&&i+e>=t}function j(t,e,i){let s,n,o;for(s=0,n=t.length;s<n;s++)o=t[s][i],isNaN(o)||(e.min=Math.min(e.min,o),e.max=Math.max(e.max,o))}function $(t){return t*(C/180)}function Y(t){return t*(180/C)}function U(t){if(!a(t))return;let e=1,i=0;for(;Math.round(t*e)/e!==t;)e*=10,i++;return i}function X(t,e){const i=e.x-t.x,s=e.y-t.y,n=Math.sqrt(i*i+s*s);let o=Math.atan2(s,i);return o<-.5*C&&(o+=O),{angle:o,distance:n}}function q(t,e){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function K(t,e){return(t-e+A)%O-C}function G(t){return(t%O+O)%O}function J(t,e,i,s){const n=G(t),o=G(e),a=G(i),r=G(o-n),l=G(a-n),h=G(n-o),c=G(n-a);return n===o||n===a||s&&o===a||r>l&&h<c}function Z(t,e,i){return Math.max(e,Math.min(i,t))}function Q(t){return Z(t,-32768,32767)}function tt(t,e,i,s=1e-6){return t>=Math.min(e,i)-s&&t<=Math.max(e,i)+s}function et(t,e,i){i=i||(i=>t[i]<e);let s,n=t.length-1,o=0;for(;n-o>1;)s=o+n>>1,i(s)?o=s:n=s;return{lo:o,hi:n}}const it=(t,e,i,s)=>et(t,i,s?s=>{const n=t[s][e];return n<i||n===i&&t[s+1][e]===i}:s=>t[s][e]<i),st=(t,e,i)=>et(t,i,(s=>t[s][e]>=i));function nt(t,e,i){let s=0,n=t.length;for(;s<n&&t[s]<e;)s++;for(;n>s&&t[n-1]>i;)n--;return s>0||n<t.length?t.slice(s,n):t}const ot=["push","pop","shift","splice","unshift"];function at(t,e){t._chartjs?t._chartjs.listeners.push(e):(Object.defineProperty(t,"_chartjs",{configurable:!0,enumerable:!1,value:{listeners:[e]}}),ot.forEach((e=>{const i="_onData"+w(e),s=t[e];Object.defineProperty(t,e,{configurable:!0,enumerable:!1,value(...eLine truncated
/*!
* @kurkle/color v0.3.2
* https://github.com/kurkle/color#readme
* (c) 2023 Jukka Kurkela
* Released under the MIT License
*/function _t(t){return t+.5|0}const yt=(t,e,i)=>Math.max(Math.min(t,i),e);function vt(t){return yt(_t(2.55*t),0,255)}function Mt(t){return yt(_t(255*t),0,255)}function wt(t){return yt(_t(t/2.55)/100,0,1)}function kt(t){return yt(_t(100*t),0,100)}const St={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15},Pt=[..."0123456789ABCDEF"],Dt=t=>Pt[15&t],Ct=t=>Pt[(240&t)>>4]+Pt[15&t],Ot=t=>(240&t)>>4==(15&t);function At(t){var e=(t=>Ot(t.r)&&Ot(t.g)&&Ot(t.b)&&Ot(t.a))(t)?Dt:Ct;return t?"#"+e(t.r)+e(t.g)+e(t.b)+((t,e)=>t<255?e(t):"")(t.a,e):void 0}const Tt=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;function Lt(t,e,i){const s=e*Math.min(i,1-i),n=(e,n=(e+t/30)%12)=>i-s*Math.max(Math.min(n-3,9-n,1),-1);return[n(0),n(8),n(4)]}function Et(t,e,i){const s=(s,n=(s+t/60)%6)=>i-i*e*Math.max(Math.min(n,4-n,1),0);return[s(5),s(3),s(1)]}function Rt(t,e,i){const s=Lt(t,1,.5);let n;for(e+i>1&&(n=1/(e+i),e*=n,i*=n),n=0;n<3;n++)s[n]*=1-e-i,s[n]+=e;return s}function It(t){const e=t.r/255,i=t.g/255,s=t.b/255,n=Math.max(e,i,s),o=Math.min(e,i,s),a=(n+o)/2;let r,l,h;return n!==o&&(h=n-o,l=a>.5?h/(2-n-o):h/(n+o),r=function(t,e,i,s,n){return t===n?(e-i)/s+(e<i?6:0):e===n?(i-t)/s+2:(t-e)/s+4}(e,i,s,h,n),r=60*r+.5),[0|r,l||0,a]}function zt(t,e,i,s){return(Array.isArray(e)?t(e[0],e[1],e[2]):t(e,i,s)).map(Mt)}function Ft(t,e,i){return zt(Lt,t,e,i)}function Vt(t){return(t%360+360)%360}function Bt(t){const e=Tt.exec(t);let i,s=255;if(!e)return;e[5]!==i&&(s=e[6]?vt(+e[5]):Mt(+e[5]));const n=Vt(+e[2]),o=+e[3]/100,a=+e[4]/100;return i="hwb"===e[1]?function(t,e,i){return zt(Rt,t,e,i)}(n,o,a):"hsv"===e[1]?function(t,e,i){return zt(Et,t,e,i)}(n,o,a):Ft(n,o,a),{r:i[0],g:i[1],b:i[2],a:s}}const Wt={x:"dark",Z:"light",Y:"re",X:"blu",W:"gr",V:"medium",U:"slate",A:"ee",T:"ol",S:"or",B:"ra",C:"lateg",D:"ights",R:"in",Q:"turquois",E:"hi",P:"ro",O:"al",N:"le",M:"de",L:"yello",F:"en",K:"ch",G:"arks",H:"ea",I:"ightg",J:"wh"},Nt={OiceXe:"f0f8ff",antiquewEte:"faebd7",aqua:"ffff",aquamarRe:"7fffd4",azuY:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"0",blanKedOmond:"ffebcd",Xe:"ff",XeviTet:"8a2be2",bPwn:"a52a2a",burlywood:"deb887",caMtXe:"5f9ea0",KartYuse:"7fff00",KocTate:"d2691e",cSO:"ff7f50",cSnflowerXe:"6495ed",cSnsilk:"fff8dc",crimson:"dc143c",cyan:"ffff",xXe:"8b",xcyan:"8b8b",xgTMnPd:"b8860b",xWay:"a9a9a9",xgYF:"6400",xgYy:"a9a9a9",xkhaki:"bdb76b",xmagFta:"8b008b",xTivegYF:"556b2f",xSange:"ff8c00",xScEd:"9932cc",xYd:"8b0000",xsOmon:"e9967a",xsHgYF:"8fbc8f",xUXe:"483d8b",xUWay:"2f4f4f",xUgYy:"2f4f4f",xQe:"ced1",xviTet:"9400d3",dAppRk:"ff1493",dApskyXe:"bfff",dimWay:"696969",dimgYy:"696969",dodgerXe:"1e90ff",fiYbrick:"b22222",flSOwEte:"fffaf0",foYstWAn:"228b22",fuKsia:"ff00ff",gaRsbSo:"dcdcdc",ghostwEte:"f8f8ff",gTd:"ffd700",gTMnPd:"daa520",Way:"808080",gYF:"8000",gYFLw:"adff2f",gYy:"808080",honeyMw:"f0fff0",hotpRk:"ff69b4",RdianYd:"cd5c5c",Rdigo:"4b0082",ivSy:"fffff0",khaki:"f0e68c",lavFMr:"e6e6fa",lavFMrXsh:"fff0f5",lawngYF:"7cfc00",NmoncEffon:"fffacd",ZXe:"add8e6",ZcSO:"f08080",Zcyan:"e0ffff",ZgTMnPdLw:"fafad2",ZWay:"d3d3d3",ZgYF:"90ee90",ZgYy:"d3d3d3",ZpRk:"ffb6c1",ZsOmon:"ffa07a",ZsHgYF:"20b2aa",ZskyXe:"87cefa",ZUWay:"778899",ZUgYy:"778899",ZstAlXe:"b0c4de",ZLw:"ffffe0",lime:"ff00",limegYF:"32cd32",lRF:"faf0e6",magFta:"ff00ff",maPon:"800000",VaquamarRe:"66cdaa",VXe:"cd",VScEd:"ba55d3",VpurpN:"9370db",VsHgYF:"3cb371",VUXe:"7b68ee",VsprRggYF:"fa9a",VQe:"48d1cc",VviTetYd:"c71585",midnightXe:"191970",mRtcYam:"f5fffa",mistyPse:"ffe4e1",moccasR:"ffe4b5",navajowEte:"ffdead",navy:"80",Tdlace:"fdf5e6",Tive:"808000",TivedBb:"6b8e23",Sange:"ffa500",SangeYd:"ff4500",ScEd:"da70d6",pOegTMnPd:"eee8aa",pOegYF:"98fb98",pOeQe:"afeeee",pOeviTetYd:"db7093",papayawEp:"ffefd5",pHKpuff:"ffdab9",peru:"cd853f",pRk:"ffc0cb",plum:"dda0dd",powMrXe:"b0e0e6",purpN:"800080",YbeccapurpN:"663399",Yd:"ff0000",Psybrown:"bc8f8f",PyOXe:"4169e1",saddNbPwn:"8b4513",sOmon:"fa8072",sandybPwn:"f4a460",sHgYF:"2e8b57",sHshell:"fff5ee",siFna:"a0522d",silver:"c0c0c0",skyXe:"87ceeb",UXe:"6a5acd",UWay:"708090",UgYy:"708090",snow:"fffafa",sprRggYF:"ff7f",stAlXe:"4682b4",tan:"d2b48c",teO:"8080",tEstN:"d8bfd8",tomato:"ff6347",Qe:"40e0d0",viTet:"ee82ee",JHt:"f5deb3",wEte:"ffffff",wEtesmoke:"f5f5f5",Lw:"ffff00",LwgYF:"9acd32"};let Ht;function jt(t){Ht||(Ht=function(){const t={},e=Object.keys(Nt),i=Object.keys(Wt);let s,n,o,a,r;for(s=0;s<e.length;s++){for(a=r=e[s],n=0;n<i.length;n++)o=i[n],r=r.replace(o,Wt[o]);o=parseInt(Nt[a],16),t[r]=[o>>16&255,o>>8&255,255&o]}return t}(),Ht.transparent=[0,0,0,0]);const e=Ht[t.toLowerCase()];return e&&{r:e[0],g:e[1],b:e[2],a:4===e.length?e[3]:255}}const $t=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;const Yt=t=>t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055,Ut=t=>t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4);function Xt(t,e,i){if(t){let s=It(t);s[e]=Math.max(0,Math.min(s[e]+s[e]*i,0===e?360:1)),Line truncated
//# sourceMappingURL=chart.umd.min.js.map
-1
View File
@@ -1 +0,0 @@
(function(){var e,t,n,r=function(e,t){return function(){return e.apply(t,arguments)}};e=function(){function e(){this.translate=r(this.translate,this);this.data={values:{},contexts:[]};this.globalContext={}}e.prototype.translate=function(e,t,n,r,i){var s,o,u,a;if(i==null){i=this.globalContext}u=function(e){var t;t=typeof e;return t==="function"||t==="object"&&!!e};if(u(t)){s=null;a=null;o=t;i=n||this.globalContext}else{if(typeof t==="number"){s=null;a=t;o=n;i=r||this.globalContext}else{s=t;if(typeof n==="number"){a=n;o=r;i=i}else{a=null;o=n;i=r||this.globalContext}}}if(u(e)){if(u(e["i18n"])){e=e["i18n"]}return this.translateHash(e,i)}else{return this.translateText(e,a,o,i,s)}};e.prototype.add=function(e){var t,n,r,i,s,o,u,a;if(e.values!=null){o=e.values;for(n in o){r=o[n];this.data.values[n]=r}}if(e.contexts!=null){u=e.contexts;a=[];for(i=0,s=u.length;i<s;i++){t=u[i];a.push(this.data.contexts.push(t))}return a}};e.prototype.setContext=function(e,t){return this.globalContext[e]=t};e.prototype.clearContext=function(e){return this.lobalContext[e]=null};e.prototype.reset=function(){this.data={values:{},contexts:[]};return this.globalContext={}};e.prototype.resetData=function(){return this.data={values:{},contexts:[]}};e.prototype.resetContext=function(){return this.globalContext={}};e.prototype.translateHash=function(e,t){var n,r;for(n in e){r=e[n];if(typeof r==="string"){e[n]=this.translateText(r,null,null,t)}}return e};e.prototype.translateText=function(e,t,n,r,i){var s,o;if(r==null){r=this.globalContext}if(this.data==null){return this.useOriginalText(i||e,t,n)}s=this.getContextData(this.data,r);if(s!=null){o=this.findTranslation(e,t,n,s.values,i)}if(o==null){o=this.findTranslation(e,t,n,this.data.values,i)}if(o==null){return this.useOriginalText(i||e,t,n)}return o};e.prototype.findTranslation=function(e,t,n,r){var i,s,o,u,a;o=r[e];if(o==null){return null}if(t==null){if(typeof o==="string"){return this.applyFormatting(o,t,n)}}else{if(o instanceof Array||o.length){for(u=0,a=o.length;u<a;u++){s=o[u];if((t>=s[0]||s[0]===null)&&(t<=s[1]||s[1]===null)){i=this.applyFormatting(s[2].replace("-%n",String(-t)),t,n);return this.applyFormatting(i.replace("%n",String(t)),t,n)}}}}return null};e.prototype.getContextData=function(e,t){var n,r,i,s,o,u,a,f;if(e.contexts==null){return null}a=e.contexts;for(o=0,u=a.length;o<u;o++){n=a[o];r=true;f=n.matches;for(i in f){s=f[i];r=r&&s===t[i]}if(r){return n}}return null};e.prototype.useOriginalText=function(e,t,n){if(t==null){return this.applyFormatting(e,t,n)}return this.applyFormatting(e.replace("%n",String(t)),t,n)};e.prototype.applyFormatting=function(e,t,n){var r,i;for(r in n){i=new RegExp("%{"+r+"}","g");e=e.replace(i,n[r])}return e};return e}();n=new e;t=n.translate;t.translator=n;t.create=function(n){var r;r=new e;if(n!=null){r.add(n)}r.translate.create=t.create;return r.translate};(typeof module!=="undefined"&&module!==null?module.exports=t:void 0)||(this.i18n=t)}).call(this)
-128
View File
@@ -1,128 +0,0 @@
class Lang {
constructor(switcher, defaultLocale = null) {
if (!(switcher instanceof Object)) {
throw new SyntaxError("switcher must be an element object");
}
this.switcher = switcher;
this.defaultLocale = defaultLocale;
this.supportedLocales = [];
this.currentLocale = null;
}
async build() {
this.bindSwitcher();
const userLocale = localStorage.getItem('locale');
if (this.localeIsSupported(userLocale)) {
await this.setLocale(userLocale);
} else {
const initialLocale = this.getSuitableLocale(this.browserLocales(true));
await this.setLocale(initialLocale);
}
this.translatePage();
}
bindSwitcher() {
this.supportedLocales = [];
for (const option of this.switcher.options) {
this.supportedLocales.push(option.value);
}
if (!this.localeIsSupported(this.defaultLocale)) {
const selected = this.switcher.selectedIndex ? this.switcher.selectedIndex : 0;
this.defaultLocale = this.switcher.options[selected].value;
}
this.switcher.addEventListener('change', async (element) => {
await this.setLocale(element.target.value);
this.translatePage();
});
}
async setLocale(newLocale) {
if (this.currentLocale == newLocale) {
return;
}
i18n.translator.reset();
i18n.translator.add(await this.fetchTranslations(newLocale));
this.currentLocale = newLocale;
localStorage.setItem('locale', this.currentLocale);
if (document.documentElement) {
document.documentElement.setAttribute("lang", this.currentLocale);
}
if (this.switcher.value != this.currentLocale) {
this.switcher.value = this.currentLocale;
}
}
async fetchTranslations(locale) {
const response = await fetch(`/static/locales/${locale}.json?{BUILD_TIME}`);
const data = await response.json();
if (data.values instanceof Object) {
data.values = this.flattenKeys({keys: data.values, prefix: ''});
}
return data;
}
translatePage() {
document
.querySelectorAll("[data-i18n]")
.forEach((element) => this.translateElement(element));
}
translateElement(element) {
let key = element.getAttribute("data-i18n");
if (!key && element.innerHTML) {
key = element.innerHTML;
element.setAttribute("data-i18n", key);
}
if (!key) {
return;
}
const arg = element.getAttribute("data-i18n-arg") || null;
const options = JSON.parse(element.getAttribute("data-i18n-options")) || null;
element.innerHTML = i18n(key, arg, options);
}
localeIsSupported(locale) {
return locale !== null && this.supportedLocales.indexOf(locale) > -1;
}
getSuitableLocale(locales) {
return locales.find(this.localeIsSupported, this) || this.defaultLocale;
}
browserLocales(codeOnly = false) {
return navigator.languages.map((locale) =>
codeOnly ? locale.split("-")[0] : locale,
);
}
flattenKeys({ keys, prefix }) {
let result = {};
for (let key in keys) {
const type = typeof keys[key];
if (type === 'string') {
result[`${prefix}${key}`] = keys[key];
}
else if (type === 'object') {
result = { ...result, ...this.flattenKeys({ keys: keys[key], prefix: `${prefix}${key}.` }) }
}
}
return result;
}
}
-106
View File
@@ -1,106 +0,0 @@
const convertLegacyBackup = (data) => {
const aliases = {
alwaysSendIndoorTemp: 'always_send_indoor_temp',
antiStuckInterval: 'antistuck_interval',
antiStuckTime: 'antistuck_time',
autoDiagReset: 'auto_diag_reset',
autoFaultReset: 'auto_fault_reset',
cascadeControl: 'cascade_control',
ch2AlwaysEnabled: 'ch2_always_enabled',
ch2DisablingAction: 'ch2_disabling_action',
coolingSupport: 'cooling_support',
dhwBlocking: 'dhw_blocking',
dhwDisablingAction: 'dhw_disabling_action',
dhwStateAsDhwBlocking: 'dhw_state_as_dhw_blocking',
dhwSupport: 'dhw_support',
dhwToCh2: 'dhw_to_ch2',
externalPump: 'ext_pump',
filteringFactor: 'filtering_factor',
freezeProtection: 'freeze_protection',
getMinMaxTemp: 'get_min_max_temp',
heatingDisablingAction: 'heating_disabling_action',
heatingStateToSummerWinterMode: 'heating_state_to_summer_winter_mode',
heatingToCh2: 'heating_to_ch2',
highTemp: 'high_temp',
homeAssistantDiscovery: 'ha_discovery',
ignoreDiagState: 'ignore_diag_state',
immergasFix: 'immergas_fix',
indoorTempAvgType: 'indoor_temp_avg_type',
inGpio: 'in_gpio',
invertState: 'invert_state',
logLevel: 'loglevel',
lowTemp: 'low_temp',
maxModulation: 'max_modulation',
maxPower: 'max_power',
maxTemp: 'max_temp',
maxTempSyncWithTargetTemp: 'max_temp_sync_with_target_temp',
memberId: 'member_id',
minPower: 'min_power',
minTemp: 'min_temp',
nativeOTC: 'native_otc',
onEnabledHeating: 'on_enabled_heating',
onFault: 'on_fault',
onLossConnection: 'on_loss_connection',
outdoorTempAvgType: 'outdoor_temp_avg_type',
outGpio: 'out_gpio',
overheatProtection: 'overheat_protection',
postCirculationTime: 'post_circulation_time',
rxLedGpio: 'rx_led_gpio',
setDateAndTime: 'set_date_and_time',
staticConfig: 'static_config',
statusLedGpio: 'status_led_gpio',
summerWinterMode: 'summer_winter_mode',
targetDiffFactor: 'target_diff_factor',
thresholdHigh: 'threshold_high',
thresholdLow: 'threshold_low',
thresholdTime: 'threshold_time',
tresholdTime: 'threshold_time',
turboFactor: 'turbo_factor',
unitSystem: 'unit_system',
useDhcp: 'use_dhcp',
webSerial: 'web_serial'
};
const logLevels = [0, 1, 1, 2, 3, 3, 4, 5];
const convert = (value) => {
if (Array.isArray(value)) {
return value.map(convert);
}
if (value === null || typeof value !== 'object') {
return value;
}
const result = Object.create(null);
for (const [key, field] of Object.entries(value)) {
const convertedKey = Object.prototype.hasOwnProperty.call(aliases, key) ? aliases[key] : key;
result[convertedKey] = convert(field);
}
return result;
};
const legacySystem = data?.settings?.system;
if (legacySystem !== null && typeof legacySystem === 'object'
&& Object.prototype.hasOwnProperty.call(legacySystem, 'logLevel')) {
const system = {...legacySystem};
if (Object.prototype.hasOwnProperty.call(system, 'loglevel')) {
delete system.logLevel;
} else if (Number.isInteger(system.logLevel) && system.logLevel >= 0 && system.logLevel < logLevels.length) {
system.logLevel = logLevels[system.logLevel];
}
data = {
...data,
settings: {...data.settings, system}
};
}
const result = convert(data);
const opentherm = result?.settings?.opentherm;
if (opentherm !== null && typeof opentherm === 'object') {
delete opentherm.unit_system;
}
return result;
};
-634
View File
@@ -1,634 +0,0 @@
const setupForm = (formSelector, onResultCallback = null, noCastItems = []) => {
const form = document.querySelector(formSelector);
if (!form) {
return;
}
form.querySelectorAll('input').forEach(item => {
item.addEventListener('change', (event) => {
if (!event.target.checkValidity()) {
event.target.setAttribute('aria-invalid', true);
} else if (event.target.hasAttribute('aria-invalid')) {
event.target.removeAttribute('aria-invalid');
}
})
});
form.addEventListener('submit', async (event) => {
event.preventDefault();
const url = form.action;
let button = form.querySelector('button[type="submit"]');
let defaultText;
if (button) {
defaultText = button.textContent;
button.textContent = i18n("button.wait");
button.setAttribute('disabled', true);
button.setAttribute('aria-busy', true);
}
const onSuccess = (result) => {
if (button) {
button.textContent = i18n('button.saved');
button.classList.add('success');
button.removeAttribute('aria-busy');
setTimeout(() => {
button.removeAttribute('disabled');
button.classList.remove('success', 'failed');
button.textContent = defaultText;
}, 5000);
}
};
const onFailed = () => {
if (button) {
button.textContent = i18n('button.error');
button.classList.add('failed');
button.removeAttribute('aria-busy');
setTimeout(() => {
button.removeAttribute('disabled');
button.classList.remove('success', 'failed');
button.textContent = defaultText;
}, 5000);
}
};
try {
let fd = new FormData(form);
let checkboxes = form.querySelectorAll('input[type="checkbox"]');
for (let checkbox of checkboxes) {
fd.append(checkbox.getAttribute('name'), checkbox.checked);
}
let response = await fetch(url, {
method: "POST",
cache: "no-cache",
credentials: "include",
headers: {
"Content-Type": "application/json"
},
body: form2json(fd, noCastItems)
});
if (!response.ok) {
throw new Error('Response not valid');
}
const result = response.status != 204 ? (await response.json()) : null;
onSuccess(result);
if (onResultCallback instanceof Function) {
onResultCallback(result);
}
} catch (err) {
console.log(err);
onFailed();
}
});
}
const setupNetworkScanForm = (formSelector, tableSelector) => {
const form = document.querySelector(formSelector);
if (!form) {
console.error("form not found");
return;
}
const url = form.action;
let button = form.querySelector('button[type="submit"]');
let defaultText;
const onSubmitFn = async (event) => {
if (event) {
event.preventDefault();
}
if (button) {
defaultText = button.innerHTML;
button.innerHTML = i18n('button.wait');
button.setAttribute('disabled', true);
button.setAttribute('aria-busy', true);
}
let table = document.querySelector(tableSelector);
if (!table) {
console.error("table not found");
return;
}
const onSuccess = async (response) => {
let result = await response.json();
console.log('networks: ', result);
let tbody = table.querySelector('tbody');
if (!tbody) {
tbody = table.createTBody();
}
while (tbody.rows.length > 0) {
tbody.rows[0].remove();
}
for (let i = 0; i < result.length; i++) {
let row = tbody.insertRow(-1);
row.classList.add("network");
row.dataset.ssid = result[i].hidden ? '' : result[i].ssid;
row.insertCell().textContent = `#${i + 1}`;
const nameCell = row.insertCell();
if (result[i].hidden) {
const hiddenName = document.createElement('i');
hiddenName.textContent = result[i].bssid;
nameCell.appendChild(hiddenName);
} else {
nameCell.textContent = result[i].ssid;
}
nameCell.onclick = (event) => {
const input = document.querySelector("[name='sta[ssid]']");
const ssid = row.dataset.ssid;
if (!input || !ssid) {
return;
}
input.value = ssid;
input.focus();
};
// info cell
let infoCell = row.insertCell();
// signal quality
let signalQualityIcon = document.createElement("i");
if (result[i].signal_quality > 80) {
signalQualityIcon.classList.add('icons-wifi-strength-4');
} else if (result[i].signal_quality > 60) {
signalQualityIcon.classList.add('icons-wifi-strength-3');
} else if (result[i].signal_quality > 40) {
signalQualityIcon.classList.add('icons-wifi-strength-2');
} else if (result[i].signal_quality > 20) {
signalQualityIcon.classList.add('icons-wifi-strength-1');
} else {
signalQualityIcon.classList.add('icons-wifi-strength-0');
}
let signalQualityContainer = document.createElement("span");
signalQualityContainer.dataset.tooltip = `${result[i].signal_quality}%`;
signalQualityContainer.appendChild(signalQualityIcon);
infoCell.appendChild(signalQualityContainer);
// auth
const authList = {
0: "Open",
1: "WEP",
2: "WPA",
3: "WPA2",
4: "WPA/WPA2",
5: "WPA/WPA2 Enterprise",
6: "WPA3",
7: "WPA2/WPA3",
8: "WAPI",
9: "OWE",
10: "WPA3 Enterprise"
};
let authIcon = document.createElement("i");
if (result[i].auth == 0) {
authIcon.classList.add('icons-unlocked');
} else {
authIcon.classList.add('icons-locked');
}
let authContainer = document.createElement("span");
authContainer.dataset.tooltip = (result[i].auth in authList) ? authList[result[i].auth] : "unknown";
authContainer.appendChild(authIcon);
infoCell.appendChild(authContainer);
}
if (button) {
button.innerHTML = defaultText;
button.removeAttribute('disabled');
button.removeAttribute('aria-busy');
}
};
const onFailed = async (response) => {
table.classList.remove('hidden');
if (button) {
button.innerHTML = defaultText;
button.removeAttribute('disabled');
button.removeAttribute('aria-busy');
}
};
let attempts = 6;
let attemptFn = async () => {
attempts--;
try {
let response = await fetch(url, {
cache: "no-cache",
credentials: "include"
});
if (response.status == 200) {
await onSuccess(response);
} else if (attempts <= 0) {
await onFailed(response);
} else {
setTimeout(attemptFn, 5000);
}
} catch (err) {
if (attempts <= 0) {
onFailed(err);
} else {
setTimeout(attemptFn, 10000);
}
}
};
attemptFn();
};
form.addEventListener('submit', onSubmitFn);
onSubmitFn();
}
const setBusy = (busySelector, contentSelector, value, parent = undefined) => {
if (!value) {
hide(busySelector, parent);
show(contentSelector, parent);
} else {
show(busySelector, parent);
hide(contentSelector, parent);
}
}
const setAriaState = (selector, value, parent = undefined) => {
if (parent === undefined) {
parent = document;
}
let item = parent.querySelector(selector);
if (!item) {
return;
}
item.setAttribute('aria-invalid', !value);
}
const setStatus = (selector, state, color = undefined, parent = undefined) => {
if (parent === undefined) {
parent = document;
}
let item = parent.querySelector(selector);
if (!item) {
return;
}
item.classList.forEach(cName => {
if (cName.indexOf("icons-") === 0) {
item.classList.remove(cName);
}
});
item.classList.add(`icons-${state}`);
if (color !== undefined) {
item.classList.add(`icons-color-${color}`);
}
}
const setState = (selector, state, parent = undefined) => {
return setStatus(
selector,
state ? "success" : "error",
state ? "green" : "gray",
parent
);
}
const setValue = (selector, value, parent = undefined) => {
if (parent === undefined) {
parent = document;
}
let items = parent.querySelectorAll(selector);
if (!items.length) {
return;
}
for (let item of items) {
item.innerHTML = value;
}
}
const setTextValue = (selector, value, parent = undefined) => {
if (parent === undefined) {
parent = document;
}
let items = parent.querySelectorAll(selector);
if (!items.length) {
return;
}
for (let item of items) {
item.textContent = value;
}
}
const appendValue = (selector, value, nl = null, parent = undefined) => {
if (parent === undefined) {
parent = document;
}
let items = parent.querySelectorAll(selector);
if (!items.length) {
return;
}
for (let item of items) {
if (item.innerHTML.trim().length > 0) {
if (nl !== null) {
item.innerHTML += nl;
}
item.innerHTML += value;
} else {
item.innerHTML = value;
}
}
}
const setCheckboxValue = (selector, value, parent = undefined) => {
if (parent === undefined) {
parent = document;
}
let item = parent.querySelector(selector);
if (!item) {
return;
}
item.checked = value;
setTimeout(() => {
item.dispatchEvent(new Event("change"));
}, 10);
}
const setRadioValue = (selector, value, parent = undefined) => {
if (parent === undefined) {
parent = document;
}
let items = parent.querySelectorAll(selector);
if (!items.length) {
return;
}
for (let item of items) {
const checked = item.value == value;
if (item.checked != checked) {
item.checked = checked;
setTimeout(() => {
item.dispatchEvent(new Event("change"));
}, 10);
}
}
}
const setInputValue = (selector, value, attrs = {}, parent = undefined) => {
if (parent === undefined) {
parent = document;
}
let items = parent.querySelectorAll(selector);
if (!items.length) {
return;
}
for (let item of items) {
if (attrs instanceof Object) {
for (let attrKey of Object.keys(attrs)) {
item.setAttribute(attrKey, attrs[attrKey]);
}
}
item.value = value;
setTimeout(() => {
item.dispatchEvent(new Event("change"));
}, 10);
}
}
const setSelectValue = (selector, value, parent = undefined) => {
if (parent === undefined) {
parent = document;
}
let item = parent.querySelector(selector);
if (!item) {
return;
}
for (let option of item.options) {
option.selected = option.value == value;
}
}
const show = (selector, parent = undefined) => {
if (parent === undefined) {
parent = document;
}
let items = parent.querySelectorAll(selector);
if (!items.length) {
return;
}
for (let item of items) {
if (item.classList.contains('hidden')) {
item.classList.remove('hidden');
}
}
}
const hide = (selector, parent = undefined) => {
if (parent === undefined) {
parent = document;
}
let items = parent.querySelectorAll(selector);
if (!items.length) {
return;
}
for (let item of items) {
if (!item.classList.contains('hidden')) {
item.classList.add('hidden');
}
}
}
function unit2str(unitSystem, units = {}, defaultValue = '?') {
return (unitSystem in units)
? units[unitSystem]
: defaultValue;
}
const temperatureUnit = (unitSystem) => {
return unit2str(unitSystem, {
0: "°C",
1: "°F"
});
}
const pressureUnit = (unitSystem) => {
return unit2str(unitSystem, {
0: "bar",
1: "psi"
});
}
const volumeUnit = (unitSystem) => {
return unit2str(unitSystem, {
0: i18n('units.liter'),
1: i18n('units.gallon')
});
}
const purposeUnit = (purpose, unitSystem) => {
const tUnit = temperatureUnit(unitSystem);
return unit2str(purpose, {
0: tUnit,
1: tUnit,
2: tUnit,
3: tUnit,
4: tUnit,
5: tUnit,
6: `${volumeUnit(unitSystem)}/${i18n('units.min')}`,
7: tUnit,
8: "%",
248: "%",
249: i18n('units.kw'),
250: i18n('units.rpm'),
251: i18n('units.ppm'),
252: pressureUnit(unitSystem),
253: "%",
254: tUnit
}, null);
}
const memberIdToVendor = (memberId) => {
// https://github.com/Jeroen88/EasyOpenTherm/blob/main/src/EasyOpenTherm.h
// https://github.com/Evgen2/SmartTherm/blob/v0.7/src/Web.cpp
const vendorList = {
1: "Baxi",
2: "AWB/Brink/Viessmann",
4: "ATAG/Baxi/Brötje/ELCO/GEMINOX",
5: "Itho Daalderop",
6: "IDEAL",
8: "Buderus/Bosch/Hoval",
9: "Ferroli",
11: "Remeha/De Dietrich",
16: "Unical",
24: "Vaillant/Bulex",
27: "Baxi",
29: "Itho Daalderop",
33: "Viessmann",
41: "Italtherm/Radiant",
56: "Baxi",
131: "Nefit",
148: "Navien",
173: "Intergas",
247: "Baxi Ampera",
248: "Zota Lux-X"
};
return (memberId in vendorList)
? vendorList[memberId]
: "unknown vendor";
}
function form2json(data, noCastItems = []) {
let method = function (object, pair) {
let keys = pair[0].replace(/\]/g, '').split('[');
let key = keys[0];
let value = pair[1];
if (!noCastItems.includes(keys.join('.'))) {
if (value === 'true' || value === 'false') {
value = value === 'true';
} else if (typeof (value) === 'string' && value.trim() !== '' && !isNaN(value)) {
value = parseFloat(value);
}
}
if (keys.length > 1) {
let i, x, segment;
let last = value;
let type = isNaN(keys[1]) ? {} : [];
value = segment = object[key] || type;
for (i = 1; i < keys.length; i++) {
x = keys[i];
if (i == keys.length - 1) {
if (Array.isArray(segment)) {
segment.push(last);
} else {
segment[x] = last;
}
} else if (segment[x] == undefined) {
segment[x] = isNaN(keys[i + 1]) ? {} : [];
}
segment = segment[x];
}
}
object[key] = value;
return object;
}
let object = Array.from(data).reduce(method, {});
return JSON.stringify(object);
}
function dec2hex(i) {
let hex = parseInt(i).toString(16);
if (hex.length % 2 != 0) {
hex = `0${hex}`;
}
return hex.toUpperCase();
}
function constrain(amt, low, high) {
return ((amt) < (low) ? (low) : ((amt) > (high) ? (high) : (amt)));
}
function c2f(value) {
return (9 / 5) * value + 32;
}
function f2c(value) {
return (value - 32) * (5 / 9);
}
-335
View File
@@ -1,335 +0,0 @@
@media (min-width: 576px) {
article {
--pico-block-spacing-vertical: calc(var(--pico-spacing) * 0.75);
--pico-block-spacing-horizontal: calc(var(--pico-spacing) * 0.75);
}
.logo {
font-size: 1.2rem;
}
}
@media (min-width: 768px) {
article {
--pico-block-spacing-vertical: var(--pico-spacing);
--pico-block-spacing-horizontal: var(--pico-spacing);
}
.logo {
font-size: 1.25rem;
}
}
@media (min-width: 1024px) {
article {
--pico-block-spacing-vertical: calc(var(--pico-spacing) * 1.25);
--pico-block-spacing-horizontal: calc(var(--pico-spacing) * 1.25);
}
.logo {
font-size: 1.25rem;
}
}
@media (min-width: 1280px) {
article {
--pico-block-spacing-vertical: calc(var(--pico-spacing) * 1.5);
--pico-block-spacing-horizontal: calc(var(--pico-spacing) * 1.5);
}
.logo {
font-size: 1.3rem;
}
.container {
max-width: 1000px;
}
}
@media (min-width: 1536px) {
article {
--pico-block-spacing-vertical: calc(var(--pico-spacing) * 1.75);
--pico-block-spacing-horizontal: calc(var(--pico-spacing) * 1.75);
}
.logo {
font-size: 1.3rem;
}
.container {
max-width: 1000px;
}
}
header,
main,
footer {
padding-top: 1rem !important;
padding-bottom: 1rem !important;
}
article {
margin-bottom: 1rem;
}
footer {
text-align: center;
}
/*nav li a:has(> div.logo) {
margin-bottom: 0;
}*/
nav li :where(a, [role=link]) {
margin: 0;
}
details>div {
padding: 0 var(--pico-form-element-spacing-horizontal);
}
pre {
padding: 0.5rem;
}
:nth-last-child(1 of table tr:not(.hidden)) th,
:nth-last-child(1 of table tr:not(.hidden)) td {
border-bottom: 0 !important;
}
.hidden {
display: none !important;
}
button.success {
background-color: var(--pico-form-element-valid-border-color);
border-color: var(--pico-form-element-valid-border-color);
}
button.failed {
background-color: var(--pico-form-element-invalid-border-color);
border-color: var(--pico-form-element-invalid-border-color);
}
tr.network:hover {
--pico-background-color: var(--pico-primary-focus);
cursor: pointer;
}
.primary {
border: 0.25rem solid var(--pico-form-element-invalid-border-color);
padding: 1rem;
margin-bottom: 1rem;
}
.logo {
display: inline-block;
padding: calc(var(--pico-nav-link-spacing-vertical) - var(--pico-border-width) * 2) var(--pico-nav-link-spacing-horizontal);
vertical-align: baseline;
line-height: var(--pico-line-height);
background-color: var(--pico-code-kbd-background-color);
border-radius: var(--pico-border-radius);
color: var(--pico-code-kbd-color);
font-weight: bolder;
/*font-size: 1.3rem;*/
font-family: var(--pico-font-family-monospace);
}
.tAction {
touch-action: none;
}
.thermostat {
display: grid;
grid-template-columns: 0.5fr 2fr 0.5fr;
grid-template-rows: 0.25fr 1fr 0.25fr;
gap: 0px 0px;
grid-auto-flow: row;
justify-content: center;
justify-items: center;
grid-template-areas:
". thermostat-header ."
"thermostat-minus thermostat-temp thermostat-plus"
"thermostat-control thermostat-control thermostat-control";
border: .25rem solid var(--pico-blockquote-border-color);
padding: 0.5rem;
}
.thermostat-header {
justify-self: center;
align-self: end;
grid-area: thermostat-header;
font-size: 1rem;
font-weight: bold;
border-bottom: .25rem solid var(--pico-primary-hover-border);
margin: 0 0 1rem 0;
}
.thermostat-temp {
display: grid;
grid-template-columns: 1fr;
grid-template-rows: 1fr 0.5fr;
gap: 0px 0px;
grid-auto-flow: row;
grid-template-areas:
"thermostat-temp-target"
"thermostat-temp-current";
grid-area: thermostat-temp;
}
.thermostat-temp-target {
justify-self: center;
align-self: center;
grid-area: thermostat-temp-target;
font-weight: bold;
font-size: 1.75rem;
}
.thermostat-temp-current {
justify-self: center;
align-self: start;
grid-area: thermostat-temp-current;
color: var(--pico-secondary);
font-size: 0.85rem;
}
.thermostat-minus {
justify-self: end;
align-self: center;
grid-area: thermostat-minus;
}
.thermostat-plus {
justify-self: start;
align-self: center;
grid-area: thermostat-plus;
}
.thermostat-control {
justify-self: center;
align-self: start;
grid-area: thermostat-control;
margin: 1.25rem 0;
}
@media (max-width: 575px) {
.notify {
display: grid;
grid-template-columns: 1fr;
grid-template-rows: 1fr 0.5fr;
gap: 0.5rem 0.5rem;
grid-template-areas:
"notify-content"
"notify-actions";
}
.notify-icon {
display: none;
}
.notify-content {
justify-self: center;
align-self: center;
grid-area: notify-content;
}
.notify-actions {
justify-self: center;
align-self: center;
grid-area: notify-actions;
}
}
@media (min-width: 576px) {
.notify {
display: grid;
grid-template-columns: 5rem 1fr 10rem;
grid-template-rows: 1fr;
gap: 0rem 0.5rem;
grid-auto-flow: row;
grid-template-areas:
"notify-icon notify-content notify-actions";
}
.notify-icon {
justify-self: center;
align-self: center;
grid-area: notify-icon;
}
.notify-content {
justify-self: center;
align-self: center;
grid-area: notify-content;
}
.notify-actions {
justify-self: center;
align-self: center;
grid-area: notify-actions;
}
}
.notify {
margin: 1rem;
padding: 0.5rem;
border: .25rem solid var(--pico-blockquote-border-color);
}
.notify-error {
border-color: var(--pico-form-element-invalid-border-color);
}
.notify-error .notify-icon {
color: var(--pico-form-element-invalid-border-color);
}
.notify-alarm {
border-color: #c89048;
}
.notify-alarm .notify-icon {
color: #c89048;
}
.notify-icon i {
font-size: 2.5rem;
}
[class*=" icons-"],
[class=icons],
[class^=icons-] {
font-size: 1.35rem;
}
*:has(> [class*=" icons-"], > [class=icons], > [class^=icons-]):has(+ * > [class*=" icons-"], + * > [class=icons], + * > [class^=icons-]) {
margin: 0 0.5rem 0 0;
}
[data-tooltip]:has(> [class*=" icons-"], > [class=icons], > [class^=icons-]) {
border: 0 !important;
}
.icons-color-green {
color: var(--pico-form-element-valid-active-border-color);
}
.icons-color-yellow {
color: #c89048;
}
.icons-color-gray {
color: var(--pico-form-element-placeholder-color);
}
.icons-color-red {
color: var(--pico-form-element-invalid-active-border-color);
}
-80
View File
@@ -1,80 +0,0 @@
/*!
* Icons icon font. Generated by Iconly: https://iconly.io/
*/
@font-face {
font-display: auto;
font-family: "Icons";
font-style: normal;
font-weight: 400;
src: url("/static/fonts/iconly.eot?1732913937966");
src: url("/static/fonts/iconly.eot?#iefix") format("embedded-opentype"), url("/static/fonts/iconly.woff2?1732913937966") format("woff2"), url("/static/fonts/iconly.woff?1732913937966") format("woff"), url("/static/fonts/iconly.ttf?1732913937966") format("truetype"), url("/static/fonts/iconly.svg?1732913937966#Icons") format("svg");
}
[class="icons"], [class^="icons-"], [class*=" icons-"] {
display: inline-block;
font-family: "Icons" !important;
font-weight: 400;
font-style: normal;
font-variant: normal;
text-rendering: auto;
line-height: 1;
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
}
.icons-plus:before {
content: "\e000";
}
.icons-minus:before {
content: "\e001";
}
.icons-unlocked:before {
content: "\e002";
}
.icons-locked:before {
content: "\e003";
}
.icons-wifi-strength-1:before {
content: "\e004";
}
.icons-wifi-strength-0:before {
content: "\e005";
}
.icons-wifi-strength-2:before {
content: "\e006";
}
.icons-error:before {
content: "\e007";
}
.icons-wifi-strength-3:before {
content: "\e008";
}
.icons-down:before {
content: "\e009";
}
.icons-wifi-strength-4:before {
content: "\e00a";
}
.icons-success:before {
content: "\e00b";
}
.icons-up:before {
content: "\e00c";
}
.icons-alarm:before {
content: "\e00d";
}
-4
View File
@@ -1,4 +0,0 @@
@charset "UTF-8";/*!
* Pico CSS ✨ v2.0.6 (https://picocss.com)
* Copyright 2019-2024 - Licensed under MIT
*/:root{--pico-font-family-emoji:"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--pico-font-family-sans-serif:system-ui,"Segoe UI",Roboto,Oxygen,Ubuntu,Cantarell,Helvetica,Arial,"Helvetica Neue",sans-serif,var(--pico-font-family-emoji);--pico-font-family-monospace:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Consolas,"Liberation Mono",monospace,var(--pico-font-family-emoji);--pico-font-family:var(--pico-font-family-sans-serif);--pico-line-height:1.5;--pico-font-weight:400;--pico-font-size:100%;--pico-text-underline-offset:0.1rem;--pico-border-radius:0.25rem;--pico-border-width:0.0625rem;--pico-outline-width:0.125rem;--pico-transition:0.2s ease-in-out;--pico-spacing:1rem;--pico-typography-spacing-vertical:1rem;--pico-block-spacing-vertical:var(--pico-spacing);--pico-block-spacing-horizontal:var(--pico-spacing);--pico-grid-column-gap:var(--pico-spacing);--pico-grid-row-gap:var(--pico-spacing);--pico-form-element-spacing-vertical:0.75rem;--pico-form-element-spacing-horizontal:1rem;--pico-group-box-shadow:0 0 0 rgba(0, 0, 0, 0);--pico-group-box-shadow-focus-with-button:0 0 0 var(--pico-outline-width) var(--pico-primary-focus);--pico-group-box-shadow-focus-with-input:0 0 0 0.0625rem var(--pico-form-element-border-color);--pico-modal-overlay-backdrop-filter:blur(0.375rem);--pico-nav-element-spacing-vertical:1rem;--pico-nav-element-spacing-horizontal:0.5rem;--pico-nav-link-spacing-vertical:0.5rem;--pico-nav-link-spacing-horizontal:0.5rem;--pico-nav-breadcrumb-divider:">";--pico-icon-checkbox:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(255, 255, 255)' stroke-width='4' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='20 6 9 17 4 12'%3E%3C/polyline%3E%3C/svg%3E");--pico-icon-minus:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(255, 255, 255)' stroke-width='4' stroke-linecap='round' stroke-linejoin='round'%3E%3Cline x1='5' y1='12' x2='19' y2='12'%3E%3C/line%3E%3C/svg%3E");--pico-icon-chevron:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(136, 145, 164)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");--pico-icon-date:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(136, 145, 164)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='3' y='4' width='18' height='18' rx='2' ry='2'%3E%3C/rect%3E%3Cline x1='16' y1='2' x2='16' y2='6'%3E%3C/line%3E%3Cline x1='8' y1='2' x2='8' y2='6'%3E%3C/line%3E%3Cline x1='3' y1='10' x2='21' y2='10'%3E%3C/line%3E%3C/svg%3E");--pico-icon-time:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(136, 145, 164)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='12' cy='12' r='10'%3E%3C/circle%3E%3Cpolyline points='12 6 12 12 16 14'%3E%3C/polyline%3E%3C/svg%3E");--pico-icon-search:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(136, 145, 164)' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='11' cy='11' r='8'%3E%3C/circle%3E%3Cline x1='21' y1='21' x2='16.65' y2='16.65'%3E%3C/line%3E%3C/svg%3E");--pico-icon-close:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(136, 145, 164)' stroke-width='3' stroke-linecap='round' stroke-linejoin='round'%3E%3Cline x1='18' y1='6' x2='6' y2='18'%3E%3C/line%3E%3Cline x1='6' y1='6' x2='18' y2='18'%3E%3C/line%3E%3C/svg%3E");--pico-icon-loading:url("data:image/svg+xml,%3Csvg fill='none' height='24' width='24' viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg' %3E%3Cstyle%3E g %7B animation: rotate 2s linear infinite; transform-origin: center center; %7D circle %7B stroke-dasharray: 75,100; stroke-dashoffset: -5; animation: dash 1.5s ease-in-out infinite; stroke-linecap: round; %7D @keyframes rotate %7B 0%25 %7B transform: rotate(0deg); %7D 100%25 %7B transform: rotate(360deg); %7D %7D @keyframes dash %7B 0%25 %7B stroke-dasharray: 1,100; stroke-dashoffset: 0; %7D 50%25 %7B stroke-dasharray: 44.5,100; stroke-dashoffset: -17.5; %7D 100%25 %7B stroke-dasharray: 44.5,100; stroke-dashoffset: -62; %7D %7D %3C/style%3E%3Cg%3E%3Ccircle cx='12' cy='12' r='10' fill='none' stroke='rgb(136, 145, 164)' stroke-width='4' /%3E%3C/g%3E%3C/svg%3E")}@media (min-width:576px){:root{--pico-font-size:106.25%}}@media (min-width:768px){:root{--pico-font-size:112.5%}}@media (min-width:1024px){:root{--pico-font-size:118.75%}}@media (min-width:1280px){:root{--pico-font-size:125%}}@media (min-Line truncated
-458
View File
@@ -1,458 +0,0 @@
{
"Africa/Abidjan":"GMT0",
"Africa/Accra":"GMT0",
"Africa/Addis_Ababa":"EAT-3",
"Africa/Algiers":"CET-1",
"Africa/Asmara":"EAT-3",
"Africa/Bamako":"GMT0",
"Africa/Bangui":"WAT-1",
"Africa/Banjul":"GMT0",
"Africa/Bissau":"GMT0",
"Africa/Blantyre":"CAT-2",
"Africa/Brazzaville":"WAT-1",
"Africa/Bujumbura":"CAT-2",
"Africa/Cairo":"EET-2EEST,M4.5.5/0,M10.5.4/24",
"Africa/Casablanca":"<+01>-1",
"Africa/Ceuta":"CET-1CEST,M3.5.0,M10.5.0/3",
"Africa/Conakry":"GMT0",
"Africa/Dakar":"GMT0",
"Africa/Dar_es_Salaam":"EAT-3",
"Africa/Djibouti":"EAT-3",
"Africa/Douala":"WAT-1",
"Africa/El_Aaiun":"<+01>-1",
"Africa/Freetown":"GMT0",
"Africa/Gaborone":"CAT-2",
"Africa/Harare":"CAT-2",
"Africa/Johannesburg":"SAST-2",
"Africa/Juba":"CAT-2",
"Africa/Kampala":"EAT-3",
"Africa/Khartoum":"CAT-2",
"Africa/Kigali":"CAT-2",
"Africa/Kinshasa":"WAT-1",
"Africa/Lagos":"WAT-1",
"Africa/Libreville":"WAT-1",
"Africa/Lome":"GMT0",
"Africa/Luanda":"WAT-1",
"Africa/Lubumbashi":"CAT-2",
"Africa/Lusaka":"CAT-2",
"Africa/Malabo":"WAT-1",
"Africa/Maputo":"CAT-2",
"Africa/Maseru":"SAST-2",
"Africa/Mbabane":"SAST-2",
"Africa/Mogadishu":"EAT-3",
"Africa/Monrovia":"GMT0",
"Africa/Nairobi":"EAT-3",
"Africa/Ndjamena":"WAT-1",
"Africa/Niamey":"WAT-1",
"Africa/Nouakchott":"GMT0",
"Africa/Ouagadougou":"GMT0",
"Africa/Porto-Novo":"WAT-1",
"Africa/Sao_Tome":"GMT0",
"Africa/Tripoli":"EET-2",
"Africa/Tunis":"CET-1",
"Africa/Windhoek":"CAT-2",
"America/Adak":"HST10HDT,M3.2.0,M11.1.0",
"America/Anchorage":"AKST9AKDT,M3.2.0,M11.1.0",
"America/Anguilla":"AST4",
"America/Antigua":"AST4",
"America/Araguaina":"<-03>3",
"America/Argentina/Buenos_Aires":"<-03>3",
"America/Argentina/Catamarca":"<-03>3",
"America/Argentina/Cordoba":"<-03>3",
"America/Argentina/Jujuy":"<-03>3",
"America/Argentina/La_Rioja":"<-03>3",
"America/Argentina/Mendoza":"<-03>3",
"America/Argentina/Rio_Gallegos":"<-03>3",
"America/Argentina/Salta":"<-03>3",
"America/Argentina/San_Juan":"<-03>3",
"America/Argentina/San_Luis":"<-03>3",
"America/Argentina/Tucuman":"<-03>3",
"America/Argentina/Ushuaia":"<-03>3",
"America/Aruba":"AST4",
"America/Asuncion":"<-04>4<-03>,M10.1.0/0,M3.4.0/0",
"America/Atikokan":"EST5",
"America/Bahia":"<-03>3",
"America/Bahia_Banderas":"CST6",
"America/Barbados":"AST4",
"America/Belem":"<-03>3",
"America/Belize":"CST6",
"America/Blanc-Sablon":"AST4",
"America/Boa_Vista":"<-04>4",
"America/Bogota":"<-05>5",
"America/Boise":"MST7MDT,M3.2.0,M11.1.0",
"America/Cambridge_Bay":"MST7MDT,M3.2.0,M11.1.0",
"America/Campo_Grande":"<-04>4",
"America/Cancun":"EST5",
"America/Caracas":"<-04>4",
"America/Cayenne":"<-03>3",
"America/Cayman":"EST5",
"America/Chicago":"CST6CDT,M3.2.0,M11.1.0",
"America/Chihuahua":"CST6",
"America/Costa_Rica":"CST6",
"America/Creston":"MST7",
"America/Cuiaba":"<-04>4",
"America/Curacao":"AST4",
"America/Danmarkshavn":"GMT0",
"America/Dawson":"MST7",
"America/Dawson_Creek":"MST7",
"America/Denver":"MST7MDT,M3.2.0,M11.1.0",
"America/Detroit":"EST5EDT,M3.2.0,M11.1.0",
"America/Dominica":"AST4",
"America/Edmonton":"MST7MDT,M3.2.0,M11.1.0",
"America/Eirunepe":"<-05>5",
"America/El_Salvador":"CST6",
"America/Fort_Nelson":"MST7",
"America/Fortaleza":"<-03>3",
"America/Glace_Bay":"AST4ADT,M3.2.0,M11.1.0",
"America/Godthab":"<-02>2<-01>,M3.5.0/-1,M10.5.0/0",
"America/Goose_Bay":"AST4ADT,M3.2.0,M11.1.0",
"America/Grand_Turk":"EST5EDT,M3.2.0,M11.1.0",
"America/Grenada":"AST4",
"America/Guadeloupe":"AST4",
"America/Guatemala":"CST6",
"America/Guayaquil":"<-05>5",
"America/Guyana":"<-04>4",
"America/Halifax":"AST4ADT,M3.2.0,M11.1.0",
"America/Havana":"CST5CDT,M3.2.0/0,M11.1.0/1",
"America/Hermosillo":"MST7",
"America/Indiana/Indianapolis":"EST5EDT,M3.2.0,M11.1.0",
"America/Indiana/Knox":"CST6CDT,M3.2.0,M11.1.0",
"America/Indiana/Marengo":"EST5EDT,M3.2.0,M11.1.0",
"America/Indiana/Petersburg":"EST5EDT,M3.2.0,M11.1.0",
"America/Indiana/Tell_City":"CST6CDT,M3.2.0,M11.1.0",
"America/Indiana/Vevay":"EST5EDT,M3.2.0,M11.1.0",
"America/Indiana/Vincennes":"EST5EDT,M3.2.0,M11.1.0",
"America/Indiana/Winamac":"EST5EDT,M3.2.0,M11.1.0",
"America/Inuvik":"MST7MDT,M3.2.0,M11.1.0",
"America/Iqaluit":"EST5EDT,M3.2.0,M11.1.0",
"America/Jamaica":"EST5",
"America/Juneau":"AKST9AKDT,M3.2.0,M11.1.0",
"America/Kentucky/Louisville":"EST5EDT,M3.2.0,M11.1.0",
"America/Kentucky/Monticello":"EST5EDT,M3.2.0,M11.1.0",
"America/Kralendijk":"AST4",
"America/La_Paz":"<-04>4",
"America/Lima":"<-05>5",
"America/Los_Angeles":"PST8PDT,M3.2.0,M11.1.0",
"America/Lower_Princes":"AST4",
"America/Maceio":"<-03>3",
"America/Managua":"CST6",
"America/Manaus":"<-04>4",
"America/Marigot":"AST4",
"America/Martinique":"AST4",
"America/Matamoros":"CST6CDT,M3.2.0,M11.1.0",
"America/Mazatlan":"MST7",
"America/Menominee":"CST6CDT,M3.2.0,M11.1.0",
"America/Merida":"CST6",
"America/Metlakatla":"AKST9AKDT,M3.2.0,M11.1.0",
"America/Mexico_City":"CST6",
"America/Miquelon":"<-03>3<-02>,M3.2.0,M11.1.0",
"America/Moncton":"AST4ADT,M3.2.0,M11.1.0",
"America/Monterrey":"CST6",
"America/Montevideo":"<-03>3",
"America/Montreal":"EST5EDT,M3.2.0,M11.1.0",
"America/Montserrat":"AST4",
"America/Nassau":"EST5EDT,M3.2.0,M11.1.0",
"America/New_York":"EST5EDT,M3.2.0,M11.1.0",
"America/Nipigon":"EST5EDT,M3.2.0,M11.1.0",
"America/Nome":"AKST9AKDT,M3.2.0,M11.1.0",
"America/Noronha":"<-02>2",
"America/North_Dakota/Beulah":"CST6CDT,M3.2.0,M11.1.0",
"America/North_Dakota/Center":"CST6CDT,M3.2.0,M11.1.0",
"America/North_Dakota/New_Salem":"CST6CDT,M3.2.0,M11.1.0",
"America/Nuuk":"<-02>2<-01>,M3.5.0/-1,M10.5.0/0",
"America/Ojinaga":"CST6CDT,M3.2.0,M11.1.0",
"America/Panama":"EST5",
"America/Pangnirtung":"EST5EDT,M3.2.0,M11.1.0",
"America/Paramaribo":"<-03>3",
"America/Phoenix":"MST7",
"America/Port-au-Prince":"EST5EDT,M3.2.0,M11.1.0",
"America/Port_of_Spain":"AST4",
"America/Porto_Velho":"<-04>4",
"America/Puerto_Rico":"AST4",
"America/Punta_Arenas":"<-03>3",
"America/Rainy_River":"CST6CDT,M3.2.0,M11.1.0",
"America/Rankin_Inlet":"CST6CDT,M3.2.0,M11.1.0",
"America/Recife":"<-03>3",
"America/Regina":"CST6",
"America/Resolute":"CST6CDT,M3.2.0,M11.1.0",
"America/Rio_Branco":"<-05>5",
"America/Santarem":"<-03>3",
"America/Santiago":"<-04>4<-03>,M9.1.6/24,M4.1.6/24",
"America/Santo_Domingo":"AST4",
"America/Sao_Paulo":"<-03>3",
"America/Scoresbysund":"<-02>2<-01>,M3.5.0/-1,M10.5.0/0",
"America/Sitka":"AKST9AKDT,M3.2.0,M11.1.0",
"America/St_Barthelemy":"AST4",
"America/St_Johns":"NST3:30NDT,M3.2.0,M11.1.0",
"America/St_Kitts":"AST4",
"America/St_Lucia":"AST4",
"America/St_Thomas":"AST4",
"America/St_Vincent":"AST4",
"America/Swift_Current":"CST6",
"America/Tegucigalpa":"CST6",
"America/Thule":"AST4ADT,M3.2.0,M11.1.0",
"America/Thunder_Bay":"EST5EDT,M3.2.0,M11.1.0",
"America/Tijuana":"PST8PDT,M3.2.0,M11.1.0",
"America/Toronto":"EST5EDT,M3.2.0,M11.1.0",
"America/Tortola":"AST4",
"America/Vancouver":"PST8PDT,M3.2.0,M11.1.0",
"America/Whitehorse":"MST7",
"America/Winnipeg":"CST6CDT,M3.2.0,M11.1.0",
"America/Yakutat":"AKST9AKDT,M3.2.0,M11.1.0",
"America/Yellowknife":"MST7MDT,M3.2.0,M11.1.0",
"Antarctica/Casey":"<+08>-8",
"Antarctica/Davis":"<+07>-7",
"Antarctica/DumontDUrville":"<+10>-10",
"Antarctica/Macquarie":"AEST-10AEDT,M10.1.0,M4.1.0/3",
"Antarctica/Mawson":"<+05>-5",
"Antarctica/McMurdo":"NZST-12NZDT,M9.5.0,M4.1.0/3",
"Antarctica/Palmer":"<-03>3",
"Antarctica/Rothera":"<-03>3",
"Antarctica/Syowa":"<+03>-3",
"Antarctica/Troll":"<+00>0<+02>-2,M3.5.0/1,M10.5.0/3",
"Antarctica/Vostok":"<+05>-5",
"Arctic/Longyearbyen":"CET-1CEST,M3.5.0,M10.5.0/3",
"Asia/Aden":"<+03>-3",
"Asia/Almaty":"<+05>-5",
"Asia/Amman":"<+03>-3",
"Asia/Anadyr":"<+12>-12",
"Asia/Aqtau":"<+05>-5",
"Asia/Aqtobe":"<+05>-5",
"Asia/Ashgabat":"<+05>-5",
"Asia/Atyrau":"<+05>-5",
"Asia/Baghdad":"<+03>-3",
"Asia/Bahrain":"<+03>-3",
"Asia/Baku":"<+04>-4",
"Asia/Bangkok":"<+07>-7",
"Asia/Barnaul":"<+07>-7",
"Asia/Beirut":"EET-2EEST,M3.5.0/0,M10.5.0/0",
"Asia/Bishkek":"<+06>-6",
"Asia/Brunei":"<+08>-8",
"Asia/Chita":"<+09>-9",
"Asia/Choibalsan":"<+08>-8",
"Asia/Colombo":"<+0530>-5:30",
"Asia/Damascus":"<+03>-3",
"Asia/Dhaka":"<+06>-6",
"Asia/Dili":"<+09>-9",
"Asia/Dubai":"<+04>-4",
"Asia/Dushanbe":"<+05>-5",
"Asia/Famagusta":"EET-2EEST,M3.5.0/3,M10.5.0/4",
"Asia/Gaza":"EET-2EEST,M3.4.4/50,M10.4.4/50",
"Asia/Hebron":"EET-2EEST,M3.4.4/50,M10.4.4/50",
"Asia/Ho_Chi_Minh":"<+07>-7",
"Asia/Hong_Kong":"HKT-8",
"Asia/Hovd":"<+07>-7",
"Asia/Irkutsk":"<+08>-8",
"Asia/Jakarta":"WIB-7",
"Asia/Jayapura":"WIT-9",
"Asia/Jerusalem":"IST-2IDT,M3.4.4/26,M10.5.0",
"Asia/Kabul":"<+0430>-4:30",
"Asia/Kamchatka":"<+12>-12",
"Asia/Karachi":"PKT-5",
"Asia/Kathmandu":"<+0545>-5:45",
"Asia/Khandyga":"<+09>-9",
"Asia/Kolkata":"IST-5:30",
"Asia/Krasnoyarsk":"<+07>-7",
"Asia/Kuala_Lumpur":"<+08>-8",
"Asia/Kuching":"<+08>-8",
"Asia/Kuwait":"<+03>-3",
"Asia/Macau":"CST-8",
"Asia/Magadan":"<+11>-11",
"Asia/Makassar":"WITA-8",
"Asia/Manila":"PST-8",
"Asia/Muscat":"<+04>-4",
"Asia/Nicosia":"EET-2EEST,M3.5.0/3,M10.5.0/4",
"Asia/Novokuznetsk":"<+07>-7",
"Asia/Novosibirsk":"<+07>-7",
"Asia/Omsk":"<+06>-6",
"Asia/Oral":"<+05>-5",
"Asia/Phnom_Penh":"<+07>-7",
"Asia/Pontianak":"WIB-7",
"Asia/Pyongyang":"KST-9",
"Asia/Qatar":"<+03>-3",
"Asia/Qyzylorda":"<+05>-5",
"Asia/Riyadh":"<+03>-3",
"Asia/Sakhalin":"<+11>-11",
"Asia/Samarkand":"<+05>-5",
"Asia/Seoul":"KST-9",
"Asia/Shanghai":"CST-8",
"Asia/Singapore":"<+08>-8",
"Asia/Srednekolymsk":"<+11>-11",
"Asia/Taipei":"CST-8",
"Asia/Tashkent":"<+05>-5",
"Asia/Tbilisi":"<+04>-4",
"Asia/Tehran":"<+0330>-3:30",
"Asia/Thimphu":"<+06>-6",
"Asia/Tokyo":"JST-9",
"Asia/Tomsk":"<+07>-7",
"Asia/Ulaanbaatar":"<+08>-8",
"Asia/Urumqi":"<+06>-6",
"Asia/Ust-Nera":"<+10>-10",
"Asia/Vientiane":"<+07>-7",
"Asia/Vladivostok":"<+10>-10",
"Asia/Yakutsk":"<+09>-9",
"Asia/Yangon":"<+0630>-6:30",
"Asia/Yekaterinburg":"<+05>-5",
"Asia/Yerevan":"<+04>-4",
"Atlantic/Azores":"<-01>1<+00>,M3.5.0/0,M10.5.0/1",
"Atlantic/Bermuda":"AST4ADT,M3.2.0,M11.1.0",
"Atlantic/Canary":"WET0WEST,M3.5.0/1,M10.5.0",
"Atlantic/Cape_Verde":"<-01>1",
"Atlantic/Faroe":"WET0WEST,M3.5.0/1,M10.5.0",
"Atlantic/Madeira":"WET0WEST,M3.5.0/1,M10.5.0",
"Atlantic/Reykjavik":"GMT0",
"Atlantic/South_Georgia":"<-02>2",
"Atlantic/St_Helena":"GMT0",
"Atlantic/Stanley":"<-03>3",
"Australia/Adelaide":"ACST-9:30ACDT,M10.1.0,M4.1.0/3",
"Australia/Brisbane":"AEST-10",
"Australia/Broken_Hill":"ACST-9:30ACDT,M10.1.0,M4.1.0/3",
"Australia/Currie":"AEST-10AEDT,M10.1.0,M4.1.0/3",
"Australia/Darwin":"ACST-9:30",
"Australia/Eucla":"<+0845>-8:45",
"Australia/Hobart":"AEST-10AEDT,M10.1.0,M4.1.0/3",
"Australia/Lindeman":"AEST-10",
"Australia/Lord_Howe":"<+1030>-10:30<+11>-11,M10.1.0,M4.1.0",
"Australia/Melbourne":"AEST-10AEDT,M10.1.0,M4.1.0/3",
"Australia/Perth":"AWST-8",
"Australia/Sydney":"AEST-10AEDT,M10.1.0,M4.1.0/3",
"Europe/Amsterdam":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Andorra":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Astrakhan":"<+04>-4",
"Europe/Athens":"EET-2EEST,M3.5.0/3,M10.5.0/4",
"Europe/Belgrade":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Berlin":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Bratislava":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Brussels":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Bucharest":"EET-2EEST,M3.5.0/3,M10.5.0/4",
"Europe/Budapest":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Busingen":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Chisinau":"EET-2EEST,M3.5.0,M10.5.0/3",
"Europe/Copenhagen":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Dublin":"IST-1GMT0,M10.5.0,M3.5.0/1",
"Europe/Gibraltar":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Guernsey":"GMT0BST,M3.5.0/1,M10.5.0",
"Europe/Helsinki":"EET-2EEST,M3.5.0/3,M10.5.0/4",
"Europe/Isle_of_Man":"GMT0BST,M3.5.0/1,M10.5.0",
"Europe/Istanbul":"<+03>-3",
"Europe/Jersey":"GMT0BST,M3.5.0/1,M10.5.0",
"Europe/Kaliningrad":"EET-2",
"Europe/Kiev":"EET-2EEST,M3.5.0/3,M10.5.0/4",
"Europe/Kirov":"MSK-3",
"Europe/Lisbon":"WET0WEST,M3.5.0/1,M10.5.0",
"Europe/Ljubljana":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/London":"GMT0BST,M3.5.0/1,M10.5.0",
"Europe/Luxembourg":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Madrid":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Malta":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Mariehamn":"EET-2EEST,M3.5.0/3,M10.5.0/4",
"Europe/Minsk":"<+03>-3",
"Europe/Monaco":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Moscow":"MSK-3",
"Europe/Oslo":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Paris":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Podgorica":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Prague":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Riga":"EET-2EEST,M3.5.0/3,M10.5.0/4",
"Europe/Rome":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Samara":"<+04>-4",
"Europe/San_Marino":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Sarajevo":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Saratov":"<+04>-4",
"Europe/Simferopol":"MSK-3",
"Europe/Skopje":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Sofia":"EET-2EEST,M3.5.0/3,M10.5.0/4",
"Europe/Stockholm":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Tallinn":"EET-2EEST,M3.5.0/3,M10.5.0/4",
"Europe/Tirane":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Ulyanovsk":"<+04>-4",
"Europe/Uzhgorod":"EET-2EEST,M3.5.0/3,M10.5.0/4",
"Europe/Vaduz":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Vatican":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Vienna":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Vilnius":"EET-2EEST,M3.5.0/3,M10.5.0/4",
"Europe/Volgograd":"MSK-3",
"Europe/Warsaw":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Zagreb":"CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Zaporozhye":"EET-2EEST,M3.5.0/3,M10.5.0/4",
"Europe/Zurich":"CET-1CEST,M3.5.0,M10.5.0/3",
"Indian/Antananarivo":"EAT-3",
"Indian/Chagos":"<+06>-6",
"Indian/Christmas":"<+07>-7",
"Indian/Cocos":"<+0630>-6:30",
"Indian/Comoro":"EAT-3",
"Indian/Kerguelen":"<+05>-5",
"Indian/Mahe":"<+04>-4",
"Indian/Maldives":"<+05>-5",
"Indian/Mauritius":"<+04>-4",
"Indian/Mayotte":"EAT-3",
"Indian/Reunion":"<+04>-4",
"Pacific/Apia":"<+13>-13",
"Pacific/Auckland":"NZST-12NZDT,M9.5.0,M4.1.0/3",
"Pacific/Bougainville":"<+11>-11",
"Pacific/Chatham":"<+1245>-12:45<+1345>,M9.5.0/2:45,M4.1.0/3:45",
"Pacific/Chuuk":"<+10>-10",
"Pacific/Easter":"<-06>6<-05>,M9.1.6/22,M4.1.6/22",
"Pacific/Efate":"<+11>-11",
"Pacific/Enderbury":"<+13>-13",
"Pacific/Fakaofo":"<+13>-13",
"Pacific/Fiji":"<+12>-12",
"Pacific/Funafuti":"<+12>-12",
"Pacific/Galapagos":"<-06>6",
"Pacific/Gambier":"<-09>9",
"Pacific/Guadalcanal":"<+11>-11",
"Pacific/Guam":"ChST-10",
"Pacific/Honolulu":"HST10",
"Pacific/Kiritimati":"<+14>-14",
"Pacific/Kosrae":"<+11>-11",
"Pacific/Kwajalein":"<+12>-12",
"Pacific/Majuro":"<+12>-12",
"Pacific/Marquesas":"<-0930>9:30",
"Pacific/Midway":"SST11",
"Pacific/Nauru":"<+12>-12",
"Pacific/Niue":"<-11>11",
"Pacific/Norfolk":"<+11>-11<+12>,M10.1.0,M4.1.0/3",
"Pacific/Noumea":"<+11>-11",
"Pacific/Pago_Pago":"SST11",
"Pacific/Palau":"<+09>-9",
"Pacific/Pitcairn":"<-08>8",
"Pacific/Pohnpei":"<+11>-11",
"Pacific/Port_Moresby":"<+10>-10",
"Pacific/Rarotonga":"<-10>10",
"Pacific/Saipan":"ChST-10",
"Pacific/Tahiti":"<-10>10",
"Pacific/Tarawa":"<+12>-12",
"Pacific/Tongatapu":"<+13>-13",
"Pacific/Wake":"<+12>-12",
"Pacific/Wallis":"<+12>-12",
"Etc/UTC":"UTC0",
"Etc/GMT":"GMT0",
"Etc/GMT+1":"<-01>1",
"Etc/GMT+2":"<-02>2",
"Etc/GMT+3":"<-03>3",
"Etc/GMT+4":"<-04>4",
"Etc/GMT+5":"<-05>5",
"Etc/GMT+6":"<-06>6",
"Etc/GMT+7":"<-07>7",
"Etc/GMT+8":"<-08>8",
"Etc/GMT+9":"<-09>9",
"Etc/GMT+10":"<-10>10",
"Etc/GMT+11":"<-11>11",
"Etc/GMT+12":"<-12>12",
"Etc/GMT-1":"<+01>-1",
"Etc/GMT-2":"<+02>-2",
"Etc/GMT-3":"<+03>-3",
"Etc/GMT-4":"<+04>-4",
"Etc/GMT-5":"<+05>-5",
"Etc/GMT-6":"<+06>-6",
"Etc/GMT-7":"<+07>-7",
"Etc/GMT-8":"<+08>-8",
"Etc/GMT-9":"<+09>-9",
"Etc/GMT-10":"<+10>-10",
"Etc/GMT-11":"<+11>-11",
"Etc/GMT-12":"<+12>-12",
"Etc/GMT-13":"<+13>-13",
"Etc/GMT-14":"<+14>-14",
"Etc/Zulu":"UTC0"
}
+117
View File
@@ -0,0 +1,117 @@
@media (min-width: 576px) {
article {
--pico-block-spacing-vertical: calc(var(--pico-spacing) * 0.75);
--pico-block-spacing-horizontal: calc(var(--pico-spacing) * 0.75);
}
}
@media (min-width: 768px) {
article {
--pico-block-spacing-vertical: var(--pico-spacing);
--pico-block-spacing-horizontal: var(--pico-spacing);
}
}
@media (min-width: 1024px) {
article {
--pico-block-spacing-vertical: calc(var(--pico-spacing) * 1.25);
--pico-block-spacing-horizontal: calc(var(--pico-spacing) * 1.25);
}
}
@media (min-width: 1280px) {
article {
--pico-block-spacing-vertical: calc(var(--pico-spacing) * 1.5);
--pico-block-spacing-horizontal: calc(var(--pico-spacing) * 1.5);
}
.container {
max-width: 1000px;
}
}
@media (min-width: 1536px) {
article {
--pico-block-spacing-vertical: calc(var(--pico-spacing) * 1.75);
--pico-block-spacing-horizontal: calc(var(--pico-spacing) * 1.75);
}
.container {
max-width: 1000px;
}
}
header,
main,
footer {
padding-top: 1rem !important;
padding-bottom: 1rem !important;
}
article {
margin-bottom: 1rem;
}
footer {
text-align: center;
}
/*nav li a:has(> div.logo) {
margin-bottom: 0;
}*/
nav li :where(a, [role=link]) {
margin: 0;
}
details>div {
padding: 0 var(--pico-form-element-spacing-horizontal);
}
pre {
padding: 0.5rem;
}
:nth-last-child(1 of table tr:not(.hidden)) th,
:nth-last-child(1 of table tr:not(.hidden)) td {
border-bottom: 0 !important;
}
.hidden {
display: none !important;
}
button.success {
background-color: var(--pico-form-element-valid-border-color);
border-color: var(--pico-form-element-valid-border-color);
}
button.failed {
background-color: var(--pico-form-element-invalid-border-color);
border-color: var(--pico-form-element-invalid-border-color);
}
.primary {
border: 0.25rem solid var(--pico-form-element-invalid-border-color);
padding: 1rem;
margin-bottom: 1rem;
}
.logo {
display: inline-block;
padding: calc(var(--pico-nav-link-spacing-vertical) - var(--pico-border-width) * 2) var(--pico-nav-link-spacing-horizontal);
vertical-align: baseline;
line-height: var(--pico-line-height);
background-color: var(--pico-code-kbd-background-color);
border-radius: var(--pico-border-radius);
color: var(--pico-code-kbd-color);
font-weight: bolder;
font-size: 1.3rem;
font-family: var(--pico-font-family-monospace);
}
.powered-by {
margin: 2rem 0 0 0;
text-align: center;
opacity: 0.5;
}
-16
View File
@@ -1,16 +0,0 @@
import subprocess
Import("env")
try:
commit_hash = "undefined"
result = subprocess.check_output(
["git", "rev-parse", "--short", "HEAD"]
)
commit_hash = result.decode("utf-8").strip()
env.Append(
CPPDEFINES=[
("BUILD_COMMIT", '\\"{}\\"'.format(commit_hash))
]
)
except Exception as error:
print("Failed to get commit hash: {}".format(error))
-55
View File
@@ -1,55 +0,0 @@
"""Apply environment flags after SDK compile environments are prepared."""
from pathlib import Path
import re
Import("env")
# HybridCompile generates app_main when the SDK source directory is empty.
dummy = Path(env.subst("$PROJECT_DIR")) / ".dummy"
dummy.mkdir(exist_ok=True)
build_frameworks = env.BuildFrameworks
def no_exception_link_flags(sdk_directory):
cmake = (Path(sdk_directory) / "components/cxx/CMakeLists.txt").read_text()
wrappers = re.findall(r"set\(WRAP_FUNCTIONS\s+([^)]*)\)", cmake, re.S)
forced = re.findall(
r'if\(NOT CONFIG_COMPILER_CXX_EXCEPTIONS\)\s+'
r'target_link_libraries\(\$\{COMPONENT_LIB\} INTERFACE "(-u [A-Za-z_][A-Za-z0-9_]*)"\)\s+endif\(\)',
cmake
)
if len(wrappers) != 1 or len(forced) != 1:
raise RuntimeError("ESP-IDF C++ linker metadata changed; review tools/after_build_sdk.py")
symbols = wrappers[0].split()
if (not symbols or len(symbols) != len(set(symbols))
or not all(re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", symbol) for symbol in symbols)):
raise RuntimeError("Unsupported ESP-IDF C++ wrapper list")
return ["-Wl,--wrap=" + symbol for symbol in symbols] + forced[0].split()
def configure_after_build_sdk_flags(build_env, frameworks):
result = build_frameworks(frameworks)
# SDK environments are already cloned; project libraries are configured later.
flags = build_env.GetProjectOption("custom_app_flags", "")
build_env.ProcessFlags(flags)
link_flags = build_env.GetProjectOption("custom_link_flags", "").split()
sdkconfig = build_env.GetProjectOption("custom_sdkconfig", "")
if any(line.strip().strip("'\"") == "# CONFIG_COMPILER_CXX_EXCEPTIONS is not set"
for line in sdkconfig.splitlines()):
# HybridCompile does not transfer this component's interface linker flags.
sdk_directory = build_env.PioPlatform().get_package_dir("framework-espidf")
if not sdk_directory:
raise RuntimeError("ESP-IDF package is required for the C++ linker bridge")
link_flags += no_exception_link_flags(sdk_directory)
build_env.Append(LINKFLAGS=link_flags)
return result
env.AddMethod(configure_after_build_sdk_flags, "BuildFrameworks")
-545
View File
@@ -1,545 +0,0 @@
"""Print or save a diagnostic TXT from an ESP-IDF core dump without runtime strings.
Run with PlatformIO's Python, which supplies esp_coredump and pygdbmi.
"""
import argparse
import contextlib
import io
import json
import re
import struct
import sys
import time
import traceback
from pathlib import Path
from esp_coredump import CoreDump
from esp_coredump.corefile import RISCV_TARGETS, SUPPORTED_TARGETS, XTENSA_TARGETS
from esp_coredump.corefile.elf import ESPCoreDumpElfFile
from esp_coredump.corefile.loader import EspCoreDumpLoader, EspCoreDumpV1Header, EspCoreDumpVersion
from esp_coredump.corefile.xtensa import print_exc_regs_info
from pygdbmi.gdbcontroller import GdbController
HEAP_INFO_FIELDS = (
('total_free_bytes', 'Total free', ' bytes'),
('total_allocated_bytes', 'Total allocated', ' bytes'),
('largest_free_block', 'Largest free block', ' bytes'),
('minimum_free_bytes', 'Minimum free (SDK counter)', ' bytes'),
('allocated_blocks', 'Allocated blocks', ''),
('free_blocks', 'Free blocks', ''),
('total_blocks', 'Total blocks', ''),
)
class AnalysisError(Exception):
"""A diagnostic that contains only known tool/target identifiers."""
class Mi:
def __init__(self, command):
self.controller = GdbController(command=command)
self.token = 0
def command(self, command):
self.token += 1
token = self.token
self.controller.write(f'{token}{command}', read_response=False)
deadline = time.monotonic() + 15
while time.monotonic() < deadline:
responses = self.controller.get_gdb_response(timeout_sec=0.2, raise_error_on_timeout=False)
for response in responses:
if response.get('type') == 'result' and response.get('token') == token:
if response.get('message') == 'error':
return None
return response.get('payload') or {}
raise TimeoutError('GDB/MI command timed out')
def number(self, expression):
result = self.command('-data-evaluate-expression ' + json.dumps(expression))
if result is None:
return None
value = result.get('value', '')
if re.fullmatch(r'(?:0x[0-9a-fA-F]+|[0-9]+)', value):
return int(value, 0)
return None
def close(self):
# Exit through MI so Windows launchers also wait for the real GDB process.
self.command('-gdb-exit')
self.controller.gdb_process.wait(timeout=5)
self.controller.exit()
def saved_bytes(core, address, size):
for segment in core.load_segments:
offset = address - segment.addr
if offset >= 0 and offset + size <= len(segment.data):
return segment.data[offset:offset + size]
return None
def saved_number(mi, core, expression):
address = mi.number(f'(unsigned long)&{expression}')
size = mi.number(f'sizeof({expression})')
raw = saved_bytes(core, address, size) if address is not None and size else None
return int.from_bytes(raw, 'little') if raw is not None else None
def crash_metrics(mi, core):
crash_address = mi.number('(unsigned long)&crashMetrics')
memory_address = mi.number('(unsigned long)&memoryMetrics')
if crash_address is not None or memory_address is not None:
captured = saved_number(mi, core, 'crashMetrics.captured') if crash_address is not None else None
memory_captured = saved_number(mi, core, 'memoryMetrics.captured') if memory_address is not None else None
values = {'source': 'crashMetrics + memoryMetrics', 'captured': captured, 'heapCaptured': memory_captured,
'core': saved_number(mi, core, 'crashMetrics.core') if captured == 1 else None,
'uptime': saved_number(mi, core, 'crashMetrics.uptime') if captured == 1 else None,
'heapUptime': saved_number(mi, core, 'memoryMetrics.uptime') if memory_captured == 1 else None}
for heap in ('heap', 'psram'):
values[heap] = {name: saved_number(mi, core, f'memoryMetrics.{heap}.{name}') if memory_captured == 1 else None
for name, _, _ in HEAP_INFO_FIELDS}
return values
if mi.number('(unsigned long)&coreDumpMetrics') is not None:
if mi.number('(unsigned long)&coreDumpMetrics.heap.total_free_bytes') is not None:
names = ('captured', 'core', 'uptime', 'heapUptime')
if mi.number('(unsigned long)&coreDumpMetrics.heapCaptured') is not None:
names += ('heapCaptured',)
values = {name: saved_number(mi, core, f'coreDumpMetrics.{name}') for name in names}
for heap in ('heap', 'psram'):
values[heap] = {name: saved_number(mi, core, f'coreDumpMetrics.{heap}.{name}')
for name, _, _ in HEAP_INFO_FIELDS}
if values['captured'] != 1:
for name in names:
values[name] = None
if values['captured'] != 1 or values.get('heapCaptured', 1) != 1:
values['heapUptime'] = None
for heap in ('heap', 'psram'):
values[heap] = {name: None for name, _, _ in HEAP_INFO_FIELDS}
return {'source': 'coreDumpMetrics', **values}
captured = mi.number('(unsigned long)&coreDumpMetrics.captured') is not None
names = (('captured', 'heap', 'minimumHeap', 'core', 'uptime') if captured
else ('version', 'heap', 'minimumHeap', 'core', 'uptimeUs'))
values = {name: saved_number(mi, core, f'coreDumpMetrics.{name}') for name in names}
# The record is valid only after the current panic hook completes it.
if values['captured' if captured else 'version'] != 1:
values = {name: None for name in names}
return {'source': 'coreDumpMetrics', **values}
return {'source': 'CrashRecorder::ext', **{
name: saved_number(mi, core, f'CrashRecorder::ext.{name}') for name in ('heap', 'core', 'uptime')}}
def build_info(mi, core):
patterns = {'version': r'[A-Za-z0-9][A-Za-z0-9_.+ /:-]{0,95}',
'date': r'[A-Z][a-z]{2} {1,2}[0-9]{1,2} [0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2}',
'commit': r'(?:[0-9a-fA-F]{7,64}|undefined|unknown)(?:-dirty)?',
'env': r'[A-Za-z0-9][A-Za-z0-9_.+-]{0,95}',
'core': r'[A-Za-z0-9][A-Za-z0-9_.+ /:-]{0,95}',
'sdk': r'[A-Za-z0-9][A-Za-z0-9_.+ /:-]{0,95}',
'chipModel': r'ESP32(?:-[A-Za-z0-9]+)*'}
values = {}
for name, pattern in patterns.items():
expression = f'coreDumpBuildInfo.{name}'
address = mi.number(f'(unsigned long)&{expression}')
size = mi.number(f'sizeof({expression})')
raw = saved_bytes(core, address, size) if address is not None and size and size <= 128 else None
# Compile-time and SDK identifiers are bounded; SDK buffers can be zero-padded.
value = raw.split(b'\0', 1)[0].decode('ascii', errors='replace') if raw and b'\0' in raw else None
values[name] = value if value is not None and re.fullmatch(pattern, value) else None
for name in ('chipRevision', 'chipCores', 'cpuFreqMHz', 'flashChipSize'):
values[name] = saved_number(mi, core, f'coreDumpBuildInfo.{name}')
return values
def render_build_info(build):
lines = []
for name, label, unit in (('version', 'Firmware version', ''), ('date', 'Build date/time', ''),
('commit', 'Git commit', ''), ('env', 'PlatformIO environment', ''),
('core', 'Arduino core version', ''), ('sdk', 'ESP-IDF SDK version', ''),
('chipModel', 'Chip model', ''), ('chipRevision', 'Chip revision', ''),
('chipCores', 'Chip CPU cores', ''), ('cpuFreqMHz', 'CPU frequency at boot', ' MHz'),
('flashChipSize', 'Flash chip size', ' bytes')):
value = build[name]
lines.append(f'{label}: ' + (f'{value}{unit}' if value is not None else 'not captured or invalid'))
lines.append('Source: coreDumpBuildInfo; build and boot hardware identifiers are read only from saved PT_LOAD bytes.')
return lines
def render_metrics(metrics):
lines = []
sampled = isinstance(metrics['heap'], dict)
labels = {'core': 'CPU core at panic'} if sampled else {'heap': 'Free internal heap at panic', 'core': 'CPU core at panic'}
if metrics['source'] != 'CrashRecorder::ext' and not sampled:
labels['minimumHeap'] = 'Minimum free internal heap since boot (SDK counter)'
for name, label in labels.items():
value = metrics[name]
unit = ' bytes' if name in ('heap', 'minimumHeap') else ''
lines.append(f'{label}: ' + (f'{value}{unit}' if value is not None else 'not captured'))
if metrics['source'] != 'CrashRecorder::ext':
if 'uptime' in metrics:
uptime = metrics['uptime']
rendered = f'{uptime} milliseconds' if uptime is not None else 'not captured'
else:
uptime = metrics['uptimeUs']
rendered = f'{uptime // 1000}.{uptime % 1000:03} milliseconds (legacy microsecond record)' if uptime is not None else 'not captured'
lines.append('Uptime at panic: ' + rendered)
if sampled:
if metrics.get('heapCaptured', 1) != 1:
lines.append('Heap statistics not captured: update incomplete or unavailable.')
sampled_at = metrics['heapUptime']
lines.append('Heap snapshot uptime: ' + (f'{sampled_at} milliseconds' if sampled_at is not None else 'not captured'))
age = uptime - sampled_at if uptime is not None and sampled_at is not None else None
rendered_age = f'{age} milliseconds' if age is not None and age >= 0 else 'not available'
if age is not None and age < 0:
rendered_age = 'not available (snapshot timestamp is after panic)'
lines += ['Heap snapshot age at panic: ' + rendered_age,
'Heap statistics are the last completed snapshot, not measurements taken in the panic handler.']
for name, label in (('heap', 'INTERNAL HEAP'), ('psram', 'PSRAM HEAP')):
info = metrics[name]
lines += ['', label + ' (last completed snapshot)']
if name == 'psram' and info['total_free_bytes'] == 0 and info['total_allocated_bytes'] == 0:
lines.append('Not available (no registered PSRAM heap in the snapshot).')
continue
for field, description, unit in HEAP_INFO_FIELDS:
value = info[field]
lines.append(f'{description}: ' + (f'{value}{unit}' if value is not None else 'not captured'))
else:
uptime = metrics['uptime']
lines.append('Uptime at panic: ' + (f'{uptime} seconds' if uptime is not None else 'not captured'))
lines.append('Legacy metrics: uptime uses the original 32-bit millis()/1000 semantics; minimum heap was not recorded.')
lines.append(f"Source: {metrics['source']}; values are read only from saved PT_LOAD bytes, never substituted from the firmware ELF or a running device.")
return lines
def task_name(mi, tcb, firmware):
expression = f'(char*)((TCB_t*){tcb})->pcTaskName'
result = mi.command('-data-evaluate-expression ' + json.dumps(expression))
match = re.search(r'"([A-Za-z0-9_ .:/-]{1,16})"$', result.get('value', '')) if result else None
if match:
name = match.group(1)
# Kernel idle names can be formatted at runtime; other names must occur in the ELF.
if name in {'IDLE0', 'IDLE1'} or name.encode() + b'\0' in firmware:
return name
return 'not captured or not a known static task name'
def stack_frames(mi, thread):
result = mi.command(f'-stack-list-frames --thread {thread}')
if result is None:
return []
return [item.get('frame', item) for item in result.get('stack', [])]
def render_frame(frame):
location = frame.get('fullname') or frame.get('file')
if location and frame.get('line'):
location += ':' + str(frame['line'])
return (f"#{frame['level']} {frame.get('addr', '<address unavailable>')} "
f"{frame.get('func', '<symbol unavailable>')}"
+ (' at ' + location if location else ' [no DWARF source location]'))
def code_context(frames, directory):
if directory is None:
return []
for frame in frames:
source = frame.get('fullname') or frame.get('file', '')
basename = source.replace('\\', '/').rsplit('/', 1)[-1]
if basename != 'system.cpp' or not frame.get('line'):
continue
path = directory / basename
if not path.is_file():
continue
lines = path.read_text(encoding='utf-8').splitlines()
number = int(frame['line'])
start = max(0, number - 9)
end = min(len(lines), number + 3)
selected = lines[start:end]
# Only emit the deliberately authored test block, never unrelated source/configuration.
if not any('OTGateway native dump test ' in line for line in selected):
continue
if not any('esp_system_abort(' in line for line in selected):
continue
result = [f'DWARF location: {source}:{number}', f'Source snapshot: {path.resolve()}']
result += [f'{index + 1:5}: {lines[index]}' for index in range(start, end)]
return result
return ['Test source context not available in the supplied source-map directory.']
def target_machine(target):
if target in XTENSA_TARGETS:
return ESPCoreDumpElfFile.EM_XTENSA
if target in RISCV_TARGETS:
return ESPCoreDumpElfFile.EM_RISCV
raise AnalysisError('The installed esp-coredump does not support this dump target.')
def native_target(path):
with path.open('rb') as source:
header = source.read(EspCoreDumpV1Header.sizeof())
if len(header) != EspCoreDumpV1Header.sizeof():
raise AnalysisError('The native core dump header is incomplete.')
version = EspCoreDumpVersion(EspCoreDumpV1Header.parse(header).ver)
targets = {getattr(EspCoreDumpVersion, target.upper()): target for target in SUPPORTED_TARGETS}
if version.chip_ver not in targets:
raise AnalysisError('The native dump chip is not supported by the installed esp-coredump. Update the decoder.')
if version.dump_ver not in EspCoreDumpLoader.CORE_VERSIONS:
raise AnalysisError('The native dump format is not supported by the installed esp-coredump.')
return targets[version.chip_ver]
def validate_target(target, requested, elf_machine, core_machine=None):
expected = target_machine(target)
if requested != 'auto' and requested != target:
raise AnalysisError(f'--chip {requested} does not match dump target {target}.')
if elf_machine != expected or (core_machine is not None and core_machine != expected):
raise AnalysisError(f'Firmware/core ELF architecture does not match dump target {target}. Use the exact matching firmware ELF.')
return target
def default_gdb(platformio_home, target):
suffix = '.exe' if sys.platform == 'win32' else ''
if target in XTENSA_TARGETS:
directory = platformio_home / 'packages/tool-xtensa-esp-elf-gdb/bin'
names = (f'xtensa-{target}-elf-gdb', 'xtensa-esp-elf-gdb', 'xtensa-esp32-elf-gdb')
else:
directory = platformio_home / 'packages/tool-riscv32-esp-elf-gdb/bin'
names = ('riscv32-esp-elf-gdb',)
candidates = [directory / (name + suffix) for name in names]
return next((path for path in candidates if path.is_file()), candidates[0])
def default_rom(platformio_home, target, chip_rev):
if chip_rev is None:
return None
directory = platformio_home / 'packages/tool-esp-rom-elfs'
candidates = []
for path in directory.glob(f'{target}_rev*_rom.elf'):
match = re.fullmatch(rf'{re.escape(target)}_rev([0-9]+)_rom\.elf', path.name)
if match and int(match.group(1)) <= chip_rev:
candidates.append((int(match.group(1)), path))
return max(candidates)[1] if candidates else None
def gdb_arguments(dump, header, rom):
command = dump.get_gdb_args(is_dbg_mode=False, **header)
if rom is not None:
# SDK's add-symbol-file command omits filename quotes; support paths with spaces.
for index, argument in enumerate(command):
if argument.startswith('add-symbol-file '):
address = argument.rsplit(' ', 1)[-1]
command[index] = f'add-symbol-file {json.dumps(rom.as_posix())} {address}'
return command
def report(args):
program = ESPCoreDumpElfFile(str(args.elf))
if program.e_machine not in (ESPCoreDumpElfFile.EM_XTENSA, ESPCoreDumpElfFile.EM_RISCV):
raise AnalysisError('Firmware ELF must target an ESP32 Xtensa or RISC-V CPU.')
validate_target(native_target(args.dump), args.chip, program.e_machine)
dump = CoreDump(chip=args.chip, core=str(args.dump), core_format='raw', prog=str(args.elf))
temporary = []
mi = None
try:
header = dump.get_core_header_info_dict(e_machine=program.e_machine)
temporary = header.pop('temp_files') or []
dump.core_elf = ESPCoreDumpElfFile(header['core_elf_path'])
target = validate_target(header['target'], args.chip, program.e_machine, dump.core_elf.e_machine)
gdb = args.gdb or default_gdb(args.platformio_home, target)
if not gdb.is_file():
raise AnalysisError(f'GDB for {target} was not found; use --gdb or --platformio-home to select installed tools.')
dump.gdb = str(gdb)
rom = args.rom or default_rom(args.platformio_home, target, header['chip_rev'])
dump.rom_elf = str(rom) if rom is not None else None
if rom is None:
resolved = dump.get_rom_elf_path(target=target, chip_rev=header['chip_rev'])
rom = Path(resolved) if resolved and Path(resolved).is_file() else None
dump.rom_elf = str(rom) if rom is not None else None
if rom is not None and ESPCoreDumpElfFile(str(rom)).e_machine != program.e_machine:
raise AnalysisError(f'ROM ELF architecture does not match dump target {target}. Select a target-compatible --rom.')
xtensa = target_machine(target) == ESPCoreDumpElfFile.EM_XTENSA
task_info, extra = dump.get_task_info_extra_note_tuple()
panic = dump.get_panic_details()
reason = panic.desc.decode('utf-8', errors='replace') if panic else ''
known_reason = re.fullmatch(
r'OTGateway native dump test OTG-S3-[0-9]{8}-r[0-9]+; uptime_us=([0-9]+); marker=43525348', reason)
low_heap = reason == 'OTGateway: low internal heap'
startup_failure = re.fullmatch(r'Failed to start (?:OpenTherm|Core|System) task manager', reason)
words = struct.unpack('<' + 'I' * (len(extra.desc) // 4), extra.desc) if extra else ()
crashed_tcb = words[0] if words else None
mi = Mi(gdb_arguments(dump, header, rom))
architecture = 'xtensa' if xtensa else 'riscv:rv32'
if mi.command('-gdb-set architecture ' + architecture) is None:
raise AnalysisError(f'The selected GDB architecture does not match dump target {target}. Use the target-compatible GDB.')
mi.command('-gdb-set architecture auto')
mi.command('-gdb-set pagination off')
mi.command('-gdb-set print frame-arguments none')
threads = mi.command('-thread-info')
if threads is None:
raise RuntimeError('Thread information unavailable')
current = str(threads.get('current-thread-id', '1'))
firmware = args.elf.read_bytes()
tasks = []
for thread in threads.get('threads', []):
thread_id = str(thread['id'])
match = re.fullmatch(r'process (0x[0-9a-fA-F]+|[0-9]+)', thread.get('target-id', ''))
tcb = int(match.group(1), 0) if match else None
fields = {}
if tcb is not None:
for field in ('uxPriority', 'uxBasePriority', 'pxStack', 'pxTopOfStack', 'pxEndOfStack'):
fields[field] = mi.number(f'(unsigned long)((TCB_t*){tcb})->{field}')
tasks.append({'id': thread_id, 'tcb': tcb, 'name': task_name(mi, tcb, firmware) if tcb else 'unknown',
'fields': fields, 'frames': stack_frames(mi, thread_id)})
if tcb == crashed_tcb:
current = thread_id
mi.command(f'-thread-select {current}')
current_task = next(task for task in tasks if task['id'] == current)
metrics = crash_metrics(mi, dump.core_elf)
build = build_info(mi, dump.core_elf)
register_names = mi.command('-data-list-register-names') or {}
registers = mi.command('-data-list-register-values x') or {}
lines = ['OTGateway ESP32 core dump report', '', f'Target: {target} ({"Xtensa" if xtensa else "RISC-V"})',
f'Dump: {args.dump.resolve()}',
f'Firmware ELF: {args.elf.resolve()}', f'Dump size: {args.dump.stat().st_size} bytes',
'Decoder: installed esp_coredump + GDB/MI; no device access',
'ROM symbols: ' + ('available' if rom is not None else 'not available; ROM frames may lack symbols'),
'', 'BUILD INFORMATION']
lines += render_build_info(build) + ['', 'PANIC CAUSE']
abort_explanation = ('IllegalInstruction is the intentional trap used by this abort call.' if xtensa
else 'The abort deliberately stopped execution; the symbolic call stack identifies the call site.')
if known_reason:
lines += [reason, 'Cause: deliberate esp_system_abort() call; the saved caller frames identify the call site.',
f'Uptime at the test call: {known_reason.group(1)} us']
origin = next((frame for frame in current_task['frames']
if (frame.get('fullname') or frame.get('file', '')).replace('\\', '/').endswith('/system.cpp')
and frame.get('line')), None)
if origin:
lines.append(f"Application call site: {origin.get('fullname') or origin['file']}:{origin['line']}")
lines.append(abort_explanation)
elif low_heap:
lines += ['OTGateway: low internal heap',
'Cause: low-heap protection deliberately called esp_system_abort() in the heap-monitoring task.',
'The protection detected less than 2048 bytes of free internal heap or largest free block.',
('The cached heap snapshot below can predate the low-heap guard; its values are not panic-time measurements.'
if isinstance(metrics['heap'], dict) else
'Largest free block is not captured; the low-heap guard can also trigger on a small largest block.'),
abort_explanation]
elif startup_failure:
lines += [reason, 'Cause: task manager startup failed; the application deliberately called esp_system_abort().',
abort_explanation]
else:
lines += ['Panic text not captured or outside the known diagnostic formats; arbitrary text omitted.',
'Use the exception registers and symbolic call stack below for the cause.']
lines += [f"Crashed thread: {current}; task: {current_task['name']}; TCB: {crashed_tcb:#x}" if crashed_tcb
else f'Crashed thread: {current}', '', 'ADDITIONAL CRASH METRICS (saved in the core dump)']
lines += render_metrics(metrics) + ['', 'EXCEPTION REGISTERS']
if xtensa and len(words) >= 5:
exception_output = io.StringIO()
with contextlib.redirect_stdout(exception_output):
print_exc_regs_info(words)
lines += exception_output.getvalue().splitlines()
elif not xtensa:
lines.append('RISC-V extra exception details are not decoded here; see the numeric GDB registers below.')
else:
lines.append('Xtensa exception registers were not captured.')
lines += ['', 'CRASHED THREAD REGISTERS']
names = register_names.get('register-names', [])
for register in registers.get('register-values', []):
value = register.get('value', '')
index = int(register['number'])
if re.fullmatch(r'0x[0-9a-fA-F]+', value) and index < len(names) and names[index]:
lines.append(f'{names[index]:16} {value}')
lines += ['', 'COMPLETE CRASHED THREAD STACK (all frames returned by GDB; arguments omitted)']
lines += [render_frame(frame) for frame in current_task['frames']]
if known_reason:
for frame in current_task['frames']:
source = (frame.get('fullname') or frame.get('file', '')).replace('\\', '/')
if source.endswith('/system.cpp'):
mi.command(f"-stack-select-frame {frame['level']}")
lines += ['', 'SELECTED TEST FRAME VALUES']
for name in ('diagnosticMarker', 'crashUptimeUs'):
value = mi.number(f'(unsigned long long){name}')
rendered = f'{value:#x} ({value})' if value is not None else 'not available in this frame'
lines.append(f'{name}: {rendered}')
break
lines += ['', 'TEST CALL SOURCE CONTEXT'] + code_context(current_task['frames'], args.source_map)
lines += ['', f'ALL SAVED TASKS ({len(tasks)})',
'Stack used/free are byte estimates from saved TCB pointers, as in esp-coredump; not high-water marks.',
'The running task TCB pxTopOfStack may precede the fault; its estimate is not an exact panic-time measurement.',
'No frame count limit is applied. Unwinding stops where GDB cannot recover further frames.',
'Missing source locations are reported explicitly; missing DWARF cannot be reconstructed.']
for task in tasks:
fields = task['fields']
tcb_text = f"0x{task['tcb']:08x}" if task['tcb'] is not None else 'unknown'
lines += ['', f"Thread {task['id']}: {task['name']}; TCB {tcb_text}" + (' [CRASHED]' if task['id'] == current else '')]
lines.append(f"Priority current/base: {fields.get('uxPriority')}/{fields.get('uxBasePriority')}")
start, top, end = (fields.get(key) for key in ('pxStack', 'pxTopOfStack', 'pxEndOfStack'))
if all(value is not None for value in (start, top, end)):
lines += [f'Stack start/top/end: {start:#x}/{top:#x}/{end:#x}',
f'Stack used/free estimate: {abs(end - top)}/{abs(top - start)} bytes']
else:
lines.append('Stack bounds/used/free: not captured')
lines += [render_frame(frame) for frame in task['frames']]
if not task['frames']:
lines.append('Stack unavailable to GDB.')
lines += ['', 'Runtime arguments, arbitrary local variables and memory strings are omitted.']
return '\n'.join(lines) + '\n', {
'tasks': len(tasks), 'current_frames': len(current_task['frames']),
'all_frames': sum(len(task['frames']) for task in tasks),
'source_frames': sum(bool(frame.get('line')) for task in tasks for frame in task['frames']),
'report_lines': len(lines),
'heap_captured': (metrics['heap']['total_free_bytes'] is not None if isinstance(metrics['heap'], dict)
else metrics['heap'] is not None)}
finally:
if mi is not None:
mi.close()
for path in temporary:
Path(path).unlink(missing_ok=True)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('dump', type=Path)
parser.add_argument('elf', type=Path)
parser.add_argument('output', type=Path, nargs='?', help='Report file; omit to print the report to stdout')
parser.add_argument('--stdout', action='store_true', help='Print the report, also when an output file is supplied')
parser.add_argument('--source-map', type=Path, help='Directory of matching source snapshots for the test call context')
parser.add_argument('--platformio-home', type=Path, default=Path.home() / '.platformio')
parser.add_argument('--chip', choices=['auto', *SUPPORTED_TARGETS], default='auto',
help='Verify the dump target; default: detect from the native core dump header')
parser.add_argument('--gdb', type=Path)
parser.add_argument('--rom', type=Path)
args = parser.parse_args()
if not args.dump.is_file():
parser.error('Core dump file not found; supply an existing native raw core dump.')
if not args.elf.is_file():
parser.error('Firmware ELF not found; supply the exact ELF from the crashed firmware build.')
if args.gdb is not None and not args.gdb.is_file():
parser.error('GDB executable not found; use --gdb or --platformio-home to select the installed PlatformIO tools.')
if args.rom is not None and not args.rom.is_file():
parser.error('ROM ELF not found; use --rom to select an existing target-compatible ROM ELF.')
# Decoder/GDB diagnostics can contain arbitrary target data: keep them in memory.
try:
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
text, result = report(args)
if args.output is not None:
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(text, encoding='utf-8')
if args.stdout or args.output is None:
print(text, end='')
else:
print(json.dumps(result))
except Exception as error:
if isinstance(error, AnalysisError):
print(str(error), file=sys.stderr)
return 1
frame = traceback.extract_tb(error.__traceback__)[-1]
print(json.dumps({'error_type': type(error).__name__,
'error_location': f'{Path(frame.filename).name}:{frame.lineno}'}), file=sys.stderr)
return 1
return 0
if __name__ == '__main__':
raise SystemExit(main())
-43
View File
@@ -1,43 +0,0 @@
import shutil
import os
Import("env")
def post_build(source, target, env):
copy_to_build_dir({
source[0].get_abspath(): "firmware_%s_%s.bin" % (env["PIOENV"], env.GetProjectOption("custom_version")),
env.subst("$BUILD_DIR/${PROGNAME}.factory.bin"): "firmware_%s_%s.factory.bin" % (env["PIOENV"], env.GetProjectOption("custom_version")),
env.subst("$BUILD_DIR/${PROGNAME}.elf"): "firmware_%s_%s.elf" % (env["PIOENV"], env.GetProjectOption("custom_version"))
}, os.path.join(env["PROJECT_DIR"], "build"));
return env.Execute('"$PYTHONEXE" -m platformio run --target buildfs --environment "$PIOENV"')
def before_buildfs(source, target, env):
result = env.Execute("npm install --silent")
if result:
return result
return env.Execute("npx gulp build_all --no-deprecation")
def after_buildfs(source, target, env):
copy_to_build_dir({
source[0].get_abspath(): "filesystem_%s_%s.bin" % (env["PIOENV"], env.GetProjectOption("custom_version")),
}, os.path.join(env["PROJECT_DIR"], "build"));
def copy_to_build_dir(files, build_dir):
if os.path.exists(build_dir) == False:
return
for src in files:
if os.path.exists(src):
dst = os.path.join(build_dir, files[src])
print("Copying '%s' to '%s'" % (src, dst))
shutil.copy(src, dst)
env.AddPostAction("buildprog", post_build)
env.AddPreAction("$BUILD_DIR/spiffs.bin", before_buildfs)
env.AddPreAction("$BUILD_DIR/littlefs.bin", before_buildfs)
env.AddPostAction("buildfs", after_buildfs)
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff. Show more