Compare commits

..
17 Commits
Author SHA1 Message Date
Yurii ca3b59b9b0 docs: add adapter enclosure photo and preview 2026-11-23 19:20:11 +03:00
Yurii ec4018310d fix: skip duplicate checks on pull request updates 2026-11-23 18:59:29 +03:00
Yurii 39a0f34798 fix: download TinyUSB sources using SDK revisions
Download lib-builder and TinyUSB source snapshots directly using the
revisions in the installed SDK versions.txt. Avoid the GitHub REST lookup
without maintaining a separate set of commit pins.

Check the archive commit ID, extract the required files and reuse completed
downloads. Incomplete extraction is retried on the next invocation.
2026-11-23 18:39:40 +03:00
Yurii 765508993a fix: recover missing source revisions in S2 TinyUSB builds
Resolve missing SDK revisions to their full GitHub commit IDs and fetch
those commits explicitly before checkout. Keep using the matching source
revision when upstream branches no longer expose it.

Always materialize the requested checkout, including fresh no-checkout
clones whose HEAD already matches the pinned revision. Cached commits
continue to work without API requests.
2026-11-23 17:52:07 +03:00
Yurii dc72966aca style: resolve cpplint warnings in firmware sources
Place C headers before C++ headers in sensor, metrics, utility and
application sources.

Document the owned cache of the applied MQTT prefix and suppress
runtime/string only for this variable. Preserve MQTT reconfiguration
and prefix buffer cleanup.

Validated with cpplint 2.0.2 over include, lib and src using CI filters.
2026-11-23 17:17:45 +03:00
Yurii 558d52fa9b fix: support clean SDK builds and portable C6 compiler flags
Create the SDK source directory before pioarduino populates it so its
project generator supplies app_main when Arduino autostart is disabled.

Skip TinyUSB setup for S2 clean targets before accessing SDK packages.
Move C6 constexpr attributes into a forced include header to preserve the
size optimizations across SDK metadata parsing and POSIX shell execution.
2026-11-23 08:41:21 +03:00
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
53 changed files with 19632 additions and 1731 deletions

No files matched your search

+22 -36
View File
@@ -35,7 +35,6 @@ jobs:
runs-on: ubuntu-latest
outputs:
envs: ${{ steps.envs.outputs.envs }}
env_titles: ${{ steps.envs.outputs.env_titles }}
steps:
- name: Checkout
@@ -56,24 +55,19 @@ jobs:
id: envs
shell: bash
run: |
ENVS=$(
pio project config --json-output \
| jq -r '
[
| jq -c '
.[]
| select(type == "array")
| select(.[0] | startswith("env:"))
| {
name: (.[0] | sub("^env:"; "")),
title: ([.[1][] | select(.[0] == "custom_title") | .[1]][0])
}
] as $envs
| {
envs: ($envs | map(.name)),
env_titles: ($envs | map({key: .name, value: .title}) | from_entries)
}
| to_entries[]
| "\(.key)=\(.value | tojson)"
' | tee -a "$GITHUB_OUTPUT"
| .[0]
| select(startswith("env:"))
| sub("^env:"; "")
' | jq -s -c '.'
)
echo "envs=$ENVS" >> "$GITHUB_OUTPUT"
echo "$ENVS"
build:
name: Build ${{ matrix.env }}
@@ -125,12 +119,12 @@ jobs:
build/*.elf
release:
name: Release Unstable
name: Release Dev
runs-on: ubuntu-latest
needs: [prepare, build]
needs: build
permissions:
contents: write
if: ${{ github.repository_owner == 'Laxilef' && github.ref == 'refs/heads/dev' }}
if: ${{ github.repository_owner == 'Laxilef' && github.ref == 'refs/heads/async' }}
steps:
- name: Checkout
@@ -138,11 +132,11 @@ jobs:
with:
fetch-depth: 0
- name: Move unstable tag
- name: Move dev tag
run: |
git fetch --tags
git tag -f unstable
git push origin refs/tags/unstable --force
git tag -f dev
git push origin refs/tags/dev --force
- name: Download artifacts
uses: actions/download-artifact@v5
@@ -150,40 +144,32 @@ jobs:
path: artifacts
merge-multiple: true
- name: Generate Web Flasher manifest
env:
ENVS: ${{ needs.prepare.outputs.envs }}
ENV_TITLES: ${{ needs.prepare.outputs.env_titles }}
run: python3 tools/generate_webflasher.py --envs "$ENVS" --titles "$ENV_TITLES"
- name: Delete old release assets
uses: mknejp/delete-release-assets@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
tag: unstable
tag: dev
fail-if-no-assets: false
fail-if-no-release: false
assets: |
*.bin
*.elf
webflasher.json
- name: Clear release body
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
gh release edit unstable --notes ""
gh release edit dev --notes ""
- name: Publish Unstable release
- name: Publish Dev release
uses: softprops/action-gh-release@v3
with:
tag_name: unstable
target_commitish: ${{ github.sha }}
name: Unstable
tag_name: dev
target_commitish: async
name: Dev (unstable)
prerelease: true
make_latest: false
generate_release_notes: true
files: |
artifacts/*.bin
artifacts/*.elf
artifacts/webflasher.json
-1
View File
@@ -53,7 +53,6 @@
- Для анализа используй только логи, из которых возможные секреты заранее
полностью удалены. Не читай и не сохраняй сырые логи ради последующего поиска
или маскировки таких значений.
- Пользователь может отменить любой вышеперечисленный запрет для выполнения конкретной задачи.
## Изменения и Git
+5 -44
View File
@@ -111,56 +111,17 @@ request
vars.master.heating.enabled, settings.opentherm.heatingDisablingAction
))
.setHotWaterEnabled(
settings.opentherm.options.dhwSupport
&& getSlaveChannelEnabled(vars.master.dhw.enabled, settings.opentherm.dhwDisablingAction)
settings.opentherm.options.dhwSupport &&
getSlaveChannelEnabled(vars.master.dhw.enabled, settings.opentherm.dhwDisablingAction)
)
.setCoolingEnabled(settings.opentherm.options.coolingSupport)
.setDhwBlocking(dhwBlocking);
```
Не считай это общим требованием переносить имя объекта перед любой цепочкой.
В многострочных логических условиях ставь `&&` и `||` в начале строки
продолжения. Для `if`/`else if` отступ продолжения — четыре пробела
от начала исходной строки. Если первый операнд уже вынесен на отдельную строку
внутри аргумента вызова или группы в скобках, следующие строки с `&&`/`||`
выравнивай по нему без дополнительных
двух пробелов. Группируй связанные условия скобками и не меняй их порядок
или приоритет ради выравнивания.
В многострочных `return` ставь `&&` и `||` в конце предыдущей строки,
а продолжение выравнивай под началом выражения после `return`.
Во вложенных группах также выравнивай операнды по первому выражению группы.
В многострочных логических присваиваниях также оставляй `&&` и `||` в конце
предыдущей строки, а продолжение выравнивай под началом правой части.
При длинном типе или имени переменной переноси правую часть целиком после `=`:
её базовый отступ — четыре пробела от начала объявления.
Простые условия из нескольких коротких проверок оставляй на одной строке.
Несколько `&&`/`||` сами по себе не требуют переноса; разбивай выражение,
когда это помогает читать длинные или сложные условия.
```cpp
if (!response.isSuccess() || response.getRequestCode() != 10 || response.getResponseCode() < 128) {
ESP_LOGE(L_OT, "Boiler diagnostic reset failed");
return;
}
return settings.mqtt.enabled && isNetworkConnected() && !isMqttBlocked() &&
!mqttConfigureTask.scheduled() && isMqttConnected();
const bool hasOutput = activeSerial.load(std::memory_order_relaxed) ||
activeWebSerial.load(std::memory_order_relaxed);
const bool hasOutput =
activeSerial.load(std::memory_order_relaxed) ||
activeWebSerial.load(std::memory_order_relaxed);
if (prevSettings && Sensors::hasEnabledAndValid(*prevSettings)
&& (metadataChanged || !settings.mqtt.homeAssistantDiscovery)) {
deleteConnectionDynamicSensor(*prevSettings);
}
```
В многострочных условиях сохраняй принятую рядом расстановку `&&` и `||`:
в проекте встречаются оба варианта переноса. Группируй связанные условия
скобками и не меняй их порядок или приоритет ради выравнивания.
## Имена и структура файлов
+27 -72
View File
@@ -1,6 +1,6 @@
<div align="center">
[![GitHub version](https://img.shields.io/github/release/Laxilef/OTGateway.svg)](https://github.com/Laxilef/OTGateway/releases)
[![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)
@@ -20,7 +20,7 @@
- PID
- Equithermic curves - adjusts the temperature based on indoor and outdoor temperatures
- Hysteresis setting _(for accurate maintenance of room temperature)_
- Ability to connect [additional (external) sensors](https://github.com/Laxilef/OTGateway/wiki/Sensors#temperature-sensors): Dallas (1-wire), NTC 10k, Bluetooth (BLE). Makes it possible to monitor indoor and outdoor temperatures, temperatures on pipes/heat exchangers/etc.
- 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:
@@ -41,81 +41,36 @@
- [Home Assistant](https://www.home-assistant.io/) integration via MQTT. The ability to create any automation for the boiler!
## Documentation
All available information and instructions can be found in the wiki:
All available information and instructions can be found in the wiki: [English](https://github.com/Laxilef/OTGateway/wiki) · [Русский](https://github.com/Laxilef/OTGateway/wiki/Home.RU).
* **Installation**
* [First installation](https://github.com/Laxilef/OTGateway/wiki/Installation-and-upgrade#first-installation)
* [Web Flasher](https://github.com/Laxilef/OTGateway/wiki/Installation-and-upgrade#web-flasher)
* [ESP Flash Download Tool](https://github.com/Laxilef/OTGateway/wiki/Installation-and-upgrade#esp-flash-download-tool)
* [Build from source](https://github.com/Laxilef/OTGateway/wiki/Installation-and-upgrade#build-from-source)
* [Update and restore](https://github.com/Laxilef/OTGateway/wiki/Installation-and-upgrade#backup-update-and-restore)
* [Save the settings](https://github.com/Laxilef/OTGateway/wiki/Installation-and-upgrade#save-the-settings)
* [Update firmware and filesystem](https://github.com/Laxilef/OTGateway/wiki/Installation-and-upgrade#update-firmware-and-filesystem)
* [Restore the settings](https://github.com/Laxilef/OTGateway/wiki/Installation-and-upgrade#restore-the-settings)
* **Hardware**
* [Boilers](https://github.com/Laxilef/OTGateway/wiki/Boilers)
* [ESP32 boards](https://github.com/Laxilef/OTGateway/wiki/Boards)
* [Temperature sensors](https://github.com/Laxilef/OTGateway/wiki/Sensors#temperature-sensors)
* [OT adapters](https://github.com/Laxilef/OTGateway/wiki/OT-adapters)
* [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)
* **Configuration**
* [Heating and OpenTherm](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm)
* [Heating hysteresis](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#heating-hysteresis)
* [Equitherm](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#equitherm)
* [Curve parameters](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#curve-parameters)
* [Tune the curve](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#tune-the-curve)
* [PID](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#pid)
* [Tune PID using indoor temperature](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#tune-pid-using-indoor-temperature)
* [Using Equitherm with PID](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#using-equitherm-with-pid)
* [Protections and emergency mode](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#protections-and-emergency-mode)
* [Overheat protection](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#overheat-protection)
* [Freeze protection](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#freeze-protection)
* [Emergency mode](https://github.com/Laxilef/OTGateway/wiki/Heating-and-OpenTherm#emergency-mode)
* [Sensor setup](https://github.com/Laxilef/OTGateway/wiki/Sensors#connect-a-temperature-sensor)
* [Choose a purpose](https://github.com/Laxilef/OTGateway/wiki/Sensors#choose-a-purpose)
* [Supply a reading from another system](https://github.com/Laxilef/OTGateway/wiki/Sensors#supply-a-reading-from-another-system)
* **Integrations**
* [MQTT](https://github.com/Laxilef/OTGateway/wiki/MQTT)
* [Topic structure and access](https://github.com/Laxilef/OTGateway/wiki/MQTT#topic-structure-and-access)
* [State topics](https://github.com/Laxilef/OTGateway/wiki/MQTT#state-topics)
* [Settings](https://github.com/Laxilef/OTGateway/wiki/MQTT#settings)
* [Sensor topics](https://github.com/Laxilef/OTGateway/wiki/MQTT#sensor-topics)
* [Examples](https://github.com/Laxilef/OTGateway/wiki/MQTT#examples)
* [REST API](https://github.com/Laxilef/OTGateway/wiki/REST)
* [Endpoints](https://github.com/Laxilef/OTGateway/wiki/REST#endpoints)
* [Settings](https://github.com/Laxilef/OTGateway/wiki/REST#settings)
* [Network](https://github.com/Laxilef/OTGateway/wiki/REST#network)
* [Sensors](https://github.com/Laxilef/OTGateway/wiki/REST#sensors)
* [Examples](https://github.com/Laxilef/OTGateway/wiki/REST#examples)
* [Home Assistant](https://github.com/Laxilef/OTGateway/wiki/Home-Assistant)
* [Connection](https://github.com/Laxilef/OTGateway/wiki/Home-Assistant#connection)
* [Report a temperature sensor](https://github.com/Laxilef/OTGateway/wiki/Home-Assistant#report-a-temperature-sensor)
* [Report outdoor weather temperature](https://github.com/Laxilef/OTGateway/wiki/Home-Assistant#report-outdoor-weather-temperature)
* [DHW meter](https://github.com/Laxilef/OTGateway/wiki/Home-Assistant#dhw-meter)
* [HOMEd](https://github.com/Laxilef/OTGateway/wiki/HOMEd)
* [Connect](https://github.com/Laxilef/OTGateway/wiki/HOMEd#connect)
* [Heating and DHW control](https://github.com/Laxilef/OTGateway/wiki/HOMEd#heating-and-dhw-control)
* [Sensors](https://github.com/Laxilef/OTGateway/wiki/HOMEd#sensors)
* [Supply a temperature to OTGateway](https://github.com/Laxilef/OTGateway/wiki/HOMEd#supply-a-temperature-from-homed-to-otgateway)
* [Diagnostics](https://github.com/Laxilef/OTGateway/wiki/HOMEd#diagnostics)
* [Migrate an existing integration](https://github.com/Laxilef/OTGateway/wiki/HOMEd#migrate-an-existing-integration)
* **Other**
* [FAQ and troubleshooting](https://github.com/Laxilef/OTGateway/wiki/FAQ-%26-Troubleshooting)
* [Installation and connection](https://github.com/Laxilef/OTGateway/wiki/FAQ-%26-Troubleshooting#installation-and-connection)
* [Heating and hot water](https://github.com/Laxilef/OTGateway/wiki/FAQ-%26-Troubleshooting#heating-and-hot-water)
* [Sensors](https://github.com/Laxilef/OTGateway/wiki/FAQ-%26-Troubleshooting#sensors)
* [MQTT and Home Assistant](https://github.com/Laxilef/OTGateway/wiki/FAQ-%26-Troubleshooting#mqtt-and-home-assistant)
* [Logs and debug](https://github.com/Laxilef/OTGateway/wiki/FAQ-%26-Troubleshooting#logs-and-debug)
* [Core dump analysis](https://github.com/Laxilef/OTGateway/wiki/Core-dump-analysis)
* [Windows (PowerShell)](https://github.com/Laxilef/OTGateway/wiki/Core-dump-analysis#windows-powershell)
* [Linux (shell)](https://github.com/Laxilef/OTGateway/wiki/Core-dump-analysis#linux-shell)
* [What the report contains](https://github.com/Laxilef/OTGateway/wiki/Core-dump-analysis#what-the-report-contains)
* [Finding the likely cause](https://github.com/Laxilef/OTGateway/wiki/Core-dump-analysis#finding-the-likely-cause)
* [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 />
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
1 Designator Device Footprint Mid X Mid Y Ref X Ref Y Pad X Pad Y Pins Layer Rotation SMD Comment
2 PCB_B1 D2MG_PCB_B_WITHOUT_TERMINALS D2MG_PCB_B_WITHOUT_TERMINALS 51.475mm -42.746mm 35.285mm -13.632mm 36.555mm -22.776mm 16 T 0 No D2MG_PCB_B_WITHOUT_TERMINALS
3 C2 100nF C0805 7.778mm -43.871mm 7.778mm -43.871mm 6.778mm -43.871mm 2 T 0 Yes 100nF
4 U3 AMS1117-3.3 SOT-223-3_L6.4-W3.5-P2.30-LS7.0-BR 5.873mm -49.078mm 5.873mm -49.078mm 8.843mm -51.378mm 4 T 0 Yes AMS1117-3.3
5 R2 0805W8F4701T5E R0805 10.668mm -63.881mm 10.668mm -63.881mm 10.668mm -64.881mm 2 T 90 Yes 4.7kΩ
6 R3 0805W8F3300T5E R0805 45.679mm -68.448mm 45.679mm -68.448mm 45.679mm -69.448mm 2 T 90 Yes 330Ω
7 R4 0805W8F2200T5E R0805 54.188mm -67.686mm 54.188mm -67.686mm 54.188mm -68.686mm 2 T 90 Yes 220Ω
8 R5 0805W8F1000T5E_C17408 R0805 56.855mm -67.686mm 56.855mm -67.686mm 56.855mm -66.686mm 2 T 270 Yes 100Ω
9 R6 0805W8F3300T5E R0805 46.822mm -59.558mm 46.822mm -59.558mm 45.822mm -59.558mm 2 T 0 Yes 330Ω
10 R7 0805W8F1501T5E R0805 56.347mm -59.558mm 56.347mm -59.558mm 57.347mm -59.558mm 2 T 180 Yes 1.5kΩ
11 R10 0805W8F4701T5E R0805 14.605mm -63.881mm 14.605mm -63.881mm 14.605mm -62.881mm 2 T 270 Yes 4.7kΩ
12 U2 HLK-PM01 PWRM-TH_HLK-PM01 22.383mm -42.728mm 22.383mm -42.728mm 24.883mm -28.028mm 4 T 270 No HLK-PM01
13 Q1 BC858A_C8583 SOT-23-3_L2.9-W1.6-P1.90-LS2.8-BR 49.743mm -68.067mm 49.743mm -68.067mm 48.508mm -67.117mm 3 T 180 Yes BC858A
14 ZD1 BZV55C4V7 SOD-80_L3.5-W1.5-RD 55.534mm -62.987mm 55.534mm -62.987mm 53.769mm -62.987mm 2 T 0 Yes BZV55C4V7
15 ZD2 BZV55C15 SOD-80_L3.5-W1.5-RD 47.457mm -64.572mm 47.457mm -64.572mm 45.692mm -64.572mm 2 T 0 Yes BZV55C15
16 ZD3 BZV55C4V3 SOD-80_L3.5-W1.5-RD 47.457mm -61.844mm 47.457mm -61.844mm 45.692mm -61.844mm 2 T 0 Yes BZV55C4V3
17 C4 100nF C0805 62.103mm -19.558mm 62.103mm -19.558mm 61.103mm -19.558mm 2 T 0 Yes 100nF
18 C5 GRM21BR61C106KE15L C0805 64.868mm -45.759mm 64.868mm -45.759mm 64.868mm -46.759mm 2 T 90 Yes 10uF
19 C6 100nF C0805 62.481mm -45.763mm 62.481mm -45.763mm 62.481mm -44.763mm 2 T 270 Yes 100nF
20 R11 0805W8F5101T5E R0805 57.887mm -19.558mm 57.887mm -19.558mm 58.887mm -19.558mm 2 T 180 Yes 5.1kΩ
21 R12 0805W8F5101T5E R0805 39.954mm -16.612mm 39.954mm -16.612mm 39.954mm -15.612mm 2 T 270 Yes 5.1kΩ
22 R13 0805W8F5101T5E R0805 51.943mm -16.637mm 51.943mm -16.637mm 51.943mm -17.637mm 2 T 90 Yes 5.1kΩ
23 SW1 TS-1088R-02026 SW-SMD_L3.9-W3.0-P4.45 59.944mm -16.383mm 59.944mm -16.383mm 57.759mm -16.383mm 2 T 0 Yes TS-1088R-02026
24 R1 0805W8F1000T5E_C17408 R0805 61.562mm -51.237mm 61.562mm -51.237mm 61.562mm -50.237mm 2 T 270 Yes 100Ω
25 R8 0805W8F1000T5E_C17408 R0805 52.342mm -51.237mm 52.342mm -51.237mm 52.342mm -50.237mm 2 T 270 Yes 100Ω
26 R9 0805W8F1000T5E_C17408 R0805 41.25mm -51.237mm 41.25mm -51.237mm 41.25mm -50.237mm 2 T 270 Yes 100Ω
27 PCB_A1 D2MG_PCB_A_WITHOUT_TERMINALS D2MG_PCB_A_WITHOUT_TERMINALS 16.458mm -42.746mm 16.458mm -43.406mm 1.538mm -22.776mm 16 T 0 No D2MG_PCB_A_WITHOUT_TERMINALS
28 F1 S6125-M2-0.5A FUSE-SMD_L6.1-W2.5 14.986mm -17.78mm 14.986mm -17.78mm 14.986mm -15.28mm 2 T 270 Yes S6125-M2-0.5A
29 VAR1 VDR-10D391K RES-TH_L12.5-W5.1-P7.50-D1.2-S2.20 20.955mm -18.796mm 20.955mm -18.796mm 22.055mm -15.047mm 2 T 270 No VDR-10D391K
30 D5 BAV99S,115 SOT-363_L2.0-W1.3-P0.65-LS2.1-TL 51.613mm -58.674mm 51.613mm -58.674mm 50.963mm -59.594mm 6 T 90 Yes BAV99S,115
31 U5 PC817 SMD-4(6.5X4.58) 61.681mm -64.511mm 61.681mm -64.511mm 60.411mm -69.511mm 4 T 90 Yes PC817
32 U4 PC817 SMD-4(6.5X4.58) 41.488mm -64.511mm 41.488mm -64.511mm 42.758mm -59.511mm 4 T 270 Yes PC817
33 U10 ESP32-S3-WROOM-1U-N4 WIRELM-SMD_ESP32-S3-WROOM-1U 51.943mm -31.75mm 51.943mm -31.75mm 60.693mm -40.645mm 49 T 180 Yes ESP32-S3-WROOM-1U-N4
34 U1 WEMOS_D1_MINI DIP-16_WEMOS_D1_MINI_PRO4 51.943mm -31.623mm 51.943mm -31.623mm 40.513mm -40.513mm 16 T 180 No WEMOS_D1_MINI
35 R14 0805W8F2200T5E R0805 24.952mm -63.881mm 24.952mm -63.881mm 24.952mm -62.881mm 2 T 270 Yes 220Ω
36 R15 0805W8F2200T5E R0805 20.955mm -63.881mm 20.955mm -63.881mm 20.955mm -62.881mm 2 T 270 Yes 220Ω
37 R16 0805W8F5101T5E R0805 18.542mm -63.881mm 18.542mm -63.881mm 18.542mm -62.881mm 2 T 270 Yes 5.1kΩ
38 SW2 TS-1088R-02026 SW-SMD_L3.9-W3.0-P4.45 37.211mm -28.575mm 37.211mm -28.575mm 37.211mm -26.39mm 2 T 270 Yes TS-1088R-02026
39 U7 XY126V-5.0-3P KLS2-300-5.00-03P-2S 23.994mm -4.267mm 28.994mm -4.267mm 28.994mm -4.267mm 3 T 180 No XY126V-5.0-3P
40 U6 XY126V-5.0-3P KLS2-300-5.00-03P-2S 8.97mm -4.267mm 13.97mm -4.267mm 13.97mm -4.267mm 3 T 180 No XY126V-5.0-3P
41 U9 XY126V-5.0-3P KLS2-300-5.00-03P-2S 8.988mm -81.242mm 3.988mm -81.242mm 3.988mm -81.242mm 3 T 0 No XY126V-5.0-3P
42 U8 XY126V-5.0-3P KLS2-300-5.00-03P-2S 23.986mm -81.242mm 18.987mm -81.242mm 18.987mm -81.242mm 3 T 0 No XY126V-5.0-3P
43 U11 TYPE-C 14PLC-H10.0 USB-C-TH_SHOUHAN_TYPE-C-14PLC-H10.0 45.949mm -16.815mm 45.949mm -16.815mm 47.948mm -14.885mm 18 T 0 No TYPE-C 14PLC-H10.0
44 C1 100uF CAP-SMD_BD6.3-L6.6-W6.6-LS7.2-FD 6.127mm -38.537mm 6.127mm -38.537mm 8.797mm -38.537mm 2 T 180 Yes 100uF
45 C3 22uF CAP-SMD_BD5.0-L5.3-W5.3-LS6.3-FD 6.934mm -56.007mm 6.934mm -56.007mm 9.08mm -56.007mm 2 T 180 Yes 22uF
46 F2 MF-MSMF110/16-2 F1812 5.207mm -30.226mm 5.207mm -30.226mm 7.06mm -30.226mm 2 T 180 Yes MF-MSMF110/16-2
47 L1 SZYY0805YG LED0805-R-RD_GREEN 64.19mm -51.174mm 64.19mm -51.174mm 64.19mm -50.123mm 2 T 90 Yes SZYY0805YG
48 L2 SZYY0805YG LED0805-R-RD_GREEN 43.87mm -51.174mm 43.87mm -51.174mm 43.87mm -50.123mm 2 T 90 Yes SZYY0805YG
49 L3 SZYY0805YG LED0805-R-RD_GREEN 54.97mm -51.174mm 54.97mm -51.174mm 54.97mm -50.123mm 2 T 90 Yes SZYY0805YG
+18957
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
BIN
View File
Binary file not shown.
+19
View File
@@ -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 }}"
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

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 242 KiB

Binary file not shown.

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

+21 -31
View File
@@ -188,29 +188,25 @@ public:
return id >= (uint8_t) ValueType::TEMPERATURE && id <= (uint8_t) ValueType::RSSI;
}
static bool isEqualAddress(const uint8_t* addr1, const uint8_t* addr2, const uint8_t length = 8) {
return memcmp(addr1, addr2, length) == 0;
}
static bool isDifferent(const Settings& previous, const Settings& current) {
return previous.enabled != current.enabled ||
strcmp(previous.name, current.name) != 0 ||
strcmp(previous.slug, current.slug) != 0 ||
previous.purpose != current.purpose ||
previous.type != current.type ||
previous.gpio != current.gpio ||
!isEqualAddress(previous.address, current.address) ||
isFloatDifferent(previous.offset, current.offset, 0.0001f) ||
isFloatDifferent(previous.factor, current.factor, 0.0001f) ||
previous.filtering != current.filtering ||
isFloatDifferent(previous.filteringFactor, current.filteringFactor, 0.0001f);
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;
return sensor.enabled
&& sensor.slug[0] != '\0'
&& sensor.type != Type::NOT_CONFIGURED
&& sensor.purpose != Purpose::NOT_CONFIGURED;
}
static bool hasEnabledAndValid(const uint8_t id) {
@@ -557,7 +553,7 @@ public:
return false;
}
if (isEqualAddress(settings[sensorId].address, address)) {
if (memcmp(settings[sensorId].address, address, sizeof(Settings::address)) == 0) {
return true;
}
@@ -613,24 +609,18 @@ public:
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)) {
const float reading = rSensor.values[valueId];
sum += rSensor.values[valueId];
amount++;
}
}
// Opposite-sign readings can overflow when subtracted.
if ((value < 0.0f) != (reading < 0.0f)) {
value -= value / amount;
value += reading / amount;
} else {
value += (reading - value) / amount;
}
}
}
value = amount == 1 ? sum : (sum / amount);
} else if (avgType == AverageType::MINIMUM) {
for (uint8_t id = 0; id <= getMaxSensorId(); id++) {
+1 -19
View File
@@ -18,7 +18,6 @@ struct NetworkSettings {
char dns[16] = "192.168.0.1";
} staticConfig;
struct {
struct {
char ssid[33] = DEFAULT_AP_SSID;
char password[65] = DEFAULT_AP_PASSWORD;
@@ -30,22 +29,6 @@ struct NetworkSettings {
char password[65] = DEFAULT_STA_PASSWORD;
uint8_t channel = 0;
} sta;
} wifi;
struct {
EthernetType type = EthernetType::W5500;
struct {
uint8_t clk = DEFAULT_ETH_CLK_GPIO;
uint8_t mosi = DEFAULT_ETH_MOSI_GPIO;
uint8_t miso = DEFAULT_ETH_MISO_GPIO;
uint8_t cs = DEFAULT_ETH_CS_GPIO;
uint8_t irq = DEFAULT_ETH_IRQ_GPIO;
uint8_t rst = DEFAULT_ETH_RST_GPIO;
} w5500;
} ethernet;
NetworkMode type = NetworkMode::STA;
};
struct SystemSettings {
@@ -118,8 +101,7 @@ struct MqttSettings {
char password[33] = DEFAULT_MQTT_PASSWORD;
char prefix[33] = DEFAULT_MQTT_PREFIX;
unsigned short interval = 5;
bool homeAssistantDiscovery = DEFAULT_HA_DISCOVERY_ENABLED;
char homeAssistantDiscoveryPrefix[33] = DEFAULT_HA_DISCOVERY_PREFIX;
bool homeAssistantDiscovery = true;
};
struct EmergencySettings {
+1 -8
View File
@@ -124,7 +124,7 @@ std::string mqttTopic(const Parts&... parts) {
// Home Assistant discovery
extern HA::Discovery haDiscovery;
bool publishHaEntity(HaEntity entityId, bool remove);
void publishHaEntity(HaEntity entityId, bool remove);
void publishDynamicSensor(
const Sensors::Settings& sensor,
Sensors::ValueType valueType = Sensors::ValueType::PRIMARY, bool enabledByDefault = true
@@ -144,13 +144,6 @@ void onNetworkEvent(NetworkEventCallback callback);
void onNetworkStateChange(NetworkStateCallback callback);
NetworkState getNetworkState(NetworkMode mode = NetworkMode::STA);
NetworkMode getNetworkMode();
const char* getNetworkConnectionType();
IPAddress getNetworkIp();
IPAddress getNetworkSubnet();
IPAddress getNetworkGateway();
IPAddress getNetworkDns();
String getNetworkMac();
bool isEthernetConfigured(const NetworkSettings& config = networkSettings);
bool isNetworkInterfaceStarted(NetworkMode mode);
// Last state published by the system worker, including during event callbacks.
bool isNetworkConnected();
-36
View File
@@ -63,10 +63,6 @@
#define USE_BLE false
#endif
#ifndef USE_ETHERNET
#define USE_ETHERNET false
#endif
#ifndef DEFAULT_HOSTNAME
#define DEFAULT_HOSTNAME ""
#endif
@@ -95,30 +91,6 @@
#define DEFAULT_STATUS_LED_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef DEFAULT_ETH_CLK_GPIO
#define DEFAULT_ETH_CLK_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef DEFAULT_ETH_MOSI_GPIO
#define DEFAULT_ETH_MOSI_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef DEFAULT_ETH_MISO_GPIO
#define DEFAULT_ETH_MISO_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef DEFAULT_ETH_CS_GPIO
#define DEFAULT_ETH_CS_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef DEFAULT_ETH_IRQ_GPIO
#define DEFAULT_ETH_IRQ_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef DEFAULT_ETH_RST_GPIO
#define DEFAULT_ETH_RST_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef DEFAULT_PORTAL_LOGIN
#define DEFAULT_PORTAL_LOGIN ""
#endif
@@ -151,14 +123,6 @@
#define DEFAULT_MQTT_PREFIX ""
#endif
#ifndef DEFAULT_HA_DISCOVERY_ENABLED
#define DEFAULT_HA_DISCOVERY_ENABLED false
#endif
#ifndef DEFAULT_HA_DISCOVERY_PREFIX
#define DEFAULT_HA_DISCOVERY_PREFIX "homeassistant"
#endif
#ifndef DEFAULT_OT_IN_GPIO
#define DEFAULT_OT_IN_GPIO GPIO_IS_NOT_CONFIGURED
#endif
-12
View File
@@ -51,17 +51,13 @@ inline const char S_CHANNEL[] = "channel";
inline const char S_CH2_ALWAYS_ENABLED[] = "ch2_always_enabled";
inline const char S_CH2_DISABLING_ACTION[] = "ch2_disabling_action";
inline const char S_CHIP[] = "chip";
inline const char S_CLK[] = "clk";
inline const char S_CODE[] = "code";
inline const char S_COMMIT[] = "commit";
inline const char S_CONFIGURED[] = "configured";
inline const char S_CONNECTED[] = "connected";
inline const char S_CONNECTION_TYPE[] = "connection_type";
inline const char S_COOLING[] = "cooling";
inline const char S_COOLING_SUPPORT[] = "cooling_support";
inline const char S_CORE[] = "core";
inline const char S_CORES[] = "cores";
inline const char S_CS[] = "cs";
inline const char S_CURRENT_TEMP[] = "current_temp";
inline const char S_DATE[] = "date";
inline const char S_DEADBAND[] = "deadband";
@@ -80,13 +76,11 @@ inline const char S_EMERGENCY[] = "emergency";
inline const char S_ENABLED[] = "enabled";
inline const char S_ENV[] = "env";
inline const char S_EQUITHERM[] = "equitherm";
inline const char S_ETHERNET[] = "ethernet";
inline const char S_EXPONENT[] = "exponent";
inline const char S_EXTERNAL_PUMP[] = "ext_pump";
inline const char S_FACTOR[] = "factor";
inline const char S_FALSE[] = "false";
inline const char S_FAULT[] = "fault";
inline const char S_FEATURES[] = "features";
inline const char S_FREEZE_PROTECTION[] = "freeze_protection";
inline const char S_FREEZING[] = "freezing";
inline const char S_FILTERING[] = "filtering";
@@ -107,7 +101,6 @@ inline const char S_HEATING_STATE_TO_SUMMER_WINTER_MODE[] = "heating_state_to_s
inline const char S_HIDDEN[] = "hidden";
inline const char S_HIGH_TEMP[] = "high_temp";
inline const char S_HOME_ASSISTANT_DISCOVERY[] = "ha_discovery";
inline const char S_HOME_ASSISTANT_DISCOVERY_PREFIX[] = "ha_discovery_prefix";
inline const char S_HOSTNAME[] = "hostname";
inline const char S_HUMIDITY[] = "humidity";
inline const char S_HYSTERESIS[] = "hysteresis";
@@ -122,7 +115,6 @@ inline const char S_INPUT[] = "input";
inline const char S_INTERVAL[] = "interval";
inline const char S_INVERT_STATE[] = "invert_state";
inline const char S_IP[] = "ip";
inline const char S_IRQ[] = "irq";
inline const char S_I_FACTOR[] = "i_factor";
inline const char S_I_MULTIPLIER[] = "i_multiplier";
inline const char S_LOGIN[] = "login";
@@ -143,10 +135,8 @@ inline const char S_MIN_FREE[] = "min_free";
inline const char S_MIN_MAX_FREE_BLOCK[] = "min_max_free_block";
inline const char S_MIN_POWER[] = "min_power";
inline const char S_MIN_TEMP[] = "min_temp";
inline const char S_MISO[] = "miso";
inline const char S_MODEL[] = "model";
inline const char S_MODULATION[] = "modulation";
inline const char S_MOSI[] = "mosi";
inline const char S_MQTT[] = "mqtt";
inline const char S_NAME[] = "name";
inline const char S_SLUG[] = "slug";
@@ -184,7 +174,6 @@ inline const char S_RESTART[] = "restart";
inline const char S_RETURN_TEMP[] = "return_temp";
inline const char S_REV[] = "rev";
inline const char S_RSSI[] = "rssi";
inline const char S_RST[] = "rst";
inline const char S_RX_LED_GPIO[] = "rx_led_gpio";
inline const char S_SDK[] = "sdk";
inline const char S_SENSORS[] = "sensors";
@@ -229,4 +218,3 @@ inline const char S_USER[] = "user";
inline const char S_VALUE[] = "value";
inline const char S_VERSION[] = "version";
inline const char S_WEBSERIAL[] = "web_serial";
inline const char S_WIFI[] = "wifi";
-18
View File
@@ -14,17 +14,6 @@ enum class ChannelDisablingAction : uint8_t {
OFF_AND_ZERO_SETPOINT = 2
};
enum class PumpStartReason {
NONE,
HEATING,
ANTISTUCK
};
enum class EthernetType : uint8_t {
NONE = 0,
W5500 = 1
};
struct SettingResult {
bool changed = false;
bool accepted = false;
@@ -88,13 +77,6 @@ enum class NetworkEvent : uint8_t {
STA_GOT_IP,
STA_LOST_IP,
STA_GOT_IP6,
ETH_STARTED,
ETH_STOPPED,
ETH_CONNECTED,
ETH_DISCONNECTED,
ETH_GOT_IP,
ETH_LOST_IP,
ETH_GOT_IP6,
AP_STARTED,
AP_STOPPED,
AP_CLIENT_CONNECTED,
+1 -1
View File
@@ -5,7 +5,7 @@
},
"devDependencies": {
"cssnano": "^9.3.2",
"cssnano-preset-advanced": "^10.0.0",
"cssnano-preset-advanced": "^9.2.2",
"gulp": "^5.0.0",
"gulp-concat": "^2.6.1",
"gulp-gzip": "^1.4.2",
+3 -29
View File
@@ -10,10 +10,10 @@ 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
https://github.com/Laxilef/MycilaHADiscovery#feature/discovery-publication-results
https://github.com/mathieucarbou/MycilaHADiscovery/
gyverlibs/FileData@^1.0.3
gyverlibs/GyverPID@^3.3.2
gyverlibs/GyverBlinker@^1.1.1
@@ -44,8 +44,6 @@ build_flags = ;-mtext-section-literals
-D DEFAULT_MQTT_USER='"${secrets.mqtt_user}"'
-D DEFAULT_MQTT_PASSWORD='"${secrets.mqtt_password}"'
-D DEFAULT_MQTT_PREFIX='"${secrets.mqtt_prefix}"'
-D DEFAULT_HA_DISCOVERY_ENABLED=${secrets.ha_discovery_enabled}
-D DEFAULT_HA_DISCOVERY_PREFIX='"${secrets.ha_discovery_prefix}"'
upload_speed = 921600
monitor_speed = 115200
;monitor_filters = direct
@@ -57,6 +55,7 @@ check_flags = ;pvs-studio: --analysis-mode=4 --exclude-path=./.pio/l
; Defaults
[esp32_defaults]
;platform = https://github.com/pioarduino/platform-espressif32.git#prep_IDF6
platform = https://github.com/pioarduino/platform-espressif32/releases/download/61.04.00/platform-espressif32.zip
platform_packages = ${env.platform_packages}
board_build.partitions = esp32_partitions.csv
@@ -153,7 +152,6 @@ check_flags = ${env.check_flags}
; Boards
[env:s2_mini]
custom_title = Wemos S2 mini (ESP32 S2)
extends = esp32_defaults
board = lolin_s2_mini
extra_scripts = ${esp32_defaults.extra_scripts}
@@ -172,13 +170,10 @@ build_flags = ${esp32_defaults.build_flags}
-D DEFAULT_OT_RX_LED_GPIO=12
[env:s3_mini]
custom_title = Wemos S3 mini (ESP32 S3)
extends = esp32_defaults
board = lolin_s3_mini
custom_sdkconfig = ${esp32_defaults.custom_sdkconfig}
'# CONFIG_TINYUSB_ENABLED is not set'
CONFIG_ETH_USE_SPI_ETHERNET=y
CONFIG_ESP_NETIF_SET_DNS_PER_DEFAULT_NETIF=y
lib_deps = ${esp32_defaults.lib_deps}
${esp32_defaults.nimble_lib}
build_flags = ${esp32_defaults.build_flags}
@@ -186,7 +181,6 @@ build_flags = ${esp32_defaults.build_flags}
-D ARDUINO_USB_CDC_ON_BOOT=1
-D MYNEWT_VAL_BLE_EXT_ADV=1
-D USE_BLE=1
-D USE_ETHERNET=1
-D DEFAULT_OT_IN_GPIO=35
-D DEFAULT_OT_OUT_GPIO=36
-D DEFAULT_SENSOR_OUTDOOR_GPIO=13
@@ -203,7 +197,6 @@ build_flags = ${esp32_defaults.build_flags}
; '# CONFIG_SPIRAM is not set'
[env:c3_mini]
custom_title = Wemos C3 mini (ESP32 C3)
extends = esp32_defaults
board = lolin_c3_mini
lib_deps = ${esp32_defaults.lib_deps}
@@ -225,7 +218,6 @@ custom_sdkconfig = ${esp32_defaults.custom_sdkconfig}
CONFIG_COMPILER_SAVE_RESTORE_LIBCALLS=y
[env:nodemcu_32]
custom_title = NodeMCU (ESP32)
extends = esp32_defaults
board = nodemcu-32s
lib_deps = ${esp32_defaults.lib_deps}
@@ -240,12 +232,10 @@ build_flags = ${esp32_defaults.build_flags}
-D DEFAULT_OT_RX_LED_GPIO=19
[env:nodemcu_32_160mhz]
custom_title = NodeMCU (ESP32, 160 mhz)
extends = env:nodemcu_32
board_build.f_cpu = 160000000L ; set frequency to 160MHz
[env:d1_mini32]
custom_title = Wemos D1 mini32 (ESP32)
extends = esp32_defaults
board = wemos_d1_mini32
lib_deps = ${esp32_defaults.lib_deps}
@@ -260,7 +250,6 @@ build_flags = ${esp32_defaults.build_flags}
-D DEFAULT_OT_RX_LED_GPIO=19
[env:esp32_c6]
custom_title = ESP32 C6
extends = esp32_defaults
board = esp32-c6-devkitc-1
lib_deps = ${esp32_defaults.lib_deps}
@@ -301,22 +290,7 @@ custom_sdkconfig = ${esp32_defaults.custom_sdkconfig}
'# CONFIG_COMPILER_CXX_GLIBCXX_CONSTEXPR_COLD is not set'
CONFIG_COMPILER_CXX_GLIBCXX_CONSTEXPR_NO_CHANGE=y
; W5500 support uses a separate build to fit the existing OTA slot.
[env:esp32_c6_ethernet]
custom_title = ESP32 C6 (Ethernet)
extends = env:esp32_c6
lib_deps = ${esp32_defaults.lib_deps}
build_unflags = ${env:esp32_c6.build_unflags}
-DUSE_BLE
build_flags = ${env:esp32_c6.build_flags}
-D USE_ETHERNET=1
custom_sdkconfig = ${env:esp32_c6.custom_sdkconfig}
'# CONFIG_BT_ENABLED is not set'
CONFIG_ETH_USE_SPI_ETHERNET=y
CONFIG_ESP_NETIF_SET_DNS_PER_DEFAULT_NETIF=y
[env:otthing]
custom_title = OT Thing board (ESP32 C3)
extends = esp32_defaults
board = lolin_c3_mini
lib_deps = ${esp32_defaults.lib_deps}
-2
View File
@@ -22,5 +22,3 @@ mqtt_port = 1883
mqtt_user =
mqtt_password =
mqtt_prefix =
ha_discovery_enabled = true
ha_discovery_prefix = homeassistant
+50 -179
View File
@@ -5,7 +5,6 @@
#include <FileData.h>
#include <LittleFS.h>
#include <cmath>
#include <cstring>
#include <string>
#include <string_view>
@@ -165,7 +164,6 @@ void saveSettingsNow() {
// Initialization
static bool loadNetworkSettings() {
bool loaded = false;
fsNetworkSettings.addWithoutWipe(true);
switch (fsNetworkSettings.read()) {
case FD_FS_ERR:
@@ -343,26 +341,13 @@ JsonVariant toJson(const NetworkSettings& src, JsonVariant dst) {
dst[S_STATIC_CONFIG][S_SUBNET] = src.staticConfig.subnet;
dst[S_STATIC_CONFIG][S_DNS] = src.staticConfig.dns;
auto wifi = dst[S_WIFI].to<JsonObject>();
wifi[S_AP][S_SSID] = src.wifi.ap.ssid;
wifi[S_AP][S_PASSWORD] = src.wifi.ap.password;
wifi[S_AP][S_CHANNEL] = src.wifi.ap.channel;
dst[S_AP][S_SSID] = src.ap.ssid;
dst[S_AP][S_PASSWORD] = src.ap.password;
dst[S_AP][S_CHANNEL] = src.ap.channel;
wifi[S_STA][S_SSID] = src.wifi.sta.ssid;
wifi[S_STA][S_PASSWORD] = src.wifi.sta.password;
wifi[S_STA][S_CHANNEL] = src.wifi.sta.channel;
#if USE_ETHERNET
auto gpio = dst[S_ETHERNET][S_GPIO].to<JsonObject>();
gpio[S_CLK] = src.ethernet.w5500.clk;
gpio[S_MOSI] = src.ethernet.w5500.mosi;
gpio[S_MISO] = src.ethernet.w5500.miso;
gpio[S_CS] = src.ethernet.w5500.cs;
gpio[S_IRQ] = src.ethernet.w5500.irq;
gpio[S_RST] = src.ethernet.w5500.rst;
#endif
dst[S_TYPE] = static_cast<uint8_t>(src.type);
dst[S_STA][S_SSID] = src.sta.ssid;
dst[S_STA][S_PASSWORD] = src.sta.password;
dst[S_STA][S_CHANNEL] = src.sta.channel;
return dst;
}
@@ -374,7 +359,6 @@ SettingResult fromJson(JsonVariantConst src, NetworkSettings& dst) {
if (src[S_HOSTNAME].is<JsonString>()) {
const JsonString value = src[S_HOSTNAME].as<JsonString>();
if (strlen(value.c_str()) == value.size()) {
if (value.size() < sizeof(dst.hostname) && isHostnameValid(value.c_str())) {
result.accepted = true;
if (strcmp(value.c_str(), dst.hostname) != 0) {
@@ -383,7 +367,6 @@ SettingResult fromJson(JsonVariantConst src, NetworkSettings& dst) {
}
}
}
}
// use dhcp
if (src[S_USE_DHCP].is<bool>()) {
@@ -401,7 +384,6 @@ SettingResult fromJson(JsonVariantConst src, NetworkSettings& dst) {
if (src[S_STATIC_CONFIG][S_IP].is<JsonString>()) {
const JsonString value = src[S_STATIC_CONFIG][S_IP].as<JsonString>();
if (strlen(value.c_str()) == value.size()) {
if (value.size() < sizeof(dst.staticConfig.ip)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.staticConfig.ip) != 0) {
@@ -410,12 +392,10 @@ SettingResult fromJson(JsonVariantConst src, NetworkSettings& dst) {
}
}
}
}
if (src[S_STATIC_CONFIG][S_GATEWAY].is<JsonString>()) {
const JsonString value = src[S_STATIC_CONFIG][S_GATEWAY].as<JsonString>();
if (strlen(value.c_str()) == value.size()) {
if (value.size() < sizeof(dst.staticConfig.gateway)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.staticConfig.gateway) != 0) {
@@ -424,12 +404,10 @@ SettingResult fromJson(JsonVariantConst src, NetworkSettings& dst) {
}
}
}
}
if (src[S_STATIC_CONFIG][S_SUBNET].is<JsonString>()) {
const JsonString value = src[S_STATIC_CONFIG][S_SUBNET].as<JsonString>();
if (strlen(value.c_str()) == value.size()) {
if (value.size() < sizeof(dst.staticConfig.subnet)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.staticConfig.subnet) != 0) {
@@ -438,12 +416,10 @@ SettingResult fromJson(JsonVariantConst src, NetworkSettings& dst) {
}
}
}
}
if (src[S_STATIC_CONFIG][S_DNS].is<JsonString>()) {
const JsonString value = src[S_STATIC_CONFIG][S_DNS].as<JsonString>();
if (strlen(value.c_str()) == value.size()) {
if (value.size() < sizeof(dst.staticConfig.dns)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.staticConfig.dns) != 0) {
@@ -452,50 +428,41 @@ SettingResult fromJson(JsonVariantConst src, NetworkSettings& dst) {
}
}
}
}
const auto wifi = src[S_WIFI];
const auto ap = wifi[S_AP];
const auto sta = wifi[S_STA];
// ap
if (ap[S_SSID].is<JsonString>()) {
const JsonString value = ap[S_SSID].as<JsonString>();
if (src[S_AP][S_SSID].is<JsonString>()) {
const JsonString value = src[S_AP][S_SSID].as<JsonString>();
if (strlen(value.c_str()) == value.size()) {
if (value.size() && value.size() < sizeof(dst.wifi.ap.ssid)) {
if (value.size() && value.size() < sizeof(dst.ap.ssid)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.wifi.ap.ssid) != 0) {
strcpy(dst.wifi.ap.ssid, value.c_str());
if (strcmp(value.c_str(), dst.ap.ssid) != 0) {
strcpy(dst.ap.ssid, value.c_str());
result.changed = true;
}
}
}
}
if (ap[S_PASSWORD].is<JsonString>()) {
const JsonString value = ap[S_PASSWORD].as<JsonString>();
if (src[S_AP][S_PASSWORD].is<JsonString>()) {
const JsonString value = src[S_AP][S_PASSWORD].as<JsonString>();
if (strlen(value.c_str()) == value.size()) {
if (value.size() && value.size() < sizeof(dst.wifi.ap.password)) {
if (value.size() && value.size() < sizeof(dst.ap.password)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.wifi.ap.password) != 0) {
strcpy(dst.wifi.ap.password, value.c_str());
if (strcmp(value.c_str(), dst.ap.password) != 0) {
strcpy(dst.ap.password, value.c_str());
result.changed = true;
}
}
}
}
if (ap[S_CHANNEL].is<uint8_t>()) {
const auto value = ap[S_CHANNEL].as<uint8_t>();
if (src[S_AP][S_CHANNEL].is<uint8_t>()) {
const auto value = src[S_AP][S_CHANNEL].as<uint8_t>();
if (value < 12) {
result.accepted = true;
if (value != dst.wifi.ap.channel) {
dst.wifi.ap.channel = value;
if (value != dst.ap.channel) {
dst.ap.channel = value;
result.changed = true;
}
}
@@ -503,92 +470,38 @@ SettingResult fromJson(JsonVariantConst src, NetworkSettings& dst) {
// sta
if (sta[S_SSID].is<JsonString>()) {
const JsonString value = sta[S_SSID].as<JsonString>();
if (src[S_STA][S_SSID].is<JsonString>()) {
const JsonString value = src[S_STA][S_SSID].as<JsonString>();
if (strlen(value.c_str()) == value.size()) {
if (value.size() && value.size() < sizeof(dst.wifi.sta.ssid)) {
if (value.size() && value.size() < sizeof(dst.sta.ssid)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.wifi.sta.ssid) != 0) {
strcpy(dst.wifi.sta.ssid, value.c_str());
if (strcmp(value.c_str(), dst.sta.ssid) != 0) {
strcpy(dst.sta.ssid, value.c_str());
result.changed = true;
}
}
}
}
if (sta[S_PASSWORD].is<JsonString>()) {
const JsonString value = sta[S_PASSWORD].as<JsonString>();
if (src[S_STA][S_PASSWORD].is<JsonString>()) {
const JsonString value = src[S_STA][S_PASSWORD].as<JsonString>();
if (strlen(value.c_str()) == value.size()) {
if (value.size() < sizeof(dst.wifi.sta.password)) {
if (value.size() < sizeof(dst.sta.password)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.wifi.sta.password) != 0) {
strcpy(dst.wifi.sta.password, value.c_str());
if (strcmp(value.c_str(), dst.sta.password) != 0) {
strcpy(dst.sta.password, value.c_str());
result.changed = true;
}
}
}
}
if (sta[S_CHANNEL].is<uint8_t>()) {
const auto value = sta[S_CHANNEL].as<uint8_t>();
if (src[S_STA][S_CHANNEL].is<uint8_t>()) {
const auto value = src[S_STA][S_CHANNEL].as<uint8_t>();
if (value < 12) {
result.accepted = true;
if (value != dst.wifi.sta.channel) {
dst.wifi.sta.channel = value;
result.changed = true;
}
}
}
#if USE_ETHERNET
// Ethernet GPIOs use the same strict numeric contract as the other GPIO settings.
const auto ethernet = src[S_ETHERNET];
const auto parseGpio = [&result](JsonVariantConst gpio, uint8_t& target, bool output) {
uint8_t value;
if (gpio.is<JsonString>() && gpio.as<JsonString>().size() == 0) {
value = GPIO_IS_NOT_CONFIGURED;
} else if (gpio.is<uint8_t>()) {
value = gpio.as<uint8_t>();
} else {
return;
}
if (value != GPIO_IS_NOT_CONFIGURED && !(output ? GPIO_IS_VALID_OUTPUT(value) : GPIO_IS_VALID_INPUT(value))) {
return;
}
result.accepted = true;
if (value != target) {
target = value;
result.changed = true;
}
};
const auto gpio = ethernet[S_GPIO];
parseGpio(gpio[S_CLK], dst.ethernet.w5500.clk, true);
parseGpio(gpio[S_MOSI], dst.ethernet.w5500.mosi, true);
parseGpio(gpio[S_MISO], dst.ethernet.w5500.miso, false);
parseGpio(gpio[S_CS], dst.ethernet.w5500.cs, true);
parseGpio(gpio[S_IRQ], dst.ethernet.w5500.irq, false);
parseGpio(gpio[S_RST], dst.ethernet.w5500.rst, true);
#endif
if (src[S_TYPE].is<uint8_t>()) {
const auto value = static_cast<NetworkMode>(src[S_TYPE].as<uint8_t>());
if (value == NetworkMode::STA
#if USE_ETHERNET
|| value == NetworkMode::ETH
#endif
) {
result.accepted = true;
if (value != dst.type) {
dst.type = value;
if (value != dst.sta.channel) {
dst.sta.channel = value;
result.changed = true;
}
}
@@ -670,7 +583,6 @@ SettingResult fromJson(JsonVariantConst src, SystemSettings& dst) {
if (src[S_NTP][S_SERVER].is<JsonString>()) {
const JsonString value = src[S_NTP][S_SERVER].as<JsonString>();
if (strlen(value.c_str()) == value.size()) {
if (value.size() < sizeof(dst.ntp.server)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.ntp.server) != 0) {
@@ -679,12 +591,10 @@ SettingResult fromJson(JsonVariantConst src, SystemSettings& dst) {
}
}
}
}
if (src[S_NTP][S_TIMEZONE].is<JsonString>()) {
const JsonString value = src[S_NTP][S_TIMEZONE].as<JsonString>();
if (strlen(value.c_str()) == value.size()) {
if (value.size() < sizeof(dst.ntp.timezone)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.ntp.timezone) != 0) {
@@ -693,7 +603,6 @@ SettingResult fromJson(JsonVariantConst src, SystemSettings& dst) {
}
}
}
}
if (src[S_UNIT_SYSTEM].is<uint8_t>()) {
const auto value = src[S_UNIT_SYSTEM].as<uint8_t>();
@@ -773,7 +682,6 @@ SettingResult fromJson(JsonVariantConst src, PortalSettings& dst) {
if (src[S_LOGIN].is<JsonString>()) {
const JsonString value = src[S_LOGIN].as<JsonString>();
if (strlen(value.c_str()) == value.size()) {
if (value.size() && value.size() < sizeof(dst.login)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.login) != 0) {
@@ -782,12 +690,10 @@ SettingResult fromJson(JsonVariantConst src, PortalSettings& dst) {
}
}
}
}
if (src[S_PASSWORD].is<JsonString>()) {
const JsonString value = src[S_PASSWORD].as<JsonString>();
if (strlen(value.c_str()) == value.size()) {
if (value.size() && value.size() < sizeof(dst.password)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.password) != 0) {
@@ -796,7 +702,6 @@ SettingResult fromJson(JsonVariantConst src, PortalSettings& dst) {
}
}
}
}
if (dst.auth && (!strlen(dst.login) || !strlen(dst.password))) {
dst.auth = false;
@@ -1213,7 +1118,6 @@ JsonVariant toJson(const MqttSettings& src, JsonVariant dst) {
mqtt[S_PREFIX] = src.prefix;
mqtt[S_INTERVAL] = src.interval;
mqtt[S_HOME_ASSISTANT_DISCOVERY] = src.homeAssistantDiscovery;
mqtt[S_HOME_ASSISTANT_DISCOVERY_PREFIX] = src.homeAssistantDiscoveryPrefix;
return dst;
}
@@ -1234,7 +1138,6 @@ SettingResult fromJson(JsonVariantConst src, MqttSettings& dst) {
if (src[S_SERVER].is<JsonString>()) {
const JsonString value = src[S_SERVER].as<JsonString>();
if (strlen(value.c_str()) == value.size()) {
if (value.size() && value.size() < sizeof(dst.server)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.server) != 0) {
@@ -1243,7 +1146,6 @@ SettingResult fromJson(JsonVariantConst src, MqttSettings& dst) {
}
}
}
}
if (src[S_PORT].is<unsigned short>()) {
const auto value = src[S_PORT].as<unsigned short>();
@@ -1260,7 +1162,6 @@ SettingResult fromJson(JsonVariantConst src, MqttSettings& dst) {
if (src[S_USER].is<JsonString>()) {
const JsonString value = src[S_USER].as<JsonString>();
if (strlen(value.c_str()) == value.size()) {
if (value.size() < sizeof(dst.user)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.user) != 0) {
@@ -1269,12 +1170,10 @@ SettingResult fromJson(JsonVariantConst src, MqttSettings& dst) {
}
}
}
}
if (src[S_PASSWORD].is<JsonString>()) {
const JsonString value = src[S_PASSWORD].as<JsonString>();
if (strlen(value.c_str()) == value.size()) {
if (value.size() < sizeof(dst.password)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.password) != 0) {
@@ -1283,12 +1182,10 @@ SettingResult fromJson(JsonVariantConst src, MqttSettings& dst) {
}
}
}
}
if (src[S_PREFIX].is<JsonString>()) {
const JsonString value = src[S_PREFIX].as<JsonString>();
if (strlen(value.c_str()) == value.size()) {
if (value.size() && value.size() < sizeof(dst.prefix)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.prefix) != 0) {
@@ -1297,7 +1194,6 @@ SettingResult fromJson(JsonVariantConst src, MqttSettings& dst) {
}
}
}
}
if (src[S_INTERVAL].is<unsigned short>()) {
const auto value = src[S_INTERVAL].as<unsigned short>();
@@ -1321,20 +1217,6 @@ SettingResult fromJson(JsonVariantConst src, MqttSettings& dst) {
}
}
if (src[S_HOME_ASSISTANT_DISCOVERY_PREFIX].is<JsonString>()) {
const JsonString value = src[S_HOME_ASSISTANT_DISCOVERY_PREFIX].as<JsonString>();
if (strlen(value.c_str()) == value.size()) {
if (value.size() && value.size() < sizeof(dst.homeAssistantDiscoveryPrefix) && strpbrk(value.c_str(), "+#") == nullptr) {
result.accepted = true;
if (strcmp(value.c_str(), dst.homeAssistantDiscoveryPrefix) != 0) {
strcpy(dst.homeAssistantDiscoveryPrefix, value.c_str());
result.changed = true;
}
}
}
}
return result;
}
@@ -1571,7 +1453,9 @@ static SettingResult applySetting(HeatingSettings& dst, std::string_view path, f
unsigned char value = static_cast<unsigned char>(input);
if (value < vars.slave.heating.minTemp || value >= vars.slave.heating.maxTemp || value == dst.maxTemp) {
if (value < vars.slave.heating.minTemp
|| value >= vars.slave.heating.maxTemp
|| value == dst.maxTemp) {
return {};
}
@@ -1592,7 +1476,9 @@ static SettingResult applySetting(HeatingSettings& dst, std::string_view path, f
unsigned char value = static_cast<unsigned char>(input);
if (value <= vars.slave.heating.minTemp || value > vars.slave.heating.maxTemp || value == dst.minTemp) {
if (value <= vars.slave.heating.minTemp
|| value > vars.slave.heating.maxTemp
|| value == dst.minTemp) {
return {};
}
@@ -1995,7 +1881,8 @@ static SettingResult applySetting(DhwSettings& dst, std::string_view path, float
unsigned char value = static_cast<unsigned char>(input);
if (value < vars.slave.dhw.minTemp || value >= vars.slave.dhw.maxTemp) {
if (value < vars.slave.dhw.minTemp
|| value >= vars.slave.dhw.maxTemp) {
return {};
}
@@ -2016,7 +1903,8 @@ static SettingResult applySetting(DhwSettings& dst, std::string_view path, float
unsigned char value = static_cast<unsigned char>(input);
if (value <= vars.slave.dhw.minTemp || value > vars.slave.dhw.maxTemp) {
if (value <= vars.slave.dhw.minTemp
|| value > vars.slave.dhw.maxTemp) {
return {};
}
@@ -3173,9 +3061,7 @@ SettingResult fromJson(const JsonVariantConst src, Sensors::Settings& dst) {
// name
if (src[S_NAME].is<JsonString>()) {
const JsonString raw = src[S_NAME].as<JsonString>();
if (strlen(raw.c_str()) == raw.size()) {
const auto raw = src[S_NAME].as<JsonString>();
const auto value = Sensors::cleanName(std::string_view(raw.c_str(), raw.size()));
if (value.size() < sizeof(dst.name) && value != dst.name) {
@@ -3202,7 +3088,6 @@ SettingResult fromJson(const JsonVariantConst src, Sensors::Settings& dst) {
result.accepted = true;
}
}
}
if (dst.enabled && !dst.slug[0]) {
dst.enabled = false;
@@ -3282,9 +3167,7 @@ SettingResult fromJson(const JsonVariantConst src, Sensors::Settings& dst) {
case static_cast<uint8_t>(Sensors::Type::NTC_10K_TEMP):
case static_cast<uint8_t>(Sensors::Type::DALLAS_TEMP):
#if USE_BLE
case static_cast<uint8_t>(Sensors::Type::BLUETOOTH):
#endif
case static_cast<uint8_t>(Sensors::Type::DHT11):
case static_cast<uint8_t>(Sensors::Type::DHT22):
case static_cast<uint8_t>(Sensors::Type::HEATING_SETPOINT_TEMP):
@@ -3304,8 +3187,8 @@ SettingResult fromJson(const JsonVariantConst src, Sensors::Settings& dst) {
// gpio
if (!src[S_GPIO].isNull()) {
if (dst.type != Sensors::Type::DALLAS_TEMP && dst.type != Sensors::Type::NTC_10K_TEMP
&& dst.type != Sensors::Type::DHT11 && dst.type != Sensors::Type::DHT22) {
if (dst.type != Sensors::Type::DALLAS_TEMP && dst.type != Sensors::Type::NTC_10K_TEMP &&
dst.type != Sensors::Type::DHT11 && dst.type != Sensors::Type::DHT22) {
if (dst.gpio != GPIO_IS_NOT_CONFIGURED) {
dst.gpio = GPIO_IS_NOT_CONFIGURED;
result.changed = true;
@@ -3321,18 +3204,9 @@ SettingResult fromJson(const JsonVariantConst src, Sensors::Settings& dst) {
} else if (src[S_GPIO].is<uint8_t>()) {
const auto value = src[S_GPIO].as<uint8_t>();
bool valid = false;
if (value == GPIO_IS_NOT_CONFIGURED) {
valid = true;
} else if (dst.type == Sensors::Type::NTC_10K_TEMP) {
valid = GPIO_IS_VALID_INPUT(value);
} else {
valid = GPIO_IS_VALID_INPUT(value) && GPIO_IS_VALID_OUTPUT(value);
}
if (valid) {
if (value == GPIO_IS_NOT_CONFIGURED
|| (GPIO_IS_VALID_INPUT(value)
&& (dst.type == Sensors::Type::NTC_10K_TEMP || GPIO_IS_VALID_OUTPUT(value)))) {
result.accepted = true;
if (value != dst.gpio) {
dst.gpio = value;
@@ -3346,7 +3220,6 @@ SettingResult fromJson(const JsonVariantConst src, Sensors::Settings& dst) {
if (src[S_ADDRESS].is<JsonString>()) {
const JsonString value = src[S_ADDRESS].as<JsonString>();
if (strlen(value.c_str()) == value.size()) {
if (dst.type == Sensors::Type::DALLAS_TEMP) {
uint8_t tmp[8];
int parsed = sscanf(
@@ -3402,7 +3275,6 @@ SettingResult fromJson(const JsonVariantConst src, Sensors::Settings& dst) {
}
}
}
}
// offset
if (src[S_OFFSET].is<float>()) {
@@ -3556,7 +3428,6 @@ JsonVariant toJson(const Variables& src, JsonVariant dst) {
master[S_NETWORK][S_CONNECTED] = isNetworkConnected();
master[S_NETWORK][S_RSSI] = src.network.rssi;
master[S_NETWORK][S_CONNECTION_TYPE] = getNetworkConnectionType();
master[S_MQTT][S_CONNECTED] = isMqttConnected();
master[S_EMERGENCY][S_STATE] = src.emergency.state;
master[S_EXTERNAL_PUMP][S_STATE] = src.externalPump.state;
+7 -7
View File
@@ -1,12 +1,13 @@
#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE
#include <app.h>
#include <esp_timer.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;
@@ -351,7 +352,6 @@ static Task cascadeTask("Cascade", [](void*) {
static Task externalPumpTask("External pump", [](void*) {
static uint8_t configuredGpio = GPIO_IS_NOT_CONFIGURED;
const uint32_t now = esp_timer_get_time() / 1000000;
if (settings.externalPump.gpio != configuredGpio) {
if (configuredGpio != GPIO_IS_NOT_CONFIGURED) {
@@ -371,7 +371,7 @@ static Task externalPumpTask("External pump", [](void*) {
if (configuredGpio == GPIO_IS_NOT_CONFIGURED) {
if (vars.externalPump.state) {
vars.externalPump.state = false;
vars.externalPump.lastEnabledTime = now;
vars.externalPump.lastEnabledTime = millis();
ESP_LOGI(L_EXTPUMP, "Disabled: use = off");
}
@@ -390,7 +390,7 @@ static Task externalPumpTask("External pump", [](void*) {
if (!settings.externalPump.use) {
if (vars.externalPump.state) {
vars.externalPump.state = false;
vars.externalPump.lastEnabledTime = now;
vars.externalPump.lastEnabledTime = millis();
ESP_LOGI(L_EXTPUMP, "Disabled: use = off");
}
@@ -398,13 +398,13 @@ static Task externalPumpTask("External pump", [](void*) {
} else if (vars.externalPump.state && !heatingEnabled) {
if (extPumpStartReason == PumpStartReason::HEATING && millis() - heatingDisabledTime > (settings.externalPump.postCirculationTime * 1000u)) {
vars.externalPump.state = false;
vars.externalPump.lastEnabledTime = now;
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 = now;
vars.externalPump.lastEnabledTime = millis();
ESP_LOGI(L_EXTPUMP, "Disabled: expired anti stuck time");
}
@@ -419,7 +419,7 @@ static Task externalPumpTask("External pump", [](void*) {
ESP_LOGI(L_EXTPUMP, "Enabled: heating on");
} else if (!vars.externalPump.state && (vars.externalPump.lastEnabledTime == 0 || now - vars.externalPump.lastEnabledTime >= settings.externalPump.antiStuckInterval)) {
} 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;
+4 -12
View File
@@ -4,7 +4,7 @@
HA::Discovery haDiscovery;
bool publishHaEntity(HaEntity entityId, bool remove) {
void publishHaEntity(HaEntity entityId, bool remove) {
std::unique_ptr<HA::Component> entity;
const UnitSystem unit = settings.system.unitSystem;
const uint32_t stateExpiration = std::max<uint32_t>(60u, 2u * settings.mqtt.interval);
@@ -532,8 +532,6 @@ bool publishHaEntity(HaEntity entityId, bool remove) {
auto gauge = std::make_unique<HA::Gauge>("rssi", "RSSI");
if (!remove) {
gauge->stateTopic = "~/state/master/network/rssi";
gauge->availabilityTopic = "~/state/master/network/connection_type";
gauge->availabilityTemplate = "{{ 'online' if value == 'wifi' else 'offline' }}";
gauge->category = HA::Category::DIAGNOSTIC;
gauge->deviceClass = "signal_strength";
gauge->icon = "mdi:signal";
@@ -837,15 +835,15 @@ bool publishHaEntity(HaEntity entityId, bool remove) {
}
default: {
return false;
return;
}
}
if (remove) {
return haDiscovery.unpublish(std::move(entity));
haDiscovery.unpublish(std::move(entity));
} else {
return haDiscovery.publish(std::move(entity));
haDiscovery.publish(std::move(entity));
}
}
@@ -908,12 +906,6 @@ static const char* getDynamicSensorIcon(Sensors::Purpose purpose) {
}
void publishDynamicSensor(const Sensors::Settings& sensor, Sensors::ValueType valueType, bool enabledByDefault) {
#if !USE_BLE
if (sensor.type == Sensors::Type::BLUETOOTH) {
return;
}
#endif
auto id = makeDynamicSensorId(sensor, valueType);
if (id.empty()) {
return;
+47 -83
View File
@@ -3,6 +3,7 @@
#include <app.h>
#include <MycilaMQTT.h>
#include <WiFi.h>
#include <algorithm>
#include <atomic>
#include <bitset>
@@ -58,8 +59,8 @@ static bool isMqttBlocked() {
}
static bool isMqttReady() {
return settings.mqtt.enabled && isNetworkConnected() && !isMqttBlocked() &&
!mqttConfigureTask.scheduled() && isMqttConnected();
return settings.mqtt.enabled && isNetworkConnected() && !isMqttBlocked()
&& !mqttConfigureTask.scheduled() && isMqttConnected();
}
static bool isMqttReadyForPublish() {
@@ -83,28 +84,29 @@ std::string mqttTopic(std::initializer_list<std::string_view> parts) {
return topic;
}
static bool publishValue(const std::string& topic, std::string_view value) {
return mqttClient->publish(topic.c_str(), value, true);
static void publishValue(const std::string& topic, std::string_view value) {
mqttClient->publish(topic.c_str(), value, true);
}
static bool publishValue(const std::string& topic, const char* value) {
return publishValue(topic, std::string_view(value));
static void publishValue(const std::string& topic, const char* value) {
publishValue(topic, std::string_view(value));
}
static bool publishValue(const std::string& topic, bool value) {
return publishValue(topic, value ? S_TRUE : S_FALSE);
static void publishValue(const std::string& topic, bool value) {
publishValue(topic, value ? S_TRUE : S_FALSE);
}
static bool publishValue(const std::string& topic, float value, uint8_t decimals = 2) {
static void publishValue(const std::string& topic, float value, uint8_t decimals = 2) {
if (!std::isfinite(value)) {
// Remove an obsolete retained reading instead of publishing nan/inf.
return publishValue(topic, "");
publishValue(topic, "");
return;
}
char payload[64];
const int length = snprintf(payload, sizeof(payload), "%.*f", decimals, value);
if (length < 0 || static_cast<size_t>(length) >= sizeof(payload)) {
return false;
return;
}
if (decimals) {
@@ -116,8 +118,7 @@ static bool publishValue(const std::string& topic, float value, uint8_t decimals
*end = '\0';
}
}
return publishValue(topic, payload);
publishValue(topic, payload);
}
static void publishHeatingSettings() {
@@ -241,6 +242,7 @@ static void publishSlaveState() {
publishValue(mqttTopic("state/slave/fault/available"), vars.slave.connected && vars.slave.fault.active);
publishValue(mqttTopic("state/slave/diag/active"), vars.slave.diag.active);
publishValue(mqttTopic("state/slave/diag/code"), std::to_string(vars.slave.diag.code));
// Preserve the diagnostic-code availability condition from async.
publishValue(mqttTopic("state/slave/diag/available"), (vars.slave.connected && vars.slave.fault.active) || vars.slave.diag.active);
}
@@ -285,7 +287,6 @@ static void publishMasterState() {
publishValue(mqttTopic("state/master/dhw/max_temp"), convertTemp(settings.dhw.maxTemp, UnitSystem::METRIC, settings.system.unitSystem), 2);
publishValue(mqttTopic("state/master/network/connected"), isNetworkConnected());
publishValue(mqttTopic("state/master/network/rssi"), std::to_string(vars.network.rssi));
publishValue(mqttTopic("state/master/network/connection_type"), getNetworkConnectionType());
publishValue(mqttTopic("state/master/emergency/state"), vars.emergency.state);
publishValue(mqttTopic("state/master/ext_pump/state"), vars.externalPump.state);
publishValue(mqttTopic("state/master/cascade_control/input"), vars.cascadeControl.input);
@@ -353,24 +354,19 @@ static bool isCommandValid(const std::string& topic, std::string_view payload) {
return true;
}
static bool publishSensor(const Sensors::Settings& sensor, const Sensors::Result& result) {
static void publishSensor(const Sensors::Settings& sensor, const Sensors::Result& result) {
if (!sensor.slug[0]) {
return false;
}
if (!publishValue(mqttTopic(S_SENSORS, sensor.slug, S_CONNECTED), result.connected)) {
return false;
return;
}
publishValue(mqttTopic(S_SENSORS, sensor.slug, S_CONNECTED), result.connected);
if (sensor.type == Sensors::Type::BLUETOOTH || sensor.type == Sensors::Type::DALLAS_TEMP
|| sensor.type == Sensors::Type::DHT11 || sensor.type == Sensors::Type::DHT22) {
if (!publishValue(mqttTopic(S_SENSORS, sensor.slug, S_SIGNAL_QUALITY), std::to_string(result.signalQuality))) {
return false;
}
publishValue(mqttTopic(S_SENSORS, sensor.slug, S_SIGNAL_QUALITY), std::to_string(result.signalQuality));
}
if (sensor.type == Sensors::Type::BLUETOOTH || sensor.type == Sensors::Type::DHT11 || sensor.type == Sensors::Type::DHT22) {
const bool published = publishValue(
publishValue(
mqttTopic(S_SENSORS, sensor.slug, S_TEMPERATURE),
convertTemp(
result.values[static_cast<uint8_t>(Sensors::ValueType::TEMPERATURE)],
@@ -378,27 +374,15 @@ static bool publishSensor(const Sensors::Settings& sensor, const Sensors::Result
),
3
);
if (!published) {
return false;
}
if (!publishValue(mqttTopic(S_SENSORS, sensor.slug, S_HUMIDITY), result.values[static_cast<uint8_t>(Sensors::ValueType::HUMIDITY)], 3)) {
return false;
}
publishValue(mqttTopic(S_SENSORS, sensor.slug, S_HUMIDITY), result.values[static_cast<uint8_t>(Sensors::ValueType::HUMIDITY)], 3);
if (sensor.type == Sensors::Type::BLUETOOTH) {
if (!publishValue(mqttTopic(S_SENSORS, sensor.slug, S_BATTERY), result.values[static_cast<uint8_t>(Sensors::ValueType::BATTERY)], 1)) {
return false;
}
if (!publishValue(mqttTopic(S_SENSORS, sensor.slug, S_RSSI), result.values[static_cast<uint8_t>(Sensors::ValueType::RSSI)], 0)) {
return false;
}
publishValue(mqttTopic(S_SENSORS, sensor.slug, S_BATTERY), result.values[static_cast<uint8_t>(Sensors::ValueType::BATTERY)], 1);
publishValue(mqttTopic(S_SENSORS, sensor.slug, S_RSSI), result.values[static_cast<uint8_t>(Sensors::ValueType::RSSI)], 0);
}
} else {
const bool published = publishValue(
publishValue(
mqttTopic(S_SENSORS, sensor.slug, S_VALUE),
Sensors::convertValue(
sensor, Sensors::ValueType::PRIMARY,
@@ -407,13 +391,7 @@ static bool publishSensor(const Sensors::Settings& sensor, const Sensors::Result
),
3
);
if (!published) {
return false;
}
}
return true;
}
static bool purgeSensor(const char* slug) {
@@ -548,7 +526,8 @@ static float mqttValueToMetric(std::string_view path, float value) {
}
const auto name = path.substr(path.find_last_of('/') + 1);
if (name == S_TARGET || name == S_MIN_TEMP || name == S_MAX_TEMP || name == S_HIGH_TEMP || name == S_LOW_TEMP) {
if (name == S_TARGET || name == S_MIN_TEMP || name == S_MAX_TEMP
|| name == S_HIGH_TEMP || name == S_LOW_TEMP) {
return convertTemp(value, settings.system.unitSystem, UnitSystem::METRIC);
}
@@ -556,14 +535,11 @@ static float mqttValueToMetric(std::string_view path, float value) {
}
static void subscribe() {
mqttClient->subscribe(
std::string(settings.mqtt.homeAssistantDiscoveryPrefix) + "/status",
[](const std::string&, const std::string_view& message) {
mqttClient->subscribe("homeassistant/status", [](const std::string&, const std::string_view& message) {
if (message == "online") {
mqttHaRefreshRequested.store(true);
}
}
);
});
const auto onSettingCommand = [](const std::string& topic, const std::string_view& message) {
if (isMqttBlocked() || !settings.mqtt.enabled || mqttConfigureTask.scheduled() || mqttConfigureTask.active()) {
@@ -707,9 +683,11 @@ static void connect() {
mqttReconfigureSensorsTask->requestEarlyRun();
ESP_LOGI(L_MQTT, "Connected");
});
}
if (mqttPrefix != settings.mqtt.prefix || haDiscovery.getDiscoveryTopic() != settings.mqtt.homeAssistantDiscoveryPrefix) {
mqttPrefix = settings.mqtt.prefix;
subscribe();
} else if (mqttPrefix != settings.mqtt.prefix) {
for (const auto& topic : mqttClient->getSubscribedTopics()) {
mqttClient->unsubscribe(topic.c_str());
}
@@ -718,7 +696,6 @@ static void connect() {
subscribe();
}
haDiscovery.setDiscoveryTopic(settings.mqtt.homeAssistantDiscoveryPrefix);
haDiscovery.setWillTopic("~/status");
haDiscovery.begin(
{
@@ -727,11 +704,11 @@ static void connect() {
.version = BUILD_VERSION,
.model = PROJECT_NAME,
.manufacturer = PROJECT_REPO,
.url = std::string("http://") + getNetworkIp().toString().c_str() + "/",
.url = std::string("http://") + WiFi.localIP().toString().c_str() + "/",
},
mqttPrefix,
[](const char* topic, const std::string& payload) {
return mqttClient->publish(topic, payload, true);
mqttClient->publish(topic, payload, true);
}
);
mqttClient->begin({
@@ -899,15 +876,9 @@ Task mqttConfigureTask("Configure MQTT", Task::Type::ONCE, [](void*) {
continue;
}
const bool published = publishHaEntity(static_cast<HaEntity>(index), !settings.mqtt.homeAssistantDiscovery);
if (published) {
mqttHaPendingEntities.reset(index);
} else {
ESP_LOGD(L_MQTT, "HA publication deferred");
}
break;
publishHaEntity(static_cast<HaEntity>(index), !settings.mqtt.homeAssistantDiscovery);
return;
}
for (uint8_t sensorId = 0; sensorId < SENSORS_AMOUNT; sensorId++) {
@@ -925,7 +896,6 @@ Task mqttConfigureTask("Configure MQTT", Task::Type::ONCE, [](void*) {
requestReconfigureMqttSensor(sensorId, std::move(sensor));
}
}
break;
}
});
@@ -952,14 +922,14 @@ Task mqttConfigureTask("Configure MQTT", Task::Type::ONCE, [](void*) {
lock.unlock();
const auto& [sensorId, prevSettings] = change;
const bool metadataChanged =
prevSettings &&
(!sensor ||
prevSettings->enabled != sensor->enabled ||
strcmp(prevSettings->name, sensor->name) != 0 ||
strcmp(prevSettings->slug, sensor->slug) != 0 ||
prevSettings->purpose != sensor->purpose ||
prevSettings->type != sensor->type);
const bool metadataChanged = prevSettings && (
!sensor
|| prevSettings->enabled != sensor->enabled
|| strcmp(prevSettings->name, sensor->name) != 0
|| strcmp(prevSettings->slug, sensor->slug) != 0
|| prevSettings->purpose != sensor->purpose
|| prevSettings->type != sensor->type
);
// Metadata changes replace entities; disabling discovery removes them.
if (prevSettings && Sensors::hasEnabledAndValid(*prevSettings)
@@ -993,8 +963,8 @@ Task mqttConfigureTask("Configure MQTT", Task::Type::ONCE, [](void*) {
}
if (settings.mqtt.homeAssistantDiscovery && sensor && Sensors::hasEnabledAndValid(*sensor)) {
if (sensor->type == Sensors::Type::BLUETOOTH || sensor->type == Sensors::Type::DALLAS_TEMP
|| sensor->type == Sensors::Type::DHT11 || sensor->type == Sensors::Type::DHT22) {
if (sensor->type == Sensors::Type::BLUETOOTH || sensor->type == Sensors::Type::DALLAS_TEMP ||
sensor->type == Sensors::Type::DHT11 || sensor->type == Sensors::Type::DHT22) {
publishConnectionDynamicSensor(*sensor);
publishSignalQualityDynamicSensor(*sensor);
@@ -1077,13 +1047,7 @@ Task mqttConfigureTask("Configure MQTT", Task::Type::ONCE, [](void*) {
mqttPublishedSensorAt[sensorId] = snapshotAt;
}
if (!publishSensor(snapshot->settings, snapshot->result)) {
{
std::lock_guard<std::mutex> lock(mqttSensorsMutex);
mqttPublishedSensorAt[sensorId] = 0;
}
ESP_LOGD(L_MQTT, "Sensor publication deferred");
}
publishSensor(snapshot->settings, snapshot->result);
}
});
+70 -417
View File
@@ -5,11 +5,6 @@
#include <DNSServer.h>
#include <ESPmDNS.h>
#include <ESPAsyncWebServer.h>
#if USE_ETHERNET
#include <ETH.h>
#include <driver/spi_common.h>
#include <esp_netif.h>
#endif
#include <Network.h>
#include <WiFi.h>
#include <esp_wifi.h>
@@ -24,10 +19,6 @@ 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};
#if USE_ETHERNET
static std::atomic<bool> ethStarted{false};
static std::atomic<NetworkState> ethState{NetworkState::NETWORK_DISABLED};
#endif
// Subscriptions are fixed before the worker starts.
static std::vector<NetworkEventCallback> networkCallbacks;
@@ -35,9 +26,9 @@ 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, ETH_GOT_IP and AP_STARTED.
uint32_t value; // IPv4 address for STA_GOT_IP and AP_STARTED.
NetworkEvent event;
uint16_t reason; // Wi-Fi disconnect reason.
uint8_t reason; // STA disconnect reason.
};
static constexpr size_t NETWORK_EVENT_QUEUE_LENGTH = 32;
@@ -75,7 +66,6 @@ static bool mdnsStarted = false;
static unsigned long lastDnsAttempt = 0;
static unsigned long lastMdnsAttempt = 0;
static char mdnsHostname[sizeof(networkSettings.hostname)] = {};
static void stopMdns();
// Event subscriptions
void onNetworkEvent(NetworkEventCallback callback) {
@@ -108,114 +98,28 @@ NetworkState getNetworkState(NetworkMode mode) {
return apState.load();
}
#if USE_ETHERNET
if (mode == NetworkMode::ETH) {
return ethState.load();
}
#endif
// Ethernet initialization and routing will be implemented separately.
return NetworkState::NETWORK_DISABLED;
}
bool isNetworkConnected() {
return getNetworkState(NetworkMode::STA) == NetworkState::NETWORK_CONNECTED ||
getNetworkState(NetworkMode::ETH) == NetworkState::NETWORK_CONNECTED;
return getNetworkState(NetworkMode::STA) == NetworkState::NETWORK_CONNECTED;
}
NetworkMode getNetworkMode() {
if (getNetworkState(NetworkMode::STA) == NetworkState::NETWORK_CONNECTED) {
if (isNetworkConnected()) {
return NetworkMode::STA;
}
if (getNetworkState(NetworkMode::ETH) == NetworkState::NETWORK_CONNECTED) {
return NetworkMode::ETH;
}
return apStarted.load() ? NetworkMode::AP : NetworkMode::NONE;
}
const char* getNetworkConnectionType() {
switch (getNetworkMode()) {
case NetworkMode::ETH:
return S_ETHERNET;
case NetworkMode::STA:
return "wifi";
case NetworkMode::AP:
return "wifi-ap";
default:
return "none";
}
}
static NetworkInterface& getNetworkInterface() {
const NetworkMode mode = getNetworkMode();
#if USE_ETHERNET
if (mode == NetworkMode::ETH) {
return ETH;
}
#endif
if (mode == NetworkMode::AP) {
return WiFi.AP;
}
return WiFi.STA;
}
IPAddress getNetworkIp() {
return getNetworkInterface().localIP();
}
IPAddress getNetworkSubnet() {
return getNetworkInterface().subnetMask();
}
IPAddress getNetworkGateway() {
return getNetworkInterface().gatewayIP();
}
IPAddress getNetworkDns() {
return getNetworkInterface().dnsIP();
}
String getNetworkMac() {
return getNetworkInterface().macAddress();
}
bool isEthernetConfigured(const NetworkSettings& config) {
#if USE_ETHERNET
const auto& gpios = config.ethernet.w5500;
return config.ethernet.type == EthernetType::W5500 &&
GPIO_IS_VALID_OUTPUT(gpios.clk) &&
GPIO_IS_VALID_OUTPUT(gpios.mosi) &&
GPIO_IS_VALID_INPUT(gpios.miso) &&
GPIO_IS_VALID_OUTPUT(gpios.cs) &&
GPIO_IS_VALID_INPUT(gpios.irq) &&
GPIO_IS_VALID_OUTPUT(gpios.rst);
#else
(void)config;
return false;
#endif
}
bool isNetworkInterfaceStarted(NetworkMode mode) {
if (mode == NetworkMode::STA) {
return staStarted.load();
}
#if USE_ETHERNET
if (mode == NetworkMode::ETH) {
return ethStarted.load();
}
#endif
if (mode == NetworkMode::AP) {
return apStarted.load();
}
return false;
return mode == NetworkMode::AP && apStarted.load();
}
// Requests from other tasks; driver operations run in the system worker.
@@ -231,20 +135,14 @@ static void notifyNetworkEvent(NetworkEvent event) {
}
static void setNetworkState(NetworkMode mode, NetworkState next) {
auto* state = mode == NetworkMode::STA ? &staState : &apState;
#if USE_ETHERNET
if (mode == NetworkMode::ETH) {
state = &ethState;
}
#endif
auto& state = mode == NetworkMode::STA ? staState : apState;
const NetworkState previous = state.load();
const NetworkState previous = state->load();
if (previous == next) {
return;
}
const bool uplink = mode == NetworkMode::STA || mode == NetworkMode::ETH;
if (uplink) {
if (mode == NetworkMode::STA) {
if (previous == NetworkState::NETWORK_CONNECTED) {
disconnectedTime = millis();
connectedIp = 0;
@@ -259,12 +157,12 @@ static void setNetworkState(NetworkMode mode, NetworkState next) {
}
// Publish before callbacks so getters and JSON already reflect the new state.
state->store(next);
state.store(next);
for (auto& callback : stateCallbacks) {
callback(mode, previous, next);
}
if (uplink) {
if (mode == NetworkMode::STA) {
if (next == NetworkState::NETWORK_CONNECTED) {
notifyNetworkEvent(NetworkEvent::CONNECTED);
@@ -275,7 +173,7 @@ static void setNetworkState(NetworkMode mode, NetworkState next) {
}
// Framework events
static void queueNetworkEvent(NetworkEvent event, uint32_t value = 0, uint16_t reason = 0) {
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().
@@ -284,7 +182,7 @@ static void queueNetworkEvent(NetworkEvent event, uint32_t value = 0, uint16_t r
}
}
static void handleNetworkEvent(arduino_event_id_t event, arduino_event_info_t info) {
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
@@ -321,7 +219,7 @@ static void handleNetworkEvent(arduino_event_id_t event, arduino_event_info_t in
queueNetworkEvent(NetworkEvent::AP_CLIENT_CONNECTED);
break;
case ARDUINO_EVENT_WIFI_AP_STADISCONNECTED:
queueNetworkEvent(NetworkEvent::AP_CLIENT_DISCONNECTED, 0, info.wifi_ap_stadisconnected.reason);
queueNetworkEvent(NetworkEvent::AP_CLIENT_DISCONNECTED);
break;
case ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED:
queueNetworkEvent(NetworkEvent::AP_CLIENT_GOT_IP);
@@ -330,56 +228,23 @@ static void handleNetworkEvent(arduino_event_id_t event, arduino_event_info_t in
queueNetworkEvent(NetworkEvent::AP_GOT_IP6);
break;
#if USE_ETHERNET
case ARDUINO_EVENT_ETH_START:
queueNetworkEvent(NetworkEvent::ETH_STARTED);
break;
case ARDUINO_EVENT_ETH_STOP:
queueNetworkEvent(NetworkEvent::ETH_STOPPED);
break;
case ARDUINO_EVENT_ETH_CONNECTED:
queueNetworkEvent(NetworkEvent::ETH_CONNECTED);
break;
case ARDUINO_EVENT_ETH_DISCONNECTED:
queueNetworkEvent(NetworkEvent::ETH_DISCONNECTED);
break;
case ARDUINO_EVENT_ETH_GOT_IP:
queueNetworkEvent(NetworkEvent::ETH_GOT_IP, info.got_ip.ip_info.ip.addr);
break;
case ARDUINO_EVENT_ETH_LOST_IP:
queueNetworkEvent(NetworkEvent::ETH_LOST_IP);
break;
case ARDUINO_EVENT_ETH_GOT_IP6:
queueNetworkEvent(NetworkEvent::ETH_GOT_IP6);
break;
#endif
default:
break;
}
}
static void postInterfaceStopped(arduino_event_id_t type) {
// Interface teardown can remove native STOP handlers. Keep our notification ordered
// 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 network requested");
ESP_LOGE(L_NETWORK, "Failed post interface stop, reset WiFi requested");
networkRecoveryRequested.store(true);
}
}
// WiFi interfaces
static bool shouldEnableWifiRadio() {
return networkSettings.type == NetworkMode::STA;
}
static void fallbackToWifi() {
ESP_LOGW(L_NETWORK, "Ethernet unavailable, switching to WiFi");
networkSettings.type = NetworkMode::STA;
}
static void configureWifiRadio() {
// Apply the existing channel policy after the WiFi driver has started.
const wifi_country_t country = {
@@ -396,7 +261,6 @@ static void configureWifiRadio() {
}
static void stopAccessPoint() {
stopMdns();
if (!WiFi.AP.end()) {
ESP_LOGE(L_NETWORK, "Failed stop AP, reset WiFi requested");
networkRecoveryRequested.store(true);
@@ -407,10 +271,6 @@ static void stopAccessPoint() {
}
static void startAccessPoint() {
if (!shouldEnableWifiRadio()) {
return;
}
lastApAttempt = millis();
setNetworkState(NetworkMode::AP, NetworkState::AP_STARTING);
@@ -426,26 +286,20 @@ static void startAccessPoint() {
configureWifiRadio();
WiFi.AP.setHostname(networkSettings.hostname);
const bool apCreated = WiFi.AP.create(
networkSettings.wifi.ap.ssid,
networkSettings.wifi.ap.password[0] ? networkSettings.wifi.ap.password : nullptr,
networkSettings.wifi.ap.channel
);
if (!apCreated) {
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");
return;
}
WiFi.scanNetworks(true, true, true);
}
static bool resetWifi() {
const bool restoreAp = WiFi.AP.started();
connectionPending = false;
stopMdns();
// A failed driver reset must also respect the retry cooldown.
lastConnectionAttempt = millis();
@@ -460,47 +314,31 @@ static bool resetWifi() {
}
lastConnectionAttempt = 0;
if (restoreAp && shouldEnableWifiRadio()) {
if (restoreAp) {
startAccessPoint();
}
return true;
}
static bool stopStation() {
static bool startNetworkConnection() {
// Ordinary retries preserve AP. Escalate only if STA cannot be stopped.
const bool wasStarted = WiFi.STA.started();
// mDNS keeps netif pointers; release them before the driver destroys STA.
stopMdns();
if (!WiFi.STA.end()) {
ESP_LOGW(L_NETWORK, "Failed stop STA, reset WiFi requested");
ESP_LOGW(L_NETWORK, "Failed stop STA, reset WiFi...");
if (!resetWifi()) {
return false;
}
if (wasStarted) {
} else if (wasStarted) {
postInterfaceStopped(ARDUINO_EVENT_WIFI_STA_STOP);
}
lastConnectionAttempt = 0;
connectionPending = false;
return true;
}
static bool startNetworkConnection() {
if (!shouldEnableWifiRadio()) {
return false;
}
if (!WiFi.STA.begin()) {
return false;
}
// Cancel an unfinished attempt without destroying the netif used by mDNS.
const esp_err_t result = esp_wifi_disconnect();
if (result != ESP_OK && result != ESP_ERR_WIFI_NOT_CONNECT) {
ESP_LOGW(L_NETWORK, "Failed cancel STA connection: %s", esp_err_to_name(result));
return false;
}
configureWifiRadio();
WiFi.STA.setAutoReconnect(false);
WiFi.STA.setScanMethod(WIFI_ALL_CHANNEL_SCAN);
@@ -533,86 +371,15 @@ static bool startNetworkConnection() {
);
return WiFi.STA.connect(
networkSettings.wifi.sta.ssid,
networkSettings.wifi.sta.password[0] ? networkSettings.wifi.sta.password : nullptr,
networkSettings.wifi.sta.channel
networkSettings.sta.ssid,
networkSettings.sta.password[0] ? networkSettings.sta.password : nullptr,
networkSettings.sta.channel
);
}
// Ethernet driver
#if USE_ETHERNET
static bool stopEthernet() {
stopMdns();
ethStarted.store(false);
setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_DISABLED);
ETH.end();
// end() can return before releasing a partially initialized driver.
if (ETH.handle() != nullptr || ETH.netif() != nullptr) {
if (ETH.netif() != nullptr) {
ETH.setRoutePrio(0);
esp_netif_action_stop(ETH.netif(), ETH_EVENT, ETHERNET_EVENT_STOP, nullptr);
}
ESP_LOGE(L_NETWORK, "Failed release Ethernet driver");
return false;
}
// end() removes the device, but leaves the SPI bus with its previous GPIOs.
const esp_err_t result = spi_bus_free(SPI2_HOST);
if (result != ESP_OK && result != ESP_ERR_INVALID_STATE) {
ESP_LOGE(L_NETWORK, "Failed release Ethernet SPI bus: %s", esp_err_to_name(result));
return false;
}
postInterfaceStopped(ARDUINO_EVENT_ETH_STOP);
return true;
}
static bool configureEthernet() {
ETH.setHostname(networkSettings.hostname);
if (networkSettings.useDhcp) {
return ETH.config();
}
IPAddress ip, gateway, subnet, dns;
ip.fromString(networkSettings.staticConfig.ip);
gateway.fromString(networkSettings.staticConfig.gateway);
subnet.fromString(networkSettings.staticConfig.subnet);
dns.fromString(networkSettings.staticConfig.dns);
return ETH.config(ip, gateway, subnet, dns);
}
static bool startEthernet() {
if ((ETH.handle() != nullptr || ETH.netif() != nullptr) && !stopEthernet()) {
return false;
}
const auto& gpios = networkSettings.ethernet.w5500;
ESP_LOGI(L_NETWORK, "Initialize W5500 Ethernet");
if (!ETH.begin(
ETH_PHY_W5500, 1, gpios.cs, gpios.irq, gpios.rst,
SPI2_HOST, gpios.clk, gpios.miso, gpios.mosi, 12
)) {
ESP_LOGE(L_NETWORK, "W5500 initialization failed, check GPIOs and wiring");
stopEthernet();
return false;
}
ethStarted.store(true);
setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_CONNECTING);
return true;
}
#endif
// Station connection and recovery timeouts
static void updateConnection() {
if (!networkSettings.wifi.sta.ssid[0]) {
return;
}
// Let the portal scan finish before starting another connection or recovery.
if (WiFi.scanComplete() == WIFI_SCAN_RUNNING) {
if (!networkSettings.sta.ssid[0]) {
return;
}
@@ -666,7 +433,7 @@ static void updateAccessPoint() {
return;
}
if (!apStarted.load() && (!networkSettings.wifi.sta.ssid[0] || millis() - disconnectedTime > 185000)) {
if (!apStarted.load() && (!networkSettings.sta.ssid[0] || millis() - disconnectedTime > 185000)) {
if (!lastApAttempt || millis() - lastApAttempt > 15000) {
ESP_LOGI(L_NETWORK, "Start fallback AP");
startAccessPoint();
@@ -707,8 +474,13 @@ static void stopMdns() {
}
static void updateNetworkServices() {
const bool ready = webServerReady;
// Serve captive DNS only while HTTP is ready and no upstream connection exists.
const bool captive = webServerReady && apStarted.load() && apIp && !isNetworkConnected();
const bool captive = ready
&& apStarted.load()
&& apIp
&& !isNetworkConnected();
if (!captive) {
stopCaptiveDns(isNetworkConnected());
@@ -730,8 +502,10 @@ static void updateNetworkServices() {
}
}
// mDNS tracks native interface/IP events without restarting the responder.
const bool enableMdns = webServerReady && settings.portal.mdns;
// 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();
@@ -769,10 +543,6 @@ static void processNetworkEvent(const PendingNetworkEvent& pending) {
switch (pending.event) {
// Station
case NetworkEvent::STA_STARTED:
if (!shouldEnableWifiRadio()) {
return;
}
// Repeated START must not invalidate an active connection.
if (staStarted.exchange(true)) {
break;
@@ -788,7 +558,6 @@ static void processNetworkEvent(const PendingNetworkEvent& pending) {
setNetworkState(NetworkMode::STA, NetworkState::NETWORK_ENABLED);
}
break;
case NetworkEvent::STA_STOPPED: {
const bool started = staStarted.exchange(false);
staAssociated = false;
@@ -801,114 +570,42 @@ static void processNetworkEvent(const PendingNetworkEvent& pending) {
}
case NetworkEvent::STA_CONNECTED:
if (!shouldEnableWifiRadio()) {
return;
}
// Association alone does not confirm a usable IP address.
staAssociated = true;
break;
case NetworkEvent::STA_GOT_IP:
if (!shouldEnableWifiRadio() || !pending.value) {
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 (getNetworkState(NetworkMode::STA) == NetworkState::NETWORK_CONNECTED && connectedIp != pending.value) {
if (isNetworkConnected() && connectedIp != pending.value) {
disconnectReason = 0;
setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISCONNECTED);
}
staAssociated = true;
connectedIp = pending.value;
if (getNetworkState(NetworkMode::STA) != NetworkState::NETWORK_CONNECTED) {
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;
#if USE_ETHERNET
case NetworkEvent::ETH_STARTED:
if (!ethStarted.load() || networkSettings.type != NetworkMode::ETH) {
return;
}
// Apply after native START so a preceding STOP cannot clear the static-IP state.
if (!configureEthernet()) {
ESP_LOGE(L_NETWORK, "Failed configure Ethernet IPv4");
setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_TIMEOUT);
break;
}
if (getNetworkState(NetworkMode::ETH) == NetworkState::NETWORK_DISABLED) {
setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_ENABLED);
}
break;
case NetworkEvent::ETH_STOPPED:
setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_DISABLED);
break;
case NetworkEvent::ETH_CONNECTED:
if (!ethStarted.load() || networkSettings.type != NetworkMode::ETH) {
return;
}
if (getNetworkState(NetworkMode::ETH) != NetworkState::NETWORK_CONNECTED) {
setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_CONNECTING);
}
break;
case NetworkEvent::ETH_GOT_IP:
if (!ethStarted.load() || networkSettings.type != NetworkMode::ETH) {
return;
}
if (!pending.value || !ETH.connected() || !ETH.hasIP()) {
return;
}
if (getNetworkState(NetworkMode::ETH) == NetworkState::NETWORK_CONNECTED && connectedIp != pending.value) {
setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_DISCONNECTED);
}
connectedIp = pending.value;
if (getNetworkState(NetworkMode::ETH) != NetworkState::NETWORK_CONNECTED) {
vars.network.rssi = 0;
setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_CONNECTED);
}
break;
case NetworkEvent::ETH_DISCONNECTED:
case NetworkEvent::ETH_LOST_IP:
setNetworkState(
NetworkMode::ETH,
ethStarted.load() ? NetworkState::NETWORK_DISCONNECTED : NetworkState::NETWORK_DISABLED
);
break;
#endif
// Access point
case NetworkEvent::AP_STARTED:
if (!shouldEnableWifiRadio()) {
return;
}
// Preserve clients and captive portal state on a repeated START.
if (apStarted.exchange(true)) {
break;
@@ -918,13 +615,15 @@ static void processNetworkEvent(const PendingNetworkEvent& pending) {
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;
}
@@ -935,16 +634,13 @@ static void processNetworkEvent(const PendingNetworkEvent& pending) {
if (apClients < UINT8_MAX) {
++apClients;
}
ESP_LOGI(L_NETWORK, "AP client connected, clients: %hhu", apClients);
break;
case NetworkEvent::AP_CLIENT_DISCONNECTED:
if (apClients) {
--apClients;
}
ESP_LOGI(L_NETWORK, "AP client disconnected, clients: %hhu, reason: %hu", apClients, pending.reason);
break;
default:
break;
}
@@ -961,20 +657,14 @@ static void processNetworkEvents() {
xQueueReset(networkEventQueue);
stopCaptiveDns();
stopMdns();
staStarted.store(false);
apStarted.store(false);
staAssociated = false;
setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISABLED);
apStarted.store(false);
setNetworkState(NetworkMode::AP, NetworkState::NETWORK_DISABLED);
#if USE_ETHERNET
setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_DISABLED);
#endif
if (overflowed) {
ESP_LOGW(L_NETWORK, "Network event queue overflow, reset network requested");
ESP_LOGW(L_NETWORK, "Network event queue overflow, reset WiFi requested");
notifyNetworkEvent(NetworkEvent::EVENTS_OVERFLOW);
}
@@ -989,13 +679,7 @@ static void processNetworkEvents() {
lastNetworkRecoveryAttempt = millis();
// Keep callbacks nonblocking; recover through the existing full-reset path.
ESP_LOGW(L_NETWORK, "Reset network after event failure...");
#if USE_ETHERNET
if (ethStarted.load() && !stopEthernet()) {
fallbackToWifi();
}
#endif
ESP_LOGW(L_NETWORK, "Reset WiFi after network event failure...");
if (!resetWifi()) {
return;
}
@@ -1016,7 +700,7 @@ static void processNetworkEvents() {
// Connection services
static void updateRssi() {
if (getNetworkMode() == NetworkMode::STA && millis() - lastRssiUpdate >= 1000) {
if (isNetworkConnected() && millis() - lastRssiUpdate >= 1000) {
vars.network.rssi = WiFi.STA.RSSI();
lastRssiUpdate = millis();
}
@@ -1032,7 +716,7 @@ static void updateNtp() {
}
static void logNetworkState(NetworkMode mode, NetworkState previous, NetworkState state) {
if (mode != networkSettings.type) {
if (mode != NetworkMode::STA) {
return;
}
@@ -1064,26 +748,25 @@ static Task networkStartTask("Start network services", Task::Type::ONCE, [](void
webServer->begin();
webServerReady = true;
configureLoggingTask.resume();
ESP_LOGD(L_PORTAL_WEBSERVER, "Started: AP up or uplink connected");
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...");
#if USE_ETHERNET
if (ethStarted.load() && !stopEthernet()) {
fallbackToWifi();
}
#endif
if (shouldEnableWifiRadio()) {
if (!stopStation()) {
networkRecoveryRequested.store(true);
const bool wasStarted = WiFi.STA.started();
if (!WiFi.STA.end()) {
ESP_LOGW(L_NETWORK, "Failed stop STA, reset WiFi...");
resetWifi();
return;
}
} else if (!resetWifi()) {
networkRecoveryRequested.store(true);
if (wasStarted) {
postInterfaceStopped(ARDUINO_EVENT_WIFI_STA_STOP);
}
lastConnectionAttempt = 0;
connectionPending = false;
});
static Task networkTask("Network", [](void*) {
@@ -1098,7 +781,10 @@ static Task networkTask("Network", [](void*) {
Sensors::setConnectionStatusByType(Sensors::Type::MANUAL, false, false);
}
if (recoveryPending || networkRecoveryRequested.load() || networkEventsOverflowed.load()) {
if (recoveryPending
|| networkRecoveryRequested.load()
|| networkEventsOverflowed.load()
) {
return;
}
@@ -1110,39 +796,6 @@ static Task networkTask("Network", [](void*) {
return;
}
if (networkSettings.type == NetworkMode::ETH && !isEthernetConfigured()) {
#if USE_ETHERNET
if (ethStarted.load()) {
stopEthernet();
}
#endif
fallbackToWifi();
}
if (networkSettings.type == NetworkMode::ETH) {
if (WiFi.getMode() != WIFI_OFF && !resetWifi()) {
networkRecoveryRequested.store(true);
return;
}
#if USE_ETHERNET
if (!ethStarted.load() && !startEthernet()) {
fallbackToWifi();
}
#endif
if (isNetworkConnected()) {
updateNtp();
}
return;
}
#if USE_ETHERNET
if (ethStarted.load()) {
stopEthernet();
}
#endif
if (isNetworkConnected()) {
if (connectionPending) {
connectionPending = false;
@@ -1183,7 +836,7 @@ void initNetwork() {
});
Network.begin();
Network.onEvent(handleNetworkEvent);
Network.onEvent(handleWifiEvent);
onNetworkStateChange(logNetworkState);
WiFi.persistent(false);
WiFi.STA.setAutoReconnect(false);
+150 -163
View File
@@ -33,9 +33,10 @@ static std::atomic<uint8_t> configuredRxLedGpio{GPIO_IS_NOT_CONFIGURED};
static bool canUseBus() {
return !restartTask.scheduled() && slave.isInitialized() &&
slave.getConfig().rxGpio == settings.opentherm.inGpio &&
slave.getConfig().txGpio == settings.opentherm.outGpio;
return !restartTask.scheduled()
&& slave.isInitialized()
&& slave.getConfig().rxGpio == settings.opentherm.inGpio
&& slave.getConfig().txGpio == settings.opentherm.outGpio;
}
static bool isMasterReady() {
@@ -85,33 +86,33 @@ static float getCh2ChannelSetpoint() {
}
static bool needWriteRoomSetpoint(const float target) {
return !roomSetpointWriteTime ||
millis() - roomSetpointWriteTime > roomSetpointWriteInterval ||
isFloatDifferent(target, vars.slave.heating.roomTargetTemp, 0.05f);
return !roomSetpointWriteTime
|| millis() - roomSetpointWriteTime > roomSetpointWriteInterval
|| isFloatDifferent(target, vars.slave.heating.roomTargetTemp, 0.05f);
}
static bool needWriteRoomSetpointCh2(const float target) {
return !ch2RoomSetpointWriteTime ||
millis() - ch2RoomSetpointWriteTime > roomSetpointWriteInterval ||
isFloatDifferent(target, vars.slave.ch2.roomTargetTemp, 0.05f);
return !ch2RoomSetpointWriteTime
|| millis() - ch2RoomSetpointWriteTime > roomSetpointWriteInterval
|| isFloatDifferent(target, vars.slave.ch2.roomTargetTemp, 0.05f);
}
static bool needWriteDhwSetpoint(const float target) {
return !dhwSetpointWriteTime ||
millis() - dhwSetpointWriteTime > dhwSetpointWriteInterval ||
isFloatDifferent(target, vars.slave.dhw.targetTemp, 0.05f);
return !dhwSetpointWriteTime
|| millis() - dhwSetpointWriteTime > dhwSetpointWriteInterval
|| isFloatDifferent(target, vars.slave.dhw.targetTemp, 0.05f);
}
static bool needWriteHeatingSetpoint(const float target) {
return !heatingSetpointWriteTime ||
millis() - heatingSetpointWriteTime > heatingSetpointWriteInterval ||
isFloatDifferent(target, vars.slave.heating.targetTemp, 0.05f);
return !heatingSetpointWriteTime
|| millis() - heatingSetpointWriteTime > heatingSetpointWriteInterval
|| isFloatDifferent(target, vars.slave.heating.targetTemp, 0.05f);
}
static bool needWriteCh2Setpoint(const float target) {
return !ch2SetpointWriteTime ||
millis() - ch2SetpointWriteTime > ch2SetpointWriteInterval ||
isFloatDifferent(target, vars.slave.ch2.targetTemp, 0.05f);
return !ch2SetpointWriteTime
|| millis() - ch2SetpointWriteTime > ch2SetpointWriteInterval
|| isFloatDifferent(target, vars.slave.ch2.targetTemp, 0.05f);
}
// ONCE identification steps keep their own callbacks and completion handling.
@@ -142,7 +143,9 @@ static Task writeMasterVersionTask("Write master version", Task::Type::ONCE, [](
);
const auto response = slave.sendRequest(request);
if (!response.isSuccess() || response.getVersion() != request.getVersion() || response.getProductType() != request.getProductType()) {
if (!response.isSuccess() ||
response.getVersion() != request.getVersion() ||
response.getProductType() != request.getProductType()) {
ESP_LOGW(L_OT, "Failed set master version");
return;
}
@@ -240,64 +243,6 @@ static Task initializeSlaveTask("Initialize slave", [](void*) {
initializedTime = millis();
});
static void onDisconnectSlave() {
if (vars.slave.connected) {
ESP_LOGW(
L_OT,
"Disconnected, uptime: %lu s.",
(millis() - connectedTime) / 1000
);
// Mark sensors as disconnected
Sensors::setConnectionStatusByType(Sensors::Type::OT_OUTDOOR_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_HEATING_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_HEATING_RETURN_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_TEMP2, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_FLOW_RATE, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_CH2_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_EXHAUST_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_HEAT_EXCHANGER_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_PRESSURE, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_MODULATION_LEVEL, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_CURRENT_POWER, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_EXHAUST_CO2, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_EXHAUST_FAN_SPEED, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_SUPPLY_FAN_SPEED, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_SOLAR_STORAGE_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_SOLAR_COLLECTOR_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_FAN_SPEED_SETPOINT, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_FAN_SPEED_CURRENT, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_BURNER_STARTS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_BURNER_STARTS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_HEATING_PUMP_STARTS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_PUMP_STARTS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_BURNER_HOURS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_BURNER_HOURS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_HEATING_PUMP_HOURS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_PUMP_HOURS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_COOLING_HOURS, false);
initializeSlaveTask.resume();
disconnectedTime = millis();
vars.slave.connected = false;
}
vars.slave.heating.enabled = false;
vars.slave.heating.active = false;
vars.slave.dhw.enabled = false;
vars.slave.dhw.active = false;
vars.slave.ch2.active = false;
vars.slave.flame = false;
vars.slave.cooling.active = false;
vars.slave.cooling.setpoint = 0;
vars.slave.fault.active = false;
vars.slave.fault.code = 0;
vars.slave.diag.active = false;
vars.slave.diag.code = 0;
}
static bool isSlaveReady() {
return canUseBus() && vars.slave.connected && !initializeSlaveTask.scheduled();
}
@@ -309,25 +254,22 @@ static bool isInitializingSlave() {
static void updateMasterState() {
// Heating settings
vars.master.heating.enabled =
isMasterReady() &&
settings.heating.enabled &&
(vars.master.heating.freezing || (vars.cascadeControl.input && !vars.master.heating.blocking)) &&
!vars.master.heating.overheat;
vars.master.heating.enabled = isMasterReady()
&& settings.heating.enabled
&& (vars.master.heating.freezing || (vars.cascadeControl.input && !vars.master.heating.blocking))
&& !vars.master.heating.overheat;
// DHW settings
vars.master.dhw.enabled =
isMasterReady() &&
settings.opentherm.options.dhwSupport &&
settings.dhw.enabled &&
!vars.master.dhw.overheat;
vars.master.dhw.enabled = isMasterReady()
&& settings.opentherm.options.dhwSupport
&& settings.dhw.enabled
&& !vars.master.dhw.overheat;
vars.master.dhw.targetTemp = settings.dhw.target;
// CH2 settings
vars.master.ch2.enabled =
settings.opentherm.options.ch2AlwaysEnabled ||
(settings.opentherm.options.heatingToCh2 && vars.master.heating.enabled) ||
(settings.opentherm.options.dhwToCh2 && vars.master.dhw.enabled);
vars.master.ch2.enabled = settings.opentherm.options.ch2AlwaysEnabled
|| (settings.opentherm.options.heatingToCh2 && vars.master.heating.enabled)
|| (settings.opentherm.options.dhwToCh2 && vars.master.dhw.enabled);
if (settings.opentherm.options.heatingToCh2) {
vars.master.ch2.targetTemp = !settings.opentherm.options.nativeOTC
@@ -358,8 +300,6 @@ static Task configureDriverTask("Configure OpenTherm driver", Task::Type::ONCE,
return;
}
onDisconnectSlave();
if (!GPIO_IS_VALID_INPUT(settings.opentherm.inGpio) || !GPIO_IS_VALID_OUTPUT(settings.opentherm.outGpio)) {
ESP_LOGW(
L_OT,
@@ -429,7 +369,8 @@ static Task configureDriverTask("Configure OpenTherm driver", Task::Type::ONCE,
});
static Task maintainOpenThermTask("Maintain OpenTherm", [](void*) {
if (slave.getConfig().rxGpio != settings.opentherm.inGpio || slave.getConfig().txGpio != settings.opentherm.outGpio) {
if (slave.getConfig().rxGpio != settings.opentherm.inGpio ||
slave.getConfig().txGpio != settings.opentherm.outGpio) {
// Apply changed GPIO before any bus exchange in this manager pass.
configureDriverTask.resume().tryRun();
@@ -442,17 +383,13 @@ static Task maintainOpenThermTask("Maintain OpenTherm", [](void*) {
initializeSlaveTask.resume();
}
// Apply channel settings even while the bus is unavailable.
updateMasterState();
if (slave.getConfig().rxGpio != settings.opentherm.inGpio || slave.getConfig().txGpio != settings.opentherm.outGpio) {
if (slave.getConfig().rxGpio != settings.opentherm.inGpio ||
slave.getConfig().txGpio != settings.opentherm.outGpio) {
maintainOpenThermTask.setInterval(5000);
return;
} else if (!slave.isInitialized()) {
// A fatal error can leave the RMT worker alive until end() succeeds.
onDisconnectSlave();
if (!slave.end() || !slave.begin()) {
ESP_LOGW(L_OT, "Failed begin");
@@ -478,6 +415,8 @@ static Task maintainOpenThermTask("Maintain OpenTherm", [](void*) {
configuredRxLedGpio.store(settings.opentherm.rxLedGpio);
}
}
updateMasterState();
});
static Task readStatusTask("Read boiler status", [](void*) {
@@ -513,8 +452,8 @@ static Task readStatusTask("Read boiler status", [](void*) {
vars.master.heating.enabled, settings.opentherm.heatingDisablingAction
))
.setHotWaterEnabled(
settings.opentherm.options.dhwSupport
&& getSlaveChannelEnabled(vars.master.dhw.enabled, settings.opentherm.dhwDisablingAction)
settings.opentherm.options.dhwSupport &&
getSlaveChannelEnabled(vars.master.dhw.enabled, settings.opentherm.dhwDisablingAction)
)
.setCoolingEnabled(settings.opentherm.options.coolingSupport)
.setOutsideTemperatureCompensationEnabled(settings.opentherm.options.nativeOTC)
@@ -564,6 +503,11 @@ static Task readStatusTask("Read boiler status", [](void*) {
);
}
// 5 request retries
// 1000ms maximum response waiting time
// 100ms delay between requests
// +15%
// 5 * (1000 + 100) * 1.15 = 6325 ms
if (!vars.slave.connected && validStatus) {
ESP_LOGI(
L_OT,
@@ -573,19 +517,64 @@ static Task readStatusTask("Read boiler status", [](void*) {
connectedTime = millis();
vars.slave.connected = true;
}
// 5 request retries
// 1000ms maximum response waiting time
// 100ms delay between requests
// +15%
// 5 * (1000 + 100) * 1.15 = 6325 ms
if (vars.slave.connected && !validStatus && millis() - lastSuccessStatusResponse > 6325) {
onDisconnectSlave();
} else if (vars.slave.connected && !validStatus && millis() - lastSuccessStatusResponse > 6325) {
ESP_LOGW(
L_OT,
"Disconnected, uptime: %lu s.",
(millis() - connectedTime) / 1000
);
// Mark sensors as disconnected
Sensors::setConnectionStatusByType(Sensors::Type::OT_OUTDOOR_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_HEATING_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_HEATING_RETURN_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_TEMP2, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_FLOW_RATE, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_CH2_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_EXHAUST_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_HEAT_EXCHANGER_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_PRESSURE, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_MODULATION_LEVEL, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_CURRENT_POWER, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_EXHAUST_CO2, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_EXHAUST_FAN_SPEED, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_SUPPLY_FAN_SPEED, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_SOLAR_STORAGE_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_SOLAR_COLLECTOR_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_FAN_SPEED_SETPOINT, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_FAN_SPEED_CURRENT, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_BURNER_STARTS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_BURNER_STARTS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_HEATING_PUMP_STARTS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_PUMP_STARTS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_BURNER_HOURS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_BURNER_HOURS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_HEATING_PUMP_HOURS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_PUMP_HOURS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_COOLING_HOURS, false);
initializeSlaveTask.resume();
disconnectedTime = millis();
vars.slave.connected = false;
}
// If boiler is disconnected, no need try setting other OT stuff
if (!vars.slave.connected) {
vars.slave.heating.enabled = false;
vars.slave.heating.active = false;
vars.slave.dhw.enabled = false;
vars.slave.dhw.active = false;
vars.slave.flame = false;
vars.slave.cooling.active = false;
vars.slave.cooling.setpoint = 0;
vars.slave.fault.active = false;
vars.slave.fault.code = 0;
vars.slave.diag.active = false;
vars.slave.diag.code = 0;
// reset bus
if (millis() - disconnectedTime > resetBusInterval) {
if (millis() - resetBusTime > resetBusInterval) {
@@ -896,7 +885,9 @@ static Task writeFaultResetTask("Write fault reset", [](void*) {
// Diag reset action
static Task writeDiagnosticResetTask("Write diagnostic reset", [](void*) {
const auto response = slave.sendRequest(ESP32OT::Messages::RemoteRequest(10));
if (!response.isSuccess() || response.getRequestCode() != 10 || response.getResponseCode() < 128) {
if (!response.isSuccess() ||
response.getRequestCode() != 10 ||
response.getResponseCode() < 128) {
ESP_LOGE(L_OT, "Boiler diagnostic reset failed");
return;
}
@@ -1927,9 +1918,9 @@ void initOpenTherm() {
// Write the DHW temperature setpoint.
writeDhwSetpointTask.setInterval(750)
.setEnabledWhen([] {
return isSlaveReady() &&
settings.opentherm.options.dhwSupport &&
needWriteDhwSetpoint(getDhwChannelSetpoint());
return isSlaveReady()
&& settings.opentherm.options.dhwSupport
&& needWriteDhwSetpoint(getDhwChannelSetpoint());
})
.onDone(onOperationDone);
openthermTaskManager.addTask(writeDhwSetpointTask);
@@ -1937,20 +1928,10 @@ void initOpenTherm() {
// Write the CH2 water temperature setpoint.
writeCh2SetpointTask.setInterval(750)
.setEnabledWhen([] {
if (!isSlaveReady()) {
return false;
}
if (settings.opentherm.options.heatingToCh2 || settings.opentherm.options.dhwToCh2) {
return needWriteCh2Setpoint(getCh2ChannelSetpoint());
}
// Without mirroring, only write the setpoint to disable CH2.
if (!vars.master.ch2.enabled && settings.opentherm.ch2DisablingAction != ChannelDisablingAction::OFF) {
return needWriteCh2Setpoint(getCh2ChannelSetpoint());
}
return false;
return isSlaveReady()
&& (settings.opentherm.options.heatingToCh2 || settings.opentherm.options.dhwToCh2
|| (!vars.master.ch2.enabled && settings.opentherm.ch2DisablingAction != ChannelDisablingAction::OFF))
&& needWriteCh2Setpoint(getCh2ChannelSetpoint());
})
.onDone(onOperationDone);
openthermTaskManager.addTask(writeCh2SetpointTask);
@@ -1958,9 +1939,9 @@ void initOpenTherm() {
// Write the heating room setpoint for native OTC.
writeRoomSetpointTask.setInterval(750)
.setEnabledWhen([] {
return isSlaveReady() &&
settings.opentherm.options.nativeOTC &&
needWriteRoomSetpoint(vars.master.heating.targetTemp);
return isSlaveReady()
&& settings.opentherm.options.nativeOTC
&& needWriteRoomSetpoint(vars.master.heating.targetTemp);
})
.onDone(onOperationDone);
openthermTaskManager.addTask(writeRoomSetpointTask);
@@ -1968,10 +1949,9 @@ void initOpenTherm() {
// Write the mirrored CH2 room setpoint for native OTC.
writeRoomSetpointCh2Task.setInterval(750)
.setEnabledWhen([] {
return isSlaveReady() &&
settings.opentherm.options.nativeOTC &&
settings.opentherm.options.heatingToCh2 &&
needWriteRoomSetpointCh2(vars.master.heating.targetTemp);
return isSlaveReady()
&& settings.opentherm.options.nativeOTC && settings.opentherm.options.heatingToCh2
&& needWriteRoomSetpointCh2(vars.master.heating.targetTemp);
})
.onDone(onOperationDone);
openthermTaskManager.addTask(writeRoomSetpointCh2Task);
@@ -1993,8 +1973,9 @@ void initOpenTherm() {
// Execute pending boiler fault reset requests.
writeFaultResetTask.setInterval(750)
.setEnabledWhen([] {
return isSlaveReady() && vars.slave.fault.active &&
(vars.actions.resetFault || settings.opentherm.options.autoFaultReset);
return isSlaveReady() && vars.slave.fault.active && (
vars.actions.resetFault || settings.opentherm.options.autoFaultReset
);
})
.onDone([](const Task& task, uint32_t elapsed) {
vars.actions.resetFault = false;
@@ -2005,8 +1986,9 @@ void initOpenTherm() {
// Execute pending service reset requests.
writeDiagnosticResetTask.setInterval(750)
.setEnabledWhen([] {
return isSlaveReady() && vars.slave.diag.active &&
(vars.actions.resetDiagnostic || settings.opentherm.options.autoDiagReset);
return isSlaveReady() && vars.slave.diag.active && (
vars.actions.resetDiagnostic || settings.opentherm.options.autoDiagReset
);
})
.onDone([](const Task& task, uint32_t elapsed) {
vars.actions.resetDiagnostic = false;
@@ -2017,8 +1999,9 @@ void initOpenTherm() {
// Send the current indoor temperature.
writeRoomTemperatureTask.setInterval(60000)
.setEnabledWhen([] {
return isSlaveReady() &&
(settings.opentherm.options.nativeOTC || settings.opentherm.options.alwaysSendIndoorTemp);
return isSlaveReady() && (
settings.opentherm.options.nativeOTC || settings.opentherm.options.alwaysSendIndoorTemp
);
})
.onDone([](const Task& task, uint32_t elapsed) {
writeRoomTemperatureTask.setInterval(60000);
@@ -2029,9 +2012,9 @@ void initOpenTherm() {
// Send the current indoor temperature to CH2.
writeRoomTemperatureCh2Task.setInterval(60000)
.setEnabledWhen([] {
return isSlaveReady() &&
(settings.opentherm.options.nativeOTC || settings.opentherm.options.alwaysSendIndoorTemp) &&
settings.opentherm.options.heatingToCh2;
return isSlaveReady() && (
settings.opentherm.options.nativeOTC || settings.opentherm.options.alwaysSendIndoorTemp
) && settings.opentherm.options.heatingToCh2;
})
.onDone([](const Task& task, uint32_t elapsed) {
writeRoomTemperatureCh2Task.setInterval(60000);
@@ -2042,9 +2025,10 @@ void initOpenTherm() {
// Read relative modulation and calculate current power.
readModulationTask.setInterval(15000)
.setEnabledWhen([] {
return isSlaveReady() &&
(Sensors::getAmountByType(Sensors::Type::OT_MODULATION_LEVEL, true) ||
Sensors::getAmountByType(Sensors::Type::OT_CURRENT_POWER, true));
return isSlaveReady() && (
Sensors::getAmountByType(Sensors::Type::OT_MODULATION_LEVEL, true) ||
Sensors::getAmountByType(Sensors::Type::OT_CURRENT_POWER, true)
);
})
.onDone(onOperationDone);
openthermTaskManager.addTask(readModulationTask);
@@ -2052,9 +2036,9 @@ void initOpenTherm() {
// Read the primary DHW temperature.
readDhwTemperatureTask.setInterval(5000)
.setEnabledWhen([] {
return isSlaveReady() &&
settings.opentherm.options.dhwSupport &&
Sensors::getAmountByType(Sensors::Type::OT_DHW_TEMP, true);
return isSlaveReady()
&& settings.opentherm.options.dhwSupport
&& Sensors::getAmountByType(Sensors::Type::OT_DHW_TEMP, true);
})
.onDone(onOperationDone);
openthermTaskManager.addTask(readDhwTemperatureTask);
@@ -2062,9 +2046,9 @@ void initOpenTherm() {
// Read the second DHW temperature.
readDhwTemperature2Task.setInterval(5000)
.setEnabledWhen([] {
return isSlaveReady() &&
settings.opentherm.options.dhwSupport &&
Sensors::getAmountByType(Sensors::Type::OT_DHW_TEMP2, true);
return isSlaveReady()
&& settings.opentherm.options.dhwSupport
&& Sensors::getAmountByType(Sensors::Type::OT_DHW_TEMP2, true);
})
.onDone(onOperationDone);
openthermTaskManager.addTask(readDhwTemperature2Task);
@@ -2072,9 +2056,9 @@ void initOpenTherm() {
// Read the DHW flow rate.
readDhwFlowTask.setInterval(5000)
.setEnabledWhen([] {
return isSlaveReady() &&
settings.opentherm.options.dhwSupport &&
Sensors::getAmountByType(Sensors::Type::OT_DHW_FLOW_RATE, true);
return isSlaveReady()
&& settings.opentherm.options.dhwSupport
&& Sensors::getAmountByType(Sensors::Type::OT_DHW_FLOW_RATE, true);
})
.onDone(onOperationDone);
openthermTaskManager.addTask(readDhwFlowTask);
@@ -2098,9 +2082,9 @@ void initOpenTherm() {
// Read the CH2 water temperature.
readCh2TemperatureTask.setInterval(5000)
.setEnabledWhen([] {
return isSlaveReady() &&
Sensors::getAmountByType(Sensors::Type::OT_CH2_TEMP, true) &&
vars.master.ch2.enabled && !settings.opentherm.options.nativeOTC;
return isSlaveReady()
&& Sensors::getAmountByType(Sensors::Type::OT_CH2_TEMP, true)
&& vars.master.ch2.enabled && !settings.opentherm.options.nativeOTC;
})
.onDone(onOperationDone);
openthermTaskManager.addTask(readCh2TemperatureTask);
@@ -2148,9 +2132,10 @@ void initOpenTherm() {
// Read the requested and actual relative fan speeds.
readFanSpeedTask.setInterval(5000)
.setEnabledWhen([] {
return isSlaveReady() &&
(Sensors::getAmountByType(Sensors::Type::OT_FAN_SPEED_SETPOINT, true) ||
Sensors::getAmountByType(Sensors::Type::OT_FAN_SPEED_CURRENT, true));
return isSlaveReady() && (
Sensors::getAmountByType(Sensors::Type::OT_FAN_SPEED_SETPOINT, true) ||
Sensors::getAmountByType(Sensors::Type::OT_FAN_SPEED_CURRENT, true)
);
})
.onDone(onOperationDone);
openthermTaskManager.addTask(readFanSpeedTask);
@@ -2240,7 +2225,9 @@ void initOpenTherm() {
// Read or clear the diagnostic code.
readDiagnosticTask.setInterval(60000)
.setEnabledWhen([] {
return isSlaveReady() && (vars.slave.diag.active || vars.slave.fault.active);
return isSlaveReady() && (
vars.slave.diag.active || vars.slave.fault.active
);
})
.onDone(onOperationDone);
openthermTaskManager.addTask(readDiagnosticTask);
+33 -79
View File
@@ -13,9 +13,6 @@
#include <Update.h>
#include <UpgradeHandler.h>
#include <WiFi.h>
#if USE_ETHERNET
#include <ETH.h>
#endif
#include <MycilaWebSerial.h>
#include <esp_core_dump.h>
@@ -50,16 +47,8 @@ static RequestInterface getRequestInterface(AsyncWebServerRequest* request) {
const IPAddress apIP = WiFi.AP.localIP();
const IPAddress staIP = WiFi.STA.localIP();
const bool matchesAp = localIP == apIP;
const bool matchesSta = localIP == staIP;
#if USE_ETHERNET
const bool matchesEth = localIP == ETH.localIP();
#else
const bool matchesEth = false;
#endif
if (matchesAp + matchesSta + matchesEth > 1) {
// Matching interface addresses cannot identify the connection.
if (localIP == apIP && localIP == staIP) {
// Matching AP/STA addresses cannot identify the interface.
return RequestInterface::UNKNOWN;
}
@@ -71,10 +60,6 @@ static RequestInterface getRequestInterface(AsyncWebServerRequest* request) {
return RequestInterface::STA;
}
if (matchesEth) {
return RequestInterface::ETH;
}
return RequestInterface::UNKNOWN;
}
@@ -388,9 +373,6 @@ static void restApi() {
auto *response = new AsyncJsonResponse();
auto& doc = response->getRoot();
toJson(networkSettings, doc);
#if USE_ETHERNET
doc[S_ETHERNET][S_CONFIGURED] = isEthernetConfigured();
#endif
// send response
response->setLength();
@@ -402,7 +384,7 @@ static void restApi() {
return request->send(503);
}
if (!requestDoc.is<JsonObjectConst>() || !requestDoc.size()) {
if (requestDoc.isNull() || !requestDoc.size()) {
return request->send(400);
}
@@ -421,9 +403,6 @@ static void restApi() {
auto *response = new AsyncJsonResponse();
auto& responseDoc = response->getRoot();
toJson(networkSettings, responseDoc);
#if USE_ETHERNET
responseDoc[S_ETHERNET][S_CONFIGURED] = isEthernetConfigured();
#endif
// send response
response->setLength();
@@ -436,16 +415,10 @@ static void restApi() {
reconnectNetwork();
}
});
nsHandler.setMaxContentLength(1024);
nsHandler.setMaxContentLength(512);
nsHandler.addMiddleware(&authMiddleware);
webServer->on("/api/network/scan", HTTP_GET, [](AsyncWebServerRequest *request) {
// Ethernet mode must not start the Wi-Fi radio for a scan.
if (networkSettings.type != NetworkMode::STA) {
request->send(409);
return;
}
auto apCount = WiFi.scanComplete();
switch (apCount) {
@@ -560,14 +533,13 @@ static void restApi() {
} 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 ||
strcmp(previousMqtt.homeAssistantDiscoveryPrefix, settings.mqtt.homeAssistantDiscoveryPrefix) != 0;
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);
@@ -716,7 +688,7 @@ static void restApi() {
return request->send(503);
}
if (!requestDoc.is<JsonObjectConst>() || !requestDoc.size()) {
if (requestDoc.isNull() || !requestDoc.size()) {
return request->send(400);
}
@@ -730,42 +702,30 @@ static void restApi() {
return request->send(404);
}
Sensors::Settings previousSettings;
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);
if (Sensors::settings == nullptr || Sensors::results == nullptr) {
return request->send(404);
}
auto& sensor = Sensors::settings[*sensorId];
previousSettings = sensor;
result = fromJson(requestDoc, sensor);
if (result.changed) {
isDifferent |= previousSettings.enabled != sensor.enabled;
isDifferent |= strcmp(previousSettings.name, sensor.name) != 0;
isDifferent |= strcmp(previousSettings.slug, sensor.slug) != 0;
isDifferent |= previousSettings.purpose != sensor.purpose;
isDifferent |= previousSettings.type != sensor.type;
bool resetResult = previousSettings.enabled != sensor.enabled;
resetResult |= previousSettings.type != sensor.type;
resetResult |= previousSettings.gpio != sensor.gpio;
resetResult |= !Sensors::isEqualAddress(previousSettings.address, sensor.address);
// A different source must provide its own readings and filter baseline.
if (resetResult) {
Sensors::results[*sensorId] = {};
Sensors::results[*sensorId].updatedAt = millis();
}
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);
requestReconfigureMqttSensor(*sensorId, *previousSettings);
}
requestSaveSensorsSettings();
@@ -885,7 +845,7 @@ static void restApi() {
return request->send(503);
}
if (!requestDoc.is<JsonObjectConst>() || !requestDoc.size()) {
if (requestDoc.isNull() || !requestDoc.size()) {
return request->send(400);
}
@@ -919,28 +879,22 @@ static void restApi() {
auto *response = new AsyncJsonResponse();
auto& doc = response->getRoot();
#if USE_ETHERNET
doc[S_FEATURES][S_ETHERNET] = true;
#endif
auto docSystem = doc[S_SYSTEM].to<JsonObject>();
docSystem[S_RESET_REASON] = getResetReason();
docSystem[S_UPTIME] = millis() / 1000;
const bool isConnected = isNetworkConnected();
const bool wifiUplink = getNetworkMode() == NetworkMode::STA;
bool isConnected = isNetworkConnected();
auto docNetwork = doc[S_NETWORK].to<JsonObject>();
docNetwork[S_HOSTNAME] = networkSettings.hostname;
docNetwork[S_MAC] = getNetworkMac();
docNetwork[S_MAC] = WiFi.STA.macAddress();
docNetwork[S_CONNECTED] = isConnected;
docNetwork[S_CONNECTION_TYPE] = getNetworkConnectionType();
docNetwork[S_SSID] = wifiUplink ? WiFi.STA.SSID() : "";
docNetwork[S_SIGNAL_QUALITY] = wifiUplink ? rssiToSignalQuality(WiFi.STA.RSSI()) : 0;
docNetwork[S_CHANNEL] = wifiUplink ? WiFi.channel() : 0;
docNetwork[S_IP] = isConnected ? getNetworkIp().toString() : "";
docNetwork[S_SUBNET] = isConnected ? getNetworkSubnet().toString() : "";
docNetwork[S_GATEWAY] = isConnected ? getNetworkGateway().toString() : "";
docNetwork[S_DNS] = isConnected ? getNetworkDns().toString() : "";
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;
+10 -12
View File
@@ -64,9 +64,9 @@ static Task pidTask("PID", Task::Type::FOREVER, [](void*) {
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);
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;
@@ -102,9 +102,8 @@ static void turbo() {
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);
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) {
@@ -208,10 +207,9 @@ static Task regulatorTask("Regulator", [](void*) {
turbo();
hysteresis();
vars.master.heating.targetTemp = settings.heating.target;
const float setpointTemp = getHeatingSetpointTemp();
vars.master.heating.targetTemp = settings.opentherm.options.nativeOTC
? setpointTemp
: settings.heating.target;
vars.master.heating.setpointTemp = roundf(constrain(
setpointTemp,
getHeatingMinSetpointTemp(),
@@ -229,9 +227,9 @@ void initRegulator() {
// 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;
return settings.pid.enabled && settings.heating.enabled
&& !vars.emergency.state && !settings.opentherm.options.nativeOTC
&& indoorSensorsConnected;
});
pidTask.setInterval(10000);
pidTask.resume(pidTask.interval());
+28 -32
View File
@@ -13,7 +13,6 @@
#if USE_BLE
#include <NimBLEDevice.h>
#include <WiFi.h>
#endif
#if USE_BLE
@@ -349,6 +348,20 @@ 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;
@@ -423,7 +436,7 @@ static void makeDallasInstances() {
continue;
}
if (!sSensor->enabled || sSensor->type != Sensors::Type::DALLAS_TEMP || sSensor->purpose == Sensors::Purpose::NOT_CONFIGURED || !GPIO_IS_VALID_OUTPUT(sSensor->gpio)) {
if (!sSensor->enabled || sSensor->type != Sensors::Type::DALLAS_TEMP || sSensor->purpose == Sensors::Purpose::NOT_CONFIGURED) {
continue;
} else if (dallasInstances.count(sSensor->gpio)) {
@@ -557,7 +570,7 @@ static void fillingAddressesDallasSensors() {
continue;
}
if (Sensors::isEqualAddress(sCheckingSensor->address, devAddr)) {
if (isEqualAddress(sCheckingSensor->address, devAddr)) {
freeAddress = false;
break;
}
@@ -730,21 +743,6 @@ static void scanBleSensors() {
ESP_LOGI(L_SENSORS_BLE, "Scanning initialized");
}
// BLE and WiFi share the radio. Pause scanning while AP clients are connected
// to keep the portal responsive and avoid disconnects.
if (isNetworkInterfaceStarted(NetworkMode::AP) && WiFi.AP.stationCount() > 0) {
if (pBLEScan->isScanning()) {
if (!pBLEScan->stop()) {
ESP_LOGW(L_SENSORS_BLE, "Unable to stop scanning for WiFi AP");
return;
}
ESP_LOGI(L_SENSORS_BLE, "Scanning paused for AP clients");
}
return;
}
if (!pBLEScan->isScanning()) {
activeScanBle = !activeScanBle;
pBLEScan->setActiveScan(activeScanBle);
@@ -954,16 +952,18 @@ void initSensors() {
pollDhtSensorsTask.setInterval(1000)
.setEnabledWhen([] {
return canRunSensors() &&
(Sensors::getAmountByType(Sensors::Type::DHT11, true) ||
Sensors::getAmountByType(Sensors::Type::DHT22, true));
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));
return canRunSensors() && (
!dallasInstances.empty() ||
Sensors::getAmountByType(Sensors::Type::DALLAS_TEMP, true)
);
})
.resume(15000);
sensorsTaskManager.addTask(maintainDallasSensorsTask);
@@ -976,14 +976,10 @@ void initSensors() {
#if USE_BLE
scanBleSensorsTask.setEnabledWhen([] {
return canRunSensors() &&
(NimBLEDevice::isInitialized() ||
Sensors::getAmountByType(Sensors::Type::BLUETOOTH, true));
})
.onDone([](const Task&, uint32_t) {
if (scanBleSensorsTask.interval() != 1000) {
scanBleSensorsTask.setInterval(1000);
}
return canRunSensors() && (
NimBLEDevice::isInitialized() ||
Sensors::getAmountByType(Sensors::Type::BLUETOOTH, true)
);
})
.resume(15000);
sensorsTaskManager.addTask(scanBleSensorsTask);
+6 -33
View File
@@ -144,34 +144,15 @@
"network": {
"title": "网络 - OpenTherm Gateway",
"name": "网络设置",
"type": {
"title": "连接方式",
"wifi": "Wi-Fi",
"ethernet": "Ethernet"
},
"section": {
"static": "静态设置",
"ethernet": "以太网",
"wifi": "Wi-Fi",
"availableNetworks": "可用网络",
"staSettings": "WiFi 设置",
"apSettings": "AP 设置"
},
"scan": {
"pos": "#",
"info": "Info",
"unavailable": "仅在 Wi-Fi 模式下可扫描网络。"
},
"ethernet": {
"notConfigured": "配置全部六个 GPIO 引脚以使用以太网。",
"clk": "SPI 时钟 GPIO",
"mosi": "SPI MOSI GPIO",
"miso": "SPI MISO GPIO",
"cs": "SPI CS GPIO",
"irq": "中断 GPIO",
"rst": "复位 GPIO",
"note": "W5500 SPI 接线"
"info": "Info"
},
"wifi": {
"ssid": "SSID",
@@ -187,14 +168,7 @@
"ip": "IP",
"subnet": "子网掩码",
"gateway": "网关",
"dns": "DNS 服务器",
"connection": "连接",
"connectionType": {
"ethernet": "以太网",
"wifi": "WiFi",
"wifi-ap": "WiFi 接入点",
"none": "无"
}
"dns": "DNS 服务器"
},
"sta": {
"channel": {
@@ -396,7 +370,7 @@
"title": "目标温度",
"note": "<b>重要提示:</b> 若启用OpenTherm选项 <i>«原生供暖控制»</i>,此处设定值为<u>目标室内温度</u>;<br />其他所有情况下,此处设定值为 <u>目标热媒出水温度</u>."
},
"thresholdTime": "状态变化延时 <small>(秒)</small>"
"thresholdTime": "进入或退出应急模式的延时 <small>(秒)</small>"
},
"equitherm": {
"slope": {
@@ -492,8 +466,7 @@
}
},
"mqtt": {
"homeAssistantDiscovery": "HomeAssistant 自动发现",
"homeAssistantDiscoveryPrefix": "HomeAssistant 自动发现前缀",
"homeAssistantDiscovery": "Home Assistant 自动发现",
"server": "服务器地址",
"port": "端口",
"user": "用户名",
@@ -515,14 +488,14 @@
"enable": "启用 input",
"gpio": "GPIO",
"invertState": "切换 GPIO 状态",
"thresholdTime": "状态变化延时 <small>(秒)</small>"
"thresholdTime": "状态变化阈值时间<small>(秒)</small>"
},
"output": {
"desc": "可通过<u>继电器</u>控制另一台锅炉的启停。",
"enable": "启用 output",
"gpio": "GPIO",
"invertState": "切换 GPIO 状态",
"thresholdTime": "状态变化延时 <small>(秒)</small>",
"thresholdTime": "状态变化阈值时间 <small>(秒)</small>",
"events": {
"desc": "事件",
"onFault": "当故障状态激活时",
+6 -33
View File
@@ -144,34 +144,15 @@
"network": {
"title": "Network - OpenTherm Gateway",
"name": "Network settings",
"type": {
"title": "Connection method",
"wifi": "Wi-Fi",
"ethernet": "Ethernet"
},
"section": {
"static": "Static settings",
"ethernet": "Ethernet",
"wifi": "Wi-Fi",
"availableNetworks": "Available networks",
"staSettings": "WiFi settings",
"apSettings": "AP settings"
},
"scan": {
"pos": "#",
"info": "Info",
"unavailable": "Network scanning is available only in Wi-Fi mode."
},
"ethernet": {
"notConfigured": "Configure all six GPIOs to use Ethernet.",
"clk": "SPI clock GPIO",
"mosi": "SPI MOSI GPIO",
"miso": "SPI MISO GPIO",
"cs": "SPI CS GPIO",
"irq": "Interrupt GPIO",
"rst": "Reset GPIO",
"note": "W5500 SPI wiring"
"info": "Info"
},
"wifi": {
"ssid": "SSID",
@@ -187,14 +168,7 @@
"ip": "IP",
"subnet": "Subnet",
"gateway": "Gateway",
"dns": "DNS",
"connection": "Connection",
"connectionType": {
"ethernet": "Ethernet",
"wifi": "WiFi",
"wifi-ap": "WiFi AP",
"none": "None"
}
"dns": "DNS"
},
"sta": {
"channel": {
@@ -396,7 +370,7 @@
"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": "State change delay <small>(sec)</small>"
"thresholdTime": "Delay before entering or leaving emergency mode <small>(sec)</small>"
},
"equitherm": {
"slope": {
@@ -492,8 +466,7 @@
}
},
"mqtt": {
"homeAssistantDiscovery": "HomeAssistant Discovery",
"homeAssistantDiscoveryPrefix": "HomeAssistant discovery prefix",
"homeAssistantDiscovery": "Home Assistant Discovery",
"server": "Server",
"port": "Port",
"user": "User",
@@ -515,14 +488,14 @@
"enable": "Enabled input",
"gpio": "GPIO",
"invertState": "Invert GPIO state",
"thresholdTime": "State change delay <small>(sec)</small>"
"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 delay <small>(sec)</small>",
"thresholdTime": "State change threshold time <small>(sec)</small>",
"events": {
"desc": "Events",
"onFault": "If the fault state is active",
+6 -33
View File
@@ -144,34 +144,15 @@
"network": {
"title": "Rete - OpenTherm Gateway",
"name": "Impostazioni rete",
"type": {
"title": "Metodo di connessione",
"wifi": "Wi-Fi",
"ethernet": "Ethernet"
},
"section": {
"static": "Impostazioni statico",
"ethernet": "Ethernet",
"wifi": "Wi-Fi",
"availableNetworks": "Reti disponibili",
"staSettings": "Impostazioni WiFi",
"apSettings": "Impostazioni AP"
},
"scan": {
"pos": "#",
"info": "Info",
"unavailable": "La ricerca delle reti è disponibile solo in modalità Wi-Fi."
},
"ethernet": {
"notConfigured": "Configura tutti e sei i GPIO per utilizzare Ethernet.",
"clk": "GPIO clock SPI",
"mosi": "GPIO MOSI SPI",
"miso": "GPIO MISO SPI",
"cs": "GPIO CS SPI",
"irq": "GPIO interrupt",
"rst": "GPIO reset",
"note": "Cablaggio SPI del W5500"
"info": "Info"
},
"wifi": {
"ssid": "SSID",
@@ -187,14 +168,7 @@
"ip": "IP",
"subnet": "Subnet",
"gateway": "Gateway",
"dns": "DNS",
"connection": "Connessione",
"connectionType": {
"ethernet": "Ethernet",
"wifi": "WiFi",
"wifi-ap": "WiFi AP",
"none": "Nessuno"
}
"dns": "DNS"
},
"sta": {
"channel": {
@@ -396,7 +370,7 @@
"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 del cambio di stato <small>(sec)</small>"
"thresholdTime": "Ritardo di entrata e uscita dalla modalità di emergenza <small>(sec)</small>"
},
"equitherm": {
"slope": {
@@ -492,8 +466,7 @@
}
},
"mqtt": {
"homeAssistantDiscovery": "HomeAssistant Discovery",
"homeAssistantDiscoveryPrefix": "Prefisso discovery di HomeAssistant",
"homeAssistantDiscovery": "Home Assistant Discovery",
"server": "Server",
"port": "Porta",
"user": "Utente",
@@ -515,14 +488,14 @@
"enable": "Ingresso abilitato",
"gpio": "GPIO",
"invertState": "Inverti stato GPIO",
"thresholdTime": "Ritardo del cambio di stato <small>(sec)</small>"
"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": "Ritardo del cambio di stato <small>(sec)</small>",
"thresholdTime": "Tempo soglia di modifica dello stato <small>(sec)</small>",
"events": {
"desc": "Eventi",
"onFault": "Se lo stato di errore è attivo",
+6 -33
View File
@@ -144,34 +144,15 @@
"network": {
"title": "Netwerk - OpenTherm Gateway",
"name": "Netwerkinstellingen",
"type": {
"title": "Verbindingsmethode",
"wifi": "Wi-Fi",
"ethernet": "Ethernet"
},
"section": {
"static": "Statische instellingen",
"ethernet": "Ethernet",
"wifi": "Wi-Fi",
"availableNetworks": "Beschikbare netwerken",
"staSettings": "WiFi-instellingen",
"apSettings": "AP-instellingen"
},
"scan": {
"pos": "#",
"info": "Info",
"unavailable": "Netwerken zoeken is alleen beschikbaar in de Wi-Fi-modus."
},
"ethernet": {
"notConfigured": "Configureer alle zes GPIO's om Ethernet te gebruiken.",
"clk": "SPI-klok GPIO",
"mosi": "SPI MOSI GPIO",
"miso": "SPI MISO GPIO",
"cs": "SPI CS GPIO",
"irq": "Interrupt GPIO",
"rst": "Reset GPIO",
"note": "W5500 SPI-bedrading"
"info": "Info"
},
"wifi": {
"ssid": "SSID",
@@ -187,14 +168,7 @@
"ip": "IP",
"subnet": "Subnet",
"gateway": "Gateway",
"dns": "DNS",
"connection": "Verbinding",
"connectionType": {
"ethernet": "Ethernet",
"wifi": "WiFi",
"wifi-ap": "WiFi AP",
"none": "Geen"
}
"dns": "DNS"
},
"sta": {
"channel": {
@@ -396,7 +370,7 @@
"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 statuswijziging <small>(sec)</small>"
"thresholdTime": "Vertraging bij in- en uitschakelen van de noodmodus <small>(sec)</small>"
},
"equitherm": {
"slope": {
@@ -492,8 +466,7 @@
}
},
"mqtt": {
"homeAssistantDiscovery": "HomeAssistant Discovery",
"homeAssistantDiscoveryPrefix": "Prefix voor HomeAssistant Discovery",
"homeAssistantDiscovery": "Home Assistant Discovery",
"server": "Server",
"port": "Poort",
"user": "Gebruiker",
@@ -515,14 +488,14 @@
"enable": "Ingang ingeschakeld",
"gpio": "GPIO",
"invertState": "Inverteer GPIO-status",
"thresholdTime": "Vertraging bij statuswijziging <small>(sec)</small>"
"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": "Vertraging bij statuswijziging <small>(sec)</small>",
"thresholdTime": "Drempeltijd statuswijziging <small>(sec)</small>",
"events": {
"desc": "Gebeurtenissen",
"onFault": "Als de storingsstatus actief is",
+6 -33
View File
@@ -144,34 +144,15 @@
"network": {
"title": "Сеть - OpenTherm Gateway",
"name": "Настройки сети",
"type": {
"title": "Способ подключения",
"wifi": "Wi-Fi",
"ethernet": "Ethernet"
},
"section": {
"static": "Статические параметры",
"ethernet": "Ethernet",
"wifi": "Wi-Fi",
"availableNetworks": "Доступные сети",
"staSettings": "Настройки подключения",
"apSettings": "Настройки точки доступа"
},
"scan": {
"pos": "#",
"info": "Инфо",
"unavailable": "Поиск сетей доступен только в режиме Wi-Fi."
},
"ethernet": {
"notConfigured": "Для подключения через Ethernet настройте все шесть GPIO.",
"clk": "GPIO тактирования SPI",
"mosi": "GPIO MOSI SPI",
"miso": "GPIO MISO SPI",
"cs": "GPIO CS SPI",
"irq": "GPIO прерывания",
"rst": "GPIO сброса",
"note": "Подключение W5500 по SPI"
"info": "Инфо"
},
"wifi": {
"ssid": "Имя сети",
@@ -187,14 +168,7 @@
"ip": "IP адрес",
"subnet": "Адрес подсети",
"gateway": "Адрес шлюза",
"dns": "DNS адрес",
"connection": "Подключение",
"connectionType": {
"ethernet": "Ethernet",
"wifi": "WiFi",
"wifi-ap": "WiFi AP",
"none": "Нет"
}
"dns": "DNS адрес"
},
"sta": {
"channel": {
@@ -396,7 +370,7 @@
"title": "Целевая температура",
"note": "<b>Важно:</b> <u>Целевая температура в помещении</u>, если включена ОТ опция <i>«Передать управление отоплением котлу»</i>.<br />Во всех остальных случаях <u>целевая температура теплоносителя</u>."
},
"thresholdTime": "Задержка изменения состояния <small>(сек)</small>"
"thresholdTime": "Задержка входа в аварийный режим и выхода из него <small>(сек)</small>"
},
"equitherm": {
"slope": {
@@ -492,8 +466,7 @@
}
},
"mqtt": {
"homeAssistantDiscovery": "Home AssistantDiscovery",
"homeAssistantDiscoveryPrefix": "HomeAssistant Discovery префикс",
"homeAssistantDiscovery": "Home Assistant Discovery",
"server": "Адрес сервера",
"port": "Порт",
"user": "Имя пользователя",
@@ -515,14 +488,14 @@
"enable": "Включить вход",
"gpio": "GPIO",
"invertState": "Инвертировать состояние GPIO",
"thresholdTime": "Задержка изменения состояния <small>(сек)</small>"
"thresholdTime": "Пороговое время изменения состояния <small>(сек)</small>"
},
"output": {
"desc": "Может использоваться для включения другого котла <u>через реле</u>.",
"enable": "Включить выход",
"gpio": "GPIO",
"invertState": "Инвертировать состояние GPIO",
"thresholdTime": "Задержка изменения состояния <small>(сек)</small>",
"thresholdTime": "Пороговое время изменения состояния <small>(сек)</small>",
"events": {
"desc": "События",
"onFault": "Если состояние fault (ошибки) активно",
+2 -12
View File
@@ -50,19 +50,15 @@
<th scope="row" data-i18n>network.params.mac</th>
<td><b id="network-mac"></b></td>
</tr>
<tr>
<th scope="row" data-i18n>network.params.connection</th>
<td><b id="network-connection"></b></td>
</tr>
<tr>
<th scope="row" data-i18n>network.wifi.connected</th>
<td><i id="network-connected"></i></td>
</tr>
<tr id="network-ssid-row">
<tr>
<th scope="row" data-i18n>network.wifi.ssid</th>
<td><b id="network-ssid"></b></td>
</tr>
<tr id="network-signal-row">
<tr>
<th scope="row" data-i18n>network.wifi.signal</th>
<td><b id="network-signal"></b> %</td>
</tr>
@@ -243,7 +239,6 @@
setTextValue('#network-hostname', result.network.hostname);
setTextValue('#network-mac', result.network.mac);
setTextValue('#network-connection', i18n(`network.params.connectionType.${result.network.connection_type}`));
setStatus(
'#network-connected',
result.network.connected ? "success" : "error",
@@ -251,11 +246,6 @@
);
setTextValue('#network-ssid', result.network.ssid);
setValue('#network-signal', result.network.signal_quality);
// SSID and signal strength describe only the Wi-Fi uplink.
const wifiUplink = result.network.connection_type === "wifi";
document.getElementById("network-ssid-row")?.classList.toggle("hidden", !wifiUplink);
document.getElementById("network-signal-row")?.classList.toggle("hidden", !wifiUplink);
setTextValue('#network-ip', result.network.ip);
setTextValue('#network-subnet', result.network.subnet);
setTextValue('#network-gateway', result.network.gateway);
+27 -148
View File
@@ -46,14 +46,6 @@
<input type="text" name="hostname" maxlength="24" pattern="[A-Za-z0-9]+[A-Za-z0-9\-]+[A-Za-z0-9]+" required>
</label>
<label>
<span data-i18n>network.type.title</span>
<select name="type">
<option value="2" data-i18n>network.type.wifi</option>
<option value="3" hidden disabled data-i18n>network.type.ethernet</option>
</select>
</label>
<label>
<input type="checkbox" name="use_dhcp" value="true">
<span data-i18n>network.params.dhcp</span>
@@ -64,7 +56,7 @@
<label>
<span data-i18n>network.params.ip</span>
<input type="text" name="static_config[ip]" maxlength="16" pattern="\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" required>
<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>
@@ -87,21 +79,14 @@
</div>
</article>
<article id="wifi-section">
<article>
<div>
<hgroup>
<h2 data-i18n>network.section.wifi</h2>
<p></p>
</hgroup>
<hgroup>
<h3 data-i18n>network.section.availableNetworks</h3>
<p></p>
</hgroup>
<form action="/api/network/scan" id="network-scan">
<fieldset id="wifi-scan-controls" disabled>
<div style="max-height: 25rem;" class="overflow-auto">
<table id="networks" role="grid">
<thead>
@@ -115,15 +100,13 @@
</table>
</div>
<p id="scan-unavailable" class="hidden" data-i18n>network.scan.unavailable</p>
<button type="submit" data-i18n>button.refresh</button>
</fieldset>
</form>
<hr />
<div>
<hgroup>
<h3 data-i18n>network.section.staSettings</h3>
<h2 data-i18n>network.section.staSettings</h2>
<p></p>
</hgroup>
@@ -131,100 +114,49 @@
<form action="/api/network/settings" id="sta-settings" class="hidden">
<label>
<span data-i18n>network.wifi.ssid</span>
<input type="text" name="wifi[sta][ssid]" maxlength="32" required>
<input type="text" name="sta[ssid]" maxlength="32" required>
</label>
<label>
<span data-i18n>network.wifi.password</span>
<input type="password" name="wifi[sta][password]" maxlength="64" required>
<input type="password" name="sta[password]" maxlength="64" required>
</label>
<label>
<span data-i18n>network.wifi.channel</span>
<input type="number" inputmode="numeric" name="wifi[sta][channel]" min="0" max="12" step="1" required>
<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>
<hr />
<div>
<hgroup>
<h3 data-i18n>network.section.apSettings</h3>
<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="wifi[ap][ssid]" maxlength="32" required>
</label>
<label>
<span data-i18n>network.wifi.password</span>
<input type="text" name="wifi[ap][password]" maxlength="64" required>
</label>
<label>
<span data-i18n>network.wifi.channel</span>
<input type="number" inputmode="numeric" name="wifi[ap][channel]" min="1" max="12" step="1" required>
</label>
<button type="submit" data-i18n>button.save</button>
</form>
</div>
</div>
</article>
<article id="ethernet-section" class="hidden">
<article>
<div>
<hgroup>
<h3 data-i18n>network.section.ethernet</h3>
<h2 data-i18n>network.section.apSettings</h2>
<p></p>
</hgroup>
<div id="ethernet-settings-busy" aria-busy="true"></div>
<form action="/api/network/settings" id="ethernet-settings" class="hidden">
<small id="ethernet-not-configured" class="hidden" data-i18n>network.ethernet.notConfigured</small>
<div class="grid">
<div id="ap-settings-busy" aria-busy="true"></div>
<form action="/api/network/settings" id="ap-settings" class="hidden">
<label>
<span data-i18n>network.ethernet.clk</span>
<input type="number" inputmode="numeric" name="ethernet[gpio][clk]" min="0" max="254" step="1">
<span data-i18n>network.wifi.ssid</span>
<input type="text" name="ap[ssid]" maxlength="32" required>
</label>
<label>
<span data-i18n>network.ethernet.mosi</span>
<input type="number" inputmode="numeric" name="ethernet[gpio][mosi]" min="0" max="254" step="1">
<span data-i18n>network.wifi.password</span>
<input type="text" name="ap[password]" maxlength="64" required>
</label>
<label>
<span data-i18n>network.ethernet.miso</span>
<input type="number" inputmode="numeric" name="ethernet[gpio][miso]" min="0" max="254" step="1">
<span data-i18n>network.wifi.channel</span>
<input type="number" inputmode="numeric" name="ap[channel]" min="1" max="12" step="1" required>
</label>
</div>
<div class="grid">
<label>
<span data-i18n>network.ethernet.cs</span>
<input type="number" inputmode="numeric" name="ethernet[gpio][cs]" min="0" max="254" step="1">
</label>
<label>
<span data-i18n>network.ethernet.irq</span>
<input type="number" inputmode="numeric" name="ethernet[gpio][irq]" min="0" max="254" step="1">
</label>
<label>
<span data-i18n>network.ethernet.rst</span>
<input type="number" inputmode="numeric" name="ethernet[gpio][rst]" min="0" max="254" step="1">
</label>
</div>
<small data-i18n>network.ethernet.note</small>
<button type="submit" data-i18n>button.save</button>
</form>
@@ -249,16 +181,7 @@
const lang = new Lang(document.getElementById('lang'));
await lang.build();
let networkType = 2;
const fillData = (data) => {
networkType = data.type;
setSelectValue("[name='type']", networkType);
const canScan = networkType === 2;
document.getElementById('wifi-scan-controls').disabled = !canScan;
document.querySelector('#scan-unavailable').classList.toggle('hidden', canScan);
setInputValue("[name='hostname']", data.hostname);
setCheckboxValue("[name='use_dhcp']", data.use_dhcp);
setInputValue("[name='static_config[ip]']", data.static_config.ip);
@@ -267,78 +190,34 @@
setInputValue("[name='static_config[dns]']", data.static_config.dns);
setBusy('#network-settings-busy', '#network-settings', false);
const ethernet = data.ethernet || {};
const ethernetConfigured = !!ethernet.configured;
const ethernetGpio = ethernet.gpio || {};
const gpioValue = (value) => (value ?? 255) < 255 ? value : '';
setInputValue("[name='ethernet[gpio][clk]']", gpioValue(ethernetGpio.clk));
setInputValue("[name='ethernet[gpio][mosi]']", gpioValue(ethernetGpio.mosi));
setInputValue("[name='ethernet[gpio][miso]']", gpioValue(ethernetGpio.miso));
setInputValue("[name='ethernet[gpio][cs]']", gpioValue(ethernetGpio.cs));
setInputValue("[name='ethernet[gpio][irq]']", gpioValue(ethernetGpio.irq));
setInputValue("[name='ethernet[gpio][rst]']", gpioValue(ethernetGpio.rst));
document.getElementById('ethernet-not-configured')?.classList.toggle('hidden', ethernetConfigured);
setBusy('#ethernet-settings-busy', '#ethernet-settings', false);
setInputValue("[name='wifi[sta][ssid]']", data.wifi.sta.ssid);
setInputValue("[name='wifi[sta][password]']", data.wifi.sta.password);
setInputValue("[name='wifi[sta][channel]']", data.wifi.sta.channel);
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='wifi[ap][ssid]']", data.wifi.ap.ssid);
setInputValue("[name='wifi[ap][password]']", data.wifi.ap.password);
setInputValue("[name='wifi[ap][channel]']", data.wifi.ap.channel);
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);
};
const applyCapabilities = (info) => {
// pages and firmware ship together: the section stays hidden unless the build says it can do ethernet
const supported = info?.features?.ethernet === true;
document.getElementById('ethernet-section')?.classList.toggle('hidden', !supported);
const ethernetOption = document.querySelector("[name='type'] option[value='3']");
ethernetOption.hidden = !supported;
ethernetOption.disabled = !supported;
return supported;
};
try {
const [response, infoResponse] = await Promise.all([
fetch("/api/network/settings", {
const response = await fetch("/api/network/settings", {
cache: "no-cache",
credentials: "include"
}),
fetch("/api/info", {
cache: "no-cache",
credentials: "include"
})
]);
});
if (!response.ok) {
throw new Error('Response not valid');
}
const info = infoResponse.ok ? await infoResponse.json() : null;
const ethernetSupported = applyCapabilities(info);
const result = await response.json();
fillData(result);
setupForm('#network-settings', fillData, ['hostname', 'static_config.ip', 'static_config.gateway', 'static_config.subnet', 'static_config.dns']);
// Keep scans disabled if an earlier request finishes after the connection method changes.
setupNetworkScanForm('#network-scan', '#networks', networkType === 2);
if (ethernetSupported) {
setupForm('#ethernet-settings', fillData);
}
setupForm('#sta-settings', fillData, ['wifi.sta.ssid', 'wifi.sta.password']);
setupForm('#ap-settings', fillData, ['wifi.ap.ssid', 'wifi.ap.password']);
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);
+1 -7
View File
@@ -803,11 +803,6 @@
</label>
</fieldset>
<label>
<span data-i18n>settings.mqtt.homeAssistantDiscoveryPrefix</span>
<input type="text" name="ha_discovery_prefix" maxlength="32" pattern="[^+#]+" required>
</label>
<div class="grid">
<label>
<span data-i18n>settings.mqtt.server</span>
@@ -1214,7 +1209,6 @@
} else if (section === 'mqtt') {
setCheckboxValue("[name='enabled']", data.mqtt.enabled, form);
setCheckboxValue("[name='ha_discovery']", data.mqtt.ha_discovery, form);
setInputValue("[name='ha_discovery_prefix']", data.mqtt.ha_discovery_prefix, {}, form);
setInputValue("[name='server']", data.mqtt.server, {}, form);
setInputValue("[name='port']", data.mqtt.port, {}, form);
setInputValue("[name='user']", data.mqtt.user, {}, form);
@@ -1509,7 +1503,7 @@
setupSettingsForm('#equitherm-settings');
setupSettingsForm('#pid-settings');
setupSettingsForm('#ot-settings');
setupSettingsForm('#mqtt-settings', ['server', 'user', 'password', 'prefix', 'ha_discovery_prefix']);
setupSettingsForm('#mqtt-settings', ['server', 'user', 'password', 'prefix']);
setupSettingsForm('#extpump-settings');
setupSettingsForm('#cc-settings');
-39
View File
@@ -23,7 +23,6 @@ const convertLegacyBackup = (data) => {
heatingToCh2: 'heating_to_ch2',
highTemp: 'high_temp',
homeAssistantDiscovery: 'ha_discovery',
homeAssistantDiscoveryPrefix: 'ha_discovery_prefix',
ignoreDiagState: 'ignore_diag_state',
immergasFix: 'immergas_fix',
indoorTempAvgType: 'indoor_temp_avg_type',
@@ -98,44 +97,6 @@ const convertLegacyBackup = (data) => {
const result = convert(data);
const network = result?.network;
if (network !== null && typeof network === 'object' && !Array.isArray(network)) {
const hasLegacyAp = Object.prototype.hasOwnProperty.call(network, 'ap');
const hasLegacySta = Object.prototype.hasOwnProperty.call(network, 'sta');
if (hasLegacyAp || hasLegacySta) {
const wifi = network.wifi !== null && typeof network.wifi === 'object' && !Array.isArray(network.wifi)
? network.wifi : Object.create(null);
if (hasLegacyAp && !Object.prototype.hasOwnProperty.call(wifi, 'ap')) {
wifi.ap = network.ap;
}
if (hasLegacySta && !Object.prototype.hasOwnProperty.call(wifi, 'sta')) {
wifi.sta = network.sta;
}
network.wifi = wifi;
delete network.ap;
delete network.sta;
}
if (!Object.prototype.hasOwnProperty.call(network, 'type')) {
if (typeof network.ethernet?.enabled === 'boolean') {
network.type = network.ethernet.enabled ? 3 : 2;
} else if (hasLegacyAp || hasLegacySta) {
network.type = 2;
}
}
if (network.ethernet !== null && typeof network.ethernet === 'object' && !Array.isArray(network.ethernet)) {
if (Object.prototype.hasOwnProperty.call(network.ethernet, 'pins')
&& !Object.prototype.hasOwnProperty.call(network.ethernet, 'gpio')) {
network.ethernet.gpio = network.ethernet.pins;
}
delete network.ethernet.pins;
delete network.ethernet.enabled;
}
}
const opentherm = result?.settings?.opentherm;
if (opentherm !== null && typeof opentherm === 'object') {
delete opentherm.unit_system;
+2 -4
View File
@@ -92,7 +92,7 @@ const setupForm = (formSelector, onResultCallback = null, noCastItems = []) => {
});
}
const setupNetworkScanForm = (formSelector, tableSelector, autorun = true) => {
const setupNetworkScanForm = (formSelector, tableSelector) => {
const form = document.querySelector(formSelector);
if (!form) {
console.error("form not found");
@@ -151,7 +151,7 @@ const setupNetworkScanForm = (formSelector, tableSelector, autorun = true) => {
}
nameCell.onclick = (event) => {
const input = document.querySelector("[name='wifi[sta][ssid]']");
const input = document.querySelector("[name='sta[ssid]']");
const ssid = row.dataset.ssid;
if (!input || !ssid) {
return;
@@ -261,9 +261,7 @@ const setupNetworkScanForm = (formSelector, tableSelector, autorun = true) => {
};
form.addEventListener('submit', onSubmitFn);
if (autorun) {
onSubmitFn();
}
}
const setBusy = (busySelector, contentSelector, value, parent = undefined) => {
-63
View File
@@ -1,63 +0,0 @@
import argparse
import json
from pathlib import Path
def generate_manifest(artifacts, environments, titles):
firmware_files = {}
# Match specific environments before their prefixes, e.g. esp32_c6_ethernet.
prefixes = sorted(environments, key=len, reverse=True)
for firmware in sorted(artifacts.glob("firmware_*.factory.bin")):
environment = next((
name for name in prefixes if firmware.name.startswith(f"firmware_{name}_")
), None)
if environment is None:
raise ValueError(f"Unexpected factory image: {firmware.name}")
if environment in firmware_files:
raise ValueError(f"Multiple factory images for {environment}")
firmware_files[environment] = firmware
manifest = []
for environment in environments:
title = titles.get(environment)
if not isinstance(title, str) or not title.strip():
raise ValueError(f"Title missing for {environment}")
firmware = firmware_files.get(environment)
if firmware is None:
raise ValueError(f"Factory image missing for {environment}")
version = firmware.name.removeprefix(f"firmware_{environment}_").removesuffix(".factory.bin")
filesystem = artifacts / f"filesystem_{environment}_{version}.bin"
if not filesystem.is_file():
raise ValueError(f"Filesystem image missing: {filesystem.name}")
manifest.append({
"name": title,
"files": [
{"address": "0x0", "name": firmware.name},
{"address": "0x370000", "name": filesystem.name},
],
})
return manifest
def main():
parser = argparse.ArgumentParser(description="Generate the release Web Flasher manifest")
parser.add_argument("--envs", required=True, type=json.loads)
parser.add_argument("--titles", required=True, type=json.loads)
parser.add_argument("--artifacts", type=Path, default=Path("artifacts"))
args = parser.parse_args()
if not isinstance(args.envs, list) or not args.envs:
parser.error("--envs must be a nonempty JSON array")
if not isinstance(args.titles, dict):
parser.error("--titles must be a JSON object")
try:
manifest = generate_manifest(args.artifacts, args.envs, args.titles)
except ValueError as error:
parser.error(str(error))
output = args.artifacts / "webflasher.json"
output.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
if __name__ == "__main__":
main()