Compare commits

..
631 Commits
Author SHA1 Message Date
Yurii 435b2fe1c5 docs: organize and refresh wiki illustrations
Move active board, adapter and Home Assistant images into assets/wiki.
Add English and Russian screenshots for weather compensation and
manual outdoor temperature configuration.

Remove unused legacy assembly and connection pictures.
2026-11-23 07:36:55 +03:00
Yurii eb5f6c9b46 fix: correct threshold names across firmware and portal
Use threshold_time for the emergency-mode delay in settings, JSON,
portal forms and all five translations.

Convert legacy tresholdTime backup fields to threshold_time.
Correct the NTC voltage threshold macro names while keeping their limits.
2026-11-23 07:36:30 +03:00
Yurii d6e1ccb22b fix: use unique device defaults and MQTT client identifiers
Allow empty hostname and MQTT prefix defaults to use chip-derived names.
Use the configured MQTT prefix as the broker client identifier.
2026-11-23 07:36:06 +03:00
Yurii 7e1d0ddff2 feat: expose smart heating control across device interfaces
Rename indoor_temp_control to smart_control across firmware, REST,
the dashboard and Home Assistant.

Publish state/master/heating/smart_control over MQTT and remove the
redundant state/master/mqtt/connected topic.
2026-11-23 07:35:37 +03:00
Yurii 9ff1bd14f5 refactor: remove unused code from firmware, portal and build scripts
Remove the unused sensor connection getter, slug prefix and suffix helpers, UTC conversion and array formatting routines. Drop unused shared strings and the CONFIG_URL macro.

Remove setupUpgradeForm from the shared browser bundle. The upgrade page registers its own submit handler.

Delete the obsolete Python gzip packer and its import. Gulp handles compression when building the web assets.
2026-11-22 03:27:25 +03:00
Yurii 3a530d721e docs: update the third-party library list in Gratitude
Replace retired dependencies with the libraries used by the firmware and credit the upstream esp32DHT project.
2026-11-22 02:43:09 +03:00
Yurii 8f659e3e55 feat: add offline ESP32 core dump analysis
Decode native ESP-IDF core dumps against a matching firmware ELF. Report the target, build identity, task stacks, registers, and saved heap metrics with the PlatformIO GDB toolchain.
2026-11-22 02:35:31 +03:00
Yurii 0a6ae9c5d8 feat: update the web portal for the new firmware APIs
Restore legacy backups through the settings APIs, update the dashboard and sensor controls, and keep translations in sync. Package the backup converter separately and wait for all compressed web assets before building LittleFS.
2026-11-22 02:35:04 +03:00
Yurii 3fb433d3eb refactor: migrate ESP32 firmware to task-managed services
Split the header-based firmware into services for OpenTherm, heating control, sensors, networking, logging, and the portal. Run these services with MycilaTaskManager and use ESP32OT for the boiler bus.

Move MQTT and Home Assistant discovery to Mycila libraries, expose native crash metrics, and align the board profiles and build hooks with the new dependencies.
2026-11-22 02:34:37 +03:00
Yurii b10d91b8fa build: enforce the firmware size limit before creating factory images
Reject images that exceed the application slot, propagate esptool failures, and run the build workflow when the PlatformIO hooks change.
2026-11-22 02:32:55 +03:00
Yurii fc00b3a391 chore: document project engineering and coding conventions
Record the ESP32 development, verification, and coding guidelines. Keep local engineering notes out of Git while retaining the directory placeholder.
2026-11-22 02:31:51 +03:00
Yurii 0439b6f7c4 perf: replace global buffer with MQTT config URL storage 2026-10-25 04:50:43 +03:00
Yurii 353452784f chore: revert README 2026-10-21 14:04:08 +03:00
Yurii b72bccb3d7 refactor: remove ESP8266 support and legacy flash wrappers 2026-10-21 04:34:00 +03:00
Yurii 959a15c11f feat: add authenticated WebSerial log viewer 2026-10-20 07:05:00 +03:00
Yurii 734615e7b5 fix: pin Python version for firmware builds 2026-10-20 05:52:08 +03:00
Yurii c698337b95 fix: always send initial OpenTherm setpoints 2026-10-20 05:26:31 +03:00
Yurii c63b8d44a1 feat: configure OpenTherm channel disabling actions 2026-10-20 05:26:31 +03:00
Yurii 4581ca49cb fix: separate room and heating setpoint state 2026-10-20 05:26:31 +03:00
Yurii cd8764bb97 fix: encode OpenTherm weekdays from one to seven 2026-10-19 20:06:23 +03:00
Yurii 16308866ce fix: render API strings as text to prevent XSS 2026-10-19 20:05:57 +03:00
Yurii f2047b18ba fix: decode heat exchanger temperature as f8.8 2026-10-19 20:05:22 +03:00
Yurii 69ed4ef86c fix: handle BLE initialization failures 2026-10-19 05:24:47 +03:00
Yurii 9cf10201f6 fix: preserve sensor names as strings 2026-10-19 05:22:31 +03:00
Yurii 549dbf4985 fix: reject invalid hostnames safely 2026-10-19 05:22:31 +03:00
Yurii 63aeb2fa25 fix: validate sensor IDs before narrowing 2026-10-19 05:22:30 +03:00
Yurii ab5b96c970 fix: render scanned Wi-Fi names as text 2026-10-19 05:22:30 +03:00
Yurii f613731183 fix: prevent hangs when processing long sensor names 2026-10-19 04:10:21 +03:00
Yurii 85dda5b859 fix: enforce minimum heating setpoint during freeze protection 2026-10-19 03:09:26 +03:00
Yurii 451fe92b7a chore: bump dependencies and fix build for ESP32 C6 2026-10-14 00:17:22 +03:00
Yurii 1695e1ea0d chore: fix build for ESP32 C6 2026-10-13 03:36:59 +03:00
Yurii 00a80f82f1 chore: bump dependencies 2026-10-12 05:44:17 +03:00
Yurii e95045b9b6 Merge branch 'master' into async 2026-10-12 05:42:21 +03:00
Yurii c6df5b59cf fix(opentherm): fixes the inability to enable channels if the max modulation level has become zero for some reason 2026-10-12 04:17:33 +03:00
dependabot[bot]andYurii 2623ac17dc chore: bump cssnano from 8.0.10 to 9.3.2 (#280)
Bumps [cssnano](https://github.com/cssnano/cssnano) from 8.0.10 to 9.3.2.
- [Release notes](https://github.com/cssnano/cssnano/releases)
- [Commits](https://github.com/cssnano/cssnano/compare/cssnano@8.0.10...cssnano@9.3.2)

---
updated-dependencies:
- dependency-name: cssnano
  dependency-version: 9.3.2
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Yurii <34578544+Laxilef@users.noreply.github.com>
2026-10-12 03:47:54 +03:00
dependabot[bot] 29321d5c53 chore: bump cssnano-preset-advanced from 8.0.10 to 9.2.2 (#279)
Bumps [cssnano-preset-advanced](https://github.com/cssnano/cssnano) from 8.0.10 to 9.2.2.
- [Release notes](https://github.com/cssnano/cssnano/releases)
- [Commits](https://github.com/cssnano/cssnano/compare/cssnano@8.0.10...cssnano@9.2.2)

---
updated-dependencies:
- dependency-name: cssnano-preset-advanced
  dependency-version: 9.2.2
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-12 03:46:15 +03:00
dependabot[bot] 1290e1d33c chore: bump actions/stale from 10 to 11 (#255)
Bumps [actions/stale](https://github.com/actions/stale) from 10 to 11.
- [Release notes](https://github.com/actions/stale/releases)
- [Changelog](https://github.com/actions/stale/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/stale/compare/v10...v11)

---
updated-dependencies:
- dependency-name: actions/stale
  dependency-version: '11'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-12 03:45:59 +03:00
Weblate (bot)andYurii ee68aba128 refactor(translation): deleted Estonian language (#254)
Co-authored-by: Yurii <34578544+Laxilef@users.noreply.github.com>
2026-07-25 21:29:44 +03:00
Yurii 54217fbbc1 chore(git): fix update notes for dev release 2026-05-21 13:37:51 +03:00
Yurii 69116aa3d2 chore(git): fix update of dev tag 2026-05-21 13:27:38 +03:00
Yurii bb6b3f1854 chore(git): update build workflow 2026-05-21 13:16:30 +03:00
Yurii a4ca20f9a9 fix(portal): fix i18n name for extPump.invertState 2026-05-19 23:25:24 +03:00
f5e08f20a2 refactor(translation): update translation files (#249)
* feat(translation): added Estonian language

* refactor(translation): updated Chinese (Simplified Han script) language

Currently translated at 100.0% (355 of 355 strings)

Translation: OTGateway/Portal
Translate-URL: https://hosted.weblate.org/projects/otgateway/portal/zh_Hans/

* refactor(translation): updated Russian language

Currently translated at 100.0% (355 of 355 strings)

Translation: OTGateway/Portal
Translate-URL: https://hosted.weblate.org/projects/otgateway/portal/ru/

* refactor(translation): updated Dutch language

Currently translated at 100.0% (355 of 355 strings)

Translation: OTGateway/Portal
Translate-URL: https://hosted.weblate.org/projects/otgateway/portal/nl/

* refactor(translation): updated Italian language

Currently translated at 100.0% (355 of 355 strings)

Translation: OTGateway/Portal
Translate-URL: https://hosted.weblate.org/projects/otgateway/portal/it/

---------

Co-authored-by: Priit Jõerüüt <jrthwlate@users.noreply.hosted.weblate.org>
Co-authored-by: Yurii <34578544+Laxilef@users.noreply.github.com>
2026-05-19 21:55:14 +03:00
Yurii 07650b4878 refactor: improved dashboard & restore settings 2026-05-19 21:39:29 +03:00
Yurii ffcacb3d48 fix: translation for volume unit 2026-05-19 19:42:29 +03:00
Yurii bdfa793c49 chore: update build workflow 2026-05-18 00:36:30 +03:00
Yurii 25280bf9b1 chore: added build workflow 2026-05-17 19:32:27 +03:00
Yurii 9c2e420ec7 refactor: use localtime_r(...) for thread safety 2026-05-17 04:46:47 +03:00
Yurii af2d4624b3 chore: fix cpplint 2026-05-17 04:38:53 +03:00
Yurii 14d2262d2f chore: added CI workflow 2026-05-17 03:57:59 +03:00
Yurii db99746ee9 feat: added choice of averaging type for indoor and outdoor temperatures (#244)
* feat: added a choice of averaging type for indoor and outdoor temperatures

* refactor: locales updated

* refactor: some changes
2026-05-16 17:58:13 +03:00
Yurii bfc1cc1118 chore: update README 2026-05-16 17:14:00 +03:00
Yurii 01a70b3288 refactor(translation): updated Dutch language
Currently translated at 100.0% (346 of 346 strings)

Translation: OTGateway/Portal
Translate-URL: https://hosted.weblate.org/projects/otgateway/portal/nl/
2026-05-16 16:40:25 +03:00
Yurii 5d053690c6 refactor(translation): updated Chinese (Simplified Han script) language
Currently translated at 100.0% (346 of 346 strings)

Translation: OTGateway/Portal
Translate-URL: https://hosted.weblate.org/projects/otgateway/portal/zh_Hans/
2026-05-16 16:40:25 +03:00
Yurii ea95b5fa7d refactor(translation): updated Italian language
Currently translated at 100.0% (346 of 346 strings)

Translation: OTGateway/Portal
Translate-URL: https://hosted.weblate.org/projects/otgateway/portal/it/
2026-05-16 16:40:25 +03:00
Yurii dd9cb0b88f refactor(translation): updated English language
Currently translated at 100.0% (346 of 346 strings)

Translation: OTGateway/Portal
Translate-URL: https://hosted.weblate.org/projects/otgateway/portal/en/
2026-05-16 16:40:25 +03:00
Weblate (bot)andYurii ec7a24ce0c refactor(translation): updated Russian language (#245)
Currently translated at 100.0% (346 of 346 strings)

Translation: OTGateway/Portal
Translate-URL: https://hosted.weblate.org/projects/otgateway/portal/ru/

Co-authored-by: Yurii <laxilef@gmail.com>
2026-05-16 16:00:23 +03:00
Yurii 44fb0afffa refactor: reformat locales 2026-05-16 13:42:28 +03:00
Yurii ef1d6bf195 refactor: update locales 2026-05-15 23:27:51 +03:00
Yurii 2bd3360880 Merge branch 'master' into async 2026-05-11 14:32:24 +03:00
Yurii cbc32fd378 refactor: reworking the freeze protection algorithm (#242)
* refactor: impoved freeze protection

* refactor: reworked freeze protection
2026-05-11 14:26:14 +03:00
Yurii 79e3c6d433 chore: update version name 2026-05-10 09:47:29 +03:00
Yurii 8186e17912 refactor: BLE scanning instead of connecting to BLE devices (#243)
* refactor: passive scan instead of connecting to BLE devices

* refactor: increased disconnected timeout for sensors

* fix: build for nodemcu32, c3, c6 boards; formatting ``platformio.ini``

* refactor: decreased interval and window for scanning BLE

* refactor: active + passive BLE scanning

* refactor: reduced tasks stack size

* style: formatting

* refactor: improved OTA upgrade

https://github.com/ESP32Async/ESPAsyncWebServer/pull/329

* chore: fix dependencies

* chore: reformat `platformio.ini`

* chore: dependencies fixed

* feat: added support BTHome v2 format for BLE sensors #215

* refactor: cosmetic changes

* fix: move OpenThermTask to 0 core

* chore: minimizing flash size with NimBLE

* chore: dependencies updated
2026-05-10 09:43:48 +03:00
dependabot[bot] 9a3a171370 chore: bump cssnano-preset-advanced from 7.0.16 to 8.0.0 (#241)
Bumps [cssnano-preset-advanced](https://github.com/cssnano/cssnano) from 7.0.16 to 8.0.0.
- [Release notes](https://github.com/cssnano/cssnano/releases)
- [Commits](https://github.com/cssnano/cssnano/compare/cssnano-preset-advanced@7.0.16...cssnano-preset-advanced@8.0.0)

---
updated-dependencies:
- dependency-name: cssnano-preset-advanced
  dependency-version: 8.0.0
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-08 07:26:41 +03:00
dependabot[bot] 7c40984298 chore: bump cssnano from 7.1.9 to 8.0.0 (#240)
Bumps [cssnano](https://github.com/cssnano/cssnano) from 7.1.9 to 8.0.0.
- [Release notes](https://github.com/cssnano/cssnano/releases)
- [Commits](https://github.com/cssnano/cssnano/compare/cssnano@7.1.9...cssnano@8.0.0)

---
updated-dependencies:
- dependency-name: cssnano
  dependency-version: 8.0.0
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-08 07:24:24 +03:00
dependabot[bot] 4775d36f1b chore: bump gulp-html-minifier-terser from 7.1.0 to 8.0.0 (#224)
Bumps [gulp-html-minifier-terser](https://github.com/pioug/gulp-html-minifier-terser) from 7.1.0 to 8.0.0.
- [Release notes](https://github.com/pioug/gulp-html-minifier-terser/releases)
- [Commits](https://github.com/pioug/gulp-html-minifier-terser/compare/v7.1.0...v8.0.0)

---
updated-dependencies:
- dependency-name: gulp-html-minifier-terser
  dependency-version: 8.0.0
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-16 23:36:56 +03:00
Yurii 5482e0b70a chore: update version name 2026-02-16 10:19:26 +03:00
Yurii 3fdb48e016 feat: added support DHT11/DHT22 sensors (#223)
* feat: Added support DHT11/DHT22 sensors

* chore: formatting

* fix: typo

* fix: `HaHelper::publishDynamicSensor()` for DHT sensors fixed

* refactor: optimization of wired sensors
2026-02-16 10:17:38 +03:00
Yurii 11747dd8bd feat: added commit hash 2026-02-16 10:06:26 +03:00
Yurii af1a9b59c4 fix: custom_sdkconfig only for ESP32 C6 2026-02-15 06:30:28 +03:00
Yurii 9c86ad4427 chore: misc 2026-02-15 05:37:09 +03:00
Yurii 5f8ca61d79 chore: added custom_sdkconfig for building 2026-02-15 01:51:30 +03:00
Yurii 1f895690db chore: bump milesburton/DallasTemperature from 4.0.5 to 4.0.6 #213
https://github.com/milesburton/Arduino-Temperature-Control-Library/pull/289
2026-02-13 14:10:08 +03:00
Yurii 13e8bedf3f fix: added await for lang.build() 2026-02-13 11:21:17 +03:00
Yurii 3a6bb03456 chore: fix build 2026-02-12 23:32:39 +03:00
Yurii ced0385d5b Merge branch 'master' into async 2026-01-26 02:19:54 +03:00
Yurii 7fcca3c4aa chore: fix ha blueprints to support all source sensors 2026-01-26 02:09:57 +03:00
Yurii 2f6bd237c7 chore: updated ha blueprints for new releases 2026-01-26 01:59:03 +03:00
Yurii e4d1ba7d7b refactor: added different timeouts for wired and wireless sensors 2026-01-26 01:03:26 +03:00
Yurii 80e2d8e939 Merge branch 'master' into async 2026-01-23 00:25:12 +03:00
Yurii b70c212235 fix: filtering fake data from ds18b20 (#217) 2026-01-23 00:19:03 +03:00
Yurii 781b2a1f9c chore: bump pioarduino/platform-espressif32 from 3.3.5 to 3.3.6 2026-01-23 00:17:30 +03:00
Yurii 725185beba chore: reformat platformio.ini and start of removing support esp8266 2026-01-19 21:34:52 +03:00
Yurii c6518db0d3 Merge branch 'master' into async 2026-01-19 20:48:16 +03:00
Konstantin 10ab75c055 feat: dynamic filenames for backup/debug (#207)
* feat: generate dynamic filenames for JSON file downloads (backup and debug) based on hostname and timestamp

* fix: threadsafe getFilename
2025-12-23 11:32:40 +03:00
Yurii 069ba8e864 fix: changes settings from dashboard page fixed 2025-12-21 12:47:37 +03:00
Yurii 3b038c4bd1 Merge branch 'master' into async 2025-12-21 12:33:43 +03:00
Yurii 56a8574aba chore: bump version to 1.6.0 2025-12-20 12:06:25 +03:00
Yurii 3adfabdf40 chore: bump pioarduino/platform-espressif32 from 3.3.4 to 3.3.5 2025-12-20 12:06:06 +03:00
Yurii a9220d9fa1 refactor: always set temperature to ID 1 2025-12-13 06:25:16 +03:00
Yurii 5a14857f52 refactor: minor changes 2025-12-13 06:21:21 +03:00
Yurii e487c78921 feat: added sensor type "OT, Cooling hours" 2025-12-13 06:17:15 +03:00
Yurii 6c3b79bda1 fix: OT protocol version in JSON of slave fixed 2025-12-13 04:15:48 +03:00
Yurii 09c50d5df8 refactor: fixed localization after #204 2025-12-12 15:27:42 +03:00
Yurii 348fab39bb refactor: refactoring after #204 2025-12-12 15:21:02 +03:00
inediblePotato f9cb421893 feat: added OT option alwaysSendIndoorTemp, rename nativeHeatingControl to nativeOTC (#204)
* added option to always send the current and target indoor temp, even if the current heating mode doesnt officially need it. This is a direct fix for WeHeat heatpumps which seem to require it.

* add option to AlwaysSendIndoorTemp and rename NativeHeatingControl to
NativeOTC.

Updated locals and settings page.

* change minor order
2025-12-12 15:08:44 +03:00
Yurii eafb33cb6a refactor: fix typo 2025-12-09 21:10:23 +03:00
Yurii 0038a200ca refactor: some fixes localization 2025-12-09 20:21:10 +03:00
Yurii 1112a25172 chore: bump h2zero/NimBLE-Arduino from 2.3.3 to 2.3.7 2025-12-09 20:20:44 +03:00
Yurii 69b3cdf05a refactor: fixed localization for equitherm 2025-12-09 19:56:33 +03:00
Yurii 01192a59f5 Advanced hysteresis settings (#201)
* feat: added more hysteresis settings

* fix: heating hysteresis switch fixed

* refactor: added localization for hysteresis
2025-12-09 19:27:47 +03:00
YuriiandP43YM cb8251dd40 Implementation of the new Equitherm algorithm (#146)
* feat: new equitherm algorithm and chart for it (#144)

* refactor: refactoring after #144

* refactor: cosmetic changes (equitherm chart)

* chore: fix typo

* refactor: cosmetic changes

* chore: remove unused files

* chore: resolve conflicts

* refactor: added notes for equitherm parameters

* fix: decimation for Equitherm chart fixed; chartjs updated

* style: HTML code formatting

* chore: added additional description of the ``T`` parameter for Equitherm

* flx: typo

* refactor: after merge

---------

Co-authored-by: P43YM <ip43ym@gmail.com>
2025-12-09 19:27:12 +03:00
Yurii 00baf10b9f chore: removed platformio_dependabot 2025-12-09 18:18:10 +03:00
Yurii 6f8c8567a0 chore: bump pioarduino/platform-espressif32 from 3.3.2 to 3.3.4 2025-11-15 13:08:43 +03:00
Yurii e573ce582f fix: generation of default_entity_id for HA fixed 2025-11-12 20:21:39 +03:00
Yurii 0b60734a3b refactor: using abbreviations for HA 2025-11-12 20:18:16 +03:00
Yurii 1d7f85f462 refactor: migrating from Telnet to WebSerial for remote logging 2025-11-06 13:29:59 +03:00
Yurii 192f4ee18b refactor: improved OTA upgrade 2025-11-06 13:23:19 +03:00
Yurii f048d973d3 chore: bump pioarduino/platform-espressif32 from 3.3.2 to 3.3.3 2025-11-06 13:21:34 +03:00
Yurii d4603aa0de fix: compatibility with HA 2025.10+ fixed #189 2025-11-02 23:43:02 +03:00
Yurii d576969ea4 refactor: initial async web server 2025-11-02 11:28:46 +03:00
Yurii b9010643f0 feat: added GPIO inversion setting for extpump 2025-10-31 21:08:35 +03:00
Yurii 5667199988 refactor: reset BLE/DALLAS address if not valid 2025-10-14 07:38:30 +03:00
Yurii cf81ff5856 refactor: improved work with BLE sensors 2025-10-10 05:35:57 +03:00
Yurii 78b5a12e90 feat: setting the cooling setpoint if cooling support is enabled 2025-10-09 22:57:04 +03:00
Yurii cc5bbb7a87 refactor: refactoring after #184 2025-10-09 08:22:07 +03:00
Douwe dda79151f3 feat: added Dutch locale #184
* Create nl.json

* Update nl.json
2025-10-09 08:19:55 +03:00
Yurii 1375d8c7a5 chore: bump pioarduino/platform-espressif32 from 3.3.1 to 3.3.2 2025-10-09 08:16:04 +03:00
Yurii d4addf887f refactor: improved work with BLE sensors 2025-10-09 08:13:33 +03:00
Yurii 9d77256051 refactor: not initialize Bluetooth if BLE sensors are not used 2025-10-03 20:56:04 +03:00
Yurii d3e7a13e1f fix: rollback NimBLE-Arduino from 2.3.6 to 2.3.3 2025-10-03 20:54:42 +03:00
Yurii 14826c10cd chore: `byte to uint8_t` 2025-09-23 04:03:36 +03:00
Yurii 28a5218b7c fix: various fixes
Found by PVS-Studio
2025-09-23 04:02:40 +03:00
Yurii f3ba43adbd docs: fix typo 2025-09-19 21:14:38 +03:00
Yurii 062c6714d1 chore: bump dependencies 2025-09-19 21:09:55 +03:00
Yurii 502f73db0e chore: bump pioarduino/platform-espressif32 from 3.3.0 to 3.3.1 2025-09-19 21:06:17 +03:00
zedwardandEdward Zhuravlov c2ee30d1ab fix: added `nodemcu_32_160mhz` env, deadband usage in PID fixed (#176)
* Small fixes: CPU limit for odemcu_32,  deadbamd usage in PID

* PR review fixes

* Fix: remove spaces

---------

Co-authored-by: Edward Zhuravlov <Edward.Zhuravlev@topsoft.by>
2025-09-19 21:00:11 +03:00
dependabot[bot] 9217bb7448 chore: bump actions/stale from 9 to 10 (#172)
Bumps [actions/stale](https://github.com/actions/stale) from 9 to 10.
- [Release notes](https://github.com/actions/stale/releases)
- [Changelog](https://github.com/actions/stale/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/stale/compare/v9...v10)

---
updated-dependencies:
- dependency-name: actions/stale
  dependency-version: '10'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-09-05 06:33:43 +03:00
Yurii d694ae18c0 chore: bump version to 1.5.6 2025-08-21 19:34:07 +03:00
dependabot[bot] 0f4fa2e406 chore(deps): bump actions/checkout from 4 to 5 (#169)
Bumps [actions/checkout](https://github.com/actions/checkout) from 4 to 5.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-08-12 13:24:55 +03:00
Yurii df2af928a5 chore: bump pioarduino/platform-espressif32 from 3.2.1 to 3.3.0 2025-08-04 07:08:37 +03:00
Yurii 3e6a2d93d4 chore: updated esp32.py
Source: https://raw.githubusercontent.com/letscontrolit/ESPEasy/mega/tools/pio/post_esp32.py
2025-08-04 07:07:31 +03:00
Yurii 062468c6b1 chore: updated esp32.py to be compatible with new versions of esptool
Source: https://raw.githubusercontent.com/letscontrolit/ESPEasy/mega/tools/pio/post_esp32.py
2025-07-04 04:12:06 +03:00
Yurii 530892dc09 chore: bump pioarduino/platform-espressif32 from 3.2.0 to 3.2.1 2025-07-04 04:10:06 +03:00
Yurii c73f74ad45 chore: upd platformio.ini 2025-07-04 03:08:51 +03:00
Yurii a67ff046b0 refactor: refactoring after #163 2025-07-04 03:00:41 +03:00
menyugurenandYurii 0f496fee42 feat: added Chinese locale by @menyuguren #163
* Add files via upload

支持中文

* fix typo

---------

Co-authored-by: Yurii <34578544+Laxilef@users.noreply.github.com>
2025-07-04 02:55:09 +03:00
Yurii e63a0dc7eb refactor: improved freeze protection & overheat protection; added desc for OT options 2025-06-30 02:41:44 +03:00
Yurii 792c6a6668 chore: upd gitignore 2025-06-30 02:38:25 +03:00
Yurii 94f6f14795 refactor: fixed logo size on mobile devices 2025-06-30 02:38:00 +03:00
Yurii 47696a0721 refactor: added print to log channel 2 activity state #155 2025-06-28 20:16:19 +03:00
Yurii 5c4ad8cd07 chore: upd readme 2025-06-27 14:53:17 +03:00
Yurii f6cfdf3263 feat: added freeze protection parameter for heating, removed forced start of heating in emergency mode #157 2025-06-27 00:28:38 +03:00
Yurii 58b0c18448 fix: added C/F temperature conversion in overheating protection 2025-06-20 02:46:25 +03:00
Yurii b985275309 feat: added software overheating protection 2025-06-17 17:50:15 +03:00
Yurii 1eee184887 feat: added OT option dhwStateAsDhwBlocking
For Baxi Slim with Bertelli
2025-06-16 01:04:07 +03:00
Yurii ba03c9cda3 fix: last sensor was ignored 2025-06-08 03:10:10 +03:00
Yurii 14b1eac732 chore: bump version to 1.5.5 2025-06-05 05:40:09 +03:00
Yurii d16f56d280 fix: build for ESP32 C6 2025-05-23 00:42:29 +03:00
Yurii 8b50ed48c1 fix: revert default value of slave max modulation; always set max modulation level
Baxi Ampera resets the maximum modulation level to 0 when the heating is turned off
2025-05-21 01:17:43 +03:00
Yurii f212d9d9a8 fix: changed default value of slave max modulation to 0 2025-05-20 00:05:29 +03:00
Yurii 0e78e71493 refactor: more logs 2025-05-19 23:39:15 +03:00
Yurii 655313562d fix: typo 2025-05-19 23:28:55 +03:00
Yurii c8e7724da8 refactor: cosmetic changes 2025-05-19 23:26:44 +03:00
Yurii f986129c72 fix: set month of date to OT fixed 2025-05-19 23:16:34 +03:00
Yurii 7b31315242 feat: added OT option to set date and time on the boiler 2025-05-19 22:38:35 +03:00
Yurii 6872cad8ce feat: added new purpose (number) for sensors and added polling for OpenTherm statistical IDs
New sensor types:
* Number of burner starts
* Number of burner starts (DHW)
* Number of pump starts (heating)
* Number of pump starts (DHW)
* Number of burner operating hours
* Number of burner operating hours (DHW)
* Number of pump operating hours (heating)
* Number of pump operating hours (DHW)
2025-05-19 21:09:39 +03:00
Yurii 4b1b7f5857 feat: added OT options: ignore diag state, auto fault reset, auto diag reset 2025-05-18 16:47:28 +03:00
Yurii a667317412 refactor: increased max. target indoor temp. from 30 to 40 degrees (for control by return temperature) 2025-05-18 16:01:04 +03:00
Yurii 612b17b86f refactor: reworked the setting of the maximum modulation level, added the parameter of the maximum modulation level for DHW 2025-05-18 15:31:49 +03:00
Yurii 7c032ddc2f fix: removed `device_class` for signal quality entities for compatibility with HA 2025.7.0 2025-05-18 15:29:32 +03:00
Yurii 9dd5ee8da5 chore: bump pioarduino/platform-espressif32 from 3.1.3 to 3.2.0 2025-05-08 09:39:30 +03:00
Yurii 7dbd503e1e fix: restarting on critically low heap #151 2025-05-07 06:12:39 +03:00
Yurii 85932fdc1d refactor: rounding `heating.setpointTemp` 2025-03-26 16:14:32 +03:00
Yurii 77d80225ad refactor: small changes 2025-03-18 09:26:53 +03:00
Yurii dc68315166 refactor: added `Msg type` output to opentherm log 2025-03-18 09:21:00 +03:00
Yurii 5d0ca68dc0 fix: `OpenThermTask::setMaxHeatingTemp(const uint8_t temperature)` changed to OpenThermTask::setMaxHeatingTemp(const float temperature) 2025-03-18 09:19:24 +03:00
Yurii d50b70c211 refactor: improved work with opentherm on esp32 2025-03-14 05:12:20 +03:00
Yurii dd53d1ef3e chore: bump version to 1.5.4 2025-03-06 19:15:56 +03:00
Yurii 3bd8010b74 refactor: BLE device support for ESP32 C6 (#147)
Building on ``Arduino``+``ESP-IDF`` with ``h2zero/esp-nimble-cpp`` for ESP32 C6
2025-03-06 04:45:13 +03:00
Yurii 6a26e27d39 refactor: heating temperature step changed
* step changed to 0.1
* added processing of long presses on thermostats in the dashboard
2025-03-06 04:29:01 +03:00
Yurii 8fa440810c refactor: status BLE sensors 2025-03-05 02:28:17 +03:00
Yurii 95b18385ba chore: gitignore update 2025-03-04 17:50:59 +03:00
Yurii 4457e16a8f refactor: increased opentherm disconnect timeout 2025-02-27 12:48:27 +03:00
Yurii 1965ca671e chore: bump pioarduino/platform-espressif32 from 3.1.2 to 3.1.3 2025-02-20 16:50:06 +03:00
Yurii 0d1873ec77 fix: set SSID on click in table of available networks fixed 2025-02-17 19:37:51 +03:00
Yurii 38ec56fb33 fix: working with `Sensors::Type::MANUAL` sensors fixed 2025-02-17 18:58:01 +03:00
Yurii bb7c3eeba3 feat: added mDNS settings 2025-02-15 00:05:10 +03:00
Yurii 0c778d4c7f refactor: added `robots.txt` to disallow indexing 2025-02-14 23:43:25 +03:00
Yurii 2e5e5e59a8 feat: added mDNS 2025-02-14 07:43:52 +03:00
Yurii e1623e7b63 chore: bump pioarduino/platform-espressif32 from 3.1.1 to 3.1.2 2025-02-14 06:34:46 +03:00
Yurii 80b91d9a01 feat: generate `network.hostname and settings.mqtt.prefix` if they are empty 2025-02-03 06:38:36 +03:00
Roman Andriadi 25b70e4db5 refactor: allow up to 100x correction of sensor values (#137) 2025-02-03 04:56:00 +03:00
Yurii 1903ee2bc7 chore: bump version to 1.5.3 2025-02-02 08:09:20 +03:00
Yurii 916a710064 refactor: improved connection to wifi 2025-01-30 21:46:06 +03:00
Yurii 38acae417d refactor: reworked BLE sensors
* add clean unused ble instances
* moved subscribe to notify to another method
* set date/time on BLE sensors
2025-01-30 01:46:55 +03:00
Yurii 3bc9fa81a8 feat: added ntp server and timezone settings 2025-01-30 01:25:05 +03:00
Yurii cc2d6ef385 fix: increase keep alive timeout for mqtt #115 2025-01-24 21:07:08 +03:00
Yurii fe93c00204 chore: locale correction for pid deadband 2025-01-24 06:42:22 +03:00
Yurii 05a2d080be refactor: default pid coefficients changed 2025-01-24 06:38:10 +03:00
Yurii 664bd7938c fix: sensors pos from 1 on Sensors settings page 2025-01-24 04:48:59 +03:00
Yurii a78f35328f refactor: increased timeout for nimble 2025-01-24 04:48:09 +03:00
Yurii eab47af0e1 refactor: added `CONFIG_BT_NIMBLE_EXT_ADV=1 to build_flags` for esp32 s3, esp32 c3 2025-01-24 04:47:29 +03:00
Yurii c524abd959 refactor: trying to improve connection to BLE devices 2025-01-24 03:17:14 +03:00
Yurii 666786fd65 refactor: small fixes 2025-01-24 03:15:15 +03:00
Yurii 8475833dce feat: added deadband for pid 2025-01-24 01:43:52 +03:00
Yurii afe710abd3 fix: `inputmode` attribute fixed for pid min temp on settings page 2025-01-20 03:48:54 +03:00
Yurii 1982843624 chore: bump version to 1.5.2 2025-01-19 22:44:52 +03:00
Yurii bf161c1200 feat: added Italian locale by @bredy73 #132 2025-01-19 22:20:16 +03:00
Yurii 57f1129cee style: formatting 2025-01-14 06:22:04 +03:00
Yurii 0425cdc499 refactor: prohibition of enabling portal auth with an empty login or password 2025-01-14 06:21:32 +03:00
Yurii 53ff69f03a fix: removed `required` attribute for optional parameters on settings page #128 2025-01-14 06:16:15 +03:00
Yurii e7cae4b950 refactor: improved OT bus reset 2025-01-13 10:56:19 +03:00
Yurii 3ff8f40654 refactor: sensors pos from 1 on `Sensors settings` page 2025-01-13 01:26:22 +03:00
Yurii d2499a2727 docs: update readme 2025-01-13 01:02:07 +03:00
Yurii 5b7da4ed2a fix: typo 2025-01-09 20:44:12 +03:00
Yurii 8d516c7f95 refactor: optimized work with etag 2025-01-09 19:35:56 +03:00
Yurii d756716497 chore: bump pioarduino/platform-espressif32 from 3.1.0 to 3.1.1 2025-01-09 19:35:24 +03:00
Stefan SandYurii 9a2f9d64ec feat: add support board "OT Thing" (#123)
* Add board "OT Thing"

* style: formatting

---------

Co-authored-by: Yurii <34578544+Laxilef@users.noreply.github.com>
2025-01-08 23:41:06 +03:00
Yurii 0d0926cdac chore: update README 2025-01-07 07:14:19 +03:00
Yurii 3ce3ce5016 chore: move web flasher to `gh-pages` branch 2025-01-07 06:53:08 +03:00
Yurii 6ca6d3cab7 chore: added web flasher 2025-01-07 06:22:41 +03:00
Yurii e7f3c66e05 chore: bump version to 1.5.1 2025-01-05 21:45:28 +03:00
Yurii 17bd31b2a2 feat: added OT option `Sync max heating temp with target temp` 2025-01-05 17:32:10 +03:00
Yurii 8662b9dc8f chore: update pcb for smt 2025-01-05 01:55:34 +03:00
Yurii 6efa3a52fe refactor: added OT bus reset; increased timings for changing OT status 2025-01-05 01:39:36 +03:00
Yurii 7e31de6c71 fix: typo 2025-01-02 23:21:54 +03:00
Yurii b53dae6a43 fix: `inputmode` attribute fixed for float settings #117 2024-12-31 01:48:44 +03:00
Yurii de2318bc6a refactor: compatibility with ArduinoJson 7.3.0 2024-12-30 23:12:31 +03:00
Yurii 081209420a chore: bump bblanchon/ArduinoJson from 7.1.0 to 7.3.0 2024-12-30 23:11:14 +03:00
Yurii 75bc4d5c4a feat: ability to reset fault on the dashboard 2024-12-26 19:37:39 +03:00
Yurii 527e9cc1d6 feat: added OT option `Heating state as summer/winter mode` 2024-12-25 19:30:09 +03:00
Yurii 60b7caf4bc fix: typo 2024-12-25 19:25:22 +03:00
Yurii e8d0ad0a4e refactor: improved work with clones (not original) of DS18B20 sensors 2024-12-23 11:37:54 +03:00
Yurii afe269aeff fix: `Content-Length` for pretty json for chunked response 2024-12-23 11:08:37 +03:00
Yurii 4702909043 fix: BLE power 9 dbm with NimBLE-Arduino 2.1.x 2024-12-18 21:58:45 +03:00
Yurii 4c32ccc450 fix: `Content-Length` on esp32 for chunked response 2024-12-18 20:53:33 +03:00
Yurii 2e3b38e14f refactor: compatibility with NimBLE-Arduino 2.1.x 2024-12-17 11:24:49 +03:00
Yurii b6c80f355f Merge branch 'master' of https://github.com/Laxilef/OTGateway 2024-12-17 11:22:13 +03:00
github-actions[bot]andgithub-actions[bot] 65b2a3c2bd chore: bump NimBLE-Arduino from 1.4.3 to 2.1.0
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-12-17 11:21:04 +03:00
Yurii 0cb361d243 refactor: OT option `heatingCh2Enabled has been renamed to ch2AlwaysEnabled` 2024-12-17 10:30:06 +03:00
Yurii c7f54ca4fb chore: bump pioarduino/platform-espressif32 from 3.1.0 rc3 to 3.1.0 2024-12-17 09:45:10 +03:00
Yurii 1d46176b5e chore: update pcb 2024-12-17 04:00:29 +03:00
Yurii 5e2f6c9cea refactor: optimization of the web portal layout 2024-12-16 00:43:32 +03:00
Yurii f439f8c5ba feat: added OT cooling support flag
* refactoring OT settings struct
* renamed some OT settings
2024-12-15 14:24:05 +03:00
Yurii bae7770371 chore: update pcb 2024-12-07 23:47:21 +03:00
Yurii 4e5a3e9da5 refactor: little changes 2024-12-07 23:10:50 +03:00
Yurii 412e1594e9 chore: update readme & assets 2024-12-07 23:10:27 +03:00
Yurii 9701e8c97b chore: update readme 2024-12-07 22:59:29 +03:00
Yurii 2fe546812c chore: update readme 2024-12-07 22:47:24 +03:00
Yurii 7efcbaa57e chore: bump version to 1.5.0 2024-12-05 00:04:58 +03:00
Yurii 43c065b97a Merge branch 'master' into 1.5.0-dev 2024-12-04 07:56:19 +03:00
Yurii 5c1e967fdc refactor: improved display of sensors on Dashboard 2024-12-04 06:09:20 +03:00
Yurii 105a79f72c refactor: optimization of OT requests for CH2 2024-12-04 05:55:01 +03:00
Yurii 50280f6db3 fix: negative temperature values from BLE devices 2024-12-04 05:36:04 +03:00
Yurii c97e50669c fix: typo in purpose of sensors for emergency mode 2024-12-04 05:35:19 +03:00
Yurii 43fd095714 fix: digest auth changed to basic
Digest auth not working on ios #99
2024-12-02 06:26:03 +03:00
Yurii 1bb9b61017 feat: display sensor values on dashboard page 2024-12-01 05:26:14 +03:00
Yurii 1eb10563ed chore: update readme 2024-11-30 23:58:54 +03:00
Yurii 222ea4feaa refactor: some changes 2024-11-29 20:58:52 +03:00
Yurii ea1406c509 fix: action state for HA `climate` entities fixed 2024-11-20 23:11:30 +03:00
Yurii b20b450736 fix: fixed ERR_CONNECTION_RESET for Chrome based browsers 2024-11-20 23:10:42 +03:00
Yurii e8c7f58e67 fix: fixed power calculation 2024-11-18 19:41:12 +03:00
Yurii 2589020428 refactor: optimized polling of unused OT IDs 2024-11-16 22:57:52 +03:00
Yurii 2bb771a4a7 chore: bump pioarduino/platform-espressif32 from 3.1.0 rc2 to 3.1.0 rc3 2024-11-16 22:56:01 +03:00
Yurii f4af237472 chore: bump version to 1.4.6 2024-11-16 14:19:40 +03:00
Yurii 5473034421 chore: deleted .ino file 2024-11-16 14:15:26 +03:00
Yurii a5996cc93d refactor: rounding sensor values 2024-11-15 01:28:28 +03:00
Yurii 9d6b6c18ab fix: pub network.rssi 2024-11-15 01:18:45 +03:00
Yurii e6119dc7ee refactor: restart action improved 2024-11-15 00:55:38 +03:00
Yurii 19feb85230 refactor: some changes 2024-11-15 00:25:41 +03:00
Yurii 0d71a674b6 feat: added more OT polled IDs & reformat code
* ID79 - exhaust CO2
* ID84 - exhaust fan speed
* ID85 - supply fan speed
* ID29 - solar storage temp
* ID30 - solar collector temp
* ID35 - boiler fan speed setpoint & actual
2024-11-14 23:02:46 +03:00
Yurii 34eabca64a refactor: improved web cache 2024-11-14 22:30:34 +03:00
Yurii d3b28c5bfb fix: building without BLE fixed 2024-11-13 12:11:36 +03:00
Yurii 640935a2b7 refactor: improved updating OT sensors 2024-11-13 01:00:04 +03:00
Yurii c0c631aab4 fix: added `step to HA entities for Sensors::Type::MANUAL` 2024-11-13 00:58:28 +03:00
Yurii 861db33765 feat: added signal quality for DALLAS sensors 2024-11-13 00:57:01 +03:00
Yurii b91266063b refactor: imporved updating OT sensors 2024-11-12 19:47:56 +03:00
Yurii b087e6e6d3 refactor: some changes 2024-11-12 15:26:28 +03:00
Yurii b205f14bae refactor: impoved sensors settings page 2024-11-12 15:25:58 +03:00
Yurii 7482eb8898 refactor: added {BUILD_TIME} in path js and css files 2024-11-12 11:44:02 +03:00
Yurii 2ff84cbddf fix: update target heating temp when restoring settings 2024-11-12 11:42:48 +03:00
Yurii 8b6e6be670 fix: display of current heating temp on dashboard 2024-11-12 11:37:09 +03:00
Yurii 636872f72d refactor: some fixes 2024-11-12 10:48:29 +03:00
Yurii c6df74f06e refactor: optimizations & fixes 2024-11-11 15:45:36 +03:00
Yurii 24a46f4c16 fix: unit of dhw flow rate fixed 2024-11-11 13:52:15 +03:00
Yurii ddc9cf7c90 fix: fix typos in settings page 2024-11-11 13:32:36 +03:00
Yurii 2d74d0c0ad refactor: gpio 17 (A0) is valid for ESP8266 2024-11-11 12:59:35 +03:00
Yurii e04462811b refactor: improved NTC polling 2024-11-11 12:56:18 +03:00
Yurii 99d82657c0 fix: restore settings on portal fixed 2024-11-11 12:54:23 +03:00
Yurii ed50208546 feat: added will msg for mqtt broker 2024-11-11 09:29:19 +03:00
Yurii fda18cdb13 refactor: memory optimization for esp8266 2024-11-11 02:41:39 +03:00
Yurii 6a9bd9673a fix: `Sensors::cleanDallasInstances()` fixed 2024-11-10 01:32:42 +03:00
Yurii 5aea80e630 fix: fix typos 2024-11-10 01:30:28 +03:00
Yurii fcf7d61ca5 fix: polling ntc on esp8266 fixed 2024-11-09 17:41:39 +03:00
Yurii e71f3868fd refactor: dynamic sensors 2024-11-09 17:10:26 +03:00
Yurii c3d0d94806 fix; fix typo 2024-11-01 12:49:35 +03:00
Yurii e4211c872c fix: hysteresis with native heating control has been fixed 2024-11-01 12:47:32 +03:00
Yurii 467cfea449 feat: ability to use return heat carrier temp as indoor temp 2024-11-01 04:16:50 +03:00
Yurii 0e3473e065 fix: fix typo 2024-11-01 04:10:56 +03:00
Yurii 8780e5245a fix: for some HA entities added missing parameter enabled_by_default 2024-11-01 03:33:35 +03:00
Yurii 94e8288d76 feat: added entities to HA: connected, rssi, battery, humidity for indoor and outdoor sensors; some entities are disabled by default 2024-11-01 02:36:45 +03:00
Yurii 261a53207c refactor: improved turbo mode 2024-10-31 22:35:23 +03:00
Yurii 1dbc895cdb refactor: increased delay before sending data to MQTT after connection 2024-10-31 22:33:11 +03:00
Yurii 747d8841bc refactor: removed resetting modulation and power if response not valid 2024-10-31 22:30:37 +03:00
Yurii 7ed47a4eca chore: updated equitherm calculator 2024-10-31 22:29:04 +03:00
Yurii 0ccea290cb fix: try to auto determine the min boiler power 2024-10-31 05:29:24 +03:00
Yurii c03df67900 fix: fixed crash if BLE service not found #88 2024-10-31 05:25:34 +03:00
Yurii f86857c279 feat: improved turbo mode
- added turbo factor parameter
- implemented turbo mode for PID
2024-10-31 05:22:41 +03:00
Yurii acd8348a5b feat: try to auto determine the min boiler power 2024-10-31 03:49:00 +03:00
Yurii cdde3c30af chore: fix typos 2024-10-31 02:42:46 +03:00
Yurii 392242ef3e refactor: vendor list updated 2024-10-31 01:36:50 +03:00
Yurii a6e8953807 refactor: reworked emergency mode; reworked hysteresis algorithm; improved detection of connection state for MANUAL & BOILER type sensors 2024-10-31 01:36:21 +03:00
Yurii 11b1277d79 refactor: added ID validation for opentherm response 2024-10-27 04:33:46 +03:00
Yurii f62e687d3f fix: fixed pressure and flow validation when using correction 2024-10-27 04:31:35 +03:00
Yurii 42fa95969f fix: compilation on windows fixed for C3, C6 2024-10-27 03:36:18 +03:00
Yurii 56a0d1322f fix: display of fault code and diag code in logs fixed 2024-10-26 21:37:23 +03:00
Yurii 45762967ee refactor: fix wifi scan on esp32, connection timeouts changed 2024-10-26 20:18:23 +03:00
Yurii 10f9cde17a chore: bump pioarduino/platform-espressif32 from 3.0.6 to 3.1.0 rc2 2024-10-26 20:16:54 +03:00
Yurii 351a884685 refactor: increased max request size for /api/settings 2024-10-24 05:13:29 +03:00
Yurii 98db62cc9e fix: fix typo 2024-10-24 05:00:52 +03:00
Yurii 355d983437 chore: copy elf to build dir 2024-10-24 04:26:46 +03:00
Yurii 3d11d13631 feat: added crash recorder and ability to save dump 2024-10-24 04:01:14 +03:00
Yurii 6c4f8a78a0 refactor: added defaults for serial & telnet 2024-10-24 04:00:06 +03:00
Yurii 3fb5eb32c3 refactor: increased max request size for /api/vars and /api/backup/restore 2024-10-24 03:54:26 +03:00
Yurii c1447098da chore: bump framework-arduinoespressif32 from 3.0.5 to 3.0.6 2024-10-24 03:52:01 +03:00
Yurii 87b222e7bc refactor: increased the max value of dt for pid to 1800 sec 2024-10-21 21:34:53 +03:00
Yurii 0eea1b8121 fix: change of log level when wifi is not connected 2024-10-18 06:45:16 +03:00
Yurii 7f701a74e7 feat: fault state gpio setting replaced with cascade control 2024-10-18 06:14:09 +03:00
Yurii 57cf98ca19 refactor: cosmetic changes; move maxModulation setting to opentherm section 2024-10-15 05:09:20 +03:00
Yurii c32c643442 refactor: more logs 2024-10-15 04:21:20 +03:00
Yurii 5553a13cc0 feat: added log level setting 2024-10-15 04:07:00 +03:00
Yurii a9e97c15ad refactor: more logs; improved sensor of current boiler power: added settings min & max boiler power 2024-10-15 02:10:46 +03:00
Yurii dc62f99b7d feat: added polling of min modulation and max boiler power; added sensor for current boiler power 2024-10-14 19:54:26 +03:00
Yurii 05ff426b28 chore: bump version to 1.4.5 2024-10-13 22:39:20 +03:00
Yurii 45af7a30d8 refactor: cosmetic changes; added coeff. setting for filtering numeric values 2024-10-13 21:42:33 +03:00
Yurii 8aab541afa fix: added min DHW flow rate of 0.1 l/min 2024-10-11 01:38:05 +03:00
Yurii 7672c4b927 fix: fix types 2024-10-11 01:33:49 +03:00
Yurii b0a9460257 feat: added correction coeff. settings for pressure and dhw flow rate 2024-10-11 01:29:50 +03:00
Yurii 3c69f1295e feat: added opentherm option for filtering numeric values 2024-10-10 21:08:13 +03:00
Yurii 282a02ecdb fix: added request for set opentherm version 2024-10-09 12:33:58 +03:00
Yurii 8503ef966f fix: small fix 2024-10-05 10:27:16 +03:00
Yurii a4ee4c5224 feat: added diagnostic code polling via opentherm, added hex value for fault code and diag code 2024-10-05 10:03:14 +03:00
Yurii 4478e8f204 chore: updated platformio.ini for ESP32 C6 2024-10-01 01:45:57 +03:00
Yurii a50c13fd8a Merge branch 'master' of https://github.com/Laxilef/OTGateway 2024-10-01 01:39:27 +03:00
Yurii ee1e7f92b2 fix: added delay before start web server 2024-10-01 01:39:23 +03:00
Yurii 5704075682 chore: switch from PaulStoffregen/OneWire to pstolarz/OneWireNg 2024-10-01 01:38:57 +03:00
Yurii 52e4933923 fix: compatibility with framework-arduinoespressif32 version 3.0.5 2024-10-01 01:36:44 +03:00
Yurii 00a82ca3e5 chore: switch from espressif/arduino-esp32 to pioarduino/platform-espressif32 for new core 2024-10-01 01:35:36 +03:00
Yurii 7658aeaa8c feat: added opentherm option 'immergasFix' 2024-10-01 01:32:35 +03:00
Yurii 790ff5a011 feat: added Radiant to vendor list 2024-09-30 23:56:52 +03:00
dependabot[bot] 935cf27139 chore: bump peterus/platformio_dependabot from 1.1.1 to 1.2.0 (#80)
Bumps [peterus/platformio_dependabot](https://github.com/peterus/platformio_dependabot) from 1.1.1 to 1.2.0.
- [Release notes](https://github.com/peterus/platformio_dependabot/releases)
- [Commits](https://github.com/peterus/platformio_dependabot/compare/v1.1.1...v1.2.0)

---
updated-dependencies:
- dependency-name: peterus/platformio_dependabot
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-09-14 00:36:24 +03:00
Yurii 503068f6e7 chore: update readme 2024-09-06 20:29:50 +03:00
Yurii 5c868d589d chore: update files for production 2024-09-06 20:25:29 +03:00
Yurii 1cca8ffd5d chore: update assets 2024-09-06 19:40:30 +03:00
Yurii f291eb33ac chore: added assets 2024-09-03 18:00:12 +03:00
Yurii f0c505c332 chore: added blueprints 2024-09-03 17:38:59 +03:00
Yurii 7eafe4a90b fix: compatibility with framework-arduinoespressif32 version 3.0.4 2024-08-22 04:57:13 +03:00
Yurii d23527a48b chore: bump framework-arduinoespressif32 from 3.0.1 to 3.0.4 2024-08-22 03:34:17 +03:00
Yurii c341f86e5c refactor: cosmetic changes 2024-08-22 03:33:12 +03:00
Yurii 939ed6cdab chore: bump bblanchon/ArduinoJson from 7.0.4 to 7.1.0 2024-08-22 00:46:13 +03:00
Yurii 2da41707a9 chore: bump version to 1.4.4 2024-08-20 23:39:50 +03:00
Yurii 460cb01146 chore: removed wowki support 2024-08-20 23:28:09 +03:00
Yurii 1b2bc8e200 feat: added feat use of BLE external sensor; added events onIndoorSensorDisconnect and onOutdoorSensorDisconnect for emergency mode; added polling of rssi, humidity, battery for BLE sensors 2024-08-20 19:06:18 +03:00
Yurii d5acb44648 fix: text of action buttons fixed 2024-08-20 19:01:08 +03:00
Yurii c64cf41757 Merge branch 'master' of https://github.com/Laxilef/OTGateway 2024-08-20 02:13:42 +03:00
Yurii 9250bb26f2 fix: locale detection error fixed 2024-08-19 14:45:06 +03:00
dependabot[bot] b2c6eca2d5 chore: bump peterus/platformio_dependabot from 1.1.0 to 1.1.1 (#77)
Bumps [peterus/platformio_dependabot](https://github.com/peterus/platformio_dependabot) from 1.1.0 to 1.1.1.
- [Release notes](https://github.com/peterus/platformio_dependabot/releases)
- [Commits](https://github.com/peterus/platformio_dependabot/compare/v1.1.0...v1.1.1)

---
updated-dependencies:
- dependency-name: peterus/platformio_dependabot
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-02 17:27:41 +03:00
Yurii 5cec043015 chore: bump platformio_dependabot to 1.1.0 2024-06-22 20:28:44 +03:00
github-actions[bot] 7c9a483677 chore: Bump NimBLE-Arduino to 1.4.2 (#75) 2024-06-21 04:18:17 +03:00
github-actions[bot]androot 1bfe7a688a chore: Bump TinyLogger to 1.1.1 (#74)
Co-authored-by: root <root@5e361a757fb5>
2024-06-21 04:17:22 +03:00
Yurii 05104aa8eb chore: create dependabot.yml, pio-dependabot.yaml 2024-06-21 03:44:25 +03:00
Yurii ca3c318d8f chore: bump version 2024-06-21 02:05:34 +03:00
Yurii 2648918dda feat: added multilanguage for portal 2024-06-21 02:01:38 +03:00
Yurii 8b50fdec21 fix: fix typo 2024-06-20 06:41:32 +03:00
Yurii 5b6e23251a fix: use static IP at startup fixed #70 2024-06-18 10:25:58 +03:00
Yurii 769daa0857 chore: bump version to 1.4.2 2024-06-15 03:03:50 +03:00
Yurii 76979531b8 feat: added more info about the build to the portal 2024-06-15 03:03:31 +03:00
Yurii 7779076498 refactor: optimizing work with network 2024-06-14 18:18:43 +03:00
Yurii 45e2e0334e chore: added nodemcu v3 board; changed default gpio for nodemcu 32s 2024-06-14 18:17:12 +03:00
Yurii b631b496cb chore: bump version to 1.4.1 2024-06-13 17:15:37 +03:00
Yurii 36328a1db5 refactor: NetworkMgr code optimization 2024-06-13 17:09:41 +03:00
Yurii a28c7f67b5 chore: added min version of espressif8266 for build #68 2024-06-13 17:07:53 +03:00
Yurii bb9b6a5f4c fix: casting types in setupForm fixed #61 2024-06-11 20:19:54 +03:00
Yurii ce7bd7e23b feat: migrate to arduino-esp32 core 3.0.1 2024-06-10 16:20:03 +03:00
Yurii 249d32ce35 chore: more info when scan wifi 2024-06-10 14:55:14 +03:00
Yurii baf8adfb02 fix: validation GPIO and reset wifi for arduino-esp32 core 3.x.x fixed 2024-06-06 16:37:57 +03:00
Yurii 018a1c5188 fix: set ssid on portal fixed 2024-06-06 02:56:19 +03:00
Yurii b600c130f0 fix: conflicts with sdk 3.x.x for esp32 fixed 2024-06-05 23:11:27 +03:00
Yurii 59eb05726a chore: bump platformio/framework-arduinoespressif32 to 2.0.17 2024-05-26 23:22:19 +03:00
Yurii f245f37dfd chore: bump version 2024-05-26 17:41:12 +03:00
Yurii a825412f37 feat: added fault state GPIO setting 2024-05-25 02:51:10 +03:00
Yurii 935f8bd0a8 fix: outdoor sensor GPIO validation fixed 2024-05-25 00:17:55 +03:00
Yurii f78d2f38b8 fix: equitherm with BLE indoor sensor in emergency mode fixed 2024-04-25 13:38:03 +03:00
Yurii ef083991e3 feat: added board info on portal 2024-04-23 10:30:42 +03:00
Yurii 3c0f846335 fix: added set target indoor temp to CH2 for native heating control #58 2024-04-23 08:13:03 +03:00
Yurii 85011ce4ea chore: bump version 2024-04-22 08:19:41 +03:00
Yurii 8687e122ca feat: added native heating control by boiler; refactoring; emergency settings removed from HA 2024-04-22 08:18:59 +03:00
Yurii d35ea81080 fix: PID optimization, correction of default PID settings 2024-04-18 00:04:23 +03:00
Yurii cca8ec58b4 fix: fix radio on settings page (portal) 2024-04-16 18:58:28 +03:00
Yurii 301b14bbd4 chore: bump version 2024-04-15 15:07:28 +03:00
Yurii 41ce9b268e fix: fix set heating temp on ITALTHERM TIME MAX 30F 2024-04-15 15:00:41 +03:00
Yurii 646939179e fix: serial on s2, s3 fixed 2024-04-15 05:49:46 +03:00
Yurii 73dddd18f0 fix: scan networks on s3 fixed 2024-04-15 02:47:42 +03:00
Yurii f069de0415 chore: fix typo 2024-04-12 21:47:09 +03:00
Yurii f4a4afeb29 chore: bump version 2024-04-12 20:47:02 +03:00
Yurii f9824337dc chore: delete .gz files 2024-04-12 20:39:56 +03:00
Yurii 1cd8c6a336 chore: html files moved to src_data dir; compression files 2024-04-12 04:13:44 +03:00
Yurii 63228baebd chore: auto file compression when building a FS 2024-04-12 04:10:55 +03:00
Yurii 6bb261dfd7 feat: ability to use compressed files for StaticPage 2024-04-12 04:08:28 +03:00
Yurii a026a962f0 fix: fixed thermostat temperature limits for different unit systems on dashboard 2024-04-12 02:03:43 +03:00
Yurii db2faad741 feat: added Italtherm to vendor list 2024-04-12 01:58:33 +03:00
Yurii fbc43dc535 feat: added settings for status led gpio, opentherm rx led gpio, emergency treshold time 2024-04-11 23:53:15 +03:00
Yurii 31dfc21d69 refactor: added info for emergency mode in settings 2024-04-11 04:38:12 +03:00
Yurii 96289cb0f7 fix: reset onewire before begin (fix DS18B20) 2024-04-11 04:09:11 +03:00
Yurii 73da3ee07a fix: fixing button groups on the mobile version 2024-04-11 03:13:39 +03:00
Yurii a14281924f chore: bump version 2024-04-11 03:08:35 +03:00
Yurii 3dec390cce feat: many features
* added dashboard on portal
* added settings for serial port and telnet
* added on/off settings for mqtt
* added event selection for emergency mode
* refactor html & css
2024-04-11 03:06:56 +03:00
Yurii 9a29819d4f refactor: reworked layout and styles of the portal 2024-04-08 05:37:36 +03:00
Yurii 2af159d566 chore: updated css framework 2024-04-07 23:00:22 +03:00
Yurii 92ca257d32 feat: added slave parameters to index page on portal; added poll ID125 (opentherm protocol version) 2024-04-07 22:59:43 +03:00
Yurii 44b6620431 fix: rounding the DHW flow rate value 2024-04-07 19:22:15 +03:00
Yurii b89f61ed58 chore: bump version 2024-04-06 20:28:41 +03:00
Yurii ab1566bd45 fix: memory leak on esp32 fixed 2024-04-06 20:28:05 +03:00
Yurii 86734ab622 refactor: update portal (unit system) 2024-04-06 18:25:30 +03:00
Yurii 0a8dd2a076 feat: added support unit systems for pressure and flow rate 2024-04-06 18:19:06 +03:00
Yurii a7a561622e Merge branch 'unit-system' 2024-04-06 17:38:24 +03:00
Yurii b0e0f6fd7d feat: added setting to enable/disable polling of min and max temperatures via opentherm 2024-04-06 15:51:49 +03:00
Yurii 53eaa1d7f1 chore: bump version 2024-04-04 21:26:48 +03:00
Yurii a7d796e0cc refactor: removed unused methods, replaced some methods to native 2024-03-31 22:29:53 +03:00
Yurii 4490b38130 fix: fixed reading exhaust gas temperature 2024-03-31 19:41:33 +03:00
Yurii 0ede2240a2 fix: temperature_unit for climate fixed; temp in vars.parameters.* by default fixed 2024-03-31 07:29:32 +03:00
Yurii 0cff35ee12 feat: update portal for unit systems 2024-03-31 06:32:23 +03:00
Yurii 14aef20234 fix: typo for HA_TEMPERATURE_UNIT 2024-03-31 02:49:36 +03:00
Yurii 560f8fbd51 feat: optimizing with different unit systems 2024-03-31 02:47:20 +03:00
Yurii 946414ad31 Merge branch 'master' into unit-system 2024-03-31 01:02:59 +03:00
Yurii 39a29042e1 fix: set max temp (ID57) as setpoint heating temp 2024-03-31 00:37:18 +03:00
Yurii f544f01caa feat: polling of exhaust gas temperature (#42) and heating return temperature; added new sensors to HA 2024-03-30 00:04:51 +03:00
Yurii 41cca76bfa chore: update README 2024-03-24 20:38:02 +03:00
Yurii 942bc53043 chore: bump version 2024-03-24 19:28:26 +03:00
Yurii 1bad689b6b fix: revert board_build.ldscript for esp8266, update OpenTherm Library 2024-03-24 19:27:16 +03:00
Yurii 2f4dbcc205 feat: added unit system selection 2024-03-20 02:37:20 +03:00
Yurii 9e3ef7a465 chore: bump version 2024-03-14 13:08:11 +03:00
Yurii a5f6749101 refactor: added SensorType enum 2024-03-14 13:07:42 +03:00
Yurii b07dd46f55 refactor: optimization
* names changed: pin => gpio
* ability to change OpenTherm GPIO without rebooting
2024-03-10 04:10:18 +03:00
Yurii 07ab121788 chore: bump OpenTherm Library to master 2024-03-09 00:03:34 +03:00
Yurii 7cbc52a8b0 chore: bump version 2024-03-01 00:26:41 +03:00
Laxilef e090be380c Merge pull request #49 from blitzu/patch-3
fix: fix typo in settings.html
2024-03-01 00:22:32 +03:00
Laxilef 0bf49d2249 Merge pull request #50 from blitzu/patch-2
fix: fix typo in network.html
2024-03-01 00:22:13 +03:00
Laxilef a83d94d361 Merge pull request #51 from blitzu/patch-1
fix: fix typo in index.html
2024-03-01 00:21:49 +03:00
Laxilef 358980da4c Merge pull request #48 from blitzu/patch-4
fix: fix typo in upgrade.html
2024-03-01 00:21:13 +03:00
blitzu f91e39d067 Update upgrade.html 2024-02-29 18:52:31 +02:00
blitzu 1d53f21d46 Update settings.html 2024-02-29 18:52:08 +02:00
blitzu c225e7c2a8 Update network.html 2024-02-29 18:51:25 +02:00
blitzu 6831c4331f Update index.html 2024-02-29 18:50:36 +02:00
Yurii 8fb62ce8ae fix: set temperature for sensors in manual mode fixed 2024-02-23 03:50:30 +03:00
Yurii e829a00355 chore: bump version 2024-02-20 16:21:20 +03:00
Yurii bee720386a refactor: changed availability conditions for HA entities 2024-02-20 16:17:03 +03:00
Yurii c4b6eadb81 refactor: using BLE advertising instead of manual requests 2024-02-20 15:29:14 +03:00
Yurii a5d2b9fcfa refactor: small fixes 2024-02-20 15:27:51 +03:00
Yurii 1a03117257 chore: bump version 2024-02-05 19:58:11 +03:00
Yurii b421780f7b fix: change channel to 6 for Wifi AP 2024-02-05 19:57:26 +03:00
Yurii 987c101394 fix: set wifi sleep if use ble 2024-02-05 19:55:40 +03:00
Yurii 4002f5b6c2 fix: added board_build.ldscript in platformio.ini for esp8266 boards 2024-02-04 05:37:31 +03:00
Yurii 21edbb7432 chore: bump version 2024-02-04 05:04:51 +03:00
Yurii 88f217abcc refactor: optimization 2024-02-04 05:03:28 +03:00
Yurii 89f3578f27 fix: #37 fixed 2024-02-04 04:48:11 +03:00
Yurii 9c47bf1ddb fix: write empty topics (mqtt) 2024-02-04 04:31:19 +03:00
Yurii 4d199876fb chore: bump lib 2024-02-04 04:28:00 +03:00
Yurii 2ffd19e850 chore: gitignore update 2024-02-04 04:26:20 +03:00
Yurii d0aabbe82a fix: set policy manual for wifi 13 ch; change timeouts 2024-02-01 21:27:22 +03:00
Yurii f2e4f2f631 fix: revert 20 ms wait before start bit 2024-02-01 21:24:22 +03:00
Yurii d374ddc02a refactor: optimization 2024-01-27 18:42:51 +03:00
Yurii cad9e50a78 fix: hostname pattern in portal fixed 2024-01-27 03:16:27 +03:00
Yurii f74d0713d7 chore: updated README 2024-01-23 22:38:45 +03:00
Yurii 114b7fb5a7 chore: bump ESP Telnet to 2.2 2024-01-23 01:59:19 +03:00
Yurii 1b969dcb33 style: indents changed 2024-01-23 01:11:13 +03:00
Yurii 0c64c08ff8 fix: changed "accept" attribute for input type=file 2024-01-23 01:10:33 +03:00
Yurii e6b9a2901c chore: bump GyverPID to 3.3.2 2024-01-23 00:56:41 +03:00
Yurii ca0ef94478 chore: bump OpenTherm Library 2024-01-19 19:42:29 +03:00
Yurii 335429a52e fix: set mqtt prefix before connection 2024-01-19 03:37:54 +03:00
Yurii 2561e92ab9 feat: added validation for BLE address 2024-01-19 03:37:18 +03:00
Yurii 2a67716f65 fix: http code for StaticPage fixed 2024-01-19 03:19:17 +03:00
Yurii 2adbda6832 feat: added form validation 2024-01-19 03:05:50 +03:00
Yurii 99088fb723 fix: data output via web server on ESP32 fixed 2024-01-18 23:37:12 +03:00
Yurii 5e3751ca03 refactor: code style 2024-01-18 23:34:47 +03:00
Yurii ef63f48f57 chore: added partition file for esp32 2024-01-18 01:59:58 +03:00
Yurii 4de7119d6c chore: pcb upd 2024-01-17 19:01:48 +03:00
Yurii 280c7f2887 refactor: heap info 2024-01-17 17:51:15 +03:00
Yurii 85ffd4188f chore: bump version 2024-01-17 16:09:24 +03:00
Yurii 133015d7b9 refactor: network management code moved to MainTask (memory optimization); removed stopping DHCP server and client on reset wifi 2024-01-17 16:08:53 +03:00
Yurii 8731311c62 fix: added close tag 2024-01-16 17:00:47 +03:00
Yurii 5856a45d37 chore: bump version 2024-01-15 20:24:28 +03:00
Yurii 827c18513b fix: set default sta password 2024-01-15 20:24:07 +03:00
Yurii 6f08685859 refactor: fix css 2024-01-15 16:19:41 +03:00
Yurii ccbec44775 feat: saving network settings after FS upgrade 2024-01-15 15:41:19 +03:00
Yurii 5a70403444 refactor: fix css, rename src_data dir 2024-01-15 15:39:31 +03:00
Yurii a9c9457918 refactor: added doc.clear() doc.shrinkToFit() in some code areas 2024-01-14 19:57:25 +03:00
Yurii 520baa4920 refactor: sensors type settings moved to portal, entities for HA have been deleted; logging settings moved; bump version 2024-01-14 19:16:24 +03:00
Yurii 30ae602ab9 refactor: JsonDocument clear before send response 2024-01-14 16:34:49 +03:00
Yurii a6098555dc refactor: optimization of connection to MQTT 2024-01-14 16:33:32 +03:00
Yurii 60c860bc26 fix: opentherm polling interval reduced 2024-01-14 15:56:04 +03:00
Yurii 7463687f1b refactor: removed unnecessary ::yield() and added call setNoDelay() for ESP8266 2024-01-14 15:50:11 +03:00
Yurii 5ee1c7029b fix: updated connection logic to MQTT and enable/disable emergency mode 2024-01-14 15:48:57 +03:00
Yurii 70f2760413 refactor: added info about the need to restart after changing the gpio 2024-01-13 20:35:40 +03:00
Yurii 07ce1db304 feat: make fs after build and copy to build dir 2024-01-13 20:34:00 +03:00
Yurii 04a6b4e1b0 refactor: additional checks when initializing sensors 2024-01-13 20:32:55 +03:00
Yurii 4c48dc048a chore: added monitor_filters to platformio.ini 2024-01-13 20:31:41 +03:00
Yurii feac3bbdf4 feat: display a message on home page if the file system is not flashed 2024-01-13 13:26:24 +03:00
Yurii 1ad1f26d4f feat: automatic restart after restoring settings 2024-01-13 13:02:12 +03:00
Yurii f22c64e30c feat: human-readable uptime formatting 2024-01-13 13:00:43 +03:00
Yurii a9db175dba fix: automatic reboot if memory is too low 2024-01-13 12:58:44 +03:00
Yurii b7c090465b refactor: moving some strings to flash memory 2024-01-12 21:06:32 +03:00
Yurii 50a049915b chore: remove unused files 2024-01-12 21:05:29 +03:00
Yurii e38bda6b4a fix: calculating pid temperature in float, fixed #23 2024-01-12 18:30:13 +03:00
Yurii ab1e9c761f * feat: new portal & network manager
* refactor: migrate from PubSubClient to ArduinoMqttClient
* refactor: migrate from EEManager to FileData
* chore: bump ESP Telnet to 2.2
* chore: bump TinyLogger to 1.1.0
2024-01-12 18:29:55 +03:00
Yurii b36e4dca42 refactoring: moving some strings to flash memory 2024-01-12 18:12:33 +03:00
Yurii fb01d9f566 chore: removed unused code 2023-12-28 20:41:18 +03:00
Yurii 46999fe61c fix: set device_class and unit_of_measurement for number.pid_dt 2023-12-25 15:59:49 +03:00
Yurii 5846812813 chore: workflow 2023-12-25 15:58:19 +03:00
Yurii 67ae236f25 fix: correction pressure and DHW flow rate, if the received value is x10 2023-12-24 18:50:54 +03:00
Yurii 347723cbba fix: rename entities #26
* Current heating min temp => Boiler heating min temp
* Current heating max temp => Boiler heating max temp
* Current DHW min temp => Boiler DHW min temp
* Current DHW max temp => Boiler DHW max temp
2023-12-22 19:15:00 +03:00
Yurii 06659b749a fix: rounding numbers in MqttTask 2023-12-22 18:54:39 +03:00
Yurii 83347765a8 chore: bump version to 1.4.0-rc.5 2023-12-21 18:56:03 +03:00
Yurii 68f412e670 fix: added timeout for wifi client 2023-12-21 18:54:59 +03:00
Yurii cf4a60dd2d fix: log messages in RegulatorTask 2023-12-21 18:54:08 +03:00
Yurii ff5da950c1 fix: correction of PID coefficients limits 2023-12-21 16:34:21 +03:00
Yurii ab21913aa7 fix: disable turbo mode if heating is off 2023-12-21 16:32:27 +03:00
Yurii 7b2014e7b4 fix: upd ESPTelnet 2023-12-21 12:38:33 +03:00
Yurii 025a185bbf refactoring: timings 2023-12-20 16:47:36 +03:00
Yurii e9bb3e46c8 bump version to 1.4.0-rc.4 2023-12-20 08:14:46 +03:00
Yurii f4fe8c7366 refactoring: arp gratuitous for esp8266 2023-12-20 08:12:39 +03:00
Yurii 4e980b6e5b feature: added settings.pid.dt, editable via mqtt 2023-12-20 08:11:08 +03:00
Yurii 2df2205d60 fix: PID interval correction #23 2023-12-20 07:50:57 +03:00
Yurii 4bf3b575db feature: use pid in emergency mode 2023-12-19 16:44:54 +03:00
Yurii c87e08c6af small fix 2023-12-18 08:05:41 +03:00
Yurii e4e349ba15 fix: change type for mqtt port in settings 2023-12-18 08:05:13 +03:00
Yurii 2b5d66173e Fix typo #24 2023-12-18 00:55:25 +03:00
Yurii 0236a0dd8a optimization for esp8266 2023-12-17 13:21:25 +03:00
Yurii 8875fd019a upd heap monitoring 2023-12-17 13:18:42 +03:00
Yurii 7149f52d62 Heap fragmentation optimization
Moving object creation to task constructors
2023-12-16 05:05:37 +03:00
Yurii 214e840ec2 fix buildings JsonDocuments 2023-12-16 01:52:17 +03:00
Laxilef 6c23d5032b Merge pull request #17 from mennodegraaf/ot-improvements
Improve opentherm handling
2023-12-16 00:43:20 +03:00
Laxilef 47879d5486 Update OpenThermTask.h 2023-12-16 00:42:17 +03:00
Yurii 315a975aa8 mqtt refactoring, change version to 1.4.0-rc.1
* added MqttWriter
* added MqttWiFiClient (modified WiFiClient for esp8266)
* adaptation HomeAssistantHelper for MqttWriter
* adaptation HaHelper for new HomeAssistantHelper
2023-12-16 00:29:19 +03:00
Yurii 21ed8f2a14 heap monitoring features 2023-12-15 23:59:20 +03:00
Yurii 8d92409d7b Fix Guru Meditation Error on esp32 2023-12-15 23:58:25 +03:00
Menno de Graaf 15645f4d30 Add log info 2023-12-15 14:46:35 +01:00
Menno de Graaf a5581f3778 Add master/slave set/get to initBoiler() 2023-12-15 12:42:22 +01:00
Menno de Graaf d5e55cf0ae Improve opentherm handling
* First try setBoilerStatus, if it fails there is no need to request other info
* Do not retry to get/set non-essential parameters that the boiler does not support
2023-12-15 11:36:29 +01:00
Yurii adbf67ac13 fix heap monitoring on esp32 2023-12-14 06:20:30 +03:00
Yurii e13984f869 small fix 2023-12-14 06:00:09 +03:00
Yurii 38889bb59d Fix issue #18 2023-12-14 05:43:12 +03:00
Yurii 6a9a069043 removed unused lib 2023-12-14 04:02:23 +03:00
Yurii 468a7dfc02 bump TinyLogger to 1.0.9, added display of time in logs 2023-12-14 03:42:47 +03:00
Yurii 2a28f664cf bump ArduinoJson to 7.x, refactoring MqttTask 2023-12-13 23:23:54 +03:00
Yurii 8e80cecc22 heap monitoring changed 2023-12-13 23:15:51 +03:00
Yurii a55c521e7b reconnection interval to mqtt increased 2023-12-13 23:13:54 +03:00
Yurii a47888c17a fix typo 2023-12-13 23:08:36 +03:00
Yurii e9c91ed6b4 fix reconnect & memory optimization 2023-12-13 00:43:12 +03:00
Yurii b6276ddb3f ble in HaHelper refactoring 2023-12-10 23:30:45 +03:00
Yurii 17b000bdfd fix build with ble 2023-12-10 23:16:15 +03:00
Yurii c048f31672 added check for success of PubSubClient::beginPublish() 2023-12-10 19:47:28 +03:00
Laxilef be5f2b74bc Merge pull request #19 from mennodegraaf/ble-support
Add support for BLE temp sensors
2023-12-10 18:22:00 +03:00
Menno de Graaf ea86bbff30 Fix merge conflict 2023-12-10 14:24:35 +01:00
Menno de Graaf b416110d4f Merge branch 'master' into ble-support 2023-12-10 14:23:20 +01:00
Menno de Graaf 84c3859c5d Use USE_BLE flag to enable/disable BLE temp sensors 2023-12-10 14:17:13 +01:00
Yurii b56146f759 temp replacing ESPTelnet with a fork 2023-12-10 01:31:38 +03:00
Yurii 2db1c5194a revert BufferedTelnetStream to ESPTelnetStream, reduced keep alive timeout for ESPTelnetStream 2023-12-10 01:30:15 +03:00
Yurii 29ff38c285 inc interval for yield in HomeAssistantHelper 2023-12-10 01:27:58 +03:00
Yurii dce94b0f98 added headers for setup page 2023-12-10 01:26:14 +03:00
Yurii 1f81ec1ba5 fix publish non static ha entities 2023-12-09 08:32:02 +03:00
Yurii e8f26aff65 fix exception due to mqtt client 2023-12-09 08:14:17 +03:00
Yurii bc0ba5bdd8 small fix externalPump 2023-12-09 08:12:36 +03:00
Yurii bc23bbc9f3 fix typo in printf 2023-12-09 08:01:34 +03:00
Yurii d61b8a8ecb fix BufferedTelnetStream 2023-12-09 04:09:49 +03:00
Yurii 3fbb26fd91 added BufferedTelnetStream 2023-12-09 03:43:14 +03:00
Menno de Graaf 3ed2b22d06 Prevent using deprecated type 2023-12-08 10:42:24 +01:00
Menno de Graaf 5ecbddc929 Add support for BLE temp sensors 2023-12-08 10:32:58 +01:00
Yurii dbcca514b0 small fix 2023-12-07 22:04:13 +03:00
Yurii 96d506ba57 refactoring 2023-12-07 22:03:41 +03:00
Yurii 03aeaa9441 ha scripts
fix bug and compatibility with older versions
2023-12-07 21:26:16 +03:00
Yurii 5bdc28675f upd readme 2023-12-07 16:29:46 +03:00
Yurii 5633d0d2ee fix ha scripts 2023-12-07 16:04:51 +03:00
Yurii 85cd37c4ae refactoring 2023-12-07 02:57:06 +03:00
Yurii 45630c3be9 fix times ext pump 2023-12-07 02:09:10 +03:00
Yurii dd293e9802 added external pump control 2023-12-07 01:01:19 +03:00
Yurii 412740c5d2 upd readme 2023-12-06 19:44:34 +03:00
Yurii c95a19eb42 fix current temperature in climate.heating entity 2023-12-05 19:52:57 +03:00
Yurii 9b32ccca16 small fix 2023-12-04 08:49:57 +03:00
Yurii 60f66a4ead attach OT task to 1 core 2023-12-04 08:49:42 +03:00
Yurii 7740d9c4c7 disable tasks before ota update 2023-12-04 08:48:02 +03:00
Yurii c5434e0a45 fix sendRequest() 2023-12-03 06:43:55 +03:00
Yurii cd0e8a6a11 bump ESP32Scheduler to 1.0.1 2023-12-02 23:10:50 +03:00
Yurii 88682eef13 modify task priority for ESP32, remove attach to core 2023-12-02 23:06:32 +03:00
Yurii c0a181632a changing intervals for some tasks 2023-12-02 23:04:30 +03:00
Yurii a457ab31be added buffer for writing to mqtt, refactoring 2023-12-02 23:03:19 +03:00
Yurii 3284e84b67 added buffer for writing to mqtt 2023-12-02 23:02:48 +03:00
Yurii e379df388c bump TinyLogger to 1.0.7 2023-12-01 14:36:06 +03:00
Yurii ff91e328cb refactoring 2023-12-01 14:35:13 +03:00
Yurii 522f8ec699 bump TinyLogger to 1.0.6 2023-11-29 23:58:05 +03:00
Yurii ad1fe601b3 fix typo 2023-11-29 23:57:38 +03:00
Yurii 40d9606bea bump TinyLogger to 1.0.5 2023-11-29 18:47:16 +03:00
Yurii 10df1c1d34 fix typo 2023-11-28 17:51:19 +03:00
Yurii ead8c64e92 upd images 2023-11-28 13:31:38 +03:00
Yurii 9bc4c06cad upd ha scripts 2023-11-28 12:45:49 +03:00
Yurii 7763ee9fa9 ha scripts 2023-11-27 21:28:27 +03:00
Yurii 2c26b1cb92 added interval for OT task 2023-11-27 14:38:19 +03:00
Yurii 02d2f0f524 move USE_TELNET & USE_SERIAL to global env section 2023-11-27 14:37:24 +03:00
Laxilef df99aae812 Merge pull request #13 from mennodegraaf/patch-1
Support for Wemos D1 mini32
2023-11-26 23:28:27 +03:00
Menno de Graaf 4d0c87f0b5 Support for Wemos D1 mini32 2023-11-26 19:14:47 +01:00
Yurii 46de4e0cfc upd readme 2023-11-26 19:52:24 +03:00
Yurii 83296855ba many changes
* added parameter "Modulation sync with heating"
* refactoring
2023-11-26 19:36:47 +03:00
Yurii 0ded2c53d8 TinyLogger bump to 1.0.4 2023-11-26 19:33:08 +03:00
Yurii 8ec3655340 add method to f8.8, rename method from f8.8 2023-11-26 16:04:56 +03:00
Yurii eb2dcd7c09 fix when using two sensors, str to flash 2023-11-26 16:02:38 +03:00
Yurii 8a4b598161 many changes
* migrate from jandrassy/TelnetStream to lennarthennigs/ESP Telnet
* ability to turn on/off output logs to telnet and serial
* memory optimization
* added OT parameter DHW blocking
* changed algorithm for setting OpenThermMessageID::MConfigMMemberIDcode
* refactoring
2023-11-26 00:17:47 +03:00
Yurii 0dee4c20ce refactoring 2023-11-23 09:08:02 +03:00
Yurii 761788792f fix state class for uptime 2023-11-23 05:18:44 +03:00
Yurii 70e577e29f states.faultCode moved to sensors.faultCode, states.rssi moved to sensors.rssi, states.uptime moved to sensors.uptime 2023-11-23 05:11:58 +03:00
Yurii b268ff4007 reformat code 2023-11-23 04:57:23 +03:00
Yurii 92a2cb9d56 added DHW flow rate from OT 2023-11-23 04:41:39 +03:00
Yurii e82d47e1dc added OT parameter DHW to CH2 2023-11-23 01:57:08 +03:00
Yurii 7bfad224fe fix set min & max dhw temp 2023-11-23 01:56:19 +03:00
Yurii d07f73edf4 added heating status pin 2023-11-23 00:30:21 +03:00
Yurii d2271513f2 rename methods 2023-11-23 00:28:23 +03:00
Yurii b5a0550c72 fixes 2023-11-22 23:29:31 +03:00
Yurii c556c38cbc small fix settings 2023-11-22 23:07:02 +03:00
Yurii 44fdff61bd fix naming 2023-11-22 23:04:34 +03:00
Yurii 18acf059fc memory optimization 2023-11-22 21:00:19 +03:00
Yurii 227060591f add parameter for max modulation 2023-11-22 20:59:37 +03:00
Yurii 31cefce4bc upd readme 2023-11-22 18:40:37 +03:00
Yurii 5672ff0c3d use TinyLogger lib 2023-11-22 17:53:43 +03:00
Yurii 8bccfcb95d Refactoring and new entities 2023-11-22 17:52:16 +03:00
Yurii 5443ab82ce Merge branch 'master' of https://github.com/Laxilef/OTGateway 2023-11-19 17:59:22 +03:00
Yurii 361628f4f5 fix typo 2023-11-19 17:59:17 +03:00
Yurii 75d31b73ff WM Parameters fix 2023-11-19 17:58:39 +03:00
Laxilef 065155c930 Update README.md 2023-11-17 22:15:46 +03:00
Yurii ee5c6fc953 upd readme, bump version 2023-11-17 22:14:45 +03:00
Yurii 7c5810e6d1 features
* Added new OT parameters
* Improved compatibility with the boiler ITALTHERM TIME MAX 30F
* Refactoring min/max temp
* Fix port forwarding: disable captive portal after connecting to wifi
* Compatible with WOKWI emulator
* upd README
2023-11-17 21:47:33 +03:00
Yurii 9f24efb0ab fix typo 2023-11-17 21:41:38 +03:00
114 changed files with 44204 additions and 10154 deletions

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
version: 2
updates:
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "daily"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"
+171
View File
@@ -0,0 +1,171 @@
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)
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
+110
View File
@@ -0,0 +1,110 @@
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
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
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
@@ -0,0 +1,20 @@
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"
+12
View File
@@ -1,3 +1,15 @@
.pio
.dummy
.vscode
.PVS-Studio
build/*
data/*
managed_components/*
node_modules/*
agent-notes/*
secrets.ini
package-lock.json
*.lock
sdkconfig.*
CMakeLists.txt
!.gitkeep
+191
View File
@@ -0,0 +1,191 @@
# Инструкции для агентов
## Роль и цели
Ты — инженерный 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
@@ -0,0 +1,344 @@
# Стиль кода 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 и рабочие заметки проекта могут быть
на русском.
## Перед завершением правки
- Сверь изменённый участок с окружающим кодом и последними указаниями пользователя.
- Проверь отступы, пустые строки, переносы цепочек, комментарии и окончания строк.
- Убери случайное переформатирование посторонних участков.
- Убедись, что сокращение кода не изменило порядок действий и обязательные ветки.
- Не добавляй правила, абстракции и исключения, не нужные для решаемой задачи.
+76 -212
View File
@@ -1,225 +1,89 @@
![logo](/assets/logo.svg)
<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
- Hot water temperature control
- 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 an external sensors to monitor outdoor and indoor temperature ([compatible sensors](#compatible-temperature-sensors))
- Emergency mode. If the Wi-Fi connection is lost or the gateway cannot connect to the MQTT server, the mode will turn on. This mode will automatically maintain the set temperature and prevent your home from freezing. In this mode it is also possible to use equithermal curves (weather-compensated control).
- Automatic error reset (not with all boilers)
- 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:
- The process of heating: works/does not work
- The process of heating water for hot water: working/not working
- Display of boiler errors
- Burner status (flame): on/off
- Burner modulation level in percent
- Pressure in the heating system
- Gateway status (depending on errors and connection status)
- Boiler connection status via OpenTherm interface
- The current temperature of the heat carrier (usually the return heat carrier)
- Set heat carrier temperature (depending on the selected mode)
- Current hot water temperature
- Auto tuning of PID and Equitherm parameters *(in development)*
- 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!
![logo](/assets/ha.png)
## Documentation
All available information and instructions can be found in the wiki:
## Tested on
| Boiler | Master Member ID | Notes |
| --- | --- | --- |
| BAXI ECO Nova | default | Pressure sensor not supported, modulation level not stable |
| BAXI Ampera | 1028 | Pressure sensor not supported, only heating (DHW not tested) |
| [Remeha Calenta Ace 40C](https://github.com/Laxilef/OTGateway/issues/1#issuecomment-1726081554) | default | - |
| [Baxi Nuvola DUO-TEC HT 16](https://github.com/Laxilef/OTGateway/issues/3#issuecomment-1751061488) | default | - |
| [AEG GBA124](https://github.com/Laxilef/OTGateway/issues/3#issuecomment-1765857609) | default | Pressure sensor not supported |
| [Ferroli DOMIcompact C 24](https://github.com/Laxilef/OTGateway/issues/3#issuecomment-1765310058)<br><sub>Board: MF08FA</sub> | 211 | Pressure sensor not supported |
| [Thermet Ecocondens Silver 35kW](https://github.com/Laxilef/OTGateway/issues/3#issuecomment-1767026384) | default | Pressure sensor not supported |
| [BAXI LUNA-3](https://github.com/Laxilef/OTGateway/issues/3#issuecomment-1794187178) | default | - |
* [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!
## PCB
<img src="/assets/pcb.svg" width="27%" /> <img src="/assets/pcb_3d.png" width="30%" /> <img src="/assets/after_assembly.png" width="40%" />
<a href="https://hosted.weblate.org/engage/otgateway/">
<img src="https://hosted.weblate.org/widget/otgateway/multi-auto.svg" alt="Translation status" />
</a>
Housing for installation on DIN rail - D2MG. Occupies only 2 DIN modules.<br>
The 220V > 5V power supply is already on the board, so additional power supplies are not needed.<br>
To save money, 2 levels are ordered as one board. After manufacturing, the boards need to be divided into 2 parts - upper and lower. The boards are inexpensively (5pcs for $2) manufactured at JLCPCB (Remove Order Number = Specify a location).<br><br>
Some components can be replaced with similar ones (for example use a fuse and led with legs). Some SMD components (for example optocouplers) can be replaced with similar SOT components.<br>Most of the components can be purchased inexpensively on Aliexpress, the rest in your local stores.
#### Connection
The outdoor temperature sensor must be connected to the **TEMP1** connector, the indoor temperature sensor must be connected to the **TEMP2** connector. The power supply for the sensors must be connected to the **3.3V** connector **(NOT 5V!)**, GND to **GND**.<br>
**The opentherm connection polarity does not matter.**
<!-- **Important!** On this board opentherm IN pin = 5, OUT pin = 4 -->
#### Leds
| LED | States |
| --- | --- |
| OT RX | Flashes when a response to the request is received from the boiler |
| Status | Controller status.<br>On, not blinking - no errors;<br>2 flashes - no connection to Wifi;<br>3 flashes - no connection to boiler;<br>4 flashes - boiler is fault;<br>5 flashes - emergency mode (no connection to Wifi or to the MQTT server)<br>10 fast flashes - end of the list of errors |
| Power | Always on when power is on |
#### Files for production
- [Schematic](/assets/Schematic.pdf)
- [BOM](/assets/BOM.xlsx)
- [Gerber](/assets/gerber.zip)
## Another compatible OpenTherm Adapters
- [Ihor Melnyk OpenTherm Adapter](http://ihormelnyk.com/opentherm_adapter)
- [DIYLESS Master OpenTherm Shield](https://diyless.com/product/master-opentherm-shield)
- [OpenTherm master shield for Wemos/Lolin](https://www.tindie.com/products/thehognl/opentherm-master-shield-for-wemoslolin/)
- And others. It's just that the adapter must implement [the schema](http://ihormelnyk.com/Content/Pages/opentherm_adapter/opentherm_adapter_schematic_o.png)
## Compatible Temperature Sensors
* DS18B20
* DS1822
* DS1820
* MAX31820
* MAX31850
[See more](https://github.com/milesburton/Arduino-Temperature-Control-Library#usage)
# Quick Start
1. Download the latest firmware from the [releases page](https://github.com/Laxilef/OTGateway/releases) (or compile yourself) and flash your ESP8266 board using the [ESP Flash Download Tool](https://www.espressif.com/en/support/download/other-tools) or other software.
2. Connect to *OpenTherm Gateway* hotspot, password: otgateway123456
3. Open configuration page in browser: 192.168.4.1
4. Set up a connection to your wifi network
5. Set up a connection to your MQTT server: ip, port, user, password
6. Set up a **Opentherm pin IN** & **Opentherm pin OUT**. No change for my board. Typically used **IN** = 4, **OUT** = 5
7. Set up a **Outdoor sensor pin** & **Indoor sensor pin**. No change for my board.
8. if necessary, set up a the master member ID ([see more](#tested-on))
9. Restart module (required after changing OT pins and/or sensors pins!)
After connecting to your wifi network, you can go to the setup page at the address that ESP8266 received.
The OTGateway device will be automatically added to homeassistant if MQTT server ip, login and password are correct.
## HomeAsssistant settings
By default, the "Equitherm" and "PID" modes are disabled. In this case, the boiler will simply maintain the temperature you set.
To use "Equitherm" or "PID" modes, the controller needs to know the temperature inside and outside the house.<br><br>
The temperature inside the house can be set using simple automation:
<details>
**sensor.livingroom_temperature** - temperature sensor inside the house.<br>
**number.opentherm_indoor_temp** - an entity that stores the temperature value inside the house. The default does not need to be changed.
```yaml
alias: Set boiler indoor temp
description: ""
trigger:
- platform: state
entity_id:
- sensor.livingroom_temperature
- platform: time_pattern
seconds: /30
condition: []
action:
- if:
- condition: template
value_template: "{{ has_value('number.opentherm_indoor_temp') and (states('sensor.livingroom_temperature')|float(0) - states('number.opentherm_indoor_temp')|float(0)) | abs | round(2) >= 0.01 }}"
then:
- service: number.set_value
data:
value: "{{ states('sensor.livingroom_temperature')|float(0)|round(2) }}"
target:
entity_id: number.opentherm_indoor_temp
mode: single
```
</details>
If your boiler does not support the installation of an outdoor temperature sensor or does not provide this value via the opentherm protocol, then you can use an external sensor or use automation.
<details>
<summary>Simple automation</summary>
**weather.home** - [weather entity](https://www.home-assistant.io/integrations/weather/). It is important that the address of your home is entered correctly in the Home Assistant settings.<br>
**number.opentherm_outdoor_temp** - an entity that stores the temperature value outside the house. The default does not need to be changed.
```yaml
alias: Set boiler outdoor temp
description: ""
trigger:
- platform: state
entity_id:
- weather.home
attribute: temperature
for:
hours: 0
minutes: 1
seconds: 0
- platform: time_pattern
seconds: /30
condition: []
action:
- if:
- condition: template
value_template: "{{ has_value('weather.home') and (state_attr('weather.home', 'temperature')|float(0) - states('number.opentherm_outdoor_temp')|float(0)) | abs | round(2) >= 0.1 }}"
then:
- service: number.set_value
data:
value: "{{ state_attr('weather.home', 'temperature')|float(0)|round(2) }}"
target:
entity_id: number.opentherm_outdoor_temp
mode: single
```
</details>
After these settings, you can enable the "Equitherm" and/or "PID" modes and configure them as described below.
## About modes
### Equitherm
Weather-compensated temperature control maintains a comfortable set temperature in the house. The algorithm requires temperature sensors in the house and outside.<br> Instead of an outdoor sensor, you can use the weather forecast and automation for HA.
#### Ratios:
***N*** - heating curve coefficient. The coefficient is selected individually, depending on the insulation of the room, the heated area, etc.<br>
Range: 0.001...10, default: 0.7, step 0.001
***K*** - сorrection for desired room temperature.<br>
Range: 0...10, default: 3, step 0.01
***T*** - thermostat correction.<br>
Range: 0...10, default: 2, step 0.01
#### Instructions for fit coefficients:
**Tip.** I created a [table in Excel](/assets/equitherm_calc.xlsx) in which you can enter temperature parameters inside and outside the house and select coefficients. On the graph you can see the temperature that the boiler will set.
1. Set the ***K*** and ***T*** coefficients to 0.
2. The first thing you need to do is to fit the curve (***N*** coefficient). If your home has low heat loss, then start with 0.5. Otherwise start at 0.7. When the temperature inside the house stops changing, increase or decrease the coefficient value in increments of 0.1 to select the optimal curve.<br>
Please note that passive heating (sun) will affect the house temperature during curve fitting. This process is not fast and will take you 1-2 days.
Important. During curve fitting, the temperature must be kept stable as the outside temperature changes.<br>
At this stage, it is important for you to stabilize the indoor temperature at exactly 20 (+- 0.5) degrees.<br>
For example. You fit curve 0.67; set temperature 20; the temperature in the house is 20.1 degrees while the outside temperature is -10 degrees and -5 degrees. This is good.
3. After fitting the curve, you must select the ***K*** coefficient. It influences the boiler temperature correction to maintain the set temperature.
For example. Set temperature: 23 degrees; temperature in the house: 20 degrees. Try setting it to 2 and see how the temperature in the house changes after stabilization. Select the value so that the temperature in the house is close to the set.
4. Now you can choose the ***T*** coefficient. Simply put, it affects the sharpness of the temperature change. If you want fast heating, then set a high value (6-10), but then the room may overheat. If you want smooth heating, set 1-5. Choose the optimal value for yourself.
5. Check to see if it works correctly at different set temperatures over several days.
Read more about the algorithm [here](https://wdn.su/blog/1154).
### PID
See [Wikipedia](https://en.wikipedia.org/wiki/PID_controller).
![PID example](https://upload.wikimedia.org/wikipedia/commons/3/33/PID_Compensation_Animated.gif)
In Google you can find instructions for tuning the PID controller.
<!--### Use Equitherm mode + PID mode
@todo-->
## Dependencies
- [ESP8266Scheduler](https://github.com/nrwiersma/ESP8266Scheduler) (for ESP8266)
- [ESP32Scheduler](https://github.com/laxilef/ESP32Scheduler) (for ESP32)
- [NTPClient](https://github.com/arduino-libraries/NTPClient)
- [ArduinoJson](https://github.com/bblanchon/ArduinoJson)
- [OpenTherm Library](https://github.com/ihormelnyk/opentherm_library)
- [PubSubClient](https://github.com/knolleary/pubsubclient)
- [TelnetStream](https://github.com/jandrassy/TelnetStream)
- [EEManager](https://github.com/GyverLibs/EEManager)
- [GyverPID](https://github.com/GyverLibs/GyverPID)
- [GyverBlinker](https://github.com/GyverLibs/GyverBlinker)
- [DallasTemperature](https://github.com/milesburton/Arduino-Temperature-Control-Library)
- [WiFiManager](https://github.com/tzapu/WiFiManager)
## Debug
To display DEBUG messages you must enable debug in settings (switch is disabled by default).
You can connect via Telnet to read messages. IP: ESP8266 ip, port: 23
## 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.
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
+18452 -5973
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 191 KiB

+19
View File
@@ -0,0 +1,19 @@
# 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
@@ -0,0 +1,51 @@
# 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 }}"
@@ -0,0 +1,51 @@
# 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 }}"
-1
View File
@@ -1 +0,0 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="73.07594615189231mm" height="93.64998729997461mm" viewBox="4010 3269.5 287.7 368.7"><title>Просмотр платы</title><rect x="4010" y="3269.5" width="287.7" height="368.7" fill="#000000" stroke="none"/><defs xmlns="http://www.w3.org/2000/svg" id="patterns"><pattern id="gridPattern" x="4000" y="3000" width="10" height="10" patternUnits="userSpaceOnUse"><rect id="gridCell" x="0" y="0" width="0.50001" height="0.50001" fill="#FFFFFF" stroke="none"/></pattern><pattern id="gridPattern2" x="4000.50001" y="3000.50001" width="10" height="10" patternUnits="userSpaceOnUse"><path id="gridCell2" d="M10 0V10H-10" fill="none" stroke="#FFFFFF" stroke-width="0.50001" stroke-opacity="0.6"/></pattern><marker id="arrowOnStart" orient="auto" refY="0" refX="0" style="overflow:visible" markerUnits="strokeWidth"><path d="M 2,0 l 4,-2, 0,4 z" stroke-width="6"/></marker><marker id="arrowOnEnd" orient="auto" refY="0" refX="0" style="overflow:visible" markerUnits="strokeWidth"><path d="M -2,0 l -4,-2, 0,4 z" stroke-width="6"/></marker><marker id="arrowOnStartChrome" orient="auto" refY="0" refX="0" style="overflow:visible" markerUnits="strokeWidth"><path d="M 2,0 l 4,-2, 0,4 z" stroke-width="3" stroke="#FFFFFF"/></marker><marker id="arrowOnEndChrome" orient="auto" refY="0" refX="0" style="overflow:visible" markerUnits="strokeWidth"><path d="M -2,0 l -4,-2, 0,4 z" stroke-width="3" stroke="#FFFFFF"/></marker><svg id="icon-lock" title="Unlock" viewBox="0 0 20 20" height="20" width="20"><path stroke="#F0F" stroke-width="2" style="cursor:pointer;fill-opacity:.001;fill:#fff" d="M 5 7 C 5 -1 15 -1 15 7L1 7 1 19 19 19 19 7 15 7"/></svg><mask id="multiLayerMask" maskUnits="userSpaceOnUse" x="4020" y="3279.5" width="267.7" height="357.5"><path d="M4020.002 3623.1135,4020.002 3286.5005,4149.9219 3286.5005,4149.9219 3437.5309,4149.9221 3437.5398,4149.9221 3437.5403,4149.9298 3437.5405,4157.789 3437.5505,4157.7971 3437.5502,4157.7972 3437.5497,4157.7974 3437.5407,4157.7974 3339.4763,4287.7173 3339.4763,4287.7173 3569.7905,4157.7974 3569.7905,4157.7974 3471.3574,4157.7972 3471.3505,4157.7892 3471.3503,4149.9291 3471.3503,4149.9211 3471.3505,4149.9209 3471.3574,4149.9219 3569.7205,4149.9219 3623.1135z" stroke="none" fill="white"/><g fill="black"><circle cx="4281.3973" cy="3543.4145" r="1.7717" stroke-width="0"/><circle cx="4177.8374" cy="3511.9995" r="1.8" stroke-width="0"/><circle cx="4187.8374" cy="3512" r="1.8" stroke-width="0"/><circle cx="4177.8374" cy="3541.9995" r="1.8" stroke-width="0"/><circle cx="4187.8374" cy="3542" r="1.8" stroke-width="0"/><circle cx="4257.3374" cy="3511.9995" r="1.8" stroke-width="0"/><circle cx="4267.34" cy="3511.9995" r="1.8" stroke-width="0"/><circle cx="4257.3374" cy="3541.9995" r="1.8" stroke-width="0"/><circle cx="4267.3374" cy="3541.9995" r="1.8" stroke-width="0"/><circle cx="4034.35" cy="3406.5" r="1.75" stroke-width="0"/><circle cx="4048.95" cy="3406.5" r="1.8" stroke-width="0"/><circle cx="4272.7174" cy="3483.6389" r="1.5" stroke-width="0"/><circle cx="4272.7174" cy="3492.3011" r="1.5" stroke-width="0"/><circle cx="4192.7174" cy="3483.6399" r="1.5" stroke-width="0"/><circle cx="4192.7174" cy="3492.3011" r="1.5" stroke-width="0"/><circle cx="4236.4176" cy="3492.3011" r="1.5" stroke-width="0"/><circle cx="4236.4501" cy="3483.6495" r="1.5" stroke-width="0"/><circle cx="4163.9174" cy="3376.1685" r="2.1654" stroke-width="0"/><circle cx="4163.9174" cy="3366.1685" r="2.1654" stroke-width="0"/><circle cx="4163.9174" cy="3356.1685" r="2.1654" stroke-width="0"/><circle cx="4163.9174" cy="3346.1685" r="2.1654" stroke-width="0"/><circle cx="4281.3974" cy="3563.4125" r="1.7717" stroke-width="0"/><circle cx="4281.3974" cy="3553.4125" r="1.7717" stroke-width="0"/><circle cx="4281.3974" cy="3543.4125" r="1.7717" stroke-width="0"/><circle cx="4163.9174" cy="3563.4125" r="1.7717" stroke-width="0"/><circle cx="4163.9174" cy="3553.4125" r="1.7717" stroke-width="0"/><circle cx="4163.9174" cy="3543.4125" r="1.7717" stroke-width="0"/><circle cx="4281.3974" cy="3366.1685" r="1.7717" stroke-width="0"/><circle cx="4281.3974" cy="3356.1685" r="1.7717" stroke-width="0"/><circle cx="4281.3974" cy="3346.1685" r="1.7717" stroke-width="0"/><circle cx="4163.9174" cy="3533.4122" r="1.7717" stroke-width="0"/><circle cx="4143.5354" cy="3346.1685" r="1.7717" stroke-width="0"/><circle cx="4143.5354" cy="3356.1685" r="1.7717" stroke-width="0"/><circle cx="4143.5354" cy="3366.1685" r="1.7717" stroke-width="0"/><circle cx="4026.056" cy="3543.412" r="1.7717" stroke-width="0"/><circle cx="4026.0558" cy="3553.4125" r="1.7717" stroke-width="0"/><circle cx="4026.0554" cy="3563.4125" r="1.7717" stroke-width="0"/><circle cx="4143.5354" cy="3543.4125" r="1.7717" stroke-width="0"/><circle cx="4143.5354" cy="3553.4125" r="1.7717" stroke-width="0"/><circle cx="4143.5354" cy="3563.4125" r="1.7717" stroke-width=Line truncated

Before

Width:  |  Height:  |  Size: 716 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 236 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 973 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 283 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 386 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 849 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 15 KiB

+12
View File
@@ -0,0 +1,12 @@
<?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>

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View File
Whitespace-only changes.
View File
Whitespace-only changes.
View File
Whitespace-only changes.
+7
View File
@@ -0,0 +1,7 @@
# 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
@@ -0,0 +1,149 @@
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);
+770
View File
@@ -0,0 +1,770 @@
#pragma once
#include <Arduino.h>
#include <esp_log.h>
#include <errno.h>
#include <cmath>
#include <functional>
#include <math.h>
#include <mutex>
#include <optional>
#include <string>
#include <string_view>
#include <stdlib.h>
#include <string.h>
#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
@@ -0,0 +1,390 @@
#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
@@ -0,0 +1,150 @@
#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();
+170
View File
@@ -0,0 +1,170 @@
#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))
+104
View File
@@ -0,0 +1,104 @@
#pragma once
#include <Arduino.h>
#include <esp_arduino_version.h>
#include <esp_heap_caps.h>
#include <esp_timer.h>
#include <mutex>
#include <stdint.h>
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
@@ -0,0 +1,220 @@
#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
@@ -0,0 +1,117 @@
#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)>;
+123
View File
@@ -0,0 +1,123 @@
#pragma once
#include <Arduino.h>
#include <cmath>
#include <stdio.h>
#include <string>
#include <string.h>
#include <time.h>
#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);
}
-128
View File
@@ -1,128 +0,0 @@
#include <Arduino.h>
#include <OpenTherm.h>
class CustomOpenTherm : public OpenTherm {
private:
unsigned long send_ts = millis();
void(*handleSendRequestCallback)(unsigned long, unsigned long, OpenThermResponseStatus status, byte attempt);
void(*yieldCallback)(void*);
void* yieldArg;
public:
CustomOpenTherm(int inPin = 4, int outPin = 5, bool isSlave = false) : OpenTherm(inPin, outPin, isSlave) {}
void setHandleSendRequestCallback(void(*handleSendRequestCallback)(unsigned long, unsigned long, OpenThermResponseStatus status, byte attempt)) {
this->handleSendRequestCallback = handleSendRequestCallback;
}
void setYieldCallback(void(*yieldCallback)(void*)) {
this->yieldCallback = yieldCallback;
this->yieldArg = nullptr;
}
void setYieldCallback(void(*yieldCallback)(void*), void* arg) {
this->yieldCallback = yieldCallback;
this->yieldArg = arg;
}
unsigned long sendRequest(unsigned long request, byte attempts = 5, byte _attempt = 0) {
_attempt++;
while (send_ts > 0 && millis() - send_ts < 200) {
if (yieldCallback != NULL) {
yieldCallback(yieldArg);
} else {
::yield();
}
}
unsigned long _response;
if (!sendRequestAync(request)) {
_response = 0;
} else {
while (!isReady()) {
if (yieldCallback != NULL) {
yieldCallback(yieldArg);
} else {
::yield();
}
process();
}
_response = getLastResponse();
}
OpenThermResponseStatus _responseStatus = getLastResponseStatus();
if (handleSendRequestCallback != NULL) {
handleSendRequestCallback(request, _response, _responseStatus, _attempt);
}
send_ts = millis();
if (_responseStatus == OpenThermResponseStatus::SUCCESS || _responseStatus == OpenThermResponseStatus::INVALID || _attempt >= attempts) {
return _response;
} else {
return sendRequest(request, attempts, _attempt);
}
}
unsigned long setBoilerStatus(bool enableCentralHeating, bool enableHotWater, bool enableCooling, bool enableOutsideTemperatureCompensation, bool enableCentralHeating2, bool summerWinterMode, bool dhwBlocking) {
return sendRequest(buildSetBoilerStatusRequest(enableCentralHeating, enableHotWater, enableCooling, enableOutsideTemperatureCompensation, enableCentralHeating2, summerWinterMode, dhwBlocking));
}
unsigned long buildSetBoilerStatusRequest(bool enableCentralHeating, bool enableHotWater, bool enableCooling, bool enableOutsideTemperatureCompensation, bool enableCentralHeating2, bool summerWinterMode, bool dhwBlocking) {
unsigned int data = enableCentralHeating | (enableHotWater << 1) | (enableCooling << 2) | (enableOutsideTemperatureCompensation << 3) | (enableCentralHeating2 << 4) | (summerWinterMode << 5) | (dhwBlocking << 6);
data <<= 8;
return buildRequest(OpenThermMessageType::READ_DATA, OpenThermMessageID::Status, data);
}
bool setBoilerTemperature(float temperature) {
unsigned int data = temperatureToData(temperature);
unsigned long response = sendRequest(buildRequest(OpenThermMessageType::WRITE_DATA, OpenThermMessageID::TSet, data));
return isValidResponse(response);
}
bool setBoilerTemperature2(float temperature) {
unsigned int data = temperatureToData(temperature);
unsigned long response = sendRequest(buildRequest(OpenThermMessageType::WRITE_DATA, OpenThermMessageID::TsetCH2, data));
return isValidResponse(response);
}
bool sendBoilerReset() {
unsigned int data = 1;
data <<= 8;
unsigned long response = sendRequest(buildRequest(OpenThermMessageType::WRITE_DATA, OpenThermMessageID::Command, data));
return isValidResponse(response);
}
bool sendServiceReset() {
unsigned int data = 10;
data <<= 8;
unsigned long response = sendRequest(buildRequest(OpenThermMessageType::WRITE_DATA, OpenThermMessageID::Command, data));
return isValidResponse(response);
}
bool sendWaterFilling() {
unsigned int data = 2;
data <<= 8;
unsigned long response = sendRequest(buildRequest(OpenThermMessageType::WRITE_DATA, OpenThermMessageID::Command, data));
return isValidResponse(response);
}
// converters
float f88(unsigned long response) {
const byte valueLB = response & 0xFF;
const byte valueHB = (response >> 8) & 0xFF;
float value = (int8_t)valueHB;
return value + (float)valueLB / 256.0;
}
int16_t s16(unsigned long response) {
const byte valueLB = response & 0xFF;
const byte valueHB = (response >> 8) & 0xFF;
int16_t value = valueHB;
return ((value << 8) + valueLB);
}
};
-63
View File
@@ -1,63 +0,0 @@
#include <Arduino.h>
#if defined(EQUITHERM_INTEGER)
// расчёты с целыми числами
typedef int datatype;
#else
// расчёты с float числами
typedef float datatype;
#endif
class Equitherm {
public:
datatype targetTemp = 0;
datatype indoorTemp = 0;
datatype outdoorTemp = 0;
float Kn = 0.0;
float Kk = 0.0;
float Kt = 0.0;
Equitherm() {}
// kn, kk, kt
Equitherm(float new_kn, float new_kk, float new_kt) {
Kn = new_kn;
Kk = new_kk;
Kt = new_kt;
}
// лимит выходной величины
void setLimits(int min_output, int max_output) {
_minOut = min_output;
_maxOut = max_output;
}
// возвращает новое значение при вызове
datatype getResult() {
datatype output = getResultN() + getResultK() + getResultT();
output = constrain(output, _minOut, _maxOut); // ограничиваем выход
return output;
}
private:
int _minOut = 20, _maxOut = 90;
// температура контура отопления в зависимости от наружной температуры
datatype getResultN() {
float a = (-0.21 * Kn) - 0.06; // a = -0,21k — 0,06
float b = (6.04 * Kn) + 1.98; // b = 6,04k + 1,98
float c = (-5.06 * Kn) + 18.06; // с = -5,06k + 18,06
float x = (-0.2 * outdoorTemp) + 5; // x = -0.2*t1 + 5
return (a * x * x) + (b * x) + c; // Tn = ax2 + bx + c
}
// поправка на желаемую комнатную температуру
datatype getResultK() {
return (targetTemp - 20) * Kk;
}
// Расчет поправки (ошибки) термостата
datatype getResultT() {
return constrain((targetTemp - indoorTemp), -2, 2) * Kt;
}
};
@@ -1,89 +0,0 @@
#pragma once
#include <Arduino.h>
class HomeAssistantHelper {
public:
HomeAssistantHelper(PubSubClient& client) :
client(&client)
{
}
void setDevicePrefix(String value) {
devicePrefix = value;
}
void setDeviceVersion(String value) {
deviceVersion = value;
}
void setDeviceManufacturer(String value) {
deviceManufacturer = value;
}
void setDeviceModel(String value) {
deviceModel = value;
}
void setDeviceName(String value) {
deviceName = value;
}
void setDeviceConfigUrl(String value) {
deviceConfigUrl = value;
}
bool publish(const char* topic, JsonDocument& doc) {
doc[FPSTR(HA_DEVICE)][FPSTR(HA_IDENTIFIERS)][0] = devicePrefix;
doc[FPSTR(HA_DEVICE)][FPSTR(HA_SW_VERSION)] = deviceVersion;
if (deviceManufacturer) {
doc[FPSTR(HA_DEVICE)][FPSTR(HA_MANUFACTURER)] = deviceManufacturer;
}
if (deviceModel) {
doc[FPSTR(HA_DEVICE)][FPSTR(HA_MODEL)] = deviceModel;
}
if (deviceName) {
doc[FPSTR(HA_DEVICE)][FPSTR(HA_NAME)] = deviceName;
}
if (deviceConfigUrl) {
doc[FPSTR(HA_DEVICE)][FPSTR(HA_CONF_URL)] = deviceConfigUrl;
}
// Feeding the watchdog
yield();
client->beginPublish(topic, measureJson(doc), true);
serializeJson(doc, *client);
return client->endPublish();
}
bool publish(const char* topic) {
return client->publish(topic, NULL, true);
}
String getTopic(const char* category, const char* name, const char* nameSeparator = "/") {
String topic = "";
topic.concat(prefix);
topic.concat("/");
topic.concat(category);
topic.concat("/");
topic.concat(devicePrefix);
topic.concat(nameSeparator);
topic.concat(name);
topic.concat("/config");
return topic;
}
protected:
PubSubClient* client;
String prefix = "homeassistant";
String devicePrefix = "";
String deviceVersion = "1.0";
String deviceManufacturer = "Community";
String deviceModel = "";
String deviceName = "";
String deviceConfigUrl = "";
};
-37
View File
@@ -1,37 +0,0 @@
#pragma once
#ifndef PROGMEM
#define PROGMEM
#endif
const char HA_DEVICE[] PROGMEM = "device";
const char HA_IDENTIFIERS[] PROGMEM = "identifiers";
const char HA_SW_VERSION[] PROGMEM = "sw_version";
const char HA_MANUFACTURER[] PROGMEM = "manufacturer";
const char HA_MODEL[] PROGMEM = "model";
const char HA_NAME[] PROGMEM = "name";
const char HA_CONF_URL[] PROGMEM = "configuration_url";
const char HA_COMMAND_TOPIC[] PROGMEM = "command_topic";
const char HA_COMMAND_TEMPLATE[] PROGMEM = "command_template";
const char HA_ENABLED_BY_DEFAULT[] PROGMEM = "enabled_by_default";
const char HA_UNIQUE_ID[] PROGMEM = "unique_id";
const char HA_OBJECT_ID[] PROGMEM = "object_id";
const char HA_ENTITY_CATEGORY[] PROGMEM = "entity_category";
const char HA_STATE_TOPIC[] PROGMEM = "state_topic";
const char HA_VALUE_TEMPLATE[] PROGMEM = "value_template";
const char HA_OPTIONS[] PROGMEM = "options";
const char HA_AVAILABILITY[] PROGMEM = "availability";
const char HA_AVAILABILITY_MODE[] PROGMEM = "availability_mode";
const char HA_TOPIC[] PROGMEM = "topic";
const char HA_DEVICE_CLASS[] PROGMEM = "device_class";
const char HA_UNIT_OF_MEASUREMENT[] PROGMEM = "unit_of_measurement";
const char HA_ICON[] PROGMEM = "icon";
const char HA_MIN[] PROGMEM = "min";
const char HA_MAX[] PROGMEM = "max";
const char HA_STEP[] PROGMEM = "step";
const char HA_MODE[] PROGMEM = "mode";
const char HA_STATE_ON[] PROGMEM = "state_on";
const char HA_STATE_OFF[] PROGMEM = "state_off";
const char HA_PAYLOAD_ON[] PROGMEM = "payload_on";
const char HA_PAYLOAD_OFF[] PROGMEM = "payload_off";
const char HA_STATE_CLASS[] PROGMEM = "state_class";
const char HA_EXPIRE_AFTER[] PROGMEM = "expire_after";
+252
View File
@@ -0,0 +1,252 @@
#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};
};
@@ -1,49 +0,0 @@
class IntParameter : public WiFiManagerParameter {
public:
IntParameter(const char* id, const char* label, int value, const uint8_t length = 10) : WiFiManagerParameter("") {
init(id, label, String(value).c_str(), length, "", WFM_LABEL_DEFAULT);
}
int getValue() {
return atoi(WiFiManagerParameter::getValue());
}
};
class UnsignedIntParameter : public WiFiManagerParameter {
public:
UnsignedIntParameter(const char* id, const char* label, unsigned int value, const uint8_t length = 10) : WiFiManagerParameter("") {
init(id, label, String(value).c_str(), length, "", WFM_LABEL_DEFAULT);
}
unsigned int getValue() {
return (unsigned int) atoi(WiFiManagerParameter::getValue());
}
};
class CheckboxParameter : public WiFiManagerParameter {
public:
const char* checked = "type=\"checkbox\" checked";
const char* noChecked = "type=\"checkbox\"";
const char* trueVal = "T";
CheckboxParameter(const char* id, const char* label, bool value) : WiFiManagerParameter("") {
init(id, label, value ? trueVal : "0", 1, "", WFM_LABEL_AFTER);
}
const char* getValue() const override {
return trueVal;
}
const char* getCustomHTML() const override {
return strcmp(WiFiManagerParameter::getValue(), trueVal) == 0 ? checked : noChecked;
}
bool getCheckboxValue() {
return strcmp(WiFiManagerParameter::getValue(), trueVal) == 0 ? true : false;
}
};
class SeparatorParameter : public WiFiManagerParameter {
public:
SeparatorParameter() : WiFiManagerParameter("<hr>") {}
};
-4
View File
@@ -1,4 +0,0 @@
/*
This file is needed by the Arduino IDE because the ino file needs to be named as the directory name.
Don't worry, the Arduino compiler will "merge" all files, including src/main.cpp
*/
+18
View File
@@ -0,0 +1,18 @@
{
"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"
}
}
+286 -129
View File
@@ -1,157 +1,314 @@
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[platformio]
;extra_configs = secrets.ini
extra_configs = secrets.default.ini
;core_dir = .pio
[env]
custom_version = 2.0.0-dev
framework = arduino
lib_deps =
arduino-libraries/NTPClient@^3.2.1
bblanchon/ArduinoJson@^6.20.0
ihormelnyk/OpenTherm Library@^1.1.4
knolleary/PubSubClient@^2.8
jandrassy/TelnetStream@^1.2.4
gyverlibs/EEManager@^2.0
gyverlibs/GyverPID@^3.3
gyverlibs/GyverBlinker@^1.0
milesburton/DallasTemperature@^3.11.0
https://github.com/Laxilef/WiFiManager/archive/refs/heads/patch-1.zip
;https://github.com/tzapu/WiFiManager.git#v2.0.16-rc.2
build_flags = -D PIO_FRAMEWORK_ARDUINO_LWIP2_HIGHER_BANDWIDTH -mtext-section-literals
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
version = 1.3.3
;monitor_filters = direct
monitor_filters = esp32_exception_decoder
board_build.flash_mode = dio
board_build.filesystem = littlefs
check_tool = ;pvs-studio
check_flags = ;pvs-studio: --analysis-mode=4 --exclude-path=./.pio/libdeps
; Defaults
[esp8266_defaults]
platform = espressif8266
lib_deps =
${env.lib_deps}
nrwiersma/ESP8266Scheduler@^1.0
lib_ignore =
extra_scripts =
post:tools/build.py
build_flags = ${env.build_flags}
[esp32_defaults]
platform = espressif32
lib_deps =
${env.lib_deps}
laxilef/ESP32Scheduler@^1.0.0
lib_ignore =
extra_scripts =
;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:d1_mini]
platform = ${esp8266_defaults.platform}
board = d1_mini
lib_deps = ${esp8266_defaults.lib_deps}
lib_ignore = ${esp8266_defaults.lib_ignore}
extra_scripts = ${esp8266_defaults.extra_scripts}
build_flags =
${esp8266_defaults.build_flags}
-D OT_IN_PIN_DEFAULT=4
-D OT_OUT_PIN_DEFAULT=5
-D SENSOR_OUTDOOR_PIN_DEFAULT=12
-D SENSOR_INDOOR_PIN_DEFAULT=14
-D LED_STATUS_PIN=13
-D LED_OT_RX_PIN=15
[env:d1_mini_lite]
platform = ${esp8266_defaults.platform}
board = d1_mini_lite
lib_deps = ${esp8266_defaults.lib_deps}
lib_ignore = ${esp8266_defaults.lib_ignore}
extra_scripts = ${esp8266_defaults.extra_scripts}
build_flags =
${esp8266_defaults.build_flags}
-D OT_IN_PIN_DEFAULT=4
-D OT_OUT_PIN_DEFAULT=5
-D SENSOR_OUTDOOR_PIN_DEFAULT=12
-D SENSOR_INDOOR_PIN_DEFAULT=14
-D LED_STATUS_PIN=13
-D LED_OT_RX_PIN=15
[env:d1_mini_pro]
platform = ${esp8266_defaults.platform}
board = d1_mini_pro
lib_deps = ${esp8266_defaults.lib_deps}
lib_ignore = ${esp8266_defaults.lib_ignore}
extra_scripts = ${esp8266_defaults.extra_scripts}
build_flags =
${esp8266_defaults.build_flags}
-D OT_IN_PIN_DEFAULT=4
-D OT_OUT_PIN_DEFAULT=5
-D SENSOR_OUTDOOR_PIN_DEFAULT=12
-D SENSOR_INDOOR_PIN_DEFAULT=14
-D LED_STATUS_PIN=13
-D LED_OT_RX_PIN=15
[env:s2_mini]
platform = ${esp32_defaults.platform}
extends = esp32_defaults
board = lolin_s2_mini
lib_deps = ${esp32_defaults.lib_deps}
lib_ignore = ${esp32_defaults.lib_ignore}
extra_scripts = ${esp32_defaults.extra_scripts}
build_flags =
${esp32_defaults.build_flags}
-D OT_IN_PIN_DEFAULT=33
-D OT_OUT_PIN_DEFAULT=35
-D SENSOR_OUTDOOR_PIN_DEFAULT=9
-D SENSOR_INDOOR_PIN_DEFAULT=7
-D LED_STATUS_PIN=11
-D LED_OT_RX_PIN=12
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]
platform = ${esp32_defaults.platform}
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}
lib_ignore = ${esp32_defaults.lib_ignore}
extra_scripts = ${esp32_defaults.extra_scripts}
build_flags =
${esp32_defaults.build_flags}
-D OT_IN_PIN_DEFAULT=35
-D OT_OUT_PIN_DEFAULT=36
-D SENSOR_OUTDOOR_PIN_DEFAULT=13
-D SENSOR_INDOOR_PIN_DEFAULT=12
-D LED_STATUS_PIN=11
-D LED_OT_RX_PIN=10
${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]
platform = ${esp32_defaults.platform}
extends = esp32_defaults
board = lolin_c3_mini
lib_deps = ${esp32_defaults.lib_deps}
lib_ignore = ${esp32_defaults.lib_ignore}
extra_scripts = ${esp32_defaults.extra_scripts}
build_flags =
-D PIO_FRAMEWORK_ARDUINO_LWIP2_HIGHER_BANDWIDTH
-D OT_IN_PIN_DEFAULT=8
-D OT_OUT_PIN_DEFAULT=10
-D SENSOR_OUTDOOR_PIN_DEFAULT=0
-D SENSOR_INDOOR_PIN_DEFAULT=1
-D LED_STATUS_PIN=4
-D LED_OT_RX_PIN=5
${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_32s]
platform = ${esp32_defaults.platform}
[env:nodemcu_32]
extends = esp32_defaults
board = nodemcu-32s
lib_deps = ${esp32_defaults.lib_deps}
lib_ignore = ${esp32_defaults.lib_ignore}
extra_scripts = ${esp32_defaults.extra_scripts}
build_flags =
${esp32_defaults.build_flags}
-D OT_IN_PIN_DEFAULT=21
-D OT_OUT_PIN_DEFAULT=22
-D SENSOR_OUTDOOR_PIN_DEFAULT=12
-D SENSOR_INDOOR_PIN_DEFAULT=13
-D LED_STATUS_PIN=2 ; 18
-D LED_OT_RX_PIN=19
${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
-D _GLIBCXX20_CONSTEXPR=__attribute__((cold))constexpr
-D _GLIBCXX23_CONSTEXPR=__attribute__((cold))constexpr
-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
; Use the compact definitions above instead of spaced native metadata.
'# 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
@@ -0,0 +1,24 @@
[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 =
-1154
View File
File diff suppressed because it is too large. Load diff
-181
View File
@@ -1,181 +0,0 @@
#include <Blinker.h>
extern MqttTask* tMqtt;
extern SensorsTask* tSensors;
extern OpenThermTask* tOt;
class MainTask : public Task {
public:
MainTask(bool _enabled = false, unsigned long _interval = 0) : Task(_enabled, _interval) {}
protected:
Blinker* blinker = nullptr;
unsigned long lastHeapInfo = 0;
unsigned long firstFailConnect = 0;
unsigned int heapSize = 0;
unsigned int minFreeHeapSize = 0;
const char* getTaskName() {
return "Main";
}
int getTaskCore() {
return 1;
}
void setup() {
#ifdef LED_STATUS_PIN
pinMode(LED_STATUS_PIN, OUTPUT);
digitalWrite(LED_STATUS_PIN, false);
#endif
#if defined(ESP32)
heapSize = ESP.getHeapSize();
#elif defined(ESP8266)
heapSize = 81920;
#elif
heapSize = 99999;
#endif
minFreeHeapSize = heapSize;
}
void loop() {
if (eeSettings.tick()) {
INFO("Settings updated (EEPROM)");
}
if (vars.parameters.restartAfterTime > 0 && millis() - vars.parameters.restartSignalTime > vars.parameters.restartAfterTime) {
vars.parameters.restartAfterTime = 0;
INFO("Received restart message...");
eeSettings.updateNow();
INFO("Restart...");
delay(1000);
ESP.restart();
}
if (WiFi.status() == WL_CONNECTED) {
if (!tMqtt->isEnabled() && strlen(settings.mqtt.server) > 0) {
tMqtt->enable();
}
if (firstFailConnect != 0) {
firstFailConnect = 0;
}
vars.states.rssi = WiFi.RSSI();
} else {
if (tMqtt->isEnabled()) {
tMqtt->disable();
}
if (settings.emergency.enable && !vars.states.emergency) {
if (firstFailConnect == 0) {
firstFailConnect = millis();
}
if (millis() - firstFailConnect > EMERGENCY_TIME_TRESHOLD) {
vars.states.emergency = true;
INFO("Emergency mode enabled");
}
}
}
if (!tOt->isEnabled() && settings.opentherm.inPin > 0 && settings.opentherm.outPin > 0 && settings.opentherm.inPin != settings.opentherm.outPin) {
tOt->enable();
}
#ifdef LED_STATUS_PIN
ledStatus(LED_STATUS_PIN);
#endif
#ifdef USE_TELNET
yield();
// anti memory leak
TelnetStream.flush();
while (TelnetStream.available() > 0) {
TelnetStream.read();
}
#endif
if (settings.debug) {
unsigned int freeHeapSize = ESP.getFreeHeap();
unsigned int minFreeHeapSizeDiff = 0;
if (freeHeapSize < minFreeHeapSize) {
minFreeHeapSizeDiff = minFreeHeapSize - freeHeapSize;
minFreeHeapSize = freeHeapSize;
}
if (millis() - lastHeapInfo > 10000 || minFreeHeapSizeDiff > 0) {
DEBUG_F("Free heap size: %u of %u bytes, min: %u bytes (diff: %u bytes)\n", freeHeapSize, heapSize, minFreeHeapSize, minFreeHeapSizeDiff);
lastHeapInfo = millis();
}
}
}
void ledStatus(uint8_t ledPin) {
uint8_t errors[4];
uint8_t errCount = 0;
static uint8_t errPos = 0;
static unsigned long endBlinkTime = 0;
static bool ledOn = false;
if (this->blinker == nullptr) {
this->blinker = new Blinker(ledPin);
}
if (WiFi.status() != WL_CONNECTED) {
errors[errCount++] = 2;
}
if (!vars.states.otStatus) {
errors[errCount++] = 3;
}
if (vars.states.fault) {
errors[errCount++] = 4;
}
if (vars.states.emergency) {
errors[errCount++] = 5;
}
if (this->blinker->ready()) {
endBlinkTime = millis();
}
if (!this->blinker->running() && millis() - endBlinkTime >= 5000) {
if (errCount == 0) {
if (!ledOn) {
digitalWrite(ledPin, true);
ledOn = true;
}
return;
} else if (ledOn) {
digitalWrite(ledPin, false);
ledOn = false;
endBlinkTime = millis();
return;
}
if (errPos >= errCount) {
errPos = 0;
// end of error list
this->blinker->blink(10, 50, 50);
} else {
this->blinker->blink(errors[errPos++], 300, 300);
}
}
this->blinker->tick();
}
};
-640
View File
@@ -1,640 +0,0 @@
#include <WiFiClient.h>
#include <PubSubClient.h>
#include "HaHelper.h"
WiFiClient espClient;
PubSubClient client(espClient);
HaHelper haHelper(client);
class MqttTask : public Task {
public:
MqttTask(bool _enabled = false, unsigned long _interval = 0) : Task(_enabled, _interval) {}
protected:
unsigned long lastReconnectAttempt = 0;
unsigned long firstFailConnect = 0;
const char* getTaskName() {
return "Mqtt";
}
int getTaskCore() {
return 0;
}
void setup() {
DEBUG("[MQTT] Started");
client.setCallback(__callback);
haHelper.setDevicePrefix(settings.mqtt.prefix);
haHelper.setDeviceVersion(OT_GATEWAY_VERSION);
haHelper.setDeviceModel("Opentherm Gateway");
haHelper.setDeviceName("Opentherm Gateway");
sprintf(buffer, CONFIG_URL, WiFi.localIP().toString().c_str());
haHelper.setDeviceConfigUrl(buffer);
}
void loop() {
if (!client.connected() && millis() - lastReconnectAttempt >= MQTT_RECONNECT_INTERVAL) {
INFO_F("Mqtt not connected, state: %i, connecting to server %s...\n", client.state(), settings.mqtt.server);
client.setServer(settings.mqtt.server, settings.mqtt.port);
if (client.connect(settings.hostname, settings.mqtt.user, settings.mqtt.password)) {
INFO("Connected to MQTT server");
client.subscribe(getTopicPath("settings/set").c_str());
client.subscribe(getTopicPath("state/set").c_str());
publishHaEntities();
publishNonStaticHaEntities(true);
firstFailConnect = 0;
lastReconnectAttempt = 0;
} else {
INFO("Failed to connect to MQTT server\n");
if (settings.emergency.enable && !vars.states.emergency) {
if (firstFailConnect == 0) {
firstFailConnect = millis();
}
if (millis() - firstFailConnect > EMERGENCY_TIME_TRESHOLD) {
vars.states.emergency = true;
INFO("Emergency mode enabled");
}
}
lastReconnectAttempt = millis();
}
}
if (client.connected()) {
if (vars.states.emergency) {
vars.states.emergency = false;
INFO("Emergency mode disabled");
}
client.loop();
bool published = publishNonStaticHaEntities();
publish(published);
}
}
static bool updateSettings(JsonDocument& doc) {
bool flag = false;
if (!doc["debug"].isNull() && doc["debug"].is<bool>()) {
settings.debug = doc["debug"].as<bool>();
flag = true;
}
// emergency
if (!doc["emergency"]["enable"].isNull() && doc["emergency"]["enable"].is<bool>()) {
settings.emergency.enable = doc["emergency"]["enable"].as<bool>();
flag = true;
}
if (!doc["emergency"]["target"].isNull() && doc["emergency"]["target"].is<float>()) {
if (doc["emergency"]["target"].as<float>() > 0 && doc["emergency"]["target"].as<float>() < 100) {
settings.emergency.target = round(doc["emergency"]["target"].as<float>() * 10) / 10;
flag = true;
}
}
if (!doc["emergency"]["useEquitherm"].isNull() && doc["emergency"]["useEquitherm"].is<bool>()) {
settings.emergency.useEquitherm = doc["emergency"]["useEquitherm"].as<bool>();
flag = true;
}
// heating
if (!doc["heating"]["enable"].isNull() && doc["heating"]["enable"].is<bool>()) {
settings.heating.enable = doc["heating"]["enable"].as<bool>();
flag = true;
}
if (!doc["heating"]["turbo"].isNull() && doc["heating"]["turbo"].is<bool>()) {
settings.heating.turbo = doc["heating"]["turbo"].as<bool>();
flag = true;
}
if (!doc["heating"]["target"].isNull() && doc["heating"]["target"].is<float>()) {
if (doc["heating"]["target"].as<float>() > 0 && doc["heating"]["target"].as<float>() < 100) {
settings.heating.target = round(doc["heating"]["target"].as<float>() * 10) / 10;
flag = true;
}
}
if (!doc["heating"]["hysteresis"].isNull() && doc["heating"]["hysteresis"].is<float>()) {
if (doc["heating"]["hysteresis"].as<float>() >= 0 && doc["heating"]["hysteresis"].as<float>() <= 5) {
settings.heating.hysteresis = round(doc["heating"]["hysteresis"].as<float>() * 10) / 10;
flag = true;
}
}
if (!doc["heating"]["maxTemp"].isNull() && doc["heating"]["maxTemp"].is<unsigned char>()) {
if (doc["heating"]["maxTemp"].as<unsigned char>() > 0 && doc["heating"]["maxTemp"].as<unsigned char>() <= 100 && doc["heating"]["maxTemp"].as<unsigned char>() > settings.heating.minTemp) {
settings.heating.maxTemp = doc["heating"]["maxTemp"].as<unsigned char>();
vars.parameters.heatingMaxTemp = settings.heating.maxTemp;
flag = true;
}
}
if (!doc["heating"]["minTemp"].isNull() && doc["heating"]["minTemp"].is<unsigned char>()) {
if (doc["heating"]["minTemp"].as<unsigned char>() >= 0 && doc["heating"]["minTemp"].as<unsigned char>() < 100 && doc["heating"]["minTemp"].as<unsigned char>() < settings.heating.maxTemp) {
settings.heating.minTemp = doc["heating"]["minTemp"].as<unsigned char>();
vars.parameters.heatingMinTemp = settings.heating.minTemp;
flag = true;
}
}
// dhw
if (!doc["dhw"]["enable"].isNull() && doc["dhw"]["enable"].is<bool>()) {
settings.dhw.enable = doc["dhw"]["enable"].as<bool>();
flag = true;
}
if (!doc["dhw"]["target"].isNull() && doc["dhw"]["target"].is<unsigned char>()) {
if (doc["dhw"]["target"].as<unsigned char>() >= 0 && doc["dhw"]["target"].as<unsigned char>() < 100) {
settings.dhw.target = doc["dhw"]["target"].as<unsigned char>();
flag = true;
}
}
if (!doc["dhw"]["maxTemp"].isNull() && doc["dhw"]["maxTemp"].is<unsigned char>()) {
if (doc["dhw"]["maxTemp"].as<unsigned char>() > 0 && doc["dhw"]["maxTemp"].as<unsigned char>() <= 100 && doc["dhw"]["maxTemp"].as<unsigned char>() > settings.dhw.minTemp) {
settings.dhw.maxTemp = doc["dhw"]["maxTemp"].as<unsigned char>();
vars.parameters.dhwMaxTemp = settings.dhw.maxTemp;
flag = true;
}
}
if (!doc["dhw"]["minTemp"].isNull() && doc["dhw"]["minTemp"].is<unsigned char>()) {
if (doc["dhw"]["minTemp"].as<unsigned char>() >= 0 && doc["dhw"]["minTemp"].as<unsigned char>() < 100 && doc["dhw"]["minTemp"].as<unsigned char>() < settings.dhw.maxTemp) {
settings.dhw.minTemp = doc["dhw"]["minTemp"].as<unsigned char>();
vars.parameters.dhwMinTemp = settings.dhw.minTemp;
flag = true;
}
}
// pid
if (!doc["pid"]["enable"].isNull() && doc["pid"]["enable"].is<bool>()) {
settings.pid.enable = doc["pid"]["enable"].as<bool>();
flag = true;
}
if (!doc["pid"]["p_factor"].isNull() && doc["pid"]["p_factor"].is<float>()) {
if (doc["pid"]["p_factor"].as<float>() > 0 && doc["pid"]["p_factor"].as<float>() <= 10) {
settings.pid.p_factor = round(doc["pid"]["p_factor"].as<float>() * 1000) / 1000;
flag = true;
}
}
if (!doc["pid"]["i_factor"].isNull() && doc["pid"]["i_factor"].is<float>()) {
if (doc["pid"]["i_factor"].as<float>() >= 0 && doc["pid"]["i_factor"].as<float>() <= 10) {
settings.pid.i_factor = round(doc["pid"]["i_factor"].as<float>() * 1000) / 1000;
flag = true;
}
}
if (!doc["pid"]["d_factor"].isNull() && doc["pid"]["d_factor"].is<float>()) {
if (doc["pid"]["d_factor"].as<float>() >= 0 && doc["pid"]["d_factor"].as<float>() <= 10) {
settings.pid.d_factor = round(doc["pid"]["d_factor"].as<float>() * 1000) / 1000;
flag = true;
}
}
if (!doc["pid"]["maxTemp"].isNull() && doc["pid"]["maxTemp"].is<unsigned char>()) {
if (doc["pid"]["maxTemp"].as<unsigned char>() > 0 && doc["pid"]["maxTemp"].as<unsigned char>() <= 100 && doc["pid"]["maxTemp"].as<unsigned char>() > settings.pid.minTemp) {
settings.pid.maxTemp = doc["pid"]["maxTemp"].as<unsigned char>();
flag = true;
}
}
if (!doc["pid"]["minTemp"].isNull() && doc["pid"]["minTemp"].is<unsigned char>()) {
if (doc["pid"]["minTemp"].as<unsigned char>() >= 0 && doc["pid"]["minTemp"].as<unsigned char>() < 100 && doc["pid"]["minTemp"].as<unsigned char>() < settings.pid.maxTemp) {
settings.pid.minTemp = doc["pid"]["minTemp"].as<unsigned char>();
flag = true;
}
}
// equitherm
if (!doc["equitherm"]["enable"].isNull() && doc["equitherm"]["enable"].is<bool>()) {
settings.equitherm.enable = doc["equitherm"]["enable"].as<bool>();
flag = true;
}
if (!doc["equitherm"]["n_factor"].isNull() && doc["equitherm"]["n_factor"].is<float>()) {
if (doc["equitherm"]["n_factor"].as<float>() > 0 && doc["equitherm"]["n_factor"].as<float>() <= 10) {
settings.equitherm.n_factor = round(doc["equitherm"]["n_factor"].as<float>() * 1000) / 1000;
flag = true;
}
}
if (!doc["equitherm"]["k_factor"].isNull() && doc["equitherm"]["k_factor"].is<float>()) {
if (doc["equitherm"]["k_factor"].as<float>() >= 0 && doc["equitherm"]["k_factor"].as<float>() <= 10) {
settings.equitherm.k_factor = round(doc["equitherm"]["k_factor"].as<float>() * 1000) / 1000;
flag = true;
}
}
if (!doc["equitherm"]["t_factor"].isNull() && doc["equitherm"]["t_factor"].is<float>()) {
if (doc["equitherm"]["t_factor"].as<float>() >= 0 && doc["equitherm"]["t_factor"].as<float>() <= 10) {
settings.equitherm.t_factor = round(doc["equitherm"]["t_factor"].as<float>() * 1000) / 1000;
flag = true;
}
}
// sensors
if (!doc["sensors"]["outdoor"]["type"].isNull() && doc["sensors"]["outdoor"]["type"].is<unsigned char>()) {
if (doc["sensors"]["outdoor"]["type"].as<unsigned char>() >= 0 && doc["sensors"]["outdoor"]["type"].as<unsigned char>() <= 2) {
settings.sensors.outdoor.type = doc["sensors"]["outdoor"]["type"].as<unsigned char>();
flag = true;
}
}
if (!doc["sensors"]["outdoor"]["offset"].isNull() && doc["sensors"]["outdoor"]["offset"].is<float>()) {
if (doc["sensors"]["outdoor"]["offset"].as<float>() >= -10 && doc["sensors"]["outdoor"]["offset"].as<float>() <= 10) {
settings.sensors.outdoor.offset = round(doc["sensors"]["outdoor"]["offset"].as<float>() * 1000) / 1000;
flag = true;
}
}
if (!doc["sensors"]["indoor"]["type"].isNull() && doc["sensors"]["indoor"]["type"].is<unsigned char>()) {
if (doc["sensors"]["indoor"]["type"].as<unsigned char>() >= 1 && doc["sensors"]["indoor"]["type"].as<unsigned char>() <= 2) {
settings.sensors.indoor.type = doc["sensors"]["indoor"]["type"].as<unsigned char>();
flag = true;
}
}
if (!doc["sensors"]["indoor"]["offset"].isNull() && doc["sensors"]["indoor"]["offset"].is<float>()) {
if (doc["sensors"]["indoor"]["offset"].as<float>() >= -10 && doc["sensors"]["indoor"]["offset"].as<float>() <= 10) {
settings.sensors.indoor.offset = round(doc["sensors"]["indoor"]["offset"].as<float>() * 1000) / 1000;
flag = true;
}
}
if (flag) {
eeSettings.update();
publish(true);
return true;
}
return false;
}
static bool updateVariables(const JsonDocument& doc) {
bool flag = false;
if (!doc["ping"].isNull() && doc["ping"]) {
flag = true;
}
if (!doc["tuning"]["enable"].isNull() && doc["tuning"]["enable"].is<bool>()) {
vars.tuning.enable = doc["tuning"]["enable"].as<bool>();
flag = true;
}
if (!doc["tuning"]["regulator"].isNull() && doc["tuning"]["regulator"].is<unsigned char>()) {
if (doc["tuning"]["regulator"].as<unsigned char>() >= 0 && doc["tuning"]["regulator"].as<unsigned char>() <= 1) {
vars.tuning.regulator = doc["tuning"]["regulator"].as<unsigned char>();
flag = true;
}
}
if (!doc["temperatures"]["indoor"].isNull() && doc["temperatures"]["indoor"].is<float>()) {
if (settings.sensors.indoor.type == 1 && doc["temperatures"]["indoor"].as<float>() > -100 && doc["temperatures"]["indoor"].as<float>() < 100) {
vars.temperatures.indoor = round(doc["temperatures"]["indoor"].as<float>() * 100) / 100;
flag = true;
}
}
if (!doc["temperatures"]["outdoor"].isNull() && doc["temperatures"]["outdoor"].is<float>()) {
if (settings.sensors.outdoor.type == 1 && doc["temperatures"]["outdoor"].as<float>() > -100 && doc["temperatures"]["outdoor"].as<float>() < 100) {
vars.temperatures.outdoor = round(doc["temperatures"]["outdoor"].as<float>() * 100) / 100;
flag = true;
}
}
if (!doc["restart"].isNull() && doc["restart"].is<bool>() && doc["restart"].as<bool>()) {
vars.parameters.restartAfterTime = 5000;
vars.parameters.restartSignalTime = millis();
}
if (flag) {
publish(true);
return true;
}
return false;
}
static void publish(bool force = false) {
static unsigned int prevPubVars = 0;
static unsigned int prevPubSettings = 0;
// publish variables and status
if (force || millis() - prevPubVars > settings.mqtt.interval) {
publishVariables(getTopicPath("state").c_str());
if (vars.states.fault) {
client.publish(getTopicPath("status").c_str(), "fault");
} else {
client.publish(getTopicPath("status").c_str(), vars.states.otStatus ? "online" : "offline");
}
prevPubVars = millis();
}
// publish settings
if (force || millis() - prevPubSettings > settings.mqtt.interval * 10) {
publishSettings(getTopicPath("settings").c_str());
prevPubSettings = millis();
}
}
static void publishHaEntities() {
// main
haHelper.publishSelectOutdoorSensorType();
haHelper.publishSelectIndoorSensorType();
haHelper.publishNumberOutdoorSensorOffset(false);
haHelper.publishNumberIndoorSensorOffset(false);
haHelper.publishSwitchDebug(false);
// emergency
haHelper.publishSwitchEmergency();
haHelper.publishNumberEmergencyTarget();
haHelper.publishSwitchEmergencyUseEquitherm();
// heating
haHelper.publishSwitchHeating(false);
haHelper.publishSwitchHeatingTurbo();
//haHelper.publishNumberHeatingTarget(false);
haHelper.publishNumberHeatingHysteresis();
haHelper.publishSensorHeatingSetpoint(false);
haHelper.publishSensorCurrentHeatingMinTemp(false);
haHelper.publishSensorCurrentHeatingMaxTemp(false);
haHelper.publishNumberHeatingMinTemp(false);
haHelper.publishNumberHeatingMaxTemp(false);
// pid
haHelper.publishSwitchPID();
haHelper.publishNumberPIDFactorP();
haHelper.publishNumberPIDFactorI();
haHelper.publishNumberPIDFactorD();
haHelper.publishNumberPIDMinTemp(false);
haHelper.publishNumberPIDMaxTemp(false);
// equitherm
haHelper.publishSwitchEquitherm();
haHelper.publishNumberEquithermFactorN();
haHelper.publishNumberEquithermFactorK();
haHelper.publishNumberEquithermFactorT();
// tuning
haHelper.publishSwitchTuning();
haHelper.publishSelectTuningRegulator();
// states
haHelper.publishBinSensorStatus();
haHelper.publishBinSensorOtStatus();
haHelper.publishBinSensorHeating();
haHelper.publishBinSensorFlame();
haHelper.publishBinSensorFault();
haHelper.publishBinSensorDiagnostic();
haHelper.publishSensorFaultCode();
haHelper.publishSensorRssi(false);
// sensors
haHelper.publishSensorModulation(false);
haHelper.publishSensorPressure(false);
// temperatures
haHelper.publishNumberIndoorTemp();
//haHelper.publishNumberOutdoorTemp();
haHelper.publishSensorHeatingTemp();
}
static bool publishNonStaticHaEntities(bool force = false) {
static byte _heatingMinTemp, _heatingMaxTemp, _dhwMinTemp, _dhwMaxTemp;
static bool _editableOutdoorTemp, _editableIndoorTemp, _dhwPresent;
bool published = false;
bool isStupidMode = !settings.pid.enable && !settings.equitherm.enable;
byte heatingMinTemp = isStupidMode ? vars.parameters.heatingMinTemp : 10;
byte heatingMaxTemp = isStupidMode ? vars.parameters.heatingMaxTemp : 30;
bool editableOutdoorTemp = settings.sensors.outdoor.type == 1;
bool editableIndoorTemp = settings.sensors.indoor.type == 1;
if (force || _dhwPresent != settings.opentherm.dhwPresent) {
_dhwPresent = settings.opentherm.dhwPresent;
if (_dhwPresent) {
haHelper.publishSwitchDHW(false);
haHelper.publishSensorCurrentDHWMinTemp(false);
haHelper.publishSensorCurrentDHWMaxTemp(false);
haHelper.publishNumberDHWMinTemp(false);
haHelper.publishNumberDHWMaxTemp(false);
haHelper.publishBinSensorDHW();
haHelper.publishSensorDHWTemp();
} else {
haHelper.deleteSwitchDHW();
haHelper.deleteSensorCurrentDHWMinTemp();
haHelper.deleteSensorCurrentDHWMaxTemp();
haHelper.deleteNumberDHWMinTemp();
haHelper.deleteNumberDHWMaxTemp();
haHelper.deleteBinSensorDHW();
haHelper.deleteSensorDHWTemp();
haHelper.deleteNumberDHWTarget();
haHelper.deleteClimateDHW();
}
published = true;
}
if (force || _heatingMinTemp != heatingMinTemp || _heatingMaxTemp != heatingMaxTemp) {
if (settings.heating.target < heatingMinTemp || settings.heating.target > heatingMaxTemp) {
settings.heating.target = constrain(settings.heating.target, heatingMinTemp, heatingMaxTemp);
}
_heatingMinTemp = heatingMinTemp;
_heatingMaxTemp = heatingMaxTemp;
haHelper.publishNumberHeatingTarget(heatingMinTemp, heatingMaxTemp, false);
haHelper.publishClimateHeating(heatingMinTemp, heatingMaxTemp);
published = true;
}
if (_dhwPresent && (force || _dhwMinTemp != vars.parameters.dhwMinTemp || _dhwMaxTemp != vars.parameters.dhwMaxTemp)) {
_dhwMinTemp = vars.parameters.dhwMinTemp;
_dhwMaxTemp = vars.parameters.dhwMaxTemp;
haHelper.publishNumberDHWTarget(vars.parameters.dhwMinTemp, vars.parameters.dhwMaxTemp, false);
haHelper.publishClimateDHW(vars.parameters.dhwMinTemp, vars.parameters.dhwMaxTemp);
published = true;
}
if (force || _editableOutdoorTemp != editableOutdoorTemp) {
_editableOutdoorTemp = editableOutdoorTemp;
if (editableOutdoorTemp) {
haHelper.deleteSensorOutdoorTemp();
haHelper.publishNumberOutdoorTemp();
} else {
haHelper.deleteNumberOutdoorTemp();
haHelper.publishSensorOutdoorTemp();
}
published = true;
}
if (force || _editableIndoorTemp != editableIndoorTemp) {
_editableIndoorTemp = editableIndoorTemp;
if (editableIndoorTemp) {
haHelper.deleteSensorIndoorTemp();
haHelper.publishNumberIndoorTemp();
} else {
haHelper.deleteNumberIndoorTemp();
haHelper.publishSensorIndoorTemp();
}
published = true;
}
return published;
}
static bool publishSettings(const char* topic) {
StaticJsonDocument<2048> doc;
doc["debug"] = settings.debug;
doc["emergency"]["enable"] = settings.emergency.enable;
doc["emergency"]["target"] = settings.emergency.target;
doc["emergency"]["useEquitherm"] = settings.emergency.useEquitherm;
doc["heating"]["enable"] = settings.heating.enable;
doc["heating"]["turbo"] = settings.heating.turbo;
doc["heating"]["target"] = settings.heating.target;
doc["heating"]["hysteresis"] = settings.heating.hysteresis;
doc["heating"]["minTemp"] = settings.heating.minTemp;
doc["heating"]["maxTemp"] = settings.heating.maxTemp;
doc["dhw"]["enable"] = settings.dhw.enable;
doc["dhw"]["target"] = settings.dhw.target;
doc["dhw"]["minTemp"] = settings.dhw.minTemp;
doc["dhw"]["maxTemp"] = settings.dhw.maxTemp;
doc["pid"]["enable"] = settings.pid.enable;
doc["pid"]["p_factor"] = settings.pid.p_factor;
doc["pid"]["i_factor"] = settings.pid.i_factor;
doc["pid"]["d_factor"] = settings.pid.d_factor;
doc["pid"]["minTemp"] = settings.pid.minTemp;
doc["pid"]["maxTemp"] = settings.pid.maxTemp;
doc["equitherm"]["enable"] = settings.equitherm.enable;
doc["equitherm"]["n_factor"] = settings.equitherm.n_factor;
doc["equitherm"]["k_factor"] = settings.equitherm.k_factor;
doc["equitherm"]["t_factor"] = settings.equitherm.t_factor;
doc["sensors"]["outdoor"]["type"] = settings.sensors.outdoor.type;
doc["sensors"]["outdoor"]["offset"] = settings.sensors.outdoor.offset;
doc["sensors"]["indoor"]["type"] = settings.sensors.indoor.type;
doc["sensors"]["indoor"]["offset"] = settings.sensors.indoor.offset;
client.beginPublish(topic, measureJson(doc), false);
//BufferingPrint bufferedClient(client, 32);
//serializeJson(doc, bufferedClient);
//bufferedClient.flush();
serializeJson(doc, client);
return client.endPublish();
}
static bool publishVariables(const char* topic) {
StaticJsonDocument<2048> doc;
doc["tuning"]["enable"] = vars.tuning.enable;
doc["tuning"]["regulator"] = vars.tuning.regulator;
doc["states"]["otStatus"] = vars.states.otStatus;
doc["states"]["heating"] = vars.states.heating;
doc["states"]["dhw"] = vars.states.dhw;
doc["states"]["flame"] = vars.states.flame;
doc["states"]["fault"] = vars.states.fault;
doc["states"]["diagnostic"] = vars.states.diagnostic;
doc["states"]["faultCode"] = vars.states.faultCode;
doc["states"]["rssi"] = vars.states.rssi;
doc["sensors"]["modulation"] = vars.sensors.modulation;
doc["sensors"]["pressure"] = vars.sensors.pressure;
doc["temperatures"]["indoor"] = vars.temperatures.indoor;
doc["temperatures"]["outdoor"] = vars.temperatures.outdoor;
doc["temperatures"]["heating"] = vars.temperatures.heating;
doc["temperatures"]["dhw"] = vars.temperatures.dhw;
doc["parameters"]["heatingEnabled"] = vars.parameters.heatingEnabled;
doc["parameters"]["heatingMinTemp"] = vars.parameters.heatingMinTemp;
doc["parameters"]["heatingMaxTemp"] = vars.parameters.heatingMaxTemp;
doc["parameters"]["heatingSetpoint"] = vars.parameters.heatingSetpoint;
doc["parameters"]["dhwMinTemp"] = vars.parameters.dhwMinTemp;
doc["parameters"]["dhwMaxTemp"] = vars.parameters.dhwMaxTemp;
client.beginPublish(topic, measureJson(doc), false);
//BufferingPrint bufferedClient(client, 32);
//serializeJson(doc, bufferedClient);
//bufferedClient.flush();
serializeJson(doc, client);
return client.endPublish();
}
static std::string getTopicPath(const char* topic) {
return std::string(settings.mqtt.prefix) + "/" + std::string(topic);
}
static void __callback(char* topic, byte* payload, unsigned int length) {
if (!length) {
return;
}
if (settings.debug) {
DEBUG_F("MQTT received message\n\r Topic: %s\n\r Data: ", topic);
for (unsigned int i = 0; i < length; i++) {
DEBUG_STREAM.print((char)payload[i]);
}
DEBUG_STREAM.print("\n");
}
StaticJsonDocument<2048> doc;
DeserializationError dErr = deserializeJson(doc, (const byte*)payload, length);
if (dErr != DeserializationError::Ok || doc.isNull()) {
return;
}
if (getTopicPath("state/set").compare(topic) == 0) {
updateVariables(doc);
client.publish(getTopicPath("state/set").c_str(), NULL, true);
} else if (getTopicPath("settings/set").compare(topic) == 0) {
updateSettings(doc);
client.publish(getTopicPath("settings/set").c_str(), NULL, true);
}
}
};
-445
View File
@@ -1,445 +0,0 @@
#include <new>
#include <CustomOpenTherm.h>
CustomOpenTherm* ot;
class OpenThermTask : public Task {
public:
OpenThermTask(bool _enabled = false, unsigned long _interval = 0) : Task(_enabled, _interval) {}
void static IRAM_ATTR handleInterrupt() {
ot->handleInterrupt();
}
protected:
const char* getTaskName() {
return "OpenTherm";
}
int getTaskCore() {
return 1;
}
void setup() {
vars.parameters.heatingMinTemp = settings.heating.minTemp;
vars.parameters.heatingMaxTemp = settings.heating.maxTemp;
vars.parameters.dhwMinTemp = settings.dhw.minTemp;
vars.parameters.dhwMaxTemp = settings.dhw.maxTemp;
ot = new CustomOpenTherm(settings.opentherm.inPin, settings.opentherm.outPin);
ot->setHandleSendRequestCallback(this->sendRequestCallback);
ot->begin(OpenThermTask::handleInterrupt, this->responseCallback);
ot->setYieldCallback([](void* self) {
static_cast<OpenThermTask*>(self)->delay(10);
}, this);
#ifdef LED_OT_RX_PIN
pinMode(LED_OT_RX_PIN, OUTPUT);
#endif
}
void loop() {
static byte currentHeatingTemp, currentDHWTemp = 0;
unsigned long localResponse;
if (setMasterMemberIdCode()) {
DEBUG_F("Slave member id code: %u\r\n", vars.parameters.slaveMemberIdCode);
DEBUG_F("Master member id code: %u\r\n", settings.opentherm.memberIdCode > 0 ? settings.opentherm.memberIdCode : vars.parameters.slaveMemberIdCode);
} else {
WARN("Slave member id failed");
}
bool heatingEnabled = (vars.states.emergency || settings.heating.enable) && pump && isReady();
localResponse = ot->setBoilerStatus(
heatingEnabled,
settings.opentherm.dhwPresent && settings.dhw.enable,
false, false, true, false, false
);
if (!ot->isValidResponse(localResponse)) {
WARN_F("Invalid response after setBoilerStatus: %s\r\n", ot->statusToString(ot->getLastResponseStatus()));
return;
}
if (vars.parameters.heatingEnabled != heatingEnabled) {
vars.parameters.heatingEnabled = heatingEnabled;
INFO_F("Heating enabled: %s\r\n", heatingEnabled ? "on\0" : "off\0");
}
vars.states.heating = ot->isCentralHeatingActive(localResponse);
vars.states.dhw = settings.opentherm.dhwPresent ? ot->isHotWaterActive(localResponse) : false;
vars.states.flame = ot->isFlameOn(localResponse);
vars.states.fault = ot->isFault(localResponse);
vars.states.diagnostic = ot->isDiagnostic(localResponse);
setMaxModulationLevel(heatingEnabled ? 100 : 0);
yield();
// Команды чтения данных котла
if (millis() - prevUpdateNonEssentialVars > 60000) {
updateSlaveParameters();
updateMasterParameters();
DEBUG_F("Master type: %u, version: %u\r\n", vars.parameters.masterType, vars.parameters.masterVersion);
DEBUG_F("Slave type: %u, version: %u\r\n", vars.parameters.slaveType, vars.parameters.slaveVersion);
if (settings.opentherm.dhwPresent) {
updateMinMaxDhwTemp();
}
updateMinMaxHeatingTemp();
if (settings.sensors.outdoor.type == 0) {
updateOutsideTemp();
}
if (vars.states.fault) {
updateFaultCode();
ot->sendBoilerReset();
}
if (vars.states.diagnostic) {
ot->sendServiceReset();
}
prevUpdateNonEssentialVars = millis();
yield();
}
updatePressure();
if ((settings.opentherm.dhwPresent && settings.dhw.enable) || settings.heating.enable || heatingEnabled) {
updateModulationLevel();
} else {
vars.sensors.modulation = 0;
}
yield();
if (settings.opentherm.dhwPresent) {
updateDHWTemp();
} else {
vars.temperatures.dhw = 0;
}
updateHeatingTemp();
yield();
//
// Температура ГВС
byte newDHWTemp = settings.dhw.target;
if (settings.opentherm.dhwPresent && settings.dhw.enable && (needSetDhwTemp() || newDHWTemp != currentDHWTemp)) {
if (newDHWTemp < vars.parameters.dhwMinTemp || newDHWTemp > vars.parameters.dhwMaxTemp) {
newDHWTemp = constrain(newDHWTemp, vars.parameters.dhwMinTemp, vars.parameters.dhwMaxTemp);
}
INFO_F("Set DHW temp = %u\r\n", newDHWTemp);
// Записываем заданную температуру ГВС
if (ot->setDHWSetpoint(newDHWTemp)) {
currentDHWTemp = newDHWTemp;
dhwSetTempTime = millis();
} else {
WARN("Failed set DHW temp");
}
}
//
// Температура отопления
if (heatingEnabled && (needSetHeatingTemp() || fabs(vars.parameters.heatingSetpoint - currentHeatingTemp) > 0.0001)) {
INFO_F("Setting heating temp = %u \n", vars.parameters.heatingSetpoint);
// Записываем заданную температуру
if (ot->setBoilerTemperature(vars.parameters.heatingSetpoint)) {
currentHeatingTemp = vars.parameters.heatingSetpoint;
heatingSetTempTime = millis();
} else {
WARN("Failed set heating temp");
}
}
// коммутационная разность (hysteresis)
// только для pid и/или equitherm
if (settings.heating.hysteresis > 0 && !vars.states.emergency && (settings.equitherm.enable || settings.pid.enable)) {
float halfHyst = settings.heating.hysteresis / 2;
if (pump && vars.temperatures.indoor - settings.heating.target + 0.0001 >= halfHyst) {
pump = false;
} else if (!pump && vars.temperatures.indoor - settings.heating.target - 0.0001 <= -(halfHyst)) {
pump = true;
}
} else if (!pump) {
pump = true;
}
}
void static sendRequestCallback(unsigned long request, unsigned long response, OpenThermResponseStatus status, byte attempt) {
printRequestDetail(ot->getDataID(request), status, request, response, attempt);
}
void static responseCallback(unsigned long result, OpenThermResponseStatus status) {
static byte attempt = 0;
switch (status) {
case OpenThermResponseStatus::TIMEOUT:
if (vars.states.otStatus && ++attempt > OPENTHERM_OFFLINE_TRESHOLD) {
vars.states.otStatus = false;
attempt = OPENTHERM_OFFLINE_TRESHOLD;
}
break;
case OpenThermResponseStatus::SUCCESS:
attempt = 0;
if (!vars.states.otStatus) {
vars.states.otStatus = true;
}
#ifdef LED_OT_RX_PIN
{
digitalWrite(LED_OT_RX_PIN, true);
unsigned long ts = millis();
while (millis() - ts < 2) {}
digitalWrite(LED_OT_RX_PIN, false);
}
#endif
break;
default:
break;
}
}
protected:
unsigned short readyTime = 60000;
unsigned short dhwSetTempInterval = 60000;
unsigned short heatingSetTempInterval = 60000;
bool pump = true;
unsigned long prevUpdateNonEssentialVars = 0;
unsigned long startupTime = millis();
unsigned long dhwSetTempTime = 0;
unsigned long heatingSetTempTime = 0;
bool isReady() {
return millis() - startupTime > readyTime;
}
bool needSetDhwTemp() {
return millis() - dhwSetTempTime > dhwSetTempInterval;
}
bool needSetHeatingTemp() {
return millis() - heatingSetTempTime > heatingSetTempInterval;
}
void static printRequestDetail(OpenThermMessageID id, OpenThermResponseStatus status, unsigned long request, unsigned long response, byte attempt) {
sprintf(buffer, "OT REQUEST ID: %4d Request: %8lx Response: %8lx Attempt: %2d Status: %s", id, request, response, attempt, ot->statusToString(status));
if (status != OpenThermResponseStatus::SUCCESS) {
//WARN(buffer);
DEBUG(buffer);
} else {
DEBUG(buffer);
}
}
bool setMasterMemberIdCode() {
//=======================================================================================
// Эта группа элементов данных определяет информацию о конфигурации как на ведомых, так
// и на главных сторонах. Каждый из них имеет группу флагов конфигурации (8 бит)
// и код MemberID (1 байт). Перед передачей информации об управлении и состоянии
// рекомендуется обмен сообщениями о допустимой конфигурации ведомого устройства
// чтения и основной конфигурации записи. Нулевой код MemberID означает клиентское
// неспецифическое устройство. Номер/тип версии продукта следует использовать в сочетании
// с "кодом идентификатора участника", который идентифицирует производителя устройства.
//=======================================================================================
unsigned long response = ot->sendRequest(ot->buildRequest(OpenThermRequestType::READ, OpenThermMessageID::SConfigSMemberIDcode, 0)); // 0xFFFF
if (ot->isValidResponse(response)) {
vars.parameters.slaveMemberIdCode = response & 0xFF;
/*uint8_t flags = (response & 0xFFFF) >> 8;
DEBUG_F(
"MasterMemberIdCode:\r\n DHW present: %u\r\n Control type: %u\r\n Cooling configuration: %u\r\n DHW configuration: %u\r\n Pump control: %u\r\n CH2 present: %u\r\n Remote water filling function: %u\r\n Heat/cool mode control: %u\r\n Slave MemberID Code: %u\r\n",
flags & 0x01,
flags & 0x02,
flags & 0x04,
flags & 0x08,
flags & 0x10,
flags & 0x20,
flags & 0x40,
flags & 0x80,
response & 0xFF
);*/
} else if (settings.opentherm.memberIdCode <= 0) {
return false;
}
response = ot->sendRequest(ot->buildRequest(
OpenThermRequestType::WRITE,
OpenThermMessageID::MConfigMMemberIDcode,
settings.opentherm.memberIdCode > 0 ? settings.opentherm.memberIdCode : vars.parameters.slaveMemberIdCode
));
return ot->isValidResponse(response);
}
bool setMaxModulationLevel(byte value) {
unsigned long response = ot->sendRequest(ot->buildRequest(OpenThermRequestType::WRITE, OpenThermMessageID::MaxRelModLevelSetting, (unsigned int)(value * 256)));
return ot->isValidResponse(response);
}
bool setOpenThermVersionMaster() {
unsigned long response;
response = ot->sendRequest(ot->buildRequest(OpenThermRequestType::READ, OpenThermMessageID::OpenThermVersionSlave, 0));
if (!ot->isValidResponse(response)) {
return false;
}
// INFO_F("Opentherm version slave: %f\n", ot->getFloat(response));
response = ot->sendRequest(ot->buildRequest(OpenThermRequestType::WRITE_DATA, OpenThermMessageID::OpenThermVersionMaster, response));
if (!ot->isValidResponse(response)) {
return false;
}
// INFO_F("Opentherm version master: %f\n", ot->getFloat(response));
return true;
}
bool updateMasterParameters() {
unsigned long response = ot->sendRequest(ot->buildRequest(OpenThermRequestType::WRITE, OpenThermMessageID::MasterVersion, 0x013F));
if (!ot->isValidResponse(response)) {
return false;
}
vars.parameters.masterType = (response & 0xFFFF) >> 8;
vars.parameters.masterVersion = response & 0xFF;
return true;
}
bool updateSlaveParameters() {
unsigned long response = ot->sendRequest(ot->buildRequest(OpenThermRequestType::READ, OpenThermMessageID::SlaveVersion, 0));
if (!ot->isValidResponse(response)) {
return false;
}
vars.parameters.slaveType = (response & 0xFFFF) >> 8;
vars.parameters.slaveVersion = response & 0xFF;
return true;
}
bool updateMinMaxDhwTemp() {
unsigned long response = ot->sendRequest(ot->buildRequest(OpenThermRequestType::READ, OpenThermMessageID::TdhwSetUBTdhwSetLB, 0));
if (!ot->isValidResponse(response)) {
return false;
}
byte minTemp = response & 0xFF;
byte maxTemp = (response & 0xFFFF) >> 8;
if (minTemp >= 0 && maxTemp > 0 && maxTemp > minTemp) {
vars.parameters.dhwMinTemp = minTemp < settings.dhw.minTemp ? settings.dhw.minTemp : minTemp;
vars.parameters.dhwMaxTemp = maxTemp > settings.dhw.maxTemp ? settings.dhw.maxTemp : maxTemp;
return true;
}
return false;
}
bool updateMinMaxHeatingTemp() {
unsigned long response = ot->sendRequest(ot->buildRequest(OpenThermRequestType::READ, OpenThermMessageID::MaxTSetUBMaxTSetLB, 0));
if (!ot->isValidResponse(response)) {
return false;
}
byte minTemp = response & 0xFF;
byte maxTemp = (response & 0xFFFF) >> 8;
if (minTemp >= 0 && maxTemp > 0 && maxTemp > minTemp) {
vars.parameters.heatingMinTemp = minTemp < settings.heating.minTemp ? settings.heating.minTemp : minTemp;
vars.parameters.heatingMaxTemp = maxTemp > settings.heating.maxTemp ? settings.heating.maxTemp : maxTemp;
return true;
}
return false;
}
bool updateOutsideTemp() {
unsigned long response = ot->sendRequest(ot->buildRequest(OpenThermRequestType::READ, OpenThermMessageID::Toutside, 0));
if (!ot->isValidResponse(response)) {
return false;
}
vars.temperatures.outdoor = ot->getFloat(response) + settings.sensors.outdoor.offset;
return true;
}
bool updateHeatingTemp() {
unsigned long response = ot->sendRequest(ot->buildGetBoilerTemperatureRequest());
if (!ot->isValidResponse(response)) {
return false;
}
vars.temperatures.heating = ot->getFloat(response);
return true;
}
bool updateDHWTemp() {
unsigned long response = ot->sendRequest(ot->buildRequest(OpenThermMessageType::READ, OpenThermMessageID::Tdhw, 0));
if (!ot->isValidResponse(response)) {
return false;
}
vars.temperatures.dhw = ot->getFloat(response);
return true;
}
bool updateFaultCode() {
unsigned long response = ot->sendRequest(ot->buildRequest(OpenThermRequestType::READ, OpenThermMessageID::ASFflags, 0));
if (!ot->isValidResponse(response)) {
return false;
}
vars.states.faultCode = response & 0xFF;
return true;
}
bool updateModulationLevel() {
unsigned long response = ot->sendRequest(ot->buildRequest(OpenThermRequestType::READ, OpenThermMessageID::RelModLevel, 0));
if (!ot->isValidResponse(response)) {
return false;
}
float modulation = ot->f88(response);
if (!vars.states.flame) {
vars.sensors.modulation = 0;
} else {
vars.sensors.modulation = modulation;
}
return true;
}
bool updatePressure() {
unsigned long response = ot->sendRequest(ot->buildRequest(OpenThermRequestType::READ, OpenThermMessageID::CHPressure, 0));
if (!ot->isValidResponse(response)) {
return false;
}
vars.sensors.pressure = ot->getFloat(response);
return true;
}
};
-313
View File
@@ -1,313 +0,0 @@
#include <Equitherm.h>
#include <GyverPID.h>
#include <PIDtuner.h>
Equitherm etRegulator;
GyverPID pidRegulator(0, 0, 0);
PIDtuner pidTuner;
class RegulatorTask : public LeanTask {
public:
RegulatorTask(bool _enabled = false, unsigned long _interval = 0) : LeanTask(_enabled, _interval) {}
protected:
bool tunerInit = false;
byte tunerState = 0;
byte tunerRegulator = 0;
float prevHeatingTarget = 0;
float prevEtResult = 0;
float prevPidResult = 0;
const char* getTaskName() {
return "Regulator";
}
int getTaskCore() {
return 1;
}
void loop() {
byte newTemp = vars.parameters.heatingSetpoint;
if (vars.states.emergency) {
if (settings.heating.turbo) {
settings.heating.turbo = false;
INFO("[REGULATOR] Turbo mode auto disabled");
}
newTemp = getEmergencyModeTemp();
} else {
if (vars.tuning.enable || tunerInit) {
if (settings.heating.turbo) {
settings.heating.turbo = false;
INFO("[REGULATOR] Turbo mode auto disabled");
}
newTemp = getTuningModeTemp();
if (newTemp == 0) {
vars.tuning.enable = false;
}
}
if (!vars.tuning.enable) {
if (settings.heating.turbo && (fabs(settings.heating.target - vars.temperatures.indoor) < 1 || (settings.equitherm.enable && settings.pid.enable))) {
settings.heating.turbo = false;
INFO("[REGULATOR] Turbo mode auto disabled");
}
newTemp = getNormalModeTemp();
}
}
// Ограничиваем, если до этого не ограничило
if (newTemp < vars.parameters.heatingMinTemp || newTemp > vars.parameters.heatingMaxTemp) {
newTemp = constrain(newTemp, vars.parameters.heatingMinTemp, vars.parameters.heatingMaxTemp);
}
if (abs(vars.parameters.heatingSetpoint - newTemp) + 0.0001 >= 1) {
vars.parameters.heatingSetpoint = newTemp;
}
}
byte getEmergencyModeTemp() {
float newTemp = 0;
// if use equitherm
if (settings.emergency.useEquitherm && settings.sensors.outdoor.type != 1) {
float etResult = getEquithermTemp(vars.parameters.heatingMinTemp, vars.parameters.heatingMaxTemp);
if (fabs(prevEtResult - etResult) + 0.0001 >= 0.5) {
prevEtResult = etResult;
newTemp += etResult;
INFO_F("[REGULATOR][EQUITHERM] New emergency result: %u (%f) \n", (int)round(etResult), etResult);
} else {
newTemp += prevEtResult;
}
} else {
// default temp, manual mode
newTemp = settings.emergency.target;
}
return round(newTemp);
}
byte getNormalModeTemp() {
float newTemp = 0;
if (fabs(prevHeatingTarget - settings.heating.target) > 0.0001) {
prevHeatingTarget = settings.heating.target;
INFO_F("[REGULATOR] New target: %f \n", settings.heating.target);
if (settings.equitherm.enable && settings.pid.enable) {
pidRegulator.integral = 0;
INFO_F("[REGULATOR][PID] Integral sum has been reset");
}
}
// if use equitherm
if (settings.equitherm.enable) {
float etResult = getEquithermTemp(vars.parameters.heatingMinTemp, vars.parameters.heatingMaxTemp);
if (fabs(prevEtResult - etResult) + 0.0001 >= 0.5) {
prevEtResult = etResult;
newTemp += etResult;
INFO_F("[REGULATOR][EQUITHERM] New result: %u (%f) \n", (int)round(etResult), etResult);
} else {
newTemp += prevEtResult;
}
}
// if use pid
if (settings.pid.enable && vars.parameters.heatingEnabled) {
float pidResult = getPidTemp(
settings.equitherm.enable ? (settings.pid.maxTemp * -1) : settings.pid.minTemp,
settings.equitherm.enable ? settings.pid.maxTemp : settings.pid.maxTemp
);
if (fabs(prevPidResult - pidResult) + 0.0001 >= 0.5) {
prevPidResult = pidResult;
newTemp += pidResult;
INFO_F("[REGULATOR][PID] New result: %d (%f) \n", (int)round(pidResult), pidResult);
} else {
newTemp += prevPidResult;
}
} else if (settings.pid.enable && !vars.parameters.heatingEnabled && prevPidResult != 0) {
newTemp += prevPidResult;
}
// default temp, manual mode
if (!settings.equitherm.enable && !settings.pid.enable) {
newTemp = settings.heating.target;
}
newTemp = round(newTemp);
newTemp = constrain(newTemp, 0, 100);
return newTemp;
}
byte getTuningModeTemp() {
if (tunerInit && (!vars.tuning.enable || vars.tuning.regulator != tunerRegulator)) {
if (tunerRegulator == 0) {
pidTuner.reset();
}
tunerInit = false;
tunerRegulator = 0;
tunerState = 0;
INFO(F("[REGULATOR][TUNING] Stopped"));
}
if (!vars.tuning.enable) {
return 0;
}
if (vars.tuning.regulator == 0) {
// @TODO дописать
INFO(F("[REGULATOR][TUNING][EQUITHERM] Not implemented"));
return 0;
} else if (vars.tuning.regulator == 1) {
// PID tuner
float defaultTemp = settings.equitherm.enable
? getEquithermTemp(vars.parameters.heatingMinTemp, vars.parameters.heatingMaxTemp)
: settings.heating.target;
if (tunerInit && pidTuner.getState() == 3) {
INFO(F("[REGULATOR][TUNING][PID] Finished"));
pidTuner.debugText(&INFO_STREAM);
pidTuner.reset();
tunerInit = false;
tunerRegulator = 0;
tunerState = 0;
if (pidTuner.getAccuracy() < 90) {
WARN(F("[REGULATOR][TUNING][PID] Bad result, try again..."));
} else {
settings.pid.p_factor = pidTuner.getPID_p();
settings.pid.i_factor = pidTuner.getPID_i();
settings.pid.d_factor = pidTuner.getPID_d();
return 0;
}
}
if (!tunerInit) {
INFO(F("[REGULATOR][TUNING][PID] Start..."));
float step;
if (vars.temperatures.indoor - vars.temperatures.outdoor > 10) {
step = ceil(vars.parameters.heatingSetpoint / vars.temperatures.indoor * 2);
} else {
step = 5.0f;
}
float startTemp = step;
INFO_F("[REGULATOR][TUNING][PID] Started. Start value: %f, step: %f \n", startTemp, step);
pidTuner.setParameters(NORMAL, startTemp, step, 20 * 60 * 1000, 0.15, 60 * 1000, 10000);
tunerInit = true;
tunerRegulator = 1;
}
pidTuner.setInput(vars.temperatures.indoor);
pidTuner.compute();
if (tunerState > 0 && pidTuner.getState() != tunerState) {
INFO(F("[REGULATOR][TUNING][PID] Log:"));
pidTuner.debugText(&INFO_STREAM);
tunerState = pidTuner.getState();
}
return round(defaultTemp + pidTuner.getOutput());
} else {
return 0;
}
}
float getEquithermTemp(int minTemp, int maxTemp) {
if (vars.states.emergency) {
etRegulator.Kt = 0;
etRegulator.indoorTemp = 0;
etRegulator.outdoorTemp = vars.temperatures.outdoor;
} else if (settings.pid.enable) {
etRegulator.Kt = 0;
etRegulator.indoorTemp = round(vars.temperatures.indoor);
etRegulator.outdoorTemp = round(vars.temperatures.outdoor);
} else {
if (settings.heating.turbo) {
etRegulator.Kt = 10;
} else {
etRegulator.Kt = settings.equitherm.t_factor;
}
etRegulator.indoorTemp = vars.temperatures.indoor;
etRegulator.outdoorTemp = vars.temperatures.outdoor;
}
etRegulator.setLimits(minTemp, maxTemp);
etRegulator.Kn = settings.equitherm.n_factor;
// etRegulator.Kn = tuneEquithermN(etRegulator.Kn, vars.temperatures.indoor, settings.heating.target, 300, 1800, 0.01, 1);
etRegulator.Kk = settings.equitherm.k_factor;
etRegulator.targetTemp = vars.states.emergency ? settings.emergency.target : settings.heating.target;
return etRegulator.getResult();
}
float getPidTemp(int minTemp, int maxTemp) {
pidRegulator.Kp = settings.pid.p_factor;
pidRegulator.Ki = settings.pid.i_factor;
pidRegulator.Kd = settings.pid.d_factor;
pidRegulator.setLimits(minTemp, maxTemp);
pidRegulator.input = vars.temperatures.indoor;
pidRegulator.setpoint = settings.heating.target;
return pidRegulator.getResultNow();
}
float tuneEquithermN(float ratio, float currentTemp, float setTemp, unsigned int dirtyInterval = 60, unsigned int accurateInterval = 1800, float accurateStep = 0.01, float accurateStepAfter = 1) {
static uint32_t _prevIteration = millis();
if (abs(currentTemp - setTemp) < accurateStepAfter) {
if (millis() - _prevIteration < (accurateInterval * 1000)) {
return ratio;
}
if (currentTemp - setTemp > 0.1f) {
ratio -= accurateStep;
} else if (currentTemp - setTemp < -0.1f) {
ratio += accurateStep;
}
} else {
if (millis() - _prevIteration < (dirtyInterval * 1000)) {
return ratio;
}
ratio = ratio * (setTemp / currentTemp);
}
_prevIteration = millis();
return ratio;
}
};
-152
View File
@@ -1,152 +0,0 @@
#include <OneWire.h>
#include <DallasTemperature.h>
class SensorsTask : public LeanTask {
public:
SensorsTask(bool _enabled = false, unsigned long _interval = 0) : LeanTask(_enabled, _interval) {}
protected:
OneWire* oneWireOutdoorSensor;
OneWire* oneWireIndoorSensor;
DallasTemperature* outdoorSensor;
DallasTemperature* indoorSensor;
bool initOutdoorSensor = false;
unsigned long startConversionTime = 0;
float filteredOutdoorTemp = 0;
bool emptyOutdoorTemp = true;
bool initIndoorSensor = false;
float filteredIndoorTemp = 0;
bool emptyIndoorTemp = true;
const char* getTaskName() {
return "Sensors";
}
void loop() {
if (settings.sensors.outdoor.type == 2) {
outdoorTemperatureSensor();
}
if (settings.sensors.indoor.type == 2) {
indoorTemperatureSensor();
}
}
void outdoorTemperatureSensor() {
if (!initOutdoorSensor) {
oneWireOutdoorSensor = new OneWire(settings.sensors.outdoor.pin);
outdoorSensor = new DallasTemperature(oneWireOutdoorSensor);
outdoorSensor->begin();
outdoorSensor->setResolution(12);
outdoorSensor->setWaitForConversion(false);
outdoorSensor->requestTemperatures();
startConversionTime = millis();
initOutdoorSensor = true;
}
unsigned long estimateConversionTime = millis() - startConversionTime;
if (estimateConversionTime < outdoorSensor->millisToWaitForConversion()) {
return;
}
bool completed = outdoorSensor->isConversionComplete();
if (!completed && estimateConversionTime >= 1000) {
// fail, retry
outdoorSensor->requestTemperatures();
startConversionTime = millis();
ERROR("[SENSORS][OUTDOOR] Could not read temperature data (no response)");
}
if (!completed) {
return;
}
float rawTemp = outdoorSensor->getTempCByIndex(0);
if (rawTemp == DEVICE_DISCONNECTED_C) {
ERROR("[SENSORS][OUTDOOR] Could not read temperature data (not connected)");
} else {
DEBUG_F("[SENSORS][OUTDOOR] Raw temp: %f \n", rawTemp);
if (emptyOutdoorTemp) {
filteredOutdoorTemp = rawTemp;
emptyOutdoorTemp = false;
} else {
filteredOutdoorTemp += (rawTemp - filteredOutdoorTemp) * EXT_SENSORS_FILTER_K;
}
filteredOutdoorTemp = floor(filteredOutdoorTemp * 100) / 100;
if (fabs(vars.temperatures.outdoor - filteredOutdoorTemp) > 0.099) {
vars.temperatures.outdoor = filteredOutdoorTemp + settings.sensors.outdoor.offset;
INFO_F("[SENSORS][OUTDOOR] New temp: %f \n", filteredOutdoorTemp);
}
}
outdoorSensor->requestTemperatures();
startConversionTime = millis();
}
void indoorTemperatureSensor() {
if (!initIndoorSensor) {
oneWireIndoorSensor = new OneWire(settings.sensors.indoor.pin);
indoorSensor = new DallasTemperature(oneWireIndoorSensor);
indoorSensor->begin();
indoorSensor->setResolution(12);
indoorSensor->setWaitForConversion(false);
indoorSensor->requestTemperatures();
startConversionTime = millis();
initIndoorSensor = true;
}
unsigned long estimateConversionTime = millis() - startConversionTime;
if (estimateConversionTime < indoorSensor->millisToWaitForConversion()) {
return;
}
bool completed = indoorSensor->isConversionComplete();
if (!completed && estimateConversionTime >= 1000) {
// fail, retry
indoorSensor->requestTemperatures();
startConversionTime = millis();
ERROR("[SENSORS][INDOOR] Could not read temperature data (no response)");
}
if (!completed) {
return;
}
float rawTemp = indoorSensor->getTempCByIndex(0);
if (rawTemp == DEVICE_DISCONNECTED_C) {
ERROR("[SENSORS][INDOOR] Could not read temperature data (not connected)");
} else {
DEBUG_F("[SENSORS][INDOOR] Raw temp: %f \n", rawTemp);
if (emptyIndoorTemp) {
filteredIndoorTemp = rawTemp;
emptyIndoorTemp = false;
} else {
filteredIndoorTemp += (rawTemp - filteredIndoorTemp) * EXT_SENSORS_FILTER_K;
}
filteredIndoorTemp = floor(filteredIndoorTemp * 100) / 100;
if (fabs(vars.temperatures.indoor - filteredIndoorTemp) > 0.099) {
vars.temperatures.indoor = filteredIndoorTemp + settings.sensors.indoor.offset;
INFO_F("[SENSORS][INDOOR] New temp: %f \n", filteredIndoorTemp);
}
}
indoorSensor->requestTemperatures();
startConversionTime = millis();
}
};
-123
View File
@@ -1,123 +0,0 @@
struct Settings {
bool debug = false;
char hostname[80] = "opentherm";
struct {
byte inPin = OT_IN_PIN_DEFAULT;
byte outPin = OT_OUT_PIN_DEFAULT;
unsigned int memberIdCode = 0;
bool dhwPresent = true;
} opentherm;
struct {
char server[80];
unsigned int port = 1883;
char user[32];
char password[32];
char prefix[80] = "opentherm";
unsigned int interval = 5000;
} mqtt;
struct {
bool enable = true;
float target = 40.0f;
bool useEquitherm = false;
} emergency;
struct {
bool enable = true;
bool turbo = false;
float target = 40.0f;
float hysteresis = 0.5f;
byte minTemp = 20.0f;
byte maxTemp = 90.0f;
} heating;
struct {
bool enable = true;
byte target = 40;
byte minTemp = 30.0f;
byte maxTemp = 60.0f;
} dhw;
struct {
bool enable = false;
float p_factor = 3;
float i_factor = 0.2f;
float d_factor = 0;
byte minTemp = 0.0f;
byte maxTemp = 90.0f;
} pid;
struct {
bool enable = false;
float n_factor = 0.7f;
float k_factor = 3.0f;
float t_factor = 2.0f;
} equitherm;
struct {
struct {
// 0 - boiler, 1 - manual, 2 - ds18b20
byte type = 0;
byte pin = SENSOR_OUTDOOR_PIN_DEFAULT;
float offset = 0.0f;
} outdoor;
struct {
// 1 - manual, 2 - ds18b20
byte type = 1;
byte pin = SENSOR_INDOOR_PIN_DEFAULT;
float offset = 0.0f;
} indoor;
} sensors;
char validationValue[8] = SETTINGS_VALID_VALUE;
} settings;
struct Variables {
struct {
bool enable = false;
byte regulator = 0;
} tuning;
struct {
bool otStatus = false;
bool emergency = false;
bool heating = false;
bool dhw = false;
bool flame = false;
bool fault = false;
bool diagnostic = false;
byte faultCode = 0;
int8_t rssi = 0;
} states;
struct {
float modulation = 0.0f;
float pressure = 0.0f;
} sensors;
struct {
float indoor = 0.0f;
float outdoor = 0.0f;
float heating = 0.0f;
float dhw = 0.0f;
} temperatures;
struct {
unsigned long restartSignalTime = 0;
unsigned int restartAfterTime = 0;
bool heatingEnabled = false;
byte heatingMinTemp = 20;
byte heatingMaxTemp = 90;
byte heatingSetpoint = 0.0f;
byte dhwMinTemp = 30;
byte dhwMaxTemp = 60;
uint8_t slaveMemberIdCode;
uint8_t slaveType;
uint8_t slaveVersion;
uint8_t masterType;
uint8_t masterVersion;
} parameters;
} vars;
-296
View File
@@ -1,296 +0,0 @@
#define WM_MDNS
#include <WiFiManager.h>
#include <WiFiManagerParameters.h>
#include <netif/etharp.h>
WiFiManager wm;
WiFiManagerParameter* wmHostname;
WiFiManagerParameter* wmMqttServer;
UnsignedIntParameter* wmMqttPort;
WiFiManagerParameter* wmMqttUser;
WiFiManagerParameter* wmMqttPassword;
WiFiManagerParameter* wmMqttPrefix;
UnsignedIntParameter* wmMqttPublishInterval;
UnsignedIntParameter* wmOtInPin;
UnsignedIntParameter* wmOtOutPin;
UnsignedIntParameter* wmOtMemberIdCode;
CheckboxParameter* wmOtDHWPresent;
UnsignedIntParameter* wmOutdoorSensorPin;
UnsignedIntParameter* wmIndoorSensorPin;
SeparatorParameter* wmSep1;
SeparatorParameter* wmSep2;
class WifiManagerTask : public Task {
public:
WifiManagerTask(bool _enabled = false, unsigned long _interval = 0) : Task(_enabled, _interval) {}
protected:
bool connected = false;
unsigned long lastArpGratuitous = 0;
const char* getTaskName() {
return "WifiManager";
}
int getTaskCore() {
return 0;
}
void setup() {
wm.setDebugOutput(settings.debug);
//wm.setDebugOutput(settings.debug, WM_DEBUG_VERBOSE);
wm.setTitle("OpenTherm Gateway");
wm.setCustomMenuHTML(PSTR(
"<style>.wrap h1 {display: none;} .wrap h3 {display: none;} .nh {margin: 0 0 1em 0;} .nh .logo {font-size: 1.8em; margin: 0.5em; text-align: center;} .nh .links {text-align: center;}</style>"
"<div class=\"nh\">"
"<div class=\"logo\">OpenTherm Gateway</div>"
"<div class=\"links\"><a href=\"" OT_GATEWAY_REPO "\" target=\"_blank\">Repo</a> | <a href=\"" OT_GATEWAY_REPO "/issues\" target=\"_blank\">Issues</a> | <a href=\"" OT_GATEWAY_REPO "/releases\" target=\"_blank\">Releases</a> | <small>v" OT_GATEWAY_VERSION " (" __DATE__ ")</small></div>"
"</div>"
));
std::vector<const char *> menu = {"custom", "wifi", "param", "sep", "info", "update", "restart"};
wm.setMenu(menu);
wmHostname = new WiFiManagerParameter("hostname", "Hostname", settings.hostname, 80);
wm.addParameter(wmHostname);
wmMqttServer = new WiFiManagerParameter("mqtt_server", "MQTT server", settings.mqtt.server, 80);
wm.addParameter(wmMqttServer);
wmMqttPort = new UnsignedIntParameter("mqtt_port", "MQTT port", settings.mqtt.port, 6);
wm.addParameter(wmMqttPort);
wmMqttUser = new WiFiManagerParameter("mqtt_user", "MQTT username", settings.mqtt.user, 32);
wm.addParameter(wmMqttUser);
wmMqttPassword = new WiFiManagerParameter("mqtt_password", "MQTT password", settings.mqtt.password, 32, "type=\"password\"");
wm.addParameter(wmMqttPassword);
wmMqttPrefix = new WiFiManagerParameter("mqtt_prefix", "MQTT prefix", settings.mqtt.prefix, 32);
wm.addParameter(wmMqttPrefix);
wmMqttPublishInterval = new UnsignedIntParameter("mqtt_publish_interval", "MQTT publish interval", settings.mqtt.interval, 5);
wm.addParameter(wmMqttPublishInterval);
wmSep1 = new SeparatorParameter();
wm.addParameter(wmSep1);
wmOtInPin = new UnsignedIntParameter("ot_in_pin", "Opentherm pin IN", settings.opentherm.inPin, 2);
wm.addParameter(wmOtInPin);
wmOtOutPin = new UnsignedIntParameter("ot_out_pin", "Opentherm pin OUT", settings.opentherm.outPin, 2);
wm.addParameter(wmOtOutPin);
wmOtMemberIdCode = new UnsignedIntParameter("ot_member_id_code", "Opentherm member id", settings.opentherm.memberIdCode, 5);
wm.addParameter(wmOtMemberIdCode);
wmOtDHWPresent = new CheckboxParameter("ot_dhw_present", "Opentherm DHW present", settings.opentherm.dhwPresent);
wm.addParameter(wmOtDHWPresent);
wmSep2 = new SeparatorParameter();
wm.addParameter(wmSep2);
wmOutdoorSensorPin = new UnsignedIntParameter("outdoor_sensor_pin", "Outdoor sensor pin", settings.sensors.outdoor.pin, 2);
wm.addParameter(wmOutdoorSensorPin);
wmIndoorSensorPin = new UnsignedIntParameter("indoor_sensor_pin", "Indoor sensor pin", settings.sensors.indoor.pin, 2);
wm.addParameter(wmIndoorSensorPin);
//wm.setCleanConnect(true);
wm.setRestorePersistent(false);
wm.setHostname(settings.hostname);
wm.setWiFiAutoReconnect(true);
wm.setAPClientCheck(true);
wm.setConfigPortalBlocking(false);
wm.setSaveParamsCallback(saveParamsCallback);
wm.setConfigPortalTimeout(wm.getWiFiIsSaved() ? 180 : 0);
wm.setDisableConfigPortal(false);
wm.autoConnect(AP_SSID, AP_PASSWORD);
}
void loop() {
if (connected && WiFi.status() != WL_CONNECTED) {
connected = false;
if (wm.getWebPortalActive()) {
wm.stopWebPortal();
}
#ifdef USE_TELNET
TelnetStream.stop();
#endif
INFO("[wifi] Disconnected");
} else if (!connected && WiFi.status() == WL_CONNECTED) {
connected = true;
wm.setConfigPortalTimeout(180);
if (wm.getConfigPortalActive()) {
wm.stopConfigPortal();
}
if (!wm.getWebPortalActive()) {
wm.startWebPortal();
}
#ifdef USE_TELNET
TelnetStream.begin();
#endif
INFO_F("[wifi] Connected. IP address: %s, RSSI: %d\n", WiFi.localIP().toString().c_str(), WiFi.RSSI());
}
#if defined(ESP8266)
if (connected && millis() - lastArpGratuitous > 60000) {
arpGratuitous();
lastArpGratuitous = millis();
}
#endif
wm.process();
}
static void saveParamsCallback() {
bool changed = false;
bool needRestart = false;
if (strcmp(wmHostname->getValue(), settings.hostname) != 0) {
changed = true;
needRestart = true;
strcpy(settings.hostname, wmHostname->getValue());
}
if (strcmp(wmMqttServer->getValue(), settings.mqtt.server) != 0) {
changed = true;
strcpy(settings.mqtt.server, wmMqttServer->getValue());
}
if (wmMqttPort->getValue() != settings.mqtt.port) {
changed = true;
settings.mqtt.port = wmMqttPort->getValue();
}
if (strcmp(wmMqttUser->getValue(), settings.mqtt.user) != 0) {
changed = true;
strcpy(settings.mqtt.user, wmMqttUser->getValue());
}
if (strcmp(wmMqttPassword->getValue(), settings.mqtt.password) != 0) {
changed = true;
strcpy(settings.mqtt.password, wmMqttPassword->getValue());
}
if (strcmp(wmMqttPrefix->getValue(), settings.mqtt.prefix) != 0) {
changed = true;
strcpy(settings.mqtt.prefix, wmMqttPrefix->getValue());
}
if (wmMqttPublishInterval->getValue() != settings.mqtt.interval) {
changed = true;
settings.mqtt.interval = wmMqttPublishInterval->getValue();
}
if (wmOtInPin->getValue() != settings.opentherm.inPin) {
changed = true;
needRestart = true;
settings.opentherm.inPin = wmOtInPin->getValue();
}
if (wmOtOutPin->getValue() != settings.opentherm.outPin) {
changed = true;
needRestart = true;
settings.opentherm.outPin = wmOtOutPin->getValue();
}
if (wmOtMemberIdCode->getValue() != settings.opentherm.memberIdCode) {
changed = true;
settings.opentherm.memberIdCode = wmOtMemberIdCode->getValue();
}
if (wmOtDHWPresent->getCheckboxValue() != settings.opentherm.dhwPresent) {
changed = true;
settings.opentherm.dhwPresent = wmOtDHWPresent->getCheckboxValue();
}
if (wmOutdoorSensorPin->getValue() != settings.sensors.outdoor.pin) {
changed = true;
needRestart = true;
settings.sensors.outdoor.pin = wmOutdoorSensorPin->getValue();
}
if (wmIndoorSensorPin->getValue() != settings.sensors.indoor.pin) {
changed = true;
needRestart = true;
settings.sensors.indoor.pin = wmIndoorSensorPin->getValue();
}
if (!changed) {
return;
}
if (needRestart) {
vars.parameters.restartAfterTime = 5000;
vars.parameters.restartSignalTime = millis();
}
INFO_F(
"New settings:\r\n"
" Hostname: %s\r\n"
" Mqtt server: %s:%d\r\n"
" Mqtt user: %s\r\n"
" Mqtt pass: %s\r\n"
" Mqtt prefix: %s\r\n"
" Mqtt publish interval: %d\r\n"
" OT in pin: %d\r\n"
" OT out pin: %d\r\n"
" OT member id code: %d\r\n"
" OT DHW present: %d\r\n"
" Outdoor sensor pin: %d\r\n"
" Indoor sensor pin: %d\r\n",
settings.hostname,
settings.mqtt.server,
settings.mqtt.port,
settings.mqtt.user,
settings.mqtt.password,
settings.mqtt.prefix,
settings.mqtt.interval,
settings.opentherm.inPin,
settings.opentherm.outPin,
settings.opentherm.memberIdCode,
settings.opentherm.dhwPresent,
settings.sensors.outdoor.pin,
settings.sensors.indoor.pin
);
eeSettings.updateNow();
INFO(F("Settings saved"));
}
static void arpGratuitous() {
struct netif* netif = netif_list;
while (netif) {
etharp_gratuitous(netif);
netif = netif->next;
}
}
};
+3513
View File
File diff suppressed because it is too large. Load diff
+455
View File
@@ -0,0 +1,455 @@
#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);
}
-59
View File
@@ -1,59 +0,0 @@
#define OT_GATEWAY_VERSION "1.3.3"
#define OT_GATEWAY_REPO "https://github.com/Laxilef/OTGateway"
#define AP_SSID "OpenTherm Gateway"
#define AP_PASSWORD "otgateway123456"
#define USE_TELNET
#define EMERGENCY_TIME_TRESHOLD 120000
#define MQTT_RECONNECT_INTERVAL 5000
#define MQTT_KEEPALIVE 30
#define OPENTHERM_OFFLINE_TRESHOLD 10
#define EXT_SENSORS_INTERVAL 5000
#define EXT_SENSORS_FILTER_K 0.15
#define CONFIG_URL "http://%s/"
#define SETTINGS_VALID_VALUE "stvalid" // only 8 chars!
#ifndef OT_IN_PIN_DEFAULT
#define OT_IN_PIN_DEFAULT 0
#endif
#ifndef OT_OUT_PIN_DEFAULT
#define OT_OUT_PIN_DEFAULT 0
#endif
#ifndef SENSOR_OUTDOOR_PIN_DEFAULT
#define SENSOR_OUTDOOR_PIN_DEFAULT 0
#endif
#ifndef SENSOR_INDOOR_PIN_DEFAULT
#define SENSOR_INDOOR_PIN_DEFAULT 0
#endif
#ifdef USE_TELNET
#define INFO_STREAM TelnetStream
#define WARN_STREAM TelnetStream
#define ERROR_STREAM TelnetStream
#define DEBUG_STREAM if (settings.debug) TelnetStream
#define WM_DEBUG_PORT TelnetStream
#else
#define INFO_STREAM Serial
#define WARN_STREAM Serial
#define ERROR_STREAM Serial
#define DEBUG_STREAM if (settings.debug) Serial
#define WM_DEBUG_PORT Serial
#endif
#define INFO(...) INFO_STREAM.print("\r[INFO] "); INFO_STREAM.println(__VA_ARGS__);
#define INFO_F(...) INFO_STREAM.print("\r[INFO] "); INFO_STREAM.printf(__VA_ARGS__);
#define WARN(...) WARN_STREAM.print("\r[WARN] "); WARN_STREAM.println(__VA_ARGS__);
#define WARN_F(...) WARN_STREAM.print("\r[WARN] "); WARN_STREAM.printf(__VA_ARGS__);
#define ERROR(...) ERROR_STREAM.print("\r[ERROR] "); ERROR_STREAM.println(__VA_ARGS__);
#define DEBUG(...) DEBUG_STREAM.print("\r[DEBUG] "); DEBUG_STREAM.println(__VA_ARGS__);
#define DEBUG_F(...) DEBUG_STREAM.print("\r[DEBUG] "); DEBUG_STREAM.printf(__VA_ARGS__);
char buffer[255];
+1181
View File
File diff suppressed because it is too large. Load diff
+91
View File
@@ -0,0 +1,91 @@
#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
@@ -0,0 +1,239 @@
#include <app.h>
#include <MycilaWebSerial.h>
#include <algorithm>
#include <atomic>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#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>
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;
}
+86 -77
View File
@@ -1,88 +1,97 @@
#include <Arduino.h>
#include "defines.h"
#include <ArduinoJson.h>
#include <TelnetStream.h>
#include <EEManager.h>
#include "Settings.h"
#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE
EEManager eeSettings(settings, 30000);
#include <app.h>
#include <metrics.h>
#include <cstdlib>
#include <esp_system.h>
#if defined(ESP32)
#include <ESP32Scheduler.h>
#include <Task.h>
#include <LeanTask.h>
#elif defined(ESP8266)
#include <Scheduler.h>
#include <Task.h>
#include <LeanTask.h>
#elif
#error Wrong board. Supported boards: esp8266, esp32
#if ARDUINO_USB_CDC_ON_BOOT && !ARDUINO_USB_MODE
#include <USB.h>
#endif
#include "WifiManagerTask.h"
#include "MqttTask.h"
#include "OpenThermTask.h"
#include "SensorsTask.h"
#include "RegulatorTask.h"
#include "MainTask.h"
#ifndef ARDUINO_ARCH_ESP32
#error Only ESP32 boards are supported
#endif
// Tasks
WifiManagerTask* tWm;
MqttTask* tMqtt;
OpenThermTask* tOt;
SensorsTask* tSensors;
RegulatorTask* tRegulator;
MainTask* tMain;
#include <LittleFS.h>
// Vars
Sensors::Result sensorsResults[SENSORS_AMOUNT];
TaskManager coreTaskManager("Core");
TaskManager systemTaskManager("System");
TaskManager openthermTaskManager("OpenTherm");
TaskManager sensorsTaskManager("Sensors");
void setup() {
#ifndef USE_TELNET
Serial.begin(115200);
Serial.println("\n\n");
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
EEPROM.begin(eeSettings.blockSize());
uint8_t eeSettingsResult = eeSettings.begin(0, 's');
if (eeSettingsResult == 0) {
INFO("Settings loaded");
if (strcmp(SETTINGS_VALID_VALUE, settings.validationValue) != 0) {
INFO("Settings not valid, reset and restart...");
eeSettings.reset();
delay(1000);
ESP.restart();
}
} else if (eeSettingsResult == 1) {
INFO("Settings NOT loaded, first start");
} else if (eeSettingsResult == 2) {
INFO("Settings NOT loaded (error)");
}
tWm = new WifiManagerTask(true);
Scheduler.start(tWm);
tMqtt = new MqttTask(false);
Scheduler.start(tMqtt);
tOt = new OpenThermTask(false);
Scheduler.start(tOt);
tSensors = new SensorsTask(true, EXT_SENSORS_INTERVAL);
Scheduler.start(tSensors);
tRegulator = new RegulatorTask(true, 10000);
Scheduler.start(tRegulator);
tMain = new MainTask(true, 50);
Scheduler.start(tMain);
Scheduler.begin();
}
void loop() {
#if defined(ESP32)
vTaskDelete(NULL);
#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());
}
+1104
View File
File diff suppressed because it is too large. Load diff
+849
View File
@@ -0,0 +1,849 @@
#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
@@ -0,0 +1,985 @@
#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
@@ -0,0 +1,242 @@
#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();
}
+990
View File
@@ -0,0 +1,990 @@
#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE
#include <app.h>
#include <atomic>
#include <optional>
#include <unordered_map>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <esp32DHT.h>
#include <math.h>
#include <string.h>
#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
@@ -0,0 +1,140 @@
#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
@@ -0,0 +1,96 @@
<?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>

After

Width:  |  Height:  |  Size: 27 KiB

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

After

Width:  |  Height:  |  Size: 15 KiB

+556
View File
@@ -0,0 +1,556 @@
{
"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
@@ -0,0 +1,556 @@
{
"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
@@ -0,0 +1,556 @@
{
"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
@@ -0,0 +1,556 @@
{
"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
@@ -0,0 +1,556 @@
{
"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
@@ -0,0 +1,834 @@
<!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
@@ -0,0 +1,290 @@
<!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
@@ -0,0 +1,664 @@
<!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
@@ -0,0 +1,228 @@
<!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
@@ -0,0 +1,347 @@
<!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
@@ -0,0 +1,418 @@
<!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
@@ -0,0 +1,2 @@
User-agent: *
Disallow: /
+14
View File
@@ -0,0 +1,14 @@
/*!
* 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
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff. Show more