Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
435b2fe1c5 | ||
|
|
eb5f6c9b46 | ||
|
|
d6e1ccb22b | ||
|
|
7e1d0ddff2 | ||
|
|
9ff1bd14f5 | ||
|
|
3a530d721e | ||
|
|
8f659e3e55 | ||
|
|
0a6ae9c5d8 | ||
|
|
3fb433d3eb | ||
|
|
b10d91b8fa | ||
|
|
fc00b3a391 | ||
|
|
0439b6f7c4 | ||
|
|
353452784f | ||
|
|
b72bccb3d7 | ||
|
|
959a15c11f | ||
|
|
734615e7b5 | ||
|
|
c698337b95 | ||
|
|
c63b8d44a1 | ||
|
|
4581ca49cb | ||
|
|
cd8764bb97 | ||
|
|
16308866ce | ||
|
|
f2047b18ba | ||
|
|
69ed4ef86c | ||
|
|
9cf10201f6 | ||
|
|
549dbf4985 | ||
|
|
63aeb2fa25 | ||
|
|
ab5b96c970 | ||
|
|
f613731183 | ||
|
|
85dda5b859 | ||
|
|
451fe92b7a | ||
|
|
1695e1ea0d | ||
|
|
00a80f82f1 | ||
|
|
e95045b9b6 | ||
|
|
c6df5b59cf | ||
|
|
2623ac17dc | ||
|
|
29321d5c53 | ||
|
|
1290e1d33c | ||
|
|
ee68aba128 | ||
|
|
54217fbbc1 | ||
|
|
69116aa3d2 | ||
|
|
bb6b3f1854 | ||
|
|
a4ca20f9a9 | ||
|
|
f5e08f20a2 | ||
|
|
07650b4878 | ||
|
|
ffcacb3d48 | ||
|
|
bdfa793c49 | ||
|
|
25280bf9b1 | ||
|
|
9c2e420ec7 | ||
|
|
af2d4624b3 | ||
|
|
14d2262d2f | ||
|
|
db99746ee9 | ||
|
|
bfc1cc1118 | ||
|
|
01a70b3288 | ||
|
|
5d053690c6 | ||
|
|
ea95b5fa7d | ||
|
|
dd9cb0b88f | ||
|
|
ec7a24ce0c | ||
|
|
44fb0afffa | ||
|
|
ef1d6bf195 | ||
|
|
2bd3360880 | ||
|
|
cbc32fd378 | ||
|
|
79e3c6d433 | ||
|
|
8186e17912 | ||
|
|
9a3a171370 | ||
|
|
7c40984298 | ||
|
|
4775d36f1b | ||
|
|
5482e0b70a | ||
|
|
3fdb48e016 | ||
|
|
11747dd8bd | ||
|
|
af1a9b59c4 | ||
|
|
9c86ad4427 | ||
|
|
5f8ca61d79 | ||
|
|
1f895690db | ||
|
|
13e8bedf3f | ||
|
|
3a6bb03456 | ||
|
|
ced0385d5b | ||
|
|
7fcca3c4aa | ||
|
|
2f6bd237c7 | ||
|
|
e4d1ba7d7b | ||
|
|
80e2d8e939 | ||
|
|
b70c212235 | ||
|
|
781b2a1f9c | ||
|
|
725185beba | ||
|
|
c6518db0d3 | ||
|
|
10ab75c055 | ||
|
|
069ba8e864 | ||
|
|
3b038c4bd1 | ||
|
|
56a8574aba | ||
|
|
3adfabdf40 | ||
|
|
a9220d9fa1 | ||
|
|
5a14857f52 | ||
|
|
e487c78921 | ||
|
|
6c3b79bda1 | ||
|
|
09c50d5df8 | ||
|
|
348fab39bb | ||
|
|
f9cb421893 | ||
|
|
eafb33cb6a | ||
|
|
0038a200ca | ||
|
|
1112a25172 | ||
|
|
69b3cdf05a | ||
|
|
01192a59f5 | ||
|
|
cb8251dd40 | ||
|
|
00baf10b9f | ||
|
|
6f8c8567a0 | ||
|
|
e573ce582f | ||
|
|
0b60734a3b | ||
|
|
1d7f85f462 | ||
|
|
192f4ee18b | ||
|
|
f048d973d3 | ||
|
|
d4603aa0de | ||
|
|
d576969ea4 | ||
|
|
b9010643f0 | ||
|
|
5667199988 | ||
|
|
cf81ff5856 | ||
|
|
78b5a12e90 | ||
|
|
cc5bbb7a87 | ||
|
|
dda79151f3 | ||
|
|
1375d8c7a5 | ||
|
|
d4addf887f | ||
|
|
9d77256051 | ||
|
|
d3e7a13e1f | ||
|
|
14826c10cd | ||
|
|
28a5218b7c | ||
|
|
f3ba43adbd | ||
|
|
062c6714d1 | ||
|
|
502f73db0e | ||
|
|
c2ee30d1ab | ||
|
|
9217bb7448 | ||
|
|
d694ae18c0 | ||
|
|
0f4fa2e406 | ||
|
|
df2af928a5 | ||
|
|
3e6a2d93d4 | ||
|
|
062468c6b1 | ||
|
|
530892dc09 | ||
|
|
c73f74ad45 | ||
|
|
a67ff046b0 | ||
|
|
0f496fee42 | ||
|
|
e63a0dc7eb | ||
|
|
792c6a6668 | ||
|
|
94f6f14795 | ||
|
|
47696a0721 | ||
|
|
5c4ad8cd07 | ||
|
|
f6cfdf3263 | ||
|
|
58b0c18448 | ||
|
|
b985275309 | ||
|
|
1eee184887 | ||
|
|
ba03c9cda3 | ||
|
|
14b1eac732 | ||
|
|
d16f56d280 | ||
|
|
8b50ed48c1 | ||
|
|
f212d9d9a8 | ||
|
|
0e78e71493 | ||
|
|
655313562d | ||
|
|
c8e7724da8 | ||
|
|
f986129c72 | ||
|
|
7b31315242 | ||
|
|
6872cad8ce | ||
|
|
4b1b7f5857 | ||
|
|
a667317412 | ||
|
|
612b17b86f | ||
|
|
7c032ddc2f | ||
|
|
9dd5ee8da5 | ||
|
|
7dbd503e1e | ||
|
|
85932fdc1d | ||
|
|
77d80225ad | ||
|
|
dc68315166 | ||
|
|
5d0ca68dc0 | ||
|
|
d50b70c211 | ||
|
|
dd53d1ef3e | ||
|
|
3bd8010b74 | ||
|
|
6a26e27d39 | ||
|
|
8fa440810c | ||
|
|
95b18385ba | ||
|
|
4457e16a8f | ||
|
|
1965ca671e | ||
|
|
0d1873ec77 | ||
|
|
38ec56fb33 | ||
|
|
bb7c3eeba3 | ||
|
|
0c778d4c7f | ||
|
|
2e5e5e59a8 | ||
|
|
e1623e7b63 | ||
|
|
80b91d9a01 | ||
|
|
25b70e4db5 | ||
|
|
1903ee2bc7 | ||
|
|
916a710064 | ||
|
|
38acae417d | ||
|
|
3bc9fa81a8 | ||
|
|
cc2d6ef385 | ||
|
|
fe93c00204 | ||
|
|
05a2d080be | ||
|
|
664bd7938c | ||
|
|
a78f35328f | ||
|
|
eab47af0e1 | ||
|
|
c524abd959 | ||
|
|
666786fd65 | ||
|
|
8475833dce | ||
|
|
afe710abd3 | ||
|
|
1982843624 | ||
|
|
bf161c1200 | ||
|
|
57f1129cee | ||
|
|
0425cdc499 | ||
|
|
53ff69f03a | ||
|
|
e7cae4b950 | ||
|
|
3ff8f40654 | ||
|
|
d2499a2727 | ||
|
|
5b7da4ed2a | ||
|
|
8d516c7f95 | ||
|
|
d756716497 | ||
|
|
9a2f9d64ec | ||
|
|
0d0926cdac | ||
|
|
3ce3ce5016 | ||
|
|
6ca6d3cab7 | ||
|
|
e7f3c66e05 | ||
|
|
17bd31b2a2 | ||
|
|
8662b9dc8f | ||
|
|
6efa3a52fe | ||
|
|
7e31de6c71 | ||
|
|
b53dae6a43 | ||
|
|
de2318bc6a | ||
|
|
081209420a | ||
|
|
75bc4d5c4a | ||
|
|
527e9cc1d6 | ||
|
|
60b7caf4bc | ||
|
|
e8d0ad0a4e | ||
|
|
afe269aeff | ||
|
|
4702909043 | ||
|
|
4c32ccc450 | ||
|
|
2e3b38e14f | ||
|
|
b6c80f355f | ||
|
|
65b2a3c2bd | ||
|
|
0cb361d243 | ||
|
|
c7f54ca4fb | ||
|
|
1d46176b5e | ||
|
|
5e2f6c9cea | ||
|
|
f439f8c5ba | ||
|
|
bae7770371 | ||
|
|
4e5a3e9da5 | ||
|
|
412e1594e9 | ||
|
|
9701e8c97b | ||
|
|
2fe546812c | ||
|
|
7efcbaa57e | ||
|
|
43c065b97a | ||
|
|
5c1e967fdc | ||
|
|
105a79f72c | ||
|
|
50280f6db3 | ||
|
|
c97e50669c | ||
|
|
43fd095714 | ||
|
|
1bb9b61017 | ||
|
|
1eb10563ed | ||
|
|
222ea4feaa | ||
|
|
ea1406c509 | ||
|
|
b20b450736 | ||
|
|
e8c7f58e67 | ||
|
|
2589020428 | ||
|
|
2bb771a4a7 | ||
|
|
f4af237472 | ||
|
|
5473034421 | ||
|
|
a5996cc93d | ||
|
|
9d6b6c18ab | ||
|
|
e6119dc7ee | ||
|
|
19feb85230 | ||
|
|
0d71a674b6 | ||
|
|
34eabca64a | ||
|
|
d3b28c5bfb | ||
|
|
640935a2b7 | ||
|
|
c0c631aab4 | ||
|
|
861db33765 | ||
|
|
b91266063b | ||
|
|
b087e6e6d3 | ||
|
|
b205f14bae | ||
|
|
7482eb8898 | ||
|
|
2ff84cbddf | ||
|
|
8b6e6be670 | ||
|
|
636872f72d | ||
|
|
c6df74f06e | ||
|
|
24a46f4c16 | ||
|
|
ddc9cf7c90 | ||
|
|
2d74d0c0ad | ||
|
|
e04462811b | ||
|
|
99d82657c0 | ||
|
|
ed50208546 | ||
|
|
fda18cdb13 | ||
|
|
6a9bd9673a | ||
|
|
5aea80e630 | ||
|
|
fcf7d61ca5 | ||
|
|
e71f3868fd | ||
|
|
c3d0d94806 | ||
|
|
e4211c872c | ||
|
|
467cfea449 | ||
|
|
0e3473e065 | ||
|
|
8780e5245a | ||
|
|
94e8288d76 | ||
|
|
261a53207c | ||
|
|
1dbc895cdb | ||
|
|
747d8841bc | ||
|
|
7ed47a4eca | ||
|
|
0ccea290cb | ||
|
|
c03df67900 | ||
|
|
f86857c279 | ||
|
|
acd8348a5b | ||
|
|
cdde3c30af | ||
|
|
392242ef3e | ||
|
|
a6e8953807 | ||
|
|
11b1277d79 | ||
|
|
f62e687d3f | ||
|
|
42fa95969f | ||
|
|
56a0d1322f | ||
|
|
45762967ee | ||
|
|
10f9cde17a | ||
|
|
351a884685 | ||
|
|
98db62cc9e | ||
|
|
355d983437 | ||
|
|
3d11d13631 | ||
|
|
6c4f8a78a0 | ||
|
|
3fb5eb32c3 | ||
|
|
c1447098da | ||
|
|
87b222e7bc | ||
|
|
0eea1b8121 | ||
|
|
7f701a74e7 | ||
|
|
57cf98ca19 | ||
|
|
c32c643442 | ||
|
|
5553a13cc0 | ||
|
|
a9e97c15ad | ||
|
|
dc62f99b7d | ||
|
|
05ff426b28 | ||
|
|
45af7a30d8 | ||
|
|
8aab541afa | ||
|
|
7672c4b927 | ||
|
|
b0a9460257 | ||
|
|
3c69f1295e | ||
|
|
282a02ecdb | ||
|
|
8503ef966f | ||
|
|
a4ee4c5224 | ||
|
|
4478e8f204 | ||
|
|
a50c13fd8a | ||
|
|
ee1e7f92b2 | ||
|
|
5704075682 | ||
|
|
52e4933923 | ||
|
|
00a82ca3e5 | ||
|
|
7658aeaa8c | ||
|
|
790ff5a011 | ||
|
|
935cf27139 | ||
|
|
503068f6e7 | ||
|
|
5c868d589d | ||
|
|
1cca8ffd5d | ||
|
|
f291eb33ac | ||
|
|
f0c505c332 | ||
|
|
7eafe4a90b | ||
|
|
d23527a48b | ||
|
|
c341f86e5c | ||
|
|
939ed6cdab | ||
|
|
2da41707a9 | ||
|
|
460cb01146 | ||
|
|
1b2bc8e200 | ||
|
|
d5acb44648 | ||
|
|
c64cf41757 | ||
|
|
9250bb26f2 | ||
|
|
b2c6eca2d5 | ||
|
|
5cec043015 | ||
|
|
7c9a483677 | ||
|
|
1bfe7a688a | ||
|
|
05104aa8eb | ||
|
|
ca3c318d8f | ||
|
|
2648918dda | ||
|
|
8b50fdec21 | ||
|
|
5b6e23251a | ||
|
|
769daa0857 | ||
|
|
76979531b8 | ||
|
|
7779076498 | ||
|
|
45e2e0334e | ||
|
|
b631b496cb | ||
|
|
36328a1db5 | ||
|
|
a28c7f67b5 | ||
|
|
bb9b6a5f4c | ||
|
|
ce7bd7e23b | ||
|
|
249d32ce35 | ||
|
|
baf8adfb02 | ||
|
|
018a1c5188 | ||
|
|
b600c130f0 | ||
|
|
59eb05726a | ||
|
|
f245f37dfd | ||
|
|
a825412f37 | ||
|
|
935f8bd0a8 | ||
|
|
f78d2f38b8 | ||
|
|
ef083991e3 | ||
|
|
3c0f846335 | ||
|
|
85011ce4ea | ||
|
|
8687e122ca | ||
|
|
d35ea81080 | ||
|
|
cca8ec58b4 | ||
|
|
301b14bbd4 | ||
|
|
41ce9b268e | ||
|
|
646939179e | ||
|
|
73dddd18f0 | ||
|
|
f069de0415 | ||
|
|
f4a4afeb29 | ||
|
|
f9824337dc | ||
|
|
1cd8c6a336 | ||
|
|
63228baebd | ||
|
|
6bb261dfd7 | ||
|
|
a026a962f0 | ||
|
|
db2faad741 | ||
|
|
fbc43dc535 | ||
|
|
31dfc21d69 | ||
|
|
96289cb0f7 | ||
|
|
73da3ee07a | ||
|
|
a14281924f | ||
|
|
3dec390cce | ||
|
|
9a29819d4f | ||
|
|
2af159d566 | ||
|
|
92ca257d32 | ||
|
|
44b6620431 | ||
|
|
b89f61ed58 | ||
|
|
ab1566bd45 | ||
|
|
86734ab622 | ||
|
|
0a8dd2a076 | ||
|
|
a7a561622e | ||
|
|
b0e0f6fd7d | ||
|
|
53eaa1d7f1 | ||
|
|
a7d796e0cc | ||
|
|
4490b38130 | ||
|
|
0ede2240a2 | ||
|
|
0cff35ee12 | ||
|
|
14aef20234 | ||
|
|
560f8fbd51 | ||
|
|
946414ad31 | ||
|
|
39a29042e1 | ||
|
|
f544f01caa | ||
|
|
41cca76bfa | ||
|
|
942bc53043 | ||
|
|
1bad689b6b | ||
|
|
2f4dbcc205 | ||
|
|
9e3ef7a465 | ||
|
|
a5f6749101 | ||
|
|
b07dd46f55 | ||
|
|
07ab121788 | ||
|
|
7cbc52a8b0 | ||
|
|
e090be380c | ||
|
|
0bf49d2249 | ||
|
|
a83d94d361 | ||
|
|
358980da4c | ||
|
|
f91e39d067 | ||
|
|
1d53f21d46 | ||
|
|
c225e7c2a8 | ||
|
|
6831c4331f | ||
|
|
8fb62ce8ae |
No files matched your search
@@ -0,0 +1,11 @@
|
|||||||
|
version: 2
|
||||||
|
updates:
|
||||||
|
- package-ecosystem: "npm"
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: "daily"
|
||||||
|
|
||||||
|
- package-ecosystem: "github-actions"
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: "daily"
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
name: Build
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
push:
|
||||||
|
paths-ignore:
|
||||||
|
- "assets/**"
|
||||||
|
- "**/*.md"
|
||||||
|
- "LICENSE"
|
||||||
|
|
||||||
|
pull_request:
|
||||||
|
paths-ignore:
|
||||||
|
- "assets/**"
|
||||||
|
- "**/*.md"
|
||||||
|
- "LICENSE"
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
env:
|
||||||
|
# Keep Python within the versions supported by pioarduino.
|
||||||
|
PYTHON_VERSION: "3.13"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
prepare:
|
||||||
|
name: Prepare (get envs)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
outputs:
|
||||||
|
envs: ${{ steps.envs.outputs.envs }}
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v6
|
||||||
|
|
||||||
|
- name: Python
|
||||||
|
uses: actions/setup-python@v6
|
||||||
|
with:
|
||||||
|
python-version: ${{ env.PYTHON_VERSION }}
|
||||||
|
|
||||||
|
- name: Install PlatformIO Core
|
||||||
|
run: |
|
||||||
|
python -m pip install --upgrade pip
|
||||||
|
pip install --upgrade platformio
|
||||||
|
pip install --upgrade intelhex
|
||||||
|
|
||||||
|
- name: Get environments
|
||||||
|
id: envs
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
ENVS=$(
|
||||||
|
pio project config --json-output \
|
||||||
|
| jq -c '
|
||||||
|
.[]
|
||||||
|
| select(type == "array")
|
||||||
|
| .[0]
|
||||||
|
| select(startswith("env:"))
|
||||||
|
| sub("^env:"; "")
|
||||||
|
' | jq -s -c '.'
|
||||||
|
)
|
||||||
|
|
||||||
|
echo "envs=$ENVS" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "$ENVS"
|
||||||
|
|
||||||
|
build:
|
||||||
|
name: Build ${{ matrix.env }}
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: prepare
|
||||||
|
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
env: ${{ fromJson(needs.prepare.outputs.envs) }}
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v6
|
||||||
|
|
||||||
|
- name: Python
|
||||||
|
uses: actions/setup-python@v6
|
||||||
|
with:
|
||||||
|
python-version: ${{ env.PYTHON_VERSION }}
|
||||||
|
|
||||||
|
- name: Install Node.js
|
||||||
|
uses: actions/setup-node@v5
|
||||||
|
with:
|
||||||
|
node-version: "22"
|
||||||
|
|
||||||
|
- name: Install PlatformIO Core
|
||||||
|
run: |
|
||||||
|
python -m pip install --upgrade pip
|
||||||
|
pip install --upgrade platformio
|
||||||
|
pip install --upgrade intelhex
|
||||||
|
|
||||||
|
- name: Full clean
|
||||||
|
run: |
|
||||||
|
pio run -e ${{ matrix.env }} -t fullclean
|
||||||
|
|
||||||
|
- name: Build firmware & filesystem
|
||||||
|
env:
|
||||||
|
PIOENV: ${{ matrix.env }}
|
||||||
|
run: |
|
||||||
|
pio run -e ${{ matrix.env }}
|
||||||
|
|
||||||
|
- name: Upload artifacts
|
||||||
|
uses: actions/upload-artifact@v7
|
||||||
|
with:
|
||||||
|
name: ${{ matrix.env }}
|
||||||
|
if-no-files-found: error
|
||||||
|
path: |
|
||||||
|
build/*.bin
|
||||||
|
build/*.elf
|
||||||
|
|
||||||
|
release:
|
||||||
|
name: Release Dev
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: build
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
if: ${{ github.repository_owner == 'Laxilef' && github.ref == 'refs/heads/async' }}
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Move dev tag
|
||||||
|
run: |
|
||||||
|
git fetch --tags
|
||||||
|
git tag -f dev
|
||||||
|
git push origin refs/tags/dev --force
|
||||||
|
|
||||||
|
- name: Download artifacts
|
||||||
|
uses: actions/download-artifact@v5
|
||||||
|
with:
|
||||||
|
path: artifacts
|
||||||
|
merge-multiple: true
|
||||||
|
|
||||||
|
- name: Delete old release assets
|
||||||
|
uses: mknejp/delete-release-assets@v1
|
||||||
|
with:
|
||||||
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
tag: dev
|
||||||
|
fail-if-no-assets: false
|
||||||
|
fail-if-no-release: false
|
||||||
|
assets: |
|
||||||
|
*.bin
|
||||||
|
*.elf
|
||||||
|
|
||||||
|
- name: Clear release body
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
run: |
|
||||||
|
gh release edit dev --notes ""
|
||||||
|
|
||||||
|
- name: Publish Dev release
|
||||||
|
uses: softprops/action-gh-release@v3
|
||||||
|
with:
|
||||||
|
tag_name: dev
|
||||||
|
target_commitish: async
|
||||||
|
name: Dev (unstable)
|
||||||
|
prerelease: true
|
||||||
|
make_latest: false
|
||||||
|
generate_release_notes: true
|
||||||
|
files: |
|
||||||
|
artifacts/*.bin
|
||||||
|
artifacts/*.elf
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
name: CI
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
push:
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
validate-json:
|
||||||
|
name: Validate JSON
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v6
|
||||||
|
|
||||||
|
- name: Install jq
|
||||||
|
run: sudo apt-get update && sudo apt-get install -y jq
|
||||||
|
|
||||||
|
- name: Validate
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
echo "Searching JSON files in src_data..."
|
||||||
|
|
||||||
|
files=$(find src_data -type f -iname "*.json")
|
||||||
|
|
||||||
|
if [ -z "$files" ]; then
|
||||||
|
echo "No JSON files found."
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
failed=0
|
||||||
|
|
||||||
|
for file in $files; do
|
||||||
|
echo "Validating: $file"
|
||||||
|
|
||||||
|
if ! jq empty "$file" >/dev/null 2>&1; then
|
||||||
|
echo "❌ Invalid JSON: $file"
|
||||||
|
failed=1
|
||||||
|
else
|
||||||
|
echo "✅ Valid JSON: $file"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
if [ "$failed" -ne 0 ]; then
|
||||||
|
echo ""
|
||||||
|
echo "JSON validation failed."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "All JSON files are valid."
|
||||||
|
|
||||||
|
cpplint:
|
||||||
|
name: cpplint
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v6
|
||||||
|
|
||||||
|
- name: Cache
|
||||||
|
uses: actions/cache@v5
|
||||||
|
with:
|
||||||
|
key: ${{ runner.os }}-cpplint
|
||||||
|
path: ~/.cache/pip
|
||||||
|
|
||||||
|
- name: Python
|
||||||
|
uses: actions/setup-python@v6
|
||||||
|
with:
|
||||||
|
python-version: "3.x"
|
||||||
|
|
||||||
|
- name: Install cpplint
|
||||||
|
run: |
|
||||||
|
python -m pip install --upgrade pip
|
||||||
|
pip install --upgrade cpplint
|
||||||
|
|
||||||
|
- name: cpplint
|
||||||
|
run: |
|
||||||
|
FILTERS="-legal/copyright,\
|
||||||
|
-runtime/int,\
|
||||||
|
-runtime/references,\
|
||||||
|
-runtime/indentation_namespace,\
|
||||||
|
-runtime/arrays,\
|
||||||
|
-runtime/printf,\
|
||||||
|
-whitespace/line_length,\
|
||||||
|
-whitespace/braces,\
|
||||||
|
-whitespace/comments,\
|
||||||
|
-whitespace/indent,\
|
||||||
|
-whitespace/newline,\
|
||||||
|
-whitespace/parens,\
|
||||||
|
-whitespace/blank_line,\
|
||||||
|
-readability/braces,\
|
||||||
|
-readability/todo,\
|
||||||
|
-readability/namespace,\
|
||||||
|
-build/header_guard,\
|
||||||
|
-build/include_subdir,\
|
||||||
|
-build/include_what_you_use,\
|
||||||
|
-build/namespaces,\
|
||||||
|
-build/c++11"
|
||||||
|
|
||||||
|
cpplint \
|
||||||
|
--repository=. \
|
||||||
|
--recursive \
|
||||||
|
--quiet \
|
||||||
|
--filter="$FILTERS" \
|
||||||
|
include lib src
|
||||||
@@ -7,7 +7,7 @@ jobs:
|
|||||||
stale:
|
stale:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/stale@v9
|
- uses: actions/stale@v11
|
||||||
with:
|
with:
|
||||||
stale-issue-message: >
|
stale-issue-message: >
|
||||||
This issue is stale because it has been open 15 days with no activity. Remove stale label or comment or this will be closed in 5 days.
|
This issue is stale because it has been open 15 days with no activity. Remove stale label or comment or this will be closed in 5 days.
|
||||||
|
|||||||
@@ -1,5 +1,15 @@
|
|||||||
.pio
|
.pio
|
||||||
|
.dummy
|
||||||
.vscode
|
.vscode
|
||||||
build/*.bin
|
.PVS-Studio
|
||||||
|
build/*
|
||||||
|
data/*
|
||||||
|
managed_components/*
|
||||||
|
node_modules/*
|
||||||
|
agent-notes/*
|
||||||
secrets.ini
|
secrets.ini
|
||||||
|
package-lock.json
|
||||||
|
*.lock
|
||||||
|
sdkconfig.*
|
||||||
|
CMakeLists.txt
|
||||||
!.gitkeep
|
!.gitkeep
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
# Инструкции для агентов
|
||||||
|
|
||||||
|
## Роль и цели
|
||||||
|
|
||||||
|
Ты — инженерный AI-ассистент проекта OTGateway. Ты помогаешь разрабатывать
|
||||||
|
и сопровождать прошивку для ESP32, её веб-интерфейс и инструменты сборки.
|
||||||
|
Изучаешь код и документацию, находишь причины ошибок, предлагаешь решения,
|
||||||
|
реализуешь согласованные изменения и проверяешь результат.
|
||||||
|
|
||||||
|
Твои цели:
|
||||||
|
|
||||||
|
- Повышать надёжность и предсказуемость работы устройства, сохраняя корректность
|
||||||
|
управления отоплением и совместимость с разными OpenTherm-устройствами (котлами и отопительными системами).
|
||||||
|
- Делать код понятным и поддерживаемым, экономно использовать flash, heap
|
||||||
|
и процессорное время ESP32.
|
||||||
|
- Доводить согласованную задачу до проверяемого результата, соблюдая её границы
|
||||||
|
и решения пользователя как автора проекта.
|
||||||
|
- Беречь время и бюджет пользователя: использовать накопленные знания,
|
||||||
|
выбирать соразмерные проверки и не повторять уже выполненные исследования
|
||||||
|
без причины. Сохранять полезные выводы для следующих агентов.
|
||||||
|
|
||||||
|
## Общение и границы задачи
|
||||||
|
|
||||||
|
- Общайся с пользователем на русском языке, кратко и по существу. Сообщай результат,
|
||||||
|
существенные ограничения и выполненные проверки; не пересказывай каждое действие.
|
||||||
|
- Учитывай всю текущую переписку: новые уточнения дополняют задачу. Последнее явное
|
||||||
|
указание пользователя важнее прежних предпочтений и этого документа.
|
||||||
|
- Если запрошены анализ или предложение, сначала изучи код и представь выводы.
|
||||||
|
Не вноси изменения без запроса на реализацию.
|
||||||
|
- Выполняй согласованный объём. Не превращай перенос кода или замену библиотеки
|
||||||
|
в глубокую переработку алгоритмов и архитектуры.
|
||||||
|
- При поэтапной работе показывай конкретный результат этапа. Если пользователь
|
||||||
|
потребовал одобрения перед следующим этапом или коммитом, дождись его.
|
||||||
|
- Не запрашивай повторного разрешения на уже согласованную работу. Задавай вопросы,
|
||||||
|
когда ответ действительно влияет на корректность, безопасность или объём задачи.
|
||||||
|
- Исправляй свои ошибочные выводы прямо, с объяснением подтверждённых фактов.
|
||||||
|
|
||||||
|
## Защита конфиденциальных данных
|
||||||
|
|
||||||
|
- Запрещены чтение, анализ, запись, сохранение, публикация и передача любых данных
|
||||||
|
из `secrets.ini` в любом виде. Не открывай и не изменяй этот файл,
|
||||||
|
не включай его содержимое в поиск, пакетное чтение или обработку инструментами,
|
||||||
|
скриптами, подпроцессами и подагентами.
|
||||||
|
- Тот же запрет действует для **возможных секретов из анализируемых логов**.
|
||||||
|
Не требуется подтверждать, что значение действительно является секретом:
|
||||||
|
при сомнении считай его конфиденциальным и не читай, не анализируй, не записывай,
|
||||||
|
не сохраняй, не публикуй и не передавай.
|
||||||
|
- Запрет охватывает исходные значения, фрагменты, копии, пересказы, маскированные,
|
||||||
|
закодированные и хешированные представления, а также другие производные данные.
|
||||||
|
Он относится к сообщениям, аргументам и результатам инструментов, контексту
|
||||||
|
подагентов, исходникам, коммитам, отчётам, `agent-notes/`, артефактам и внешним
|
||||||
|
сервисам независимо от того, являются ли они публичными или локальными.
|
||||||
|
- Для анализа используй только логи, из которых возможные секреты заранее
|
||||||
|
полностью удалены. Не читай и не сохраняй сырые логи ради последующего поиска
|
||||||
|
или маскировки таких значений.
|
||||||
|
|
||||||
|
## Изменения и Git
|
||||||
|
|
||||||
|
- Перед правками изучи состояние рабочей директории и относящиеся к задаче изменения.
|
||||||
|
Здесь могут одновременно находиться незакоммиченные изменения пользователя и агента.
|
||||||
|
- Сохраняй посторонние изменения. Откатывай только изменения нужной задачи;
|
||||||
|
не применяй общий reset/checkout для частичного отката.
|
||||||
|
- При использовании stash указывай, что именно скрыто, идентификатор stash и точную
|
||||||
|
команду восстановления. Проверяй также новые файлы, которых ещё нет в Git.
|
||||||
|
- Создавай коммиты по запросу пользователя и соблюдай согласованное разделение.
|
||||||
|
Если запрошен один файл, другие файлы в коммит попадать не должны.
|
||||||
|
- Сообщения коммитов — Semantic Commit Messages, обычно **без scope**:
|
||||||
|
`fix: ...`, `feat: ...`, `refactor: ...`. Описание обычно на английском.
|
||||||
|
- Пароли, секреты, SSID, токены и личные конфиги для тестирования не должны попадать
|
||||||
|
в коммиты или публичные отчёты!
|
||||||
|
|
||||||
|
## Читаемость кода
|
||||||
|
|
||||||
|
Подробные правила оформления и примеры приведены в [CODESTYLE.md](CODESTYLE.md).
|
||||||
|
|
||||||
|
- Следуй форматированию и стилю окружающего кода. Для нового кода проекта обычно
|
||||||
|
используются отступы в два пробела и фигурные скобки у условных блоков.
|
||||||
|
- Не сокращай `if`, `while`, `for` и прочие блоки до однострочных конструкций без скобок. Исходники должны быть удобны для поддержки; JavaScript при сборке всё равно минифицируется.
|
||||||
|
- Предпочитай понятный `while` конструкциям вроде `for (; условие; ...)`.
|
||||||
|
- Давай переменным имена по смыслу протокола и данных. Не смешивай комнатную
|
||||||
|
температуру, температуру теплоносителя, запрошенное состояние и переданный флаг.
|
||||||
|
- Сохраняй полезное разделение алгоритма на небольшие функции. Простые тела задач
|
||||||
|
можно писать непосредственно в callback; обёртки ради одной передачи управления
|
||||||
|
и отдельные задачи ради нескольких простых условий не нужны.
|
||||||
|
- Для локальных функций и данных в `.cpp` пользователь предпочитает `static`
|
||||||
|
анонимному namespace. `this->` необязателен.
|
||||||
|
- Не дублируй проверки, парсинг и состояние. Используй существующие методы валидации
|
||||||
|
и данные `settings`/`vars`, вместо параллельных копий и искусственных флагов.
|
||||||
|
- Общедоступные значения обмена с ведомым устройством сохраняй в соответствующих
|
||||||
|
полях `vars.slave`, когда они нужны остальному проекту.
|
||||||
|
- Добавляй короткие комментарии к неочевидной причине или ограничению.
|
||||||
|
Сразу после открывающей `{` пустая строка перед комментарием не нужна.
|
||||||
|
`constexpr`, шаблоны, `std::move`, mutex и новые абстракции должны решать реальную
|
||||||
|
задачу. В частности, `std::move` для обычного `float` не даёт выигрыша.
|
||||||
|
- Для сравнений `float` выбирай допуск по физическому смыслу величины и требуемой
|
||||||
|
точности. Не вводи произвольный общий epsilon для всего проекта.
|
||||||
|
|
||||||
|
## Платформа, зависимости и ресурсы
|
||||||
|
|
||||||
|
- Проект ориентирован на **ESP32**. Не возвращай совместимость и обходные решения
|
||||||
|
для ESP8266. Перед удалением строковых обёрток проверяй типы и выбранные перегрузки.
|
||||||
|
- Минимизация `flash` и `heap` критична! Сохраняй подход с общими строками
|
||||||
|
в `strings.h`; не заменяй его множеством одинаковых литералов и копий в RAM.
|
||||||
|
- Не добавляй `.cpp`, классы или отдельные объекты только ради формальной структуры.
|
||||||
|
Простые объявления и константы допустимо оставлять в заголовках с корректным ODR.
|
||||||
|
- Не меняй код сторонних зависимостей, установленных пакетов PlatformIO и SDK
|
||||||
|
без явной необходимости и разрешения. В `lib/` есть также собственный код проекта:
|
||||||
|
наличие файла в этой папке само по себе не делает его сторонней зависимостью.
|
||||||
|
- Изучай фактическую версию библиотеки и официальную документацию. Не переноси
|
||||||
|
предположения о старом SDK на новый; комментарий библиотеки не заменяет проверку кода.
|
||||||
|
- Используй установленный PlatformIO. Не создавай отдельную изолированную установку
|
||||||
|
или копии всех пакетов без запроса пользователя.
|
||||||
|
- Учитывай `heap`, временные выделения, стеки задач, flash и IRAM раздельно.
|
||||||
|
Длинные логи и WebSocket могут менять расход памяти даже без активного клиента.
|
||||||
|
- Если при анализе backtrace ты видишь ошибку в зависимостях, сначала поищи открытые и закрытые issue в репозиториях зависимости: очень часто проблема уже известна и её решение описано в issue.
|
||||||
|
|
||||||
|
## Задачи и синхронизация
|
||||||
|
|
||||||
|
- Сохраняй последовательность вычислений, периодичность и условия включения логики.
|
||||||
|
Изменение периода PID влияет на алгоритм; оно должно быть осознанным.
|
||||||
|
- Учитывай, что задачи одного MycilaTaskManager выполняются последовательно.
|
||||||
|
Блокирующее ожидание результата другой задачи того же менеджера может остановить
|
||||||
|
его работу. OpenTherm требует возможности переключения контекста при ожиданиях.
|
||||||
|
- Проверяй семантику ONCE, pause/resume, scheduled и onDone именно используемой
|
||||||
|
версии библиотеки. Не добавляй ручные флаги и обходные циклы без необходимости.
|
||||||
|
- Добавляй mutex только для конкретного межзадачного конфликта. Не приостанавливай
|
||||||
|
задачу, которая может держать lock; учитывай callbacks и завершение текущей работы.
|
||||||
|
- Отключённая настройками функциональность не должна выполнять дорогую работу
|
||||||
|
без необходимости. При этом упрощение расписания не должно ломать зависимости.
|
||||||
|
|
||||||
|
## Поведение устройства и интерфейсов
|
||||||
|
|
||||||
|
- Сохраняй оба способа отключения контуров: флаг и нулевая уставка, а также их
|
||||||
|
комбинацию. Соблюдай выбранное пользователем действие независимо от причины
|
||||||
|
отключения; не вводи дополнительных исключений самовольно.
|
||||||
|
- **Не передавай нулевой room setpoint ради отключения отопления.** Это может
|
||||||
|
интерпретироваться котлом или тепловым насосом как запрос охлаждения.
|
||||||
|
- Различай фактическое состояние контура и значение, передаваемое OpenTherm.
|
||||||
|
`dhwBlocking` и `summerWinterMode` должны отражать фактическое состояние.
|
||||||
|
- Не объявляй нулевую температуру запрещённой для всех ID. Например, ID56 допускает
|
||||||
|
значение 0 в f8.8. Проверяй диапазоны и семантику по спецификации конкретного ID.
|
||||||
|
- **Модуляция 0% — валидный ответ.** При `flame = on` это работа котла на
|
||||||
|
минимальной мощности. Не отбрасывай ноль и не считай его признаком отсутствия
|
||||||
|
ответа или выключенной горелки. Состояние пламени определяется отдельно по
|
||||||
|
Status; при расчёте мощности горящего котла сохраняй минимальную мощность.
|
||||||
|
- При переносе алгоритма исходный код служит референсом поведения. Любое изменение
|
||||||
|
защит, единиц измерения, таймеров и условий должно быть явно обосновано.
|
||||||
|
- Сохраняй настройки сети при OTA и перед перезапуском, включая перезапуск по
|
||||||
|
недостатку памяти. Не меняй таблицу разделов или формат хранения попутно.
|
||||||
|
- Используй существующие структуры `Settings.h`. Не добавляй перенос в NVS или
|
||||||
|
миграции старых настроек автоматически, когда они не входят в задачу.
|
||||||
|
- Порядок полей в сериализации и `jsonToSettings` должен соответствовать порядку
|
||||||
|
структур настроек. При изменении настроек проверяй также API и веб-интерфейс.
|
||||||
|
- Для переводов используй русскую локаль как референс и обновляй остальные локали.
|
||||||
|
- Для недоверенного текста используй `textContent`/`setTextValue`. `setValue` с HTML
|
||||||
|
допустим только там, где HTML нужен и данные не создают XSS.
|
||||||
|
- Сохраняй аутентификацию и для страниц, и для WebSocket/служебных endpoint.
|
||||||
|
Размер страниц и ресурсов важен для ограниченного flash.
|
||||||
|
|
||||||
|
## Проверки и оборудование
|
||||||
|
|
||||||
|
- По умолчанию работай с **S3**.
|
||||||
|
Если сказано «пока не собирать», ограничься изменениями и статической проверкой.
|
||||||
|
- Выполняй проверки по масштабу изменения. Не добавляй тяжёлые тесты для простых
|
||||||
|
обратимых правок и не повторяй успешную полную сборку без новой причины.
|
||||||
|
- Не выдавай сборку за проверку на устройстве, а host-тест — за замер на ESP32.
|
||||||
|
Отделяй наблюдения, выводы и предположения; указывай условия и ограничения замеров.
|
||||||
|
- При сравнении производительности учитывай SDK, BLE, MQTT, наличие клиентов,
|
||||||
|
прогрев, длину/формат сообщений и влияние измерительного кода. Не выбирай только
|
||||||
|
удачный повтор и не называй короткую проверку доказательством отсутствия утечек.
|
||||||
|
- ESP может управлять реальным котлом в жилом доме. До прошивки или управляющих
|
||||||
|
действий установи, с каким устройством работаешь и на что есть разрешение.
|
||||||
|
Разрешение на тестовую плату не распространяется на устройство с реальным котлом.
|
||||||
|
- Для разрешённого чтения логов не меняй настройки и состояние оборудования.
|
||||||
|
После захвата освобождай COM-порт и закрывай WS-клиент.
|
||||||
|
|
||||||
|
## Рабочие знания
|
||||||
|
|
||||||
|
- Перед повторным исследованием прочитай `agent-notes/README.md` и относящиеся
|
||||||
|
к задаче заметки, если они есть. Сверяй их с текущей версией кода и зависимостей.
|
||||||
|
- Сохраняй в `agent-notes/` Markdown-файлы с выводами для будущих агентов: контекст,
|
||||||
|
проверенные факты, краткое обоснование решения, проверки, ограничения и ссылки
|
||||||
|
на источники/артефакты. Обновляй индекс, чтобы работу не приходилось повторять.
|
||||||
|
Каталог игнорируется Git: при поиске читай его явно или используй `rg --no-ignore`.
|
||||||
|
- Каталог локальный: `.gitignore` исключает его содержимое, кроме самого `.gitignore`.
|
||||||
|
Не делай принудительный `git add -f` заметок без указания пользователя.
|
||||||
|
- Если пользователь назначил конкретный файл отчёта, например `PROJECT_AUDIT.md`,
|
||||||
|
веди его по указанному пути. Не переноси существующие документы самовольно.
|
||||||
|
- Если чего-то не знаешь и не можешь найти - скажи об этом, а не придумывай.
|
||||||
|
- В этом AGENTS.md должны оставаться общие правила. Планы, текущий статус и выводы
|
||||||
|
отдельных исследований храни в заметках, а не в инструкциях.
|
||||||
@@ -0,0 +1,344 @@
|
|||||||
|
# Стиль кода OTGateway
|
||||||
|
|
||||||
|
Документ задаёт правила оформления и читаемости для всего проекта OTGateway:
|
||||||
|
прошивки, веб-интерфейса, инструментов, примеров и документации. Основной образец
|
||||||
|
C++ — `src/opentherm.cpp`. Существующий код не требуется массово
|
||||||
|
переформатировать: применяй правила к изменяемому участку, если нет явного требования переформатировать весь код в файле.
|
||||||
|
|
||||||
|
Последнее явное указание пользователя важнее этого документа. В остальных
|
||||||
|
случаях сохраняй стиль окружающего кода и учитывай приведённые ниже исключения.
|
||||||
|
Рабочие процедуры описаны в `AGENTS.md`, особенности алгоритмов и совместимости
|
||||||
|
OpenTherm — в коде, спецификации и `agent-notes/`. Изменение оформления само по
|
||||||
|
себе не является основанием менять поведение.
|
||||||
|
|
||||||
|
## Базовое оформление
|
||||||
|
|
||||||
|
- Используй два пробела на уровень вложенности, без табуляции.
|
||||||
|
- Сохраняй UTF-8 и существующие окончания строк. В `src/opentherm.cpp` — CRLF.
|
||||||
|
Проверяй, что кириллица в документации и строках не повредилась при записи.
|
||||||
|
- Открывающая `{` находится на строке объявления или управляющей конструкции.
|
||||||
|
- У `if`, `else`, `while`, `for` и других блоков обязательны фигурные скобки,
|
||||||
|
даже если внутри одно действие. Это относится и к JavaScript.
|
||||||
|
- После `if`, `while`, `for`, `switch` ставь пробел перед `(`; между именем
|
||||||
|
функции и `(` пробела нет.
|
||||||
|
- Оформляй `*` и `&` по окружающему коду. В новых фрагментах `opentherm.cpp`
|
||||||
|
используются, например, `const uint8_t* buffer` и `const auto& config`.
|
||||||
|
Не вводи ради этого массовую правку существующих объявлений.
|
||||||
|
- Не оставляй пробелы в конце строк; файл заканчивается переводом строки.
|
||||||
|
- Не вводи произвольный жёсткий лимит длины строки. Переноси выражения по смыслу,
|
||||||
|
когда строка становится трудной для чтения.
|
||||||
|
|
||||||
|
В проекте принято отделять следующую ветку условного блока пустой строкой,
|
||||||
|
сохраняя `} else` на одной строке:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
if (response.isSuccess()) {
|
||||||
|
handleResponse(response);
|
||||||
|
|
||||||
|
} else if (shouldRetry()) {
|
||||||
|
scheduleRetry();
|
||||||
|
|
||||||
|
} else {
|
||||||
|
reportFailure();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Пустые строки и комментарии
|
||||||
|
|
||||||
|
- Разделяй самостоятельные смысловые блоки пустой строкой, в том числе два
|
||||||
|
соседних блока настройки задач.
|
||||||
|
- Перед комментарием, начинающим новый смысловой блок, нужна пустая строка.
|
||||||
|
Исключение: комментарий стоит первым сразу после открывающей `{`.
|
||||||
|
- Между комментарием и относящимся к нему кодом пустая строка не нужна.
|
||||||
|
- Новые комментарии к коду пиши на английском. Объясняй причину, ограничение
|
||||||
|
или неочевидное действие; не пересказывай очевидное присваивание.
|
||||||
|
- Не удаляй комментарии о совместимости с устройствами при упрощении кода.
|
||||||
|
- В примерах для начинающих поясняй назначение существенных вызовов API,
|
||||||
|
даже если опытному разработчику они понятны.
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
if (response.isSuccess()) {
|
||||||
|
// Store the acknowledged value for the rest of the application.
|
||||||
|
vars.slave.heating.indoorTemp = response.get();
|
||||||
|
|
||||||
|
// Publish the acknowledged temperature.
|
||||||
|
ESP_LOGI(L_OT_HEATING, "Received indoor temp: %.2f", vars.slave.heating.indoorTemp);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Переносы строк и цепочки методов
|
||||||
|
|
||||||
|
Короткий вызов оставляй на одной строке. В длинном вызове переноси аргументы
|
||||||
|
с дополнительным отступом в два пробела, закрывающую скобку ставь отдельно.
|
||||||
|
Связанные короткие аргументы можно оставлять на одной строке:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
ESP_LOGI(
|
||||||
|
L_OT_HEATING, "Set current indoor temp: %.2f (converted: %.2f, response: %.2f)",
|
||||||
|
indoorTemp, convertedTemp, vars.slave.heating.indoorTemp
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
В обычной цепочке настройки задачи первый метод начинается на строке переменной.
|
||||||
|
Следующие методы — с новой строки и дополнительным отступом. Используй
|
||||||
|
возвращаемую ссылку `Task&`, чтобы не повторять имя задачи:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
// Read the DHW burner operating hours.
|
||||||
|
readDhwBurnerHoursTask.setInterval(60000)
|
||||||
|
.setEnabledWhen([] {
|
||||||
|
return isSlaveReady()
|
||||||
|
&& Sensors::getAmountByType(Sensors::Type::OT_DHW_BURNER_HOURS, true);
|
||||||
|
})
|
||||||
|
.onDone(onOperationDone);
|
||||||
|
openthermTaskManager.addTask(readDhwBurnerHoursTask);
|
||||||
|
```
|
||||||
|
|
||||||
|
Одиночный вызов не оформляй как цепочку с отдельно стоящим именем переменной:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
initializeSlaveTask.setEnabledWhen([] {
|
||||||
|
return canUseBus() && vars.slave.connected;
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
Для сложных построителей отдельно согласовано оформление с именем
|
||||||
|
объекта на собственной строке. Сохраняй его при работе с такой цепочкой:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
request
|
||||||
|
.setCentralHeatingEnabled(getSlaveChannelEnabled(
|
||||||
|
vars.master.heating.enabled, settings.opentherm.heatingDisablingAction
|
||||||
|
))
|
||||||
|
.setHotWaterEnabled(
|
||||||
|
settings.opentherm.options.dhwSupport &&
|
||||||
|
getSlaveChannelEnabled(vars.master.dhw.enabled, settings.opentherm.dhwDisablingAction)
|
||||||
|
)
|
||||||
|
.setCoolingEnabled(settings.opentherm.options.coolingSupport)
|
||||||
|
.setDhwBlocking(dhwBlocking);
|
||||||
|
```
|
||||||
|
|
||||||
|
Не считай это общим требованием переносить имя объекта перед любой цепочкой.
|
||||||
|
В многострочных условиях сохраняй принятую рядом расстановку `&&` и `||`:
|
||||||
|
в проекте встречаются оба варианта переноса. Группируй связанные условия
|
||||||
|
скобками и не меняй их порядок или приоритет ради выравнивания.
|
||||||
|
|
||||||
|
## Имена и структура файлов
|
||||||
|
|
||||||
|
| Элемент | Принятый вид |
|
||||||
|
| --- | --- |
|
||||||
|
| Функции, методы, переменные, поля | `camelCase`: `readPressure`, `targetTemp` |
|
||||||
|
| Классы и структуры | `PascalCase`: `Message`, `Config`, `Float` |
|
||||||
|
| Задачи | Действие + предмет + `Task`: `writeRoomSetpointTask` |
|
||||||
|
| Менеджеры | Назначение + `TaskManager`: `openthermTaskManager` |
|
||||||
|
| Логические предикаты | По смыслу: `isSlaveReady`, `canUseBus`, `needWriteRoomSetpoint` |
|
||||||
|
| Макросы и значения обычных перечислений | `UPPER_SNAKE_CASE` по принятому API |
|
||||||
|
| Идентификаторы OpenTherm | Согласованное имя из API/спецификации: `TSet`, `Tr`, `TsetCH2` |
|
||||||
|
|
||||||
|
- Чтение ID обозначай префиксом `read`, запись — `write`. Если выделена функция,
|
||||||
|
её имя должно соответствовать задаче: `writeRoomSetpointTask` вызывает
|
||||||
|
`writeRoomSetpoint`, а не `setRoomSetpoint`.
|
||||||
|
- `get` уместен для получения уже имеющихся данных, например `Float::get()`.
|
||||||
|
Имя должно давать понять, выполняется ли обмен с устройством.
|
||||||
|
- Давай имена по смыслу данных. Различай комнатную температуру, температуру
|
||||||
|
теплоносителя, уставку, фактическое состояние и передаваемый флаг.
|
||||||
|
- Для GPIO используй `gpio`, направления — `rx` и `tx`: `rxGpio`, `txGpio`.
|
||||||
|
Тип номера GPIO ESP32 — `gpio_num_t`.
|
||||||
|
- Не добавляй избыточный контекст к имени внутри уже понятного namespace:
|
||||||
|
`Config`, а не `WorkerConfig`, если это общая конфигурация объекта.
|
||||||
|
- Для общей отправки сообщения используй согласованный термин `sendMessage`.
|
||||||
|
Не возвращай неясные `exchange` и `submit` в этот API.
|
||||||
|
- Не вводи служебные `Kind`, лишние псевдонимы и сокращения без понятной задачи.
|
||||||
|
- Имена модулей проекта сохраняй в существующем виде: `opentherm.cpp`,
|
||||||
|
`network.cpp`, `logging.cpp`; заголовки классов — по стилю соответствующего модуля.
|
||||||
|
- Группируй связанные типы осмысленными namespace и каталогами с заглавной буквы:
|
||||||
|
`ESP32OT::Messages`, `Messages/Float.h`.
|
||||||
|
Часто используемые общие типы не прячь без необходимости глубже:
|
||||||
|
`ESP32OT::MessageID::TSet`.
|
||||||
|
|
||||||
|
Внутри namespace тоже нужен отступ:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
namespace ESP32OT {
|
||||||
|
namespace Messages {
|
||||||
|
// Message declarations belong here.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Выравнивай колонки длинных перечислений и таблиц констант по окружающему коду.
|
||||||
|
Не добавляй дублирующие значения перечислений ради короткого синонима.
|
||||||
|
|
||||||
|
## Условия и поток выполнения
|
||||||
|
|
||||||
|
Для неуспешного результата предпочитай ранний выход, после которого основной
|
||||||
|
путь остаётся линейным:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
if (!response.isSuccess()) {
|
||||||
|
ESP_LOGW(L_OT_HEATING, "Failed set current indoor temp");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
vars.slave.heating.indoorTemp = response.get();
|
||||||
|
|
||||||
|
if (response.getData() != request.getData()) {
|
||||||
|
ESP_LOGW(
|
||||||
|
L_OT_HEATING, responseMismatchMessage,
|
||||||
|
request.getData(), response.getData()
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
ESP_LOGI(L_OT_HEATING, "Set current indoor temp: %.2f", vars.slave.heating.indoorTemp);
|
||||||
|
```
|
||||||
|
|
||||||
|
Ранний выход не должен пропускать обязательную последующую работу: проверку
|
||||||
|
связи, коррекцию ограничений, следующую независимую операцию или обновление
|
||||||
|
состояния. Сохраняй порядок действий исходного алгоритма.
|
||||||
|
|
||||||
|
Вложенность уместна, когда она показывает настоящую зависимость операций.
|
||||||
|
Например, ошибка необязательной записи `MaxTSet` не должна отменять следующую
|
||||||
|
обязательную запись `TSet`:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
if (settings.opentherm.options.maxTempSyncWithTargetTemp) {
|
||||||
|
const auto response = slave.sendRequest(maxTemperatureRequest);
|
||||||
|
|
||||||
|
if (response.isSuccess() && response.getData() == maxTemperatureRequest.getData()) {
|
||||||
|
ESP_LOGI(L_OT_HEATING, "Set max heating temp");
|
||||||
|
|
||||||
|
} else {
|
||||||
|
ESP_LOGW(L_OT_HEATING, "Failed set max heating temp");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send TSet even if the optional MaxTSet write failed.
|
||||||
|
const auto response = slave.sendRequest(heatingSetpointRequest);
|
||||||
|
```
|
||||||
|
|
||||||
|
Общее присваивание перед проверкой echo можно сохранить и в линейном коде
|
||||||
|
с ранними выходами; само по себе оно не требует дополнительной вложенности.
|
||||||
|
|
||||||
|
- Не заменяй все условия одним шаблоном автоматически. Выбирай структуру,
|
||||||
|
которая ясно показывает зависимости и сохраняет побочные эффекты.
|
||||||
|
- Предпочитай обычный `while` конструкции `for (; condition; ...)`.
|
||||||
|
- Не строй большие `switch` для ручной диспетчеризации ID или шагов, если
|
||||||
|
операции естественно выражаются отдельными задачами.
|
||||||
|
- В небольших учебных примерах, например Slave, `switch` по ID уместен.
|
||||||
|
Ветви одного уровня оформляй одинаково: `if / else if / else`, с `break`
|
||||||
|
для завершения `case`. Не смешивай без причины выход из `case` и всей функции.
|
||||||
|
|
||||||
|
## Функции, типы и абстракции
|
||||||
|
|
||||||
|
- Для локальных функций и данных `.cpp` используй `static`, а не анонимный namespace.
|
||||||
|
- Не добавляй `inline` только потому, что функция короткая. В `.cpp` это не нужно
|
||||||
|
для выбора оптимизации компилятором; в заголовках учитывай ODR и способ определения.
|
||||||
|
- `this->` необязателен. Не добавляй без необходимости (конфликтов).
|
||||||
|
- Небольшую функцию, вызываемую только одной задачей, можно встроить в callback.
|
||||||
|
Содержательный повторно используемый алгоритм оставляй отдельной функцией.
|
||||||
|
- Callback, используемый один раз, обычно записывай лямбдой на месте регистрации.
|
||||||
|
Общий `onDone` нескольких задач может быть отдельной `static` функцией.
|
||||||
|
- Никогда не объявляй лямбды и callbacks в заголовках `if`, `for`, `while`.
|
||||||
|
Вызов с callback записывай отдельным выражением; в условии проверяй результат.
|
||||||
|
- Не создавай обёртку, класс, файл, диспетчер или таблицу только ради структуры.
|
||||||
|
`constexpr`, шаблоны, наследование и контейнеры должны давать конкретную пользу.
|
||||||
|
- Используй `const` для неизменяемых данных. `auto` подходит, когда тип очевиден
|
||||||
|
из вызова; явный тип нужен там, где он поясняет формат или единицы данных.
|
||||||
|
- Выбирай тип по данным: фиксированную разрядность для бинарных полей протокола,
|
||||||
|
`gpio_num_t` для GPIO. Не вводи динамическое выделение там, где хватает значения.
|
||||||
|
- Не применяй `std::move` к обычному `float` и не усложняй владение без причины.
|
||||||
|
- Не дублируй состояние, проверки и парсинг, уже представленные в библиотеке,
|
||||||
|
`settings` или `vars`. Отдельный флаг нужен только для отдельного состояния.
|
||||||
|
- Сохраняй экономное использование flash и heap: общие строки в `strings.h`,
|
||||||
|
минимум лишних копий и частых выделений памяти. Рост динамических буферов
|
||||||
|
должен быть обоснован и ограничен по потребностям задачи.
|
||||||
|
|
||||||
|
## Оформление задач
|
||||||
|
|
||||||
|
- Перед каждым самостоятельным блоком добавления задач в менеджер пиши короткий
|
||||||
|
английский комментарий о назначении блока.
|
||||||
|
- Простые условия включения — поддержка функции, наличие датчика, готовность
|
||||||
|
устройства — размещай в `setEnabledWhen`, если нет отдельной причины проверять
|
||||||
|
их внутри тела. Не дублируй одно и то же условие механически в двух местах.
|
||||||
|
- Повторная проверка состояния оправдана, если оно могло измениться во время
|
||||||
|
блокирующей операции или определяет завершение последовательности.
|
||||||
|
- Настраивай период через `setInterval`. Не добавляй второй ручной таймер для
|
||||||
|
того же ограничения частоты. Время успешного ответа или потери связи может
|
||||||
|
иметь самостоятельный смысл и не является таким дублем.
|
||||||
|
- Не добавляй `resume(delay)` по шаблону: период задачи и отложенное возобновление
|
||||||
|
имеют разное назначение. Проверяй семантику используемой версии библиотеки.
|
||||||
|
- Не рассчитывай, что `forceRun()` проверяет `setEnabledWhen`: в используемой
|
||||||
|
Mycila он обходит условия. Для условного запуска ONCE нужен корректный вызов
|
||||||
|
с учётом её pause/resume, например `resume().tryRun()` или явная проверка:
|
||||||
|
```cpp
|
||||||
|
if (readModulationTask.idle() && readModulationTask.enabled()) {
|
||||||
|
readModulationTask.forceRun();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
- Не вводи ручной арбитраж, массивы шагов или систему приоритетов, когда достаточно
|
||||||
|
последовательного менеджера, интервалов и предикатов.
|
||||||
|
- Для обычных запросов внутри OpenTherm-задач используй понятный синхронный код.
|
||||||
|
Не превращай его в цепочки callback с большим `switch` только ради асинхронности, если это не влияет на производительность.
|
||||||
|
- Изменяй задачу через её изменяемый объект. Параметр `const Mycila::Task&`
|
||||||
|
в `onDone` нельзя использовать для вызова неконстантного `setInterval`.
|
||||||
|
|
||||||
|
Это правила читаемости, а не разрешение менять периоды, порядок операций или
|
||||||
|
условия управления устройством. Такие изменения требуют отдельного основания.
|
||||||
|
|
||||||
|
## Сообщения и логи
|
||||||
|
|
||||||
|
- Используй готовые типизированные Message-обёртки для сборки и разбора данных.
|
||||||
|
Не собирай raw вручную, чтобы затем сразу завернуть его в подходящий тип.
|
||||||
|
- Обёртка содержит функциональность своего формата/ID. Избыточное уточнение типа
|
||||||
|
в методе не нужно: `Float::get()`, а не `Float::getFloat()`.
|
||||||
|
- Доступ к raw сохраняй для низкоуровневой работы и логирования. Не создавай
|
||||||
|
автоматическую фабрику подклассов, `variant` или полиморфную диспетчеризацию,
|
||||||
|
если вызывающий код всё равно вручную выбирает формат и это не даёт другой пользы.
|
||||||
|
- Различай ошибку обмена и несовпадение подтверждённых данных. Для mismatch
|
||||||
|
используй понятный текст с ожидаемым и полученным значениями.
|
||||||
|
- Общий формат повторяющегося сообщения выноси в общую строку/константу.
|
||||||
|
Форматные спецификаторы должны соответствовать фактическим типам аргументов.
|
||||||
|
- Значения, нужные остальному проекту, сохраняй в соответствующих полях `vars`.
|
||||||
|
Не меняй порядок сохранения и проверки ответа только ради красивой ветки.
|
||||||
|
- При сравнении `float` выбирай допуск по физическому смыслу величины. Если
|
||||||
|
требуется точное совпадение переданных данных, используй их кодированное
|
||||||
|
представление, когда это предусмотрено логикой.
|
||||||
|
- Не помещай пароли, токены, секреты и приватные конфигурации в диагностические сообщения.
|
||||||
|
|
||||||
|
## Примеры, веб-код и документация
|
||||||
|
|
||||||
|
- Примеры показывают простой основной путь использования API. Избегай служебной
|
||||||
|
«магии», ручных счётчиков, флагов ожидания и скрытых требований к порядку вызовов,
|
||||||
|
если библиотека уже предоставляет нужный механизм.
|
||||||
|
- Поясняй неочевидные проверки результата, например зачем нужен `hasFrame()`
|
||||||
|
в обработчике статусов, допускающем завершение без принятого кадра.
|
||||||
|
- В примерах с GPIO-настройками через build flags, как TransparentProxy,
|
||||||
|
используй защищённые `#ifndef` значения по умолчанию. Вложенные директивы
|
||||||
|
оформляй с отступом:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
#ifndef BOILER_RX_GPIO
|
||||||
|
#define BOILER_RX_GPIO GPIO_NUM_35
|
||||||
|
#endif
|
||||||
|
```
|
||||||
|
|
||||||
|
- Не переноси в основной код предположения, допустимые только в демонстрации,
|
||||||
|
например безусловный `Serial.printf` из callback.
|
||||||
|
- HTML, CSS и JavaScript оформляй читаемо с отступами окружающего файла;
|
||||||
|
минификация выполняется при сборке. Для JS действуют те же требования к скобкам
|
||||||
|
и смысловому разделению блоков.
|
||||||
|
- Для недоверенного текста используй `textContent`/`setTextValue`. Вставка HTML
|
||||||
|
должна быть необходима по смыслу и учитывать происхождение данных.
|
||||||
|
- Сохраняй порядок полей структур в сериализации и обратном преобразовании.
|
||||||
|
- Основной README и комментарии — на английском, русская версия README —
|
||||||
|
отдельный документ. Этот CODESTYLE и рабочие заметки проекта могут быть
|
||||||
|
на русском.
|
||||||
|
|
||||||
|
## Перед завершением правки
|
||||||
|
|
||||||
|
- Сверь изменённый участок с окружающим кодом и последними указаниями пользователя.
|
||||||
|
- Проверь отступы, пустые строки, переносы цепочек, комментарии и окончания строк.
|
||||||
|
- Убери случайное переформатирование посторонних участков.
|
||||||
|
- Убедись, что сокращение кода не изменило порядок действий и обязательные ветки.
|
||||||
|
- Не добавляй правила, абстракции и исключения, не нужные для решаемой задачи.
|
||||||
@@ -1,50 +1,56 @@
|
|||||||
<div align="center">
|
<div align="center">
|
||||||
|
|
||||||

|
[](https://github.com/Laxilef/OTGateway/releases)
|
||||||
<br>
|
|
||||||
[](https://github.com/Laxilef/OTGateway/releases)
|
|
||||||
[](https://github.com/Laxilef/OTGateway/releases/latest)
|
[](https://github.com/Laxilef/OTGateway/releases/latest)
|
||||||
|
[](https://hosted.weblate.org/engage/otgateway/)
|
||||||
[](LICENSE.txt)
|
[](LICENSE.txt)
|
||||||
[](https://t.me/otgateway)
|
[](https://t.me/otgateway)
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
<hr />
|
||||||
|
|
||||||
|

|
||||||
|

|
||||||
|

|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
- Hot water temperature control
|
- DHW temperature control
|
||||||
- Heating temperature control
|
- Heating temperature control
|
||||||
- Smart heating temperature control modes:
|
- Smart heating temperature control modes:
|
||||||
- PID
|
- PID
|
||||||
- Equithermic curves - adjusts the temperature based on indoor and outdoor temperatures
|
- Equithermic curves - adjusts the temperature based on indoor and outdoor temperatures
|
||||||
- Hysteresis setting (for accurate maintenance of room temperature)
|
- Hysteresis setting _(for accurate maintenance of room temperature)_
|
||||||
- Ability to connect an external sensors to monitor outdoor and indoor temperature ([compatible sensors](#compatible-temperature-sensors))
|
- 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. If the Wi-Fi connection is lost or the gateway cannot connect to the MQTT server, the mode will turn on. This mode will automatically maintain the set temperature and prevent your home from freezing. In this mode it is also possible to use equithermal curves (weather-compensated control).
|
- Emergency mode. In any dangerous situation _(loss of connection with Wifi, MQTT, sensors, etc)_ it will not let you and your home freeze.
|
||||||
- Automatic error reset (not with all boilers)
|
- Ability of remote fault reset _(not with all boilers)_
|
||||||
- Diagnostics:
|
- Diagnostics:
|
||||||
- The process of heating: works/does not work
|
- Displaying gateway status
|
||||||
- The process of heating water for hot water: working/not working
|
- Displaying the connection status to the boiler via OpenTherm
|
||||||
- Display of boiler errors
|
- Displaying the fault status and fault code
|
||||||
- Burner status (flame): on/off
|
- Displaying the diagnostic status & diagnostic code
|
||||||
- Burner modulation level in percent
|
- Display of the process of heating: works/does not work
|
||||||
- Pressure in the heating system
|
- Display of burner (flame) status: on/off
|
||||||
- Gateway status (depending on errors and connection status)
|
- Display of burner modulation level in percent
|
||||||
- Boiler connection status via OpenTherm interface
|
- Display of pressure in the heating system
|
||||||
- The current temperature of the heat carrier (usually the return heat carrier)
|
- Display of current temperature of the heat carrier
|
||||||
- Set heat carrier temperature (depending on the selected mode)
|
- Display of return temperature of the heat carrier
|
||||||
- Current hot water temperature
|
- Display of setpoint heat carrier temperature (useful when using PID or Equitherm)
|
||||||
- Auto tuning of PID and Equitherm parameters *(in development)*
|
- Display of the process of DHW: working/not working
|
||||||
|
- Display of current DHW temperature
|
||||||
|
- _And other information..._
|
||||||
- [Home Assistant](https://www.home-assistant.io/) integration via MQTT. The ability to create any automation for the boiler!
|
- [Home Assistant](https://www.home-assistant.io/) integration via MQTT. The ability to create any automation for the boiler!
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
All available information and instructions can be found in the wiki:
|
All available information and instructions can be found in the wiki:
|
||||||
|
|
||||||
* [Home](https://github.com/Laxilef/OTGateway/wiki)
|
* [Home](https://github.com/Laxilef/OTGateway/wiki)
|
||||||
* [Quick Start](https://github.com/Laxilef/OTGateway/wiki#quick-start)
|
* [Quick Start](https://github.com/Laxilef/OTGateway/wiki#quick-start)
|
||||||
* [Build firmware](https://github.com/Laxilef/OTGateway/wiki#build-firmware)
|
* [Build firmware](https://github.com/Laxilef/OTGateway/wiki#build-firmware)
|
||||||
* [Flash firmware via ESP Flash Download Tool](https://github.com/Laxilef/OTGateway/wiki#flash-firmware-via-esp-flash-download-tool)
|
* [Flashing via Web Flasher](https://github.com/Laxilef/OTGateway/wiki#flashing-via-web-flasher)
|
||||||
* [HomeAsssistant settings](https://github.com/Laxilef/OTGateway/wiki#homeasssistant-settings)
|
* [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)
|
* [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 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)
|
* [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)
|
* [DHW meter](https://github.com/Laxilef/OTGateway/wiki#dhw-meter)
|
||||||
@@ -53,6 +59,7 @@ All available information and instructions can be found in the wiki:
|
|||||||
* [Ratios](https://github.com/Laxilef/OTGateway/wiki#ratios)
|
* [Ratios](https://github.com/Laxilef/OTGateway/wiki#ratios)
|
||||||
* [Fit coefficients](https://github.com/Laxilef/OTGateway/wiki#fit-coefficients)
|
* [Fit coefficients](https://github.com/Laxilef/OTGateway/wiki#fit-coefficients)
|
||||||
* [PID mode](https://github.com/Laxilef/OTGateway/wiki#pid-mode)
|
* [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)
|
* [Compatibility](https://github.com/Laxilef/OTGateway/wiki/Compatibility)
|
||||||
* [Boilers](https://github.com/Laxilef/OTGateway/wiki/Compatibility#boilers)
|
* [Boilers](https://github.com/Laxilef/OTGateway/wiki/Compatibility#boilers)
|
||||||
* [Boards](https://github.com/Laxilef/OTGateway/wiki/Compatibility#boards)
|
* [Boards](https://github.com/Laxilef/OTGateway/wiki/Compatibility#boards)
|
||||||
@@ -65,21 +72,18 @@ All available information and instructions can be found in the wiki:
|
|||||||
* [Connection](https://github.com/Laxilef/OTGateway/wiki/OT-adapters#connection)
|
* [Connection](https://github.com/Laxilef/OTGateway/wiki/OT-adapters#connection)
|
||||||
* [Leds on board](https://github.com/Laxilef/OTGateway/wiki/OT-adapters#leds-on-board)
|
* [Leds on board](https://github.com/Laxilef/OTGateway/wiki/OT-adapters#leds-on-board)
|
||||||
|
|
||||||
|
## Translations
|
||||||
|
The project uses [Weblate](https://hosted.weblate.org/new-lang/otgateway/) to manage translations of the interface.<br />
|
||||||
|
Anyone is welcome to add their native language as a [new localization](https://hosted.weblate.org/new-lang/otgateway/portal/). All contributions are welcome!
|
||||||
|
|
||||||
|
<a href="https://hosted.weblate.org/engage/otgateway/">
|
||||||
|
<img src="https://hosted.weblate.org/widget/otgateway/multi-auto.svg" alt="Translation status" />
|
||||||
|
</a>
|
||||||
|
|
||||||
## Dependencies
|
## Gratitude
|
||||||
- [ESP8266Scheduler](https://github.com/nrwiersma/ESP8266Scheduler) (for ESP8266)
|
* To the developers of the libraries used: [ArduinoJson](https://github.com/bblanchon/ArduinoJson), [NimBLE-Arduino](https://github.com/h2zero/NimBLE-Arduino), [MycilaMQTT](https://github.com/mathieucarbou/MycilaMQTT), [MycilaHADiscovery](https://github.com/mathieucarbou/MycilaHADiscovery), [AsyncTCP](https://github.com/ESP32Async/AsyncTCP), [ESPAsyncWebServer](https://github.com/ESP32Async/ESPAsyncWebServer), [MycilaWebSerial](https://github.com/mathieucarbou/MycilaWebSerial), [MycilaTaskManager](https://github.com/mathieucarbou/MycilaTaskManager), [FileData](https://github.com/GyverLibs/FileData), [GyverPID](https://github.com/GyverLibs/GyverPID), [GyverBlinker](https://github.com/GyverLibs/GyverBlinker), [OneWireNg](https://github.com/pstolarz/OneWireNg), [DallasTemperature](https://github.com/milesburton/Arduino-Temperature-Control-Library) & [esp32DHT](https://github.com/bertmelis/esp32DHT)
|
||||||
- [ESP32Scheduler](https://github.com/laxilef/ESP32Scheduler) (for ESP32)
|
* To the [PlatformIO](https://platformio.org/) Team
|
||||||
- [ArduinoJson](https://github.com/bblanchon/ArduinoJson)
|
* To the team and contributors of the [pioarduino](https://github.com/pioarduino/platform-espressif32) project
|
||||||
- [OpenTherm Library](https://github.com/ihormelnyk/opentherm_library)
|
* To the [BrowserStack](https://www.browserstack.com/) team. This project is tested with BrowserStack.
|
||||||
- [ArduinoMqttClient](https://github.com/arduino-libraries/ArduinoMqttClient) /
|
* To the [PVS-Studio](https://pvs-studio.com/pvs-studio/?utm_source=website&utm_medium=github&utm_campaign=open_source) - static analyzer for C, C++, C#, and Java code.
|
||||||
- [ESPTelnet](https://github.com/LennartHennigs/ESPTelnet)
|
* And of course to the contributors for their contribution to the development of the project!
|
||||||
- [FileData](https://github.com/GyverLibs/FileData)
|
|
||||||
- [GyverPID](https://github.com/GyverLibs/GyverPID)
|
|
||||||
- [GyverBlinker](https://github.com/GyverLibs/GyverBlinker)
|
|
||||||
- [DallasTemperature](https://github.com/milesburton/Arduino-Temperature-Control-Library)
|
|
||||||
- [TinyLogger](https://github.com/laxilef/TinyLogger)
|
|
||||||
|
|
||||||
## Debug
|
|
||||||
To display DEBUG messages you must enable debug in settings (switch is disabled by default).
|
|
||||||
You can connect via Telnet to read messages. IP: ESP8266 ip, port: 23
|
|
||||||
|
Before Width: | Height: | Size: 2.0 MiB |
|
Before Width: | Height: | Size: 97 KiB |
|
Before Width: | Height: | Size: 191 KiB |
@@ -1,3 +1,6 @@
|
|||||||
|
# Package for Home Assistant Packages
|
||||||
|
# More info: https://www.home-assistant.io/docs/configuration/packages/
|
||||||
|
|
||||||
dhw_meter:
|
dhw_meter:
|
||||||
sensor:
|
sensor:
|
||||||
- platform: integration
|
- platform: integration
|
||||||
|
|||||||
@@ -1,29 +0,0 @@
|
|||||||
# Script for reporting outdoor temperature to the controller from home assistant weather integration
|
|
||||||
# Updated: 07.12.2023
|
|
||||||
|
|
||||||
alias: Report outdoor temp to controller from weather
|
|
||||||
description: ""
|
|
||||||
variables:
|
|
||||||
# The source weather from which we take the temperature
|
|
||||||
source_entity: "weather.home"
|
|
||||||
|
|
||||||
# Target entity number where we set the temperature
|
|
||||||
# If the prefix has not changed, then you do not need to change it
|
|
||||||
target_entity: "number.opentherm_outdoor_temp"
|
|
||||||
trigger:
|
|
||||||
- platform: time_pattern
|
|
||||||
seconds: /30
|
|
||||||
condition:
|
|
||||||
- condition: template
|
|
||||||
value_template: "{{ states(source_entity) != 'unavailable' and states(target_entity) != 'unavailable' }}"
|
|
||||||
action:
|
|
||||||
- if:
|
|
||||||
- condition: template
|
|
||||||
value_template: "{{ (state_attr(source_entity, 'temperature')|float(0) - states(target_entity)|float(0)) | abs | round(2) >= 0.1 }}"
|
|
||||||
then:
|
|
||||||
- service: number.set_value
|
|
||||||
data:
|
|
||||||
value: "{{ state_attr(source_entity, 'temperature')|float(0)|round(2) }}"
|
|
||||||
target:
|
|
||||||
entity_id: "{{ target_entity }}"
|
|
||||||
mode: single
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
# Script for reporting indoor/outdoor temperature to the controller from any home assistant sensor
|
|
||||||
# Updated: 07.12.2023
|
|
||||||
|
|
||||||
alias: Report temp to controller
|
|
||||||
description: ""
|
|
||||||
variables:
|
|
||||||
# The source sensor from which we take the temperature
|
|
||||||
source_entity: "sensor.livingroom_temperature"
|
|
||||||
|
|
||||||
# Target entity number where we set the temperature
|
|
||||||
# To report indoor temperature: number.opentherm_indoor_temp
|
|
||||||
# To report outdoor temperature: number.opentherm_outdoor_temp
|
|
||||||
target_entity: "number.opentherm_indoor_temp"
|
|
||||||
trigger:
|
|
||||||
- platform: time_pattern
|
|
||||||
seconds: /30
|
|
||||||
condition:
|
|
||||||
- condition: template
|
|
||||||
value_template: "{{ states(source_entity) != 'unavailable' and states(target_entity) != 'unavailable' }}"
|
|
||||||
action:
|
|
||||||
- if:
|
|
||||||
- condition: template
|
|
||||||
value_template: "{{ (states(source_entity)|float(0) - states(target_entity)|float(0)) | abs | round(2) >= 0.01 }}"
|
|
||||||
then:
|
|
||||||
- service: number.set_value
|
|
||||||
data:
|
|
||||||
value: "{{ states(source_entity)|float(0)|round(2) }}"
|
|
||||||
target:
|
|
||||||
entity_id: "{{ target_entity }}"
|
|
||||||
mode: single
|
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
# Blueprint for reporting indoor/outdoor temperature to OpenTherm Gateway from any home assistant sensor
|
||||||
|
# Updated: 26.01.2026
|
||||||
|
|
||||||
|
blueprint:
|
||||||
|
name: Report temp to OpenTherm Gateway
|
||||||
|
domain: automation
|
||||||
|
author: "Laxilef"
|
||||||
|
|
||||||
|
input:
|
||||||
|
source_entity:
|
||||||
|
name: Source entity
|
||||||
|
description: "Temperature data source"
|
||||||
|
selector:
|
||||||
|
entity:
|
||||||
|
multiple: false
|
||||||
|
filter:
|
||||||
|
- domain: sensor
|
||||||
|
target_entity:
|
||||||
|
name: Target entity
|
||||||
|
description: "Usually ``number.opentherm_indoor_temp`` or ``number.opentherm_outdoor_temp``"
|
||||||
|
default: "number.opentherm_indoor_temp"
|
||||||
|
selector:
|
||||||
|
entity:
|
||||||
|
multiple: false
|
||||||
|
filter:
|
||||||
|
- domain: number
|
||||||
|
|
||||||
|
mode: single
|
||||||
|
variables:
|
||||||
|
source_entity: !input source_entity
|
||||||
|
target_entity: !input target_entity
|
||||||
|
trigger:
|
||||||
|
- platform: time_pattern
|
||||||
|
seconds: /30
|
||||||
|
condition:
|
||||||
|
- condition: template
|
||||||
|
value_template: "{{ states(source_entity) != 'unavailable' and states(target_entity) != 'unavailable' }}"
|
||||||
|
action:
|
||||||
|
- if:
|
||||||
|
- condition: or
|
||||||
|
conditions:
|
||||||
|
- condition: template
|
||||||
|
value_template: "{{ (states(source_entity)|float(0) - states(target_entity)|float(0)) | abs | round(2) >= 0.01 }}"
|
||||||
|
- condition: template
|
||||||
|
value_template: "{{ (as_timestamp(now()) - as_timestamp(states[target_entity].last_updated)) | int(0) > 300 }}"
|
||||||
|
then:
|
||||||
|
- service: number.set_value
|
||||||
|
data:
|
||||||
|
value: "{{ states(source_entity)|float(0)|round(2) }}"
|
||||||
|
target:
|
||||||
|
entity_id: "{{ target_entity }}"
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
# Blueprint for reporting temperature to OpenTherm Gateway from home assistant weather integration
|
||||||
|
# Updated: 26.01.2026
|
||||||
|
|
||||||
|
blueprint:
|
||||||
|
name: Report temp to OpenTherm Gateway from Weather
|
||||||
|
domain: automation
|
||||||
|
author: "Laxilef"
|
||||||
|
|
||||||
|
input:
|
||||||
|
source_entity:
|
||||||
|
name: Source entity
|
||||||
|
description: "Temperature data source"
|
||||||
|
selector:
|
||||||
|
entity:
|
||||||
|
multiple: false
|
||||||
|
filter:
|
||||||
|
- domain: weather
|
||||||
|
target_entity:
|
||||||
|
name: Target entity
|
||||||
|
description: "Usually ``number.opentherm_outdoor_temp``"
|
||||||
|
default: "number.opentherm_outdoor_temp"
|
||||||
|
selector:
|
||||||
|
entity:
|
||||||
|
multiple: false
|
||||||
|
filter:
|
||||||
|
- domain: number
|
||||||
|
|
||||||
|
mode: single
|
||||||
|
variables:
|
||||||
|
source_entity: !input source_entity
|
||||||
|
target_entity: !input target_entity
|
||||||
|
trigger:
|
||||||
|
- platform: time_pattern
|
||||||
|
seconds: /30
|
||||||
|
condition:
|
||||||
|
- condition: template
|
||||||
|
value_template: "{{ states(source_entity) != 'unavailable' and states(target_entity) != 'unavailable' }}"
|
||||||
|
action:
|
||||||
|
- if:
|
||||||
|
- condition: or
|
||||||
|
conditions:
|
||||||
|
- condition: template
|
||||||
|
value_template: "{{ (state_attr(source_entity, 'temperature')|float(0) - states(target_entity)|float(0)) | abs | round(2) >= 0.1 }}"
|
||||||
|
- condition: template
|
||||||
|
value_template: "{{ (as_timestamp(now()) - as_timestamp(states[target_entity].last_updated)) | int(0) > 300 }}"
|
||||||
|
then:
|
||||||
|
- service: number.set_value
|
||||||
|
data:
|
||||||
|
value: "{{ state_attr(source_entity, 'temperature')|float(0)|round(2) }}"
|
||||||
|
target:
|
||||||
|
entity_id: "{{ target_entity }}"
|
||||||
@@ -1 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8" standalone="no"?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="73.07594615189231mm" height="93.64998729997461mm" viewBox="4010 3269.5 287.7 368.7"><title>Просмотр платы</title><rect x="4010" y="3269.5" width="287.7" height="368.7" fill="#000000" stroke="none"/><defs xmlns="http://www.w3.org/2000/svg" id="patterns"><pattern id="gridPattern" x="4000" y="3000" width="10" height="10" patternUnits="userSpaceOnUse"><rect id="gridCell" x="0" y="0" width="0.7143" height="0.7143" fill="#FFFFFF" stroke="none"/></pattern><pattern id="gridPattern2" x="4000.7143" y="3000.7143" width="10" height="10" patternUnits="userSpaceOnUse"><path id="gridCell2" d="M10 0V10H-10" fill="none" stroke="#FFFFFF" stroke-width="0.7143" stroke-opacity="0.6"/></pattern><marker id="arrowOnStart" orient="auto" refY="0" refX="0" style="overflow:visible" markerUnits="strokeWidth"><path d="M 2,0 l 4,-2, 0,4 z" stroke-width="6"/></marker><marker id="arrowOnEnd" orient="auto" refY="0" refX="0" style="overflow:visible" markerUnits="strokeWidth"><path d="M -2,0 l -4,-2, 0,4 z" stroke-width="6"/></marker><marker id="arrowOnStartChrome" orient="auto" refY="0" refX="0" style="overflow:visible" markerUnits="strokeWidth"><path d="M 2,0 l 4,-2, 0,4 z" stroke-width="3" stroke="#FFFFFF"/></marker><marker id="arrowOnEndChrome" orient="auto" refY="0" refX="0" style="overflow:visible" markerUnits="strokeWidth"><path d="M -2,0 l -4,-2, 0,4 z" stroke-width="3" stroke="#FFFFFF"/></marker><svg id="icon-lock" title="Unlock" viewBox="0 0 20 20" height="20" width="20"><path stroke="#F0F" stroke-width="2" style="cursor:pointer;fill-opacity:.001;fill:#fff" d="M 5 7 C 5 -1 15 -1 15 7L1 7 1 19 19 19 19 7 15 7"/></svg><mask id="multiLayerMask" maskUnits="userSpaceOnUse" x="4020" y="3279.5" width="267.7" height="357.5"><path d="M4020.002 3623.1135,4020.002 3286.5005,4149.9219 3286.5005,4149.9219 3437.5309,4149.9221 3437.5398,4149.9221 3437.5403,4149.9298 3437.5405,4157.789 3437.5505,4157.7971 3437.5502,4157.7972 3437.5497,4157.7974 3437.5407,4157.7974 3339.4763,4287.7173 3339.4763,4287.7173 3569.7905,4157.7974 3569.7905,4157.7974 3471.3574,4157.7972 3471.3505,4157.7892 3471.3503,4149.9291 3471.3503,4149.9211 3471.3505,4149.9209 3471.3574,4149.9219 3569.7205,4149.9219 3623.1135z" stroke="none" fill="white"/><g fill="black"><circle cx="4281.3973" cy="3543.4145" r="1.7717" stroke-width="0"/><circle cx="4177.8374" cy="3511.9995" r="1.8" stroke-width="0"/><circle cx="4187.8374" cy="3512" r="1.8" stroke-width="0"/><circle cx="4177.8374" cy="3541.9995" r="1.8" stroke-width="0"/><circle cx="4187.8374" cy="3542" r="1.8" stroke-width="0"/><circle cx="4257.3374" cy="3511.9995" r="1.8" stroke-width="0"/><circle cx="4267.34" cy="3511.9995" r="1.8" stroke-width="0"/><circle cx="4257.3374" cy="3541.9995" r="1.8" stroke-width="0"/><circle cx="4267.3374" cy="3541.9995" r="1.8" stroke-width="0"/><circle cx="4034.35" cy="3406.5" r="1.75" stroke-width="0"/><circle cx="4048.95" cy="3406.5" r="1.8" stroke-width="0"/><circle cx="4272.7174" cy="3483.6389" r="1.5" stroke-width="0"/><circle cx="4272.7174" cy="3492.3011" r="1.5" stroke-width="0"/><circle cx="4192.7174" cy="3483.6399" r="1.5" stroke-width="0"/><circle cx="4192.7174" cy="3492.3011" r="1.5" stroke-width="0"/><circle cx="4236.4176" cy="3492.3011" r="1.5" stroke-width="0"/><circle cx="4236.4501" cy="3483.6495" r="1.5" stroke-width="0"/><circle cx="4163.9174" cy="3376.1685" r="2.1654" stroke-width="0"/><circle cx="4163.9174" cy="3366.1685" r="2.1654" stroke-width="0"/><circle cx="4163.9174" cy="3356.1685" r="2.1654" stroke-width="0"/><circle cx="4163.9174" cy="3346.1685" r="2.1654" stroke-width="0"/><circle cx="4281.3974" cy="3563.4125" r="1.7717" stroke-width="0"/><circle cx="4281.3974" cy="3553.4125" r="1.7717" stroke-width="0"/><circle cx="4281.3974" cy="3543.4125" r="1.7717" stroke-width="0"/><circle cx="4163.9174" cy="3563.4125" r="1.7717" stroke-width="0"/><circle cx="4163.9174" cy="3553.4125" r="1.7717" stroke-width="0"/><circle cx="4163.9174" cy="3543.4125" r="1.7717" stroke-width="0"/><circle cx="4281.3974" cy="3366.1685" r="1.7717" stroke-width="0"/><circle cx="4281.3974" cy="3356.1685" r="1.7717" stroke-width="0"/><circle cx="4281.3974" cy="3346.1685" r="1.7717" stroke-width="0"/><circle cx="4163.9174" cy="3533.4122" r="1.7717" stroke-width="0"/><circle cx="4143.5354" cy="3346.1685" r="1.7717" stroke-width="0"/><circle cx="4143.5354" cy="3356.1685" r="1.7717" stroke-width="0"/><circle cx="4143.5354" cy="3366.1685" r="1.7717" stroke-width="0"/><circle cx="4026.056" cy="3543.412" r="1.7717" stroke-width="0"/><circle cx="4026.0558" cy="3553.4125" r="1.7717" stroke-width="0"/><circle cx="4026.0554" cy="3563.4125" r="1.7717" stroke-width="0"/><circle cx="4143.5354" cy="3543.4125" r="1.7717" stroke-width="0"/><circle cx="4143.5354" cy="3553.4125" r="1.7717" stroke-width="0"/><circle cx="4143.5354" cy="3563.4125" r="1.7717" stroke-width="0"/>Line truncated
|
|
||||||
|
Before Width: | Height: | Size: 675 KiB |
|
Before Width: | Height: | Size: 155 KiB |
|
After Width: | Height: | Size: 1.0 MiB |
|
After Width: | Height: | Size: 1.0 MiB |
|
After Width: | Height: | Size: 973 KiB |
|
After Width: | Height: | Size: 283 KiB |
|
After Width: | Height: | Size: 386 KiB |
|
After Width: | Height: | Size: 849 KiB |
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 15 KiB |
@@ -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 |
|
Before Width: | Height: | Size: 37 KiB After Width: | Height: | Size: 37 KiB |
|
After Width: | Height: | Size: 33 KiB |
|
After Width: | Height: | Size: 33 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 17 KiB |
@@ -1,230 +0,0 @@
|
|||||||
<!doctype html>
|
|
||||||
<html lang="en">
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8" />
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
||||||
<title>OpenTherm Gateway</title>
|
|
||||||
<link rel="stylesheet" href="/static/pico.min.css">
|
|
||||||
<link rel="stylesheet" href="/static/app.css"/>
|
|
||||||
</head>
|
|
||||||
|
|
||||||
<body>
|
|
||||||
<header class="container">
|
|
||||||
<nav>
|
|
||||||
<ul>
|
|
||||||
<li><a href="/"><div class="logo">OpenTherm Gateway</div></a></li>
|
|
||||||
</ul>
|
|
||||||
<ul>
|
|
||||||
<li><a href="https://github.com/Laxilef/OTGateway/wiki" role="button" class="secondary" target="_blank">Help</a></li>
|
|
||||||
</ul>
|
|
||||||
</nav>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<main class="container">
|
|
||||||
<article>
|
|
||||||
<div>
|
|
||||||
<hgroup>
|
|
||||||
<h2>Network</h2>
|
|
||||||
<p></p>
|
|
||||||
</hgroup>
|
|
||||||
|
|
||||||
<div class="main-busy" aria-busy="true"></div>
|
|
||||||
<table class="main-table hidden">
|
|
||||||
<tbody>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">Hostname:</th>
|
|
||||||
<td><b class="network-hostname"></b></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">MAC:</th>
|
|
||||||
<td><b class="network-mac"></b></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">Connected:</th>
|
|
||||||
<td><input type="radio" class="network-connected" aria-invalid="false" checked disabled /></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">SSID:</th>
|
|
||||||
<td><b class="network-ssid"></b></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">Signal:</th>
|
|
||||||
<td><b class="network-signal"></b> %</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">IP:</th>
|
|
||||||
<td><b class="network-ip"></b></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">Subnet:</th>
|
|
||||||
<td><b class="network-subnet"></b></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">Gateway:</th>
|
|
||||||
<td><b class="network-gateway"></b></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">DNS:</th>
|
|
||||||
<td><b class="network-dns"></b></td>
|
|
||||||
</tr>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
<div class="grid">
|
|
||||||
<a href="/network.html" role="button">Network settings</a>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</article>
|
|
||||||
|
|
||||||
<article>
|
|
||||||
<div>
|
|
||||||
<hgroup>
|
|
||||||
<h2>System</h2>
|
|
||||||
<p></p>
|
|
||||||
</hgroup>
|
|
||||||
|
|
||||||
<div class="system-busy" aria-busy="true"></div>
|
|
||||||
<table class="system-table hidden">
|
|
||||||
<tbody>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">Version:</th>
|
|
||||||
<td><b class="version"></b></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">Build date:</th>
|
|
||||||
<td><b class="build-date"></b></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">Uptime:</th>
|
|
||||||
<td><b class="uptime-days"></b> days, <b class="uptime-hours"></b> hours, <b class="uptime-min"></b> min., <b class="uptime-sec"></b> sec.</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">Free memory:</th>
|
|
||||||
<td><b class="free-heap"></b> of <b class="total-heap"></b> bytes (min: <b class="min-free-heap"></b> bytes)<br>max free block: <b class="max-free-block-heap"></b> bytes (min: <b class="min-max-free-block-heap"></b> bytes)</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">Last reset reason:</th>
|
|
||||||
<td><b class="reset-reason"></b></td>
|
|
||||||
</tr>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
<div class="grid">
|
|
||||||
<a href="/settings.html" role="button">Settings</a>
|
|
||||||
<a href="/upgrade.html" role="button">Upgrade</a>
|
|
||||||
<a href="/restart.html" role="button" class="secondary restart">Restart</a>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</article>
|
|
||||||
|
|
||||||
<article>
|
|
||||||
<div>
|
|
||||||
<hgroup>
|
|
||||||
<h2>States and sensors</h2>
|
|
||||||
<p>More information and settings can be found in your home assistant after setting up network and MQTT</p>
|
|
||||||
</hgroup>
|
|
||||||
|
|
||||||
<div class="ot-busy" aria-busy="true"></div>
|
|
||||||
<table class="ot-table hidden">
|
|
||||||
<tbody>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">OpenTherm connected:</th>
|
|
||||||
<td><input type="radio" class="ot-connected" aria-invalid="false" checked disabled /></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">MQTT connected:</th>
|
|
||||||
<td><input type="radio" class="mqtt-connected" aria-invalid="false" checked disabled /></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">Emergency:</th>
|
|
||||||
<td><input type="radio" class="ot-emergency" aria-invalid="false" checked disabled /></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">Heating:</th>
|
|
||||||
<td><input type="radio" class="ot-heating" aria-invalid="false" checked disabled /></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">DHW:</th>
|
|
||||||
<td><input type="radio" class="ot-dhw" aria-invalid="false" checked disabled /></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">Flame:</th>
|
|
||||||
<td><input type="radio" class="ot-flame" aria-invalid="false" checked disabled /></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">Fault:</th>
|
|
||||||
<td><input type="radio" class="ot-fault" aria-invalid="false" checked disabled /></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">Diagnostic:</th>
|
|
||||||
<td><input type="radio" class="ot-diagnostic" aria-invalid="false" checked disabled /></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">External pump:</th>
|
|
||||||
<td><input type="radio" class="ot-external-pump" aria-invalid="false" checked disabled /></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">Modulation:</th>
|
|
||||||
<td><b class="ot-modulation"></b> %</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">Pressure:</th>
|
|
||||||
<td><b class="ot-pressure"></b> bar</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">DHW flow rate:</th>
|
|
||||||
<td><b class="ot-dhw-flow-rate"></b> l/min</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">Fault code:</th>
|
|
||||||
<td><b class="ot-fault-code"></b></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">Indoor temp:</th>
|
|
||||||
<td><b class="indoor-temp"></b> C</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">Outdoor temp:</th>
|
|
||||||
<td><b class="outdoor-temp"></b> C</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">Heating temp:</th>
|
|
||||||
<td><b class="heating-temp"></b> C</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">Heating setpoint temp:</th>
|
|
||||||
<td><b class="heating-setpoint-temp"></b> C</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<th scope="row">DHW temp:</th>
|
|
||||||
<td><b class="dhw-temp"></b> C</td>
|
|
||||||
</tr>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</article>
|
|
||||||
</main>
|
|
||||||
|
|
||||||
<footer class="container">
|
|
||||||
<small>
|
|
||||||
<b>Made by Laxilef</b>
|
|
||||||
• <a href="https://github.com/Laxilef/OTGateway/blob/master/LICENSE" target="_blank" class="secondary">License</a>
|
|
||||||
• <a href="https://github.com/Laxilef/OTGateway/blob/master/" target="_blank" class="secondary">Source code</a>
|
|
||||||
• <a href="https://github.com/Laxilef/OTGateway/wiki" target="_blank" class="secondary">Help</a>
|
|
||||||
• <a href="https://github.com/Laxilef/OTGateway/issue" target="_blank" class="secondary">Issue & questions</a>
|
|
||||||
• <a href="https://github.com/Laxilef/OTGateway/releases" target="_blank" class="secondary">Releases</a>
|
|
||||||
</small>
|
|
||||||
</footer>
|
|
||||||
|
|
||||||
<script src="/static/app.js"></script>
|
|
||||||
<script>
|
|
||||||
window.onload = async function () {
|
|
||||||
setTimeout(async function onLoadPage() {
|
|
||||||
await loadNetworkStatus();
|
|
||||||
await loadVars();
|
|
||||||
|
|
||||||
setTimeout(onLoadPage, 10000);
|
|
||||||
}, 1000);
|
|
||||||
};
|
|
||||||
</script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
@@ -1,166 +0,0 @@
|
|||||||
<!doctype html>
|
|
||||||
<html lang="en">
|
|
||||||
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8" />
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
||||||
<title>Network - OpenTherm Gateway</title>
|
|
||||||
<link rel="stylesheet" href="/static/pico.min.css">
|
|
||||||
<link rel="stylesheet" href="/static/app.css" />
|
|
||||||
</head>
|
|
||||||
|
|
||||||
<body>
|
|
||||||
<header class="container">
|
|
||||||
<nav>
|
|
||||||
<ul>
|
|
||||||
<li><a href="/"><div class="logo">OpenTherm Gateway</div></a></li>
|
|
||||||
</ul>
|
|
||||||
<ul>
|
|
||||||
<li><a href="https://github.com/Laxilef/OTGateway/wiki" role="button" class="secondary" target="_blank">Help</a></li>
|
|
||||||
</ul>
|
|
||||||
</nav>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<main class="container">
|
|
||||||
<article>
|
|
||||||
<div>
|
|
||||||
<hgroup>
|
|
||||||
<h2>Network settings</h2>
|
|
||||||
<p></p>
|
|
||||||
</hgroup>
|
|
||||||
|
|
||||||
<div id="network-settings-busy" aria-busy="true"></div>
|
|
||||||
<form action="/api/network/settings" id="network-settings" class="hidden">
|
|
||||||
<label for="hostname">
|
|
||||||
Hostname
|
|
||||||
<input type="text" class="network-hostname" name="hostname" maxlength="24" pattern="[A-Za-z0-9]+[A-Za-z0-9\-]+[A-Za-z0-9]+" required>
|
|
||||||
</label>
|
|
||||||
<label for="network-use-dhcp">
|
|
||||||
<input type="checkbox" class="network-use-dhcp" name="useDhcp" value="true">
|
|
||||||
Use DHCP
|
|
||||||
</label>
|
|
||||||
<br>
|
|
||||||
<hr>
|
|
||||||
<label for="network-static-ip">
|
|
||||||
Static IP:
|
|
||||||
<input type="text" class="network-static-ip" name="staticConfig[ip]" value="true" maxlength="16" pattern="\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" required>
|
|
||||||
</label>
|
|
||||||
<label for="network-static-gateway">
|
|
||||||
Static gateway:
|
|
||||||
<input type="text" class="network-static-gateway" name="staticConfig[gateway]" maxlength="16" pattern="\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" required>
|
|
||||||
</label>
|
|
||||||
<label for="network-static-subnet">
|
|
||||||
Static subnet:
|
|
||||||
<input type="text" class="network-static-subnet" name="staticConfig[subnet]" maxlength="16" pattern="\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" required>
|
|
||||||
</label>
|
|
||||||
<label for="network-static-dns">
|
|
||||||
Static DNS:
|
|
||||||
<input type="text" class="network-static-dns" name="staticConfig[dns]" maxlength="16" pattern="\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" required>
|
|
||||||
</label>
|
|
||||||
<button type="submit">Save</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</article>
|
|
||||||
|
|
||||||
<article>
|
|
||||||
<div>
|
|
||||||
<hgroup>
|
|
||||||
<h3>Available networks</h3>
|
|
||||||
<p></p>
|
|
||||||
</hgroup>
|
|
||||||
|
|
||||||
<form action="/api/network/scan" id="network-scan">
|
|
||||||
<figure style="max-height: 25em;">
|
|
||||||
<table id="networks" role="grid">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th scope="col">#</th>
|
|
||||||
<th scope="col">SSID</th>
|
|
||||||
<th scope="col">Signal</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody></tbody>
|
|
||||||
</table>
|
|
||||||
</figure>
|
|
||||||
<button type="submit">Refresh</button>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
<div>
|
|
||||||
<hgroup>
|
|
||||||
<h2>WiFi settings</h2>
|
|
||||||
<p></p>
|
|
||||||
</hgroup>
|
|
||||||
<div id="sta-settings-busy" aria-busy="true"></div>
|
|
||||||
<form action="/api/network/settings" id="sta-settings" class="hidden">
|
|
||||||
<label for="sta-ssid">
|
|
||||||
SSID:
|
|
||||||
<input type="text" class="sta-ssid" name="sta[ssid]" maxlength="32" required>
|
|
||||||
</label>
|
|
||||||
<label for="sta-password">
|
|
||||||
Password:
|
|
||||||
<input type="password" class="sta-password" name="sta[password]" maxlength="64" required>
|
|
||||||
</label>
|
|
||||||
<label for="sta-channel">
|
|
||||||
Channel:
|
|
||||||
<input type="number" inputmode="numeric" class="sta-channel" name="sta[channel]" min="0" max="12" step="1" required>
|
|
||||||
<small>set 0 for auto select</small>
|
|
||||||
</label>
|
|
||||||
|
|
||||||
<button type="submit">Save</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</article>
|
|
||||||
|
|
||||||
<article>
|
|
||||||
<div>
|
|
||||||
<hgroup>
|
|
||||||
<h2>AP settings</h2>
|
|
||||||
<p></p>
|
|
||||||
</hgroup>
|
|
||||||
<div id="ap-settings-busy" aria-busy="true"></div>
|
|
||||||
<form action="/api/network/settings" id="ap-settings" class="hidden">
|
|
||||||
<label for="ap-ssid">
|
|
||||||
SSID:
|
|
||||||
<input type="text" class="ap-ssid" name="ap[ssid]" maxlength="32" required>
|
|
||||||
</label>
|
|
||||||
<label for="ap-password">
|
|
||||||
Password:
|
|
||||||
<input type="text" class="ap-password" name="ap[password]" maxlength="64" required>
|
|
||||||
</label>
|
|
||||||
<label for="ap-channel">
|
|
||||||
Channel:
|
|
||||||
<input type="number" inputmode="numeric" class="ap-channel" name="ap[channel]" min="1" max="12" step="1" required>
|
|
||||||
</label>
|
|
||||||
<button type="submit">Save</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</article>
|
|
||||||
</main>
|
|
||||||
|
|
||||||
<footer class="container">
|
|
||||||
<small>
|
|
||||||
<b>Made by Laxilef</b>
|
|
||||||
• <a href="https://github.com/Laxilef/OTGateway/blob/master/LICENSE" target="_blank" class="secondary">License</a>
|
|
||||||
• <a href="https://github.com/Laxilef/OTGateway/blob/master/" target="_blank" class="secondary">Source code</a>
|
|
||||||
• <a href="https://github.com/Laxilef/OTGateway/wiki" target="_blank" class="secondary">Help</a>
|
|
||||||
• <a href="https://github.com/Laxilef/OTGateway/issue" target="_blank" class="secondary">Issue & questions</a>
|
|
||||||
• <a href="https://github.com/Laxilef/OTGateway/releases" target="_blank" class="secondary">Releases</a>
|
|
||||||
</small>
|
|
||||||
</footer>
|
|
||||||
|
|
||||||
<script src="/static/app.js"></script>
|
|
||||||
<script>
|
|
||||||
window.onload = async function () {
|
|
||||||
await loadNetworkSettings();
|
|
||||||
|
|
||||||
setupForm('#network-settings');
|
|
||||||
setupNetworkScanForm('#network-scan', '#networks');
|
|
||||||
setupForm('#sta-settings');
|
|
||||||
setupForm('#ap-settings');
|
|
||||||
};
|
|
||||||
</script>
|
|
||||||
</body>
|
|
||||||
|
|
||||||
</html>
|
|
||||||
@@ -1,357 +0,0 @@
|
|||||||
<!doctype html>
|
|
||||||
<html lang="en">
|
|
||||||
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8" />
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
||||||
<title>Settings - OpenTherm Gateway</title>
|
|
||||||
<link rel="stylesheet" href="/static/pico.min.css">
|
|
||||||
<link rel="stylesheet" href="/static/app.css" />
|
|
||||||
</head>
|
|
||||||
|
|
||||||
<body>
|
|
||||||
<header class="container">
|
|
||||||
<nav>
|
|
||||||
<ul>
|
|
||||||
<li><a href="/"><div class="logo">OpenTherm Gateway</div></a></li>
|
|
||||||
</ul>
|
|
||||||
<ul>
|
|
||||||
<li><a href="https://github.com/Laxilef/OTGateway/wiki" role="button" class="secondary" target="_blank">Help</a></li>
|
|
||||||
</ul>
|
|
||||||
</nav>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<main class="container">
|
|
||||||
<article>
|
|
||||||
<div>
|
|
||||||
<hgroup>
|
|
||||||
<h2>Portal settings</h2>
|
|
||||||
<p></p>
|
|
||||||
</hgroup>
|
|
||||||
|
|
||||||
<div id="portal-settings-busy" aria-busy="true"></div>
|
|
||||||
<form action="/api/settings" id="portal-settings" class="hidden">
|
|
||||||
<div class="grid">
|
|
||||||
<label for="portal-login">
|
|
||||||
Login
|
|
||||||
<input type="text" class="portal-login" name="portal[login]" maxlength="12" required>
|
|
||||||
</label>
|
|
||||||
<label for="portal-password">
|
|
||||||
Password
|
|
||||||
<input type="password" class="portal-password" name="portal[password]" maxlength="32" required>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<label for="portal-use-auth">
|
|
||||||
<input type="checkbox" class="portal-use-auth" name="portal[useAuth]" value="true">
|
|
||||||
Use auth
|
|
||||||
</label>
|
|
||||||
<br>
|
|
||||||
|
|
||||||
<button type="submit">Save</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</article>
|
|
||||||
|
|
||||||
<article>
|
|
||||||
<div>
|
|
||||||
<hgroup>
|
|
||||||
<h2>OpenTherm settings</h2>
|
|
||||||
<p></p>
|
|
||||||
</hgroup>
|
|
||||||
|
|
||||||
<div id="opentherm-settings-busy" aria-busy="true"></div>
|
|
||||||
<form action="/api/settings" id="opentherm-settings" class="hidden">
|
|
||||||
<div class="grid">
|
|
||||||
<label for="opentherm-in-pin">
|
|
||||||
In GPIO
|
|
||||||
<input type="number" inputmode="numeric" class="opentherm-in-pin" name="opentherm[inPin]" min="0" max="99" step="1" required>
|
|
||||||
</label>
|
|
||||||
<label for="opentherm-in-pin">
|
|
||||||
Out GPIO
|
|
||||||
<input type="number" inputmode="numeric" class="opentherm-out-pin" name="opentherm[outPin]" min="0" max="99" step="1" required>
|
|
||||||
</label>
|
|
||||||
<label for="opentherm-member-id-code">
|
|
||||||
Master MemberID code
|
|
||||||
<input type="number" inputmode="numeric" class="opentherm-member-id-code" name="opentherm[memberIdCode]" min="0" max="65535" step="1" required>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<fieldset>
|
|
||||||
<mark>After changing GPIO, the ESP must be restarted for the changes to take effect.</mark>
|
|
||||||
</fieldset>
|
|
||||||
|
|
||||||
<fieldset>
|
|
||||||
<legend>Options</legend>
|
|
||||||
<label for="opentherm-dhw-present">
|
|
||||||
<input type="checkbox" class="opentherm-dhw-present" name="opentherm[dhwPresent]" value="true">
|
|
||||||
DHW present
|
|
||||||
</label>
|
|
||||||
<label for="opentherm-sw-mode">
|
|
||||||
<input type="checkbox" class="opentherm-sw-mode" name="opentherm[summerWinterMode]" value="true">
|
|
||||||
Summer/winter mode
|
|
||||||
</label>
|
|
||||||
<label for="opentherm-heating-ch2-enabled">
|
|
||||||
<input type="checkbox" class="opentherm-heating-ch2-enabled" name="opentherm[heatingCh2Enabled]" value="true">
|
|
||||||
Heating CH2 always enabled
|
|
||||||
</label>
|
|
||||||
<label for="opentherm-heating-ch1-to-ch2">
|
|
||||||
<input type="checkbox" class="opentherm-heating-ch1-to-ch2" name="opentherm[heatingCh1ToCh2]" value="true">
|
|
||||||
Duplicate heating CH1 to CH2
|
|
||||||
</label>
|
|
||||||
<label for="opentherm-dhw-to-ch2">
|
|
||||||
<input type="checkbox" class="opentherm-dhw-to-ch2" name="opentherm[dhwToCh2]" value="true">
|
|
||||||
Duplicate DHW to CH2
|
|
||||||
</label>
|
|
||||||
<label for="opentherm-dhw-blocking">
|
|
||||||
<input type="checkbox" class="opentherm-dhw-blocking" name="opentherm[dhwBlocking]" value="true">
|
|
||||||
DHW blocking
|
|
||||||
</label>
|
|
||||||
<label for="opentherm-sync-modulation-with-heating">
|
|
||||||
<input type="checkbox" class="opentherm-sync-modulation-with-heating" name="opentherm[modulationSyncWithHeating]" value="true">
|
|
||||||
Sync modulation with heating
|
|
||||||
</label>
|
|
||||||
</fieldset>
|
|
||||||
|
|
||||||
<button type="submit">Save</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</article>
|
|
||||||
|
|
||||||
<article>
|
|
||||||
<div>
|
|
||||||
<hgroup>
|
|
||||||
<h2>MQTT settings</h2>
|
|
||||||
<p></p>
|
|
||||||
</hgroup>
|
|
||||||
|
|
||||||
<div id="mqtt-settings-busy" aria-busy="true"></div>
|
|
||||||
<form action="/api/settings" id="mqtt-settings" class="hidden">
|
|
||||||
<div class="grid">
|
|
||||||
<label for="mqtt-server">
|
|
||||||
Server
|
|
||||||
<input type="text" class="mqtt-server" name="mqtt[server]" maxlength="80" required>
|
|
||||||
</label>
|
|
||||||
<label for="mqtt-port">
|
|
||||||
Port
|
|
||||||
<input type="number" inputmode="numeric" class="mqtt-port" name="mqtt[port]" min="1" max="65535" step="1" required>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="grid">
|
|
||||||
<label for="mqtt-user">
|
|
||||||
User
|
|
||||||
<input type="text" class="mqtt-user" name="mqtt[user]" maxlength="32" required>
|
|
||||||
</label>
|
|
||||||
<label for="mqtt-password">
|
|
||||||
Password
|
|
||||||
<input type="password" class="mqtt-password" name="mqtt[password]" maxlength="32">
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="grid">
|
|
||||||
<label for="mqtt-prefix">
|
|
||||||
Prefix
|
|
||||||
<input type="text" class="mqtt-prefix" name="mqtt[prefix]" maxlength="32" required>
|
|
||||||
</label>
|
|
||||||
<label for="mqtt-interval">
|
|
||||||
Publish interval <small>(sec)</small>
|
|
||||||
<input type="number" inputmode="numeric" class="mqtt-interval" name="mqtt[interval]" min="3" max="60" step="1" required>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button type="submit">Save</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</article>
|
|
||||||
|
|
||||||
<article>
|
|
||||||
<div>
|
|
||||||
<hgroup>
|
|
||||||
<h2>Outdoor sensor settings</h2>
|
|
||||||
<p></p>
|
|
||||||
</hgroup>
|
|
||||||
|
|
||||||
<div id="outdoor-sensor-settings-busy" aria-busy="true"></div>
|
|
||||||
<form action="/api/settings" id="outdoor-sensor-settings" class="hidden">
|
|
||||||
<fieldset>
|
|
||||||
<legend>Source type</legend>
|
|
||||||
<label>
|
|
||||||
<input type="radio" class="outdoor-sensor-type" name="sensors[outdoor][type]" value="0" />
|
|
||||||
From boiler via OpenTherm
|
|
||||||
</label>
|
|
||||||
<label>
|
|
||||||
<input type="radio" class="outdoor-sensor-type" name="sensors[outdoor][type]" value="1" />
|
|
||||||
Manual via MQTT/API
|
|
||||||
</label>
|
|
||||||
<label>
|
|
||||||
<input type="radio" class="outdoor-sensor-type" name="sensors[outdoor][type]" value="2" />
|
|
||||||
External (DS18B20)
|
|
||||||
</label>
|
|
||||||
</fieldset>
|
|
||||||
|
|
||||||
<label for="outdoor-sensor-pin">
|
|
||||||
GPIO
|
|
||||||
<input type="number" inputmode="numeric" class="outdoor-sensor-pin" name="sensors[outdoor][pin]" min="0" max="99" step="1" required>
|
|
||||||
</label>
|
|
||||||
<label for="outdoor-sensor-offset">
|
|
||||||
Temp offset (calibration)
|
|
||||||
<input type="number" inputmode="numeric" class="outdoor-sensor-offset" name="sensors[outdoor][offset]" min="-20" max="20" step="0.01" required>
|
|
||||||
</label>
|
|
||||||
|
|
||||||
<button type="submit">Save</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</article>
|
|
||||||
|
|
||||||
<article>
|
|
||||||
<div>
|
|
||||||
<hgroup>
|
|
||||||
<h2>Indoor sensor settings</h2>
|
|
||||||
<p></p>
|
|
||||||
</hgroup>
|
|
||||||
|
|
||||||
<div id="indoor-sensor-settings-busy" aria-busy="true"></div>
|
|
||||||
<form action="/api/settings" id="indoor-sensor-settings" class="hidden">
|
|
||||||
<fieldset>
|
|
||||||
<legend>Source type</legend>
|
|
||||||
<label>
|
|
||||||
<input type="radio" class="indoor-sensor-type" name="sensors[indoor][type]" value="1" />
|
|
||||||
Manual via MQTT/API
|
|
||||||
</label>
|
|
||||||
<label>
|
|
||||||
<input type="radio" class="indoor-sensor-type" name="sensors[indoor][type]" value="2" />
|
|
||||||
External (DS18B20)
|
|
||||||
</label>
|
|
||||||
<label>
|
|
||||||
<input type="radio" class="indoor-sensor-type" name="sensors[indoor][type]" value="3" />
|
|
||||||
BLE device <i>(ONLY for some ESP32 which support BLE)</i>
|
|
||||||
</label>
|
|
||||||
</fieldset>
|
|
||||||
|
|
||||||
<label for="indoor-sensor-pin">
|
|
||||||
GPIO
|
|
||||||
<input type="number" inputmode="numeric" class="indoor-sensor-pin" name="sensors[indoor][pin]" min="0" max="99" step="1" required>
|
|
||||||
</label>
|
|
||||||
|
|
||||||
<div class="grid">
|
|
||||||
<label for="indoor-sensor-offset">
|
|
||||||
Temp offset (calibration)
|
|
||||||
<input type="number" inputmode="numeric" class="indoor-sensor-offset" name="sensors[indoor][offset]" min="-20" max="20" step="0.01" required>
|
|
||||||
</label>
|
|
||||||
<label for="indoor-sensor-ble-addresss">
|
|
||||||
BLE addresss
|
|
||||||
<input type="text" class="indoor-sensor-ble-addresss" name="sensors[indoor][bleAddresss]" pattern="([A-Fa-f0-9]{2}:){5}[A-Fa-f0-9]{2}">
|
|
||||||
<small>ONLY for some ESP32 which support BLE</small>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button type="submit">Save</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</article>
|
|
||||||
|
|
||||||
<article>
|
|
||||||
<div>
|
|
||||||
<hgroup>
|
|
||||||
<h2>External pump settings</h2>
|
|
||||||
<p></p>
|
|
||||||
</hgroup>
|
|
||||||
|
|
||||||
<div id="extpump-settings-busy" aria-busy="true"></div>
|
|
||||||
<form action="/api/settings" id="extpump-settings" class="hidden">
|
|
||||||
<label for="extpump-use">
|
|
||||||
<input type="checkbox" class="extpump-use" name="externalPump[use]" value="true">
|
|
||||||
Use external pump
|
|
||||||
</label>
|
|
||||||
<br>
|
|
||||||
|
|
||||||
<div class="grid">
|
|
||||||
<label for="extpump-pin">
|
|
||||||
Relay GPIO
|
|
||||||
<input type="number" inputmode="numeric" class="extpump-pin" name="externalPump[pin]" min="0" max="99" step="1" required>
|
|
||||||
</label>
|
|
||||||
<label for="extpump-pc-time">
|
|
||||||
Post circulation time <small>(min)</small>
|
|
||||||
<input type="number" inputmode="numeric" class="extpump-pc-time" name="externalPump[postCirculationTime]" min="1" max="120" step="1" required>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="grid">
|
|
||||||
<label for="extpump-as-interval">
|
|
||||||
Anti stuck interval <small>(days)</small>
|
|
||||||
<input type="number" inputmode="numeric" class="extpump-as-interval" name="externalPump[antiStuckInterval]" min="1" max="366" step="1" required>
|
|
||||||
</label>
|
|
||||||
<label for="extpump-as-time">
|
|
||||||
Anti stuck time <small>(min)</small>
|
|
||||||
<input type="number" inputmode="numeric" class="extpump-as-time" name="externalPump[antiStuckTime]" min="1" max="20" step="1" required>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button type="submit">Save</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</article>
|
|
||||||
|
|
||||||
<article>
|
|
||||||
<div>
|
|
||||||
<hgroup>
|
|
||||||
<h2>System settings</h2>
|
|
||||||
<p></p>
|
|
||||||
</hgroup>
|
|
||||||
|
|
||||||
<div id="system-settings-busy" aria-busy="true"></div>
|
|
||||||
<form action="/api/settings" id="system-settings" class="hidden">
|
|
||||||
<fieldset>
|
|
||||||
<label for="system-debug">
|
|
||||||
<input type="checkbox" class="system-debug" name="system[debug]" value="true">
|
|
||||||
Debug mode
|
|
||||||
</label>
|
|
||||||
<label for="system-use-serial">
|
|
||||||
<input type="checkbox" class="system-use-serial" name="system[useSerial]" value="true">
|
|
||||||
Enable serial port
|
|
||||||
</label>
|
|
||||||
<label for="system-use-telnet">
|
|
||||||
<input type="checkbox" class="system-use-telnet" name="system[useTelnet]" value="true">
|
|
||||||
Enable telnet
|
|
||||||
</label>
|
|
||||||
</fieldset>
|
|
||||||
|
|
||||||
<fieldset>
|
|
||||||
<mark>After changing this settings, the ESP must be restarted for the changes to take effect.</mark>
|
|
||||||
</fieldset>
|
|
||||||
|
|
||||||
<button type="submit">Save</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</article>
|
|
||||||
</main>
|
|
||||||
|
|
||||||
<footer class="container">
|
|
||||||
<small>
|
|
||||||
<b>Made by Laxilef</b>
|
|
||||||
• <a href="https://github.com/Laxilef/OTGateway/blob/master/LICENSE" target="_blank" class="secondary">License</a>
|
|
||||||
• <a href="https://github.com/Laxilef/OTGateway/blob/master/" target="_blank" class="secondary">Source code</a>
|
|
||||||
• <a href="https://github.com/Laxilef/OTGateway/wiki" target="_blank" class="secondary">Help</a>
|
|
||||||
• <a href="https://github.com/Laxilef/OTGateway/issue" target="_blank" class="secondary">Issue & questions</a>
|
|
||||||
• <a href="https://github.com/Laxilef/OTGateway/releases" target="_blank" class="secondary">Releases</a>
|
|
||||||
</small>
|
|
||||||
</footer>
|
|
||||||
|
|
||||||
<script src="/static/app.js"></script>
|
|
||||||
<script>
|
|
||||||
window.onload = async function () {
|
|
||||||
await loadSettings();
|
|
||||||
|
|
||||||
setupForm('#portal-settings');
|
|
||||||
setupForm('#opentherm-settings');
|
|
||||||
setupForm('#mqtt-settings');
|
|
||||||
setupForm('#outdoor-sensor-settings');
|
|
||||||
setupForm('#indoor-sensor-settings');
|
|
||||||
setupForm('#extpump-settings');
|
|
||||||
setupForm('#system-settings');
|
|
||||||
};
|
|
||||||
</script>
|
|
||||||
</body>
|
|
||||||
|
|
||||||
</html>
|
|
||||||
@@ -1,108 +0,0 @@
|
|||||||
<!doctype html>
|
|
||||||
<html lang="en">
|
|
||||||
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8" />
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
||||||
<title>Upgrade - OpenTherm Gateway</title>
|
|
||||||
<link rel="stylesheet" href="/static/pico.min.css">
|
|
||||||
<link rel="stylesheet" href="/static/app.css">
|
|
||||||
</head>
|
|
||||||
|
|
||||||
<body>
|
|
||||||
<header class="container">
|
|
||||||
<nav>
|
|
||||||
<ul>
|
|
||||||
<li><a href="/"><div class="logo">OpenTherm Gateway</div></a></li>
|
|
||||||
</ul>
|
|
||||||
<ul>
|
|
||||||
<li><a href="https://github.com/Laxilef/OTGateway/wiki" role="button" class="secondary" target="_blank">Help</a></li>
|
|
||||||
</ul>
|
|
||||||
</nav>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<main class="container">
|
|
||||||
<article>
|
|
||||||
<div>
|
|
||||||
<hgroup>
|
|
||||||
<h2>Backup & restore</h2>
|
|
||||||
<p>
|
|
||||||
In this section you can save and restore a backup of ALL settings.
|
|
||||||
</p>
|
|
||||||
</hgroup>
|
|
||||||
|
|
||||||
<form action="/api/backup/restore" id="restore">
|
|
||||||
<label for="restore-file">
|
|
||||||
Settings file:
|
|
||||||
<input type="file" name="settings" id="restore-file" accept=".json">
|
|
||||||
</label>
|
|
||||||
|
|
||||||
<div class="grid">
|
|
||||||
<button type="submit">Restore</button>
|
|
||||||
<button type="button" class="secondary" onclick="window.location='/api/backup/save';">Backup</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</article>
|
|
||||||
|
|
||||||
<article>
|
|
||||||
<div>
|
|
||||||
<hgroup>
|
|
||||||
<h2>Upgrade</h2>
|
|
||||||
<p>
|
|
||||||
In this section you can upgrade the firmware and filesystem of your device.<br>
|
|
||||||
Latest releases can be downloaded from the <a href="https://github.com/Laxilef/OTGateway/releases" target="_blank">Releases page</a> of the project repository.
|
|
||||||
</p>
|
|
||||||
</hgroup>
|
|
||||||
|
|
||||||
<form action="/api/upgrade" id="upgrade">
|
|
||||||
<fieldset class="primary">
|
|
||||||
<label for="firmware-file">
|
|
||||||
Firmware:
|
|
||||||
<div class="grid">
|
|
||||||
<input type="file" name="firmware" id="firmware-file" accept=".bin">
|
|
||||||
<button type="button" class="upgrade-firmware-result hidden" disabled></button>
|
|
||||||
</div>
|
|
||||||
</label>
|
|
||||||
|
|
||||||
<label for="filesystem-file">
|
|
||||||
Filesystem:
|
|
||||||
<div class="grid">
|
|
||||||
<input type="file" name="filesystem" id="filesystem-file" accept=".bin">
|
|
||||||
<button type="button" class="upgrade-filesystem-result hidden" disabled></button>
|
|
||||||
</div>
|
|
||||||
</label>
|
|
||||||
</fieldset>
|
|
||||||
|
|
||||||
<ul>
|
|
||||||
<li><mark>After a successful upgrade the filesystem, ALL settings will be reset to default values! Save backup before upgrading.</mark></li>
|
|
||||||
<li><mark>After a successful upgrade, the device will automatically reboot after 10 seconds.</mark></li>
|
|
||||||
</ul>
|
|
||||||
|
|
||||||
<button type="submit">Upgrade</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</article>
|
|
||||||
</main>
|
|
||||||
|
|
||||||
<footer class="container">
|
|
||||||
<small>
|
|
||||||
<b>Made by Laxilef</b>
|
|
||||||
• <a href="https://github.com/Laxilef/OTGateway/blob/master/LICENSE" target="_blank" class="secondary">License</a>
|
|
||||||
• <a href="https://github.com/Laxilef/OTGateway/blob/master/" target="_blank" class="secondary">Source code</a>
|
|
||||||
• <a href="https://github.com/Laxilef/OTGateway/wiki" target="_blank" class="secondary">Help</a>
|
|
||||||
• <a href="https://github.com/Laxilef/OTGateway/issue" target="_blank" class="secondary">Issue & questions</a>
|
|
||||||
• <a href="https://github.com/Laxilef/OTGateway/releases" target="_blank" class="secondary">Releases</a>
|
|
||||||
</small>
|
|
||||||
</footer>
|
|
||||||
|
|
||||||
<script src="/static/app.js"></script>
|
|
||||||
<script>
|
|
||||||
window.onload = async function () {
|
|
||||||
setupRestoreBackupForm('#restore');
|
|
||||||
setupUpgradeForm('#upgrade');
|
|
||||||
};
|
|
||||||
</script>
|
|
||||||
</body>
|
|
||||||
|
|
||||||
</html>
|
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
const { src, dest, parallel } = require('gulp');
|
||||||
|
const concat = require('gulp-concat');
|
||||||
|
const gzip = require('gulp-gzip');
|
||||||
|
const postcss = require('gulp-postcss');
|
||||||
|
const cssnano = require('cssnano');
|
||||||
|
const terser = require('gulp-terser');
|
||||||
|
const jsonminify = require('gulp-jsonminify');
|
||||||
|
const htmlmin = require('gulp-html-minifier-terser');
|
||||||
|
const replace = require('gulp-replace');
|
||||||
|
|
||||||
|
// Paths for tasks
|
||||||
|
let paths = {
|
||||||
|
styles: {
|
||||||
|
dest: 'data/static/',
|
||||||
|
bundles: {
|
||||||
|
'app.css': [
|
||||||
|
'src_data/styles/pico.min.css',
|
||||||
|
'src_data/styles/iconly.css',
|
||||||
|
'src_data/styles/app.css'
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
scripts: {
|
||||||
|
dest: 'data/static/',
|
||||||
|
bundles: {
|
||||||
|
'app.js': [
|
||||||
|
'src_data/scripts/i18n.min.js',
|
||||||
|
'src_data/scripts/lang.js',
|
||||||
|
'src_data/scripts/utils.js'
|
||||||
|
],
|
||||||
|
'settings-converter.js': [
|
||||||
|
'src_data/scripts/settings-converter.js'
|
||||||
|
],
|
||||||
|
'chart.js': [
|
||||||
|
'src_data/scripts/chart.js'
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
json: [
|
||||||
|
{
|
||||||
|
src: 'src_data/locales/*.json',
|
||||||
|
dest: 'data/static/locales/'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
src: 'src_data/*.json',
|
||||||
|
dest: 'data/static/'
|
||||||
|
}
|
||||||
|
],
|
||||||
|
static: [
|
||||||
|
{
|
||||||
|
src: 'src_data/fonts/*.*',
|
||||||
|
dest: 'data/static/fonts/'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
src: 'src_data/images/*.*',
|
||||||
|
dest: 'data/static/images/'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
src: 'src_data/*.txt',
|
||||||
|
dest: 'data/static/'
|
||||||
|
}
|
||||||
|
],
|
||||||
|
pages: {
|
||||||
|
src: 'src_data/pages/*.html',
|
||||||
|
dest: 'data/pages/'
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// Tasks
|
||||||
|
const styles = parallel(...Object.entries(paths.styles.bundles).map(([name, items]) => {
|
||||||
|
return () => src(items)
|
||||||
|
.pipe(replace(
|
||||||
|
"{BUILD_TIME}",
|
||||||
|
Math.floor(Date.now() / 1000)
|
||||||
|
))
|
||||||
|
.pipe(postcss([
|
||||||
|
cssnano({ preset: 'advanced' })
|
||||||
|
]))
|
||||||
|
.pipe(concat(name))
|
||||||
|
.pipe(gzip({
|
||||||
|
append: true
|
||||||
|
}))
|
||||||
|
.pipe(dest(paths.styles.dest));
|
||||||
|
}));
|
||||||
|
|
||||||
|
const scripts = parallel(...Object.entries(paths.scripts.bundles).map(([name, items]) => {
|
||||||
|
return () => src(items)
|
||||||
|
.pipe(replace(
|
||||||
|
"{BUILD_TIME}",
|
||||||
|
Math.floor(Date.now() / 1000)
|
||||||
|
))
|
||||||
|
.pipe(terser())
|
||||||
|
.pipe(concat(name))
|
||||||
|
.pipe(gzip({
|
||||||
|
append: true
|
||||||
|
}))
|
||||||
|
.pipe(dest(paths.scripts.dest));
|
||||||
|
}));
|
||||||
|
|
||||||
|
const jsonFiles = parallel(...paths.json.map((item) => {
|
||||||
|
return () => src(item.src)
|
||||||
|
.pipe(replace(
|
||||||
|
"{BUILD_TIME}",
|
||||||
|
Math.floor(Date.now() / 1000)
|
||||||
|
))
|
||||||
|
.pipe(jsonminify())
|
||||||
|
.pipe(gzip({
|
||||||
|
append: true
|
||||||
|
}))
|
||||||
|
.pipe(dest(item.dest));
|
||||||
|
}));
|
||||||
|
|
||||||
|
const staticFiles = parallel(...paths.static.map((item) => {
|
||||||
|
return () => src(item.src, { encoding: false })
|
||||||
|
.pipe(gzip({
|
||||||
|
append: true
|
||||||
|
}))
|
||||||
|
.pipe(dest(item.dest));
|
||||||
|
}));
|
||||||
|
|
||||||
|
const pages = () => {
|
||||||
|
return src(paths.pages.src)
|
||||||
|
.pipe(replace(
|
||||||
|
"{BUILD_TIME}",
|
||||||
|
Math.floor(Date.now() / 1000)
|
||||||
|
))
|
||||||
|
.pipe(htmlmin({
|
||||||
|
html5: true,
|
||||||
|
caseSensitive: true,
|
||||||
|
collapseWhitespace: true,
|
||||||
|
collapseInlineTagWhitespace: true,
|
||||||
|
conservativeCollapse: true,
|
||||||
|
removeComments: true,
|
||||||
|
minifyJS: true
|
||||||
|
}))
|
||||||
|
.pipe(gzip({
|
||||||
|
append: true
|
||||||
|
}))
|
||||||
|
.pipe(dest(paths.pages.dest));
|
||||||
|
}
|
||||||
|
|
||||||
|
exports.build_styles = styles;
|
||||||
|
exports.build_scripts = scripts;
|
||||||
|
exports.build_json = jsonFiles;
|
||||||
|
exports.build_static = staticFiles;
|
||||||
|
exports.build_pages = pages;
|
||||||
|
exports.build_all = parallel(styles, scripts, jsonFiles, staticFiles, pages);
|
||||||
@@ -0,0 +1,770 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include <esp_log.h>
|
||||||
|
#include <errno.h>
|
||||||
|
#include <cmath>
|
||||||
|
#include <functional>
|
||||||
|
#include <math.h>
|
||||||
|
#include <mutex>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "macros.h"
|
||||||
|
#include "utils.h"
|
||||||
|
#include "strings_shared.h"
|
||||||
|
|
||||||
|
class Sensors {
|
||||||
|
protected:
|
||||||
|
static uint8_t maxSensors;
|
||||||
|
|
||||||
|
public:
|
||||||
|
enum class Type : uint8_t {
|
||||||
|
OT_OUTDOOR_TEMP = 0,
|
||||||
|
OT_HEATING_TEMP = 1,
|
||||||
|
OT_HEATING_RETURN_TEMP = 2,
|
||||||
|
OT_DHW_TEMP = 3,
|
||||||
|
OT_DHW_TEMP2 = 4,
|
||||||
|
OT_DHW_FLOW_RATE = 5,
|
||||||
|
OT_CH2_TEMP = 6,
|
||||||
|
OT_EXHAUST_TEMP = 7,
|
||||||
|
OT_HEAT_EXCHANGER_TEMP = 8,
|
||||||
|
OT_PRESSURE = 9,
|
||||||
|
OT_MODULATION_LEVEL = 10,
|
||||||
|
OT_CURRENT_POWER = 11,
|
||||||
|
OT_EXHAUST_CO2 = 12,
|
||||||
|
OT_EXHAUST_FAN_SPEED = 13,
|
||||||
|
OT_SUPPLY_FAN_SPEED = 14,
|
||||||
|
OT_SOLAR_STORAGE_TEMP = 15,
|
||||||
|
OT_SOLAR_COLLECTOR_TEMP = 16,
|
||||||
|
OT_FAN_SPEED_SETPOINT = 17,
|
||||||
|
OT_FAN_SPEED_CURRENT = 18,
|
||||||
|
|
||||||
|
OT_BURNER_STARTS = 19,
|
||||||
|
OT_DHW_BURNER_STARTS = 20,
|
||||||
|
OT_HEATING_PUMP_STARTS = 21,
|
||||||
|
OT_DHW_PUMP_STARTS = 22,
|
||||||
|
OT_BURNER_HOURS = 23,
|
||||||
|
OT_DHW_BURNER_HOURS = 24,
|
||||||
|
OT_HEATING_PUMP_HOURS = 25,
|
||||||
|
OT_DHW_PUMP_HOURS = 26,
|
||||||
|
OT_COOLING_HOURS = 27,
|
||||||
|
|
||||||
|
NTC_10K_TEMP = 50,
|
||||||
|
DALLAS_TEMP = 51,
|
||||||
|
BLUETOOTH = 52,
|
||||||
|
DHT11 = 53,
|
||||||
|
DHT22 = 54,
|
||||||
|
|
||||||
|
HEATING_SETPOINT_TEMP = 253,
|
||||||
|
MANUAL = 254,
|
||||||
|
NOT_CONFIGURED = 255
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class Purpose : uint8_t {
|
||||||
|
OUTDOOR_TEMP = 0,
|
||||||
|
INDOOR_TEMP = 1,
|
||||||
|
HEATING_TEMP = 2,
|
||||||
|
HEATING_RETURN_TEMP = 3,
|
||||||
|
DHW_TEMP = 4,
|
||||||
|
DHW_RETURN_TEMP = 5,
|
||||||
|
DHW_FLOW_RATE = 6,
|
||||||
|
EXHAUST_TEMP = 7,
|
||||||
|
MODULATION_LEVEL = 8,
|
||||||
|
|
||||||
|
NUMBER = 247,
|
||||||
|
POWER_FACTOR = 248,
|
||||||
|
POWER = 249,
|
||||||
|
FAN_SPEED = 250,
|
||||||
|
CO2 = 251,
|
||||||
|
PRESSURE = 252,
|
||||||
|
HUMIDITY = 253,
|
||||||
|
TEMPERATURE = 254,
|
||||||
|
NOT_CONFIGURED = 255
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class ValueType : uint8_t {
|
||||||
|
PRIMARY = 0,
|
||||||
|
TEMPERATURE = 0,
|
||||||
|
HUMIDITY = 1,
|
||||||
|
BATTERY = 2,
|
||||||
|
RSSI = 3
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class AverageType : uint8_t {
|
||||||
|
MEAN = 0,
|
||||||
|
MINIMUM = 1,
|
||||||
|
MAXIMUM = 2
|
||||||
|
};
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
bool enabled = false;
|
||||||
|
char name[33];
|
||||||
|
char slug[33] = {};
|
||||||
|
Purpose purpose = Purpose::NOT_CONFIGURED;
|
||||||
|
Type type = Type::NOT_CONFIGURED;
|
||||||
|
uint8_t gpio = GPIO_IS_NOT_CONFIGURED;
|
||||||
|
uint8_t address[8] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
|
||||||
|
float offset = 0.0f;
|
||||||
|
float factor = 1.0f;
|
||||||
|
bool filtering = false;
|
||||||
|
float filteringFactor = 0.15f;
|
||||||
|
} Settings;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
bool connected = false;
|
||||||
|
unsigned long activityAt = 0;
|
||||||
|
unsigned long updatedAt = 0;
|
||||||
|
uint8_t signalQuality = 100;
|
||||||
|
//float raw[4] = {0.0f, 0.0f, 0.0f, 0.0f};
|
||||||
|
float values[4] = {0.0f, 0.0f, 0.0f, 0.0f};
|
||||||
|
} Result;
|
||||||
|
|
||||||
|
struct Snapshot {
|
||||||
|
Settings settings;
|
||||||
|
Result result;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Set the backing pointers before starting workers.
|
||||||
|
// Methods lock internally; hold mutex when accessing the arrays directly.
|
||||||
|
static Settings* settings;
|
||||||
|
static Result* results;
|
||||||
|
static std::mutex mutex;
|
||||||
|
|
||||||
|
static std::optional<Settings> getSettings(uint8_t sensorId) {
|
||||||
|
std::lock_guard<std::mutex> lock(mutex);
|
||||||
|
if (settings == nullptr || !isValidSensorId(sensorId)) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return settings[sensorId];
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::optional<Snapshot> getSnapshot(uint8_t sensorId) {
|
||||||
|
std::lock_guard<std::mutex> lock(mutex);
|
||||||
|
if (settings == nullptr || results == nullptr || !isValidSensorId(sensorId)) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return Snapshot{settings[sensorId], results[sensorId]};
|
||||||
|
}
|
||||||
|
|
||||||
|
static inline void setMaxSensors(uint8_t value) {
|
||||||
|
// The slot count and backing arrays are configured before starting workers.
|
||||||
|
maxSensors = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
static inline uint8_t getMaxSensors() {
|
||||||
|
return maxSensors;
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint8_t getMaxSensorId() {
|
||||||
|
uint8_t maxSensors = getMaxSensors();
|
||||||
|
return maxSensors > 1 ? (maxSensors - 1) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <class T>
|
||||||
|
static bool isValidSensorId(const T id) {
|
||||||
|
return id >= 0 && id <= getMaxSensorId();
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::optional<uint8_t> parseId(const char* value) {
|
||||||
|
if (!isDigit(value)) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
errno = 0;
|
||||||
|
const unsigned long parsed = strtoul(value, nullptr, 10);
|
||||||
|
if (errno == ERANGE || !isValidSensorId(parsed)) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
return static_cast<uint8_t>(parsed);
|
||||||
|
}
|
||||||
|
|
||||||
|
static inline bool isValidValueId(const uint8_t id) {
|
||||||
|
return id >= (uint8_t) ValueType::TEMPERATURE && id <= (uint8_t) ValueType::RSSI;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool isDifferent(const Settings& previous, const Settings& current) {
|
||||||
|
return previous.enabled != current.enabled
|
||||||
|
|| strcmp(previous.name, current.name) != 0
|
||||||
|
|| strcmp(previous.slug, current.slug) != 0
|
||||||
|
|| previous.purpose != current.purpose
|
||||||
|
|| previous.type != current.type
|
||||||
|
|| previous.gpio != current.gpio
|
||||||
|
|| memcmp(previous.address, current.address, sizeof(previous.address)) != 0
|
||||||
|
|| isFloatDifferent(previous.offset, current.offset, 0.0001f)
|
||||||
|
|| isFloatDifferent(previous.factor, current.factor, 0.0001f)
|
||||||
|
|| previous.filtering != current.filtering
|
||||||
|
|| isFloatDifferent(previous.filteringFactor, current.filteringFactor, 0.0001f);
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool hasEnabledAndValid(const Settings& sensor) {
|
||||||
|
return sensor.enabled
|
||||||
|
&& sensor.slug[0] != '\0'
|
||||||
|
&& sensor.type != Type::NOT_CONFIGURED
|
||||||
|
&& sensor.purpose != Purpose::NOT_CONFIGURED;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool hasEnabledAndValid(const uint8_t id) {
|
||||||
|
std::lock_guard<std::mutex> lock(mutex);
|
||||||
|
if (settings == nullptr || !isValidSensorId(id)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return hasEnabledAndValid(settings[id]);
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint8_t getAmountByType(Type type, bool onlyEnabled = false) {
|
||||||
|
std::lock_guard<std::mutex> lock(mutex);
|
||||||
|
if (settings == nullptr) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t amount = 0;
|
||||||
|
for (uint8_t id = 0; id <= getMaxSensorId(); id++) {
|
||||||
|
if (settings[id].type == type && (!onlyEnabled || settings[id].enabled)) {
|
||||||
|
amount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return amount;
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::optional<uint8_t> getIdByName(const char* name) {
|
||||||
|
std::lock_guard<std::mutex> lock(mutex);
|
||||||
|
if (settings == nullptr) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (uint8_t id = 0; id <= getMaxSensorId(); id++) {
|
||||||
|
if (strcmp(settings[id].name, name) == 0) {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::optional<uint8_t> getIdBySlug(const char* slug) {
|
||||||
|
if (slug == nullptr || !slug[0]) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::lock_guard<std::mutex> lock(mutex);
|
||||||
|
if (settings == nullptr) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (uint8_t id = 0; id <= getMaxSensorId(); id++) {
|
||||||
|
if (strcmp(settings[id].slug, slug) == 0) {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
static float convertValue(const Settings& sensor, const ValueType valueType, float value, const UnitSystem unitFrom, const UnitSystem unitTo) {
|
||||||
|
if (valueType != ValueType::PRIMARY || unitFrom == unitTo) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sensor.type == Type::HEATING_SETPOINT_TEMP && value == 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
Purpose purpose = sensor.purpose;
|
||||||
|
if (sensor.type != Type::MANUAL) {
|
||||||
|
switch (sensor.type) {
|
||||||
|
case Type::OT_OUTDOOR_TEMP:
|
||||||
|
case Type::OT_HEATING_TEMP:
|
||||||
|
case Type::OT_HEATING_RETURN_TEMP:
|
||||||
|
case Type::OT_DHW_TEMP:
|
||||||
|
case Type::OT_DHW_TEMP2:
|
||||||
|
case Type::OT_CH2_TEMP:
|
||||||
|
case Type::OT_EXHAUST_TEMP:
|
||||||
|
case Type::OT_HEAT_EXCHANGER_TEMP:
|
||||||
|
case Type::OT_SOLAR_STORAGE_TEMP:
|
||||||
|
case Type::OT_SOLAR_COLLECTOR_TEMP:
|
||||||
|
case Type::NTC_10K_TEMP:
|
||||||
|
case Type::DALLAS_TEMP:
|
||||||
|
case Type::BLUETOOTH:
|
||||||
|
case Type::DHT11:
|
||||||
|
case Type::DHT22:
|
||||||
|
case Type::HEATING_SETPOINT_TEMP:
|
||||||
|
purpose = Purpose::TEMPERATURE;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case Type::OT_PRESSURE:
|
||||||
|
purpose = Purpose::PRESSURE;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case Type::OT_DHW_FLOW_RATE:
|
||||||
|
purpose = Purpose::DHW_FLOW_RATE;
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (purpose) {
|
||||||
|
case Purpose::OUTDOOR_TEMP:
|
||||||
|
case Purpose::INDOOR_TEMP:
|
||||||
|
case Purpose::HEATING_TEMP:
|
||||||
|
case Purpose::HEATING_RETURN_TEMP:
|
||||||
|
case Purpose::DHW_TEMP:
|
||||||
|
case Purpose::DHW_RETURN_TEMP:
|
||||||
|
case Purpose::EXHAUST_TEMP:
|
||||||
|
case Purpose::TEMPERATURE:
|
||||||
|
return convertTemp(value, unitFrom, unitTo);
|
||||||
|
|
||||||
|
case Purpose::PRESSURE:
|
||||||
|
return convertPressure(value, unitFrom, unitTo);
|
||||||
|
|
||||||
|
case Purpose::DHW_FLOW_RATE:
|
||||||
|
return convertVolume(value, unitFrom, unitTo);
|
||||||
|
|
||||||
|
default:
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool setValueById(const uint8_t sensorId, float value, const ValueType valueType, const bool updateActivityAt = false, const bool markConnected = false) {
|
||||||
|
const uint8_t valueId = static_cast<uint8_t>(valueType);
|
||||||
|
char name[sizeof(Settings::name)];
|
||||||
|
float compensatedValue = value;
|
||||||
|
float loggedValue;
|
||||||
|
bool connectedChanged;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex);
|
||||||
|
if (settings == nullptr || results == nullptr || !isValidSensorId(sensorId) || !isValidValueId(valueId)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const auto& sensor = settings[sensorId];
|
||||||
|
auto& result = results[sensorId];
|
||||||
|
if (sensor.type == Type::HEATING_SETPOINT_TEMP || sensor.type == Type::MANUAL) {
|
||||||
|
result.values[valueId] = compensatedValue;
|
||||||
|
|
||||||
|
} else {
|
||||||
|
if (valueType == ValueType::PRIMARY) {
|
||||||
|
if (fabsf(sensor.factor) > 0.001f) {
|
||||||
|
compensatedValue *= sensor.factor;
|
||||||
|
}
|
||||||
|
if (fabsf(sensor.offset) > 0.001f) {
|
||||||
|
compensatedValue += sensor.offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
} else if (valueType == ValueType::RSSI) {
|
||||||
|
if (sensor.type == Type::BLUETOOTH) {
|
||||||
|
result.signalQuality = Sensors::bluetoothRssiToQuality(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sensor.filtering && fabsf(result.values[valueId]) >= 0.1f) {
|
||||||
|
result.values[valueId] += (compensatedValue - result.values[valueId]) * sensor.filteringFactor;
|
||||||
|
|
||||||
|
} else {
|
||||||
|
result.values[valueId] = compensatedValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto now = millis();
|
||||||
|
result.updatedAt = now;
|
||||||
|
if (updateActivityAt) {
|
||||||
|
result.activityAt = now;
|
||||||
|
}
|
||||||
|
connectedChanged = markConnected && !result.connected;
|
||||||
|
if (connectedChanged) {
|
||||||
|
result.connected = true;
|
||||||
|
}
|
||||||
|
memcpy(name, sensor.name, sizeof(name));
|
||||||
|
loggedValue = result.values[valueId];
|
||||||
|
}
|
||||||
|
if (connectedChanged) {
|
||||||
|
logConnectionStatus(sensorId, name, true);
|
||||||
|
}
|
||||||
|
ESP_LOGI(
|
||||||
|
L_SENSORS, "#%hhu '%s' new value %hhu: %.2f, compensated: %.2f, raw: %.2f",
|
||||||
|
sensorId, name, valueId, loggedValue, compensatedValue, value
|
||||||
|
);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool setManualValueById(uint8_t sensorId, float value, const UnitSystem srcUnit) {
|
||||||
|
char name[sizeof(Settings::name)];
|
||||||
|
bool connectedChanged;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex);
|
||||||
|
if (settings == nullptr || results == nullptr || !isValidSensorId(sensorId)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto& sensor = settings[sensorId];
|
||||||
|
if (!sensor.enabled || sensor.type != Type::MANUAL) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
value = convertValue(sensor, ValueType::PRIMARY, value, srcUnit, UnitSystem::METRIC);
|
||||||
|
if (!std::isfinite(value)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
results[sensorId].values[static_cast<uint8_t>(ValueType::PRIMARY)] = value;
|
||||||
|
connectedChanged = applyConnectionStatus(sensorId, true, true);
|
||||||
|
memcpy(name, sensor.name, sizeof(name));
|
||||||
|
}
|
||||||
|
if (connectedChanged) {
|
||||||
|
logConnectionStatus(sensorId, name, true);
|
||||||
|
}
|
||||||
|
ESP_LOGI(
|
||||||
|
L_SENSORS, "#%hhu '%s' new value %hhu: %.2f, compensated: %.2f, raw: %.2f",
|
||||||
|
sensorId, name, static_cast<uint8_t>(ValueType::PRIMARY), value, value, value
|
||||||
|
);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::optional<uint8_t> setManualValueBySlug(std::string_view slug, float value, const UnitSystem srcUnit) {
|
||||||
|
if (slug.empty()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<uint8_t> sensorId;
|
||||||
|
char name[sizeof(Settings::name)];
|
||||||
|
bool connectedChanged = false;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex);
|
||||||
|
if (settings == nullptr || results == nullptr) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (uint8_t id = 0; id <= getMaxSensorId(); id++) {
|
||||||
|
const auto& sensor = settings[id];
|
||||||
|
if (!sensor.enabled || sensor.type != Type::MANUAL) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (slug != sensor.slug) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
value = convertValue(sensor, ValueType::PRIMARY, value, srcUnit, UnitSystem::METRIC);
|
||||||
|
if (!std::isfinite(value)) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
sensorId = id;
|
||||||
|
results[id].values[static_cast<uint8_t>(ValueType::PRIMARY)] = value;
|
||||||
|
connectedChanged = applyConnectionStatus(id, true, true);
|
||||||
|
memcpy(name, sensor.name, sizeof(name));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!sensorId) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
if (connectedChanged) {
|
||||||
|
logConnectionStatus(*sensorId, name, true);
|
||||||
|
}
|
||||||
|
ESP_LOGI(
|
||||||
|
L_SENSORS, "#%hhu '%s' new value %hhu: %.2f, compensated: %.2f, raw: %.2f",
|
||||||
|
*sensorId, name, static_cast<uint8_t>(ValueType::PRIMARY), value, value, value
|
||||||
|
);
|
||||||
|
return sensorId;
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint8_t setValueByType(Type type, float value, const ValueType valueType, const bool updateActivityAt = false, const bool markConnected = false) {
|
||||||
|
uint8_t updated = 0;
|
||||||
|
for (uint8_t sensorId = 0; sensorId <= getMaxSensorId(); sensorId++) {
|
||||||
|
const auto sensor = getSettings(sensorId);
|
||||||
|
if (!sensor || !sensor->enabled || sensor->type != type) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (setValueById(sensorId, value, valueType, updateActivityAt, markConnected)) {
|
||||||
|
updated++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return updated;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool setConnectionStatusById(const uint8_t sensorId, const bool status, const bool updateActivityAt = true) {
|
||||||
|
char name[sizeof(Settings::name)];
|
||||||
|
bool changed;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex);
|
||||||
|
if (settings == nullptr || results == nullptr || !isValidSensorId(sensorId)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
changed = applyConnectionStatus(sensorId, status, updateActivityAt);
|
||||||
|
memcpy(name, settings[sensorId].name, sizeof(name));
|
||||||
|
}
|
||||||
|
if (changed) {
|
||||||
|
logConnectionStatus(sensorId, name, status);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint8_t setConnectionStatusByType(Type type, const bool status, const bool updateActivityAt = true) {
|
||||||
|
uint8_t updated = 0;
|
||||||
|
for (uint8_t sensorId = 0; sensorId <= getMaxSensorId(); sensorId++) {
|
||||||
|
char name[sizeof(Settings::name)];
|
||||||
|
bool changed;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex);
|
||||||
|
if (settings == nullptr || results == nullptr) {
|
||||||
|
return updated;
|
||||||
|
}
|
||||||
|
const auto& sensor = settings[sensorId];
|
||||||
|
if (!sensor.enabled || sensor.type != type) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
changed = applyConnectionStatus(sensorId, status, updateActivityAt);
|
||||||
|
memcpy(name, sensor.name, sizeof(name));
|
||||||
|
}
|
||||||
|
if (changed) {
|
||||||
|
logConnectionStatus(sensorId, name, status);
|
||||||
|
}
|
||||||
|
updated++;
|
||||||
|
}
|
||||||
|
return updated;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool adjustSignalQuality(uint8_t sensorId, int8_t delta) {
|
||||||
|
std::lock_guard<std::mutex> lock(mutex);
|
||||||
|
if (settings == nullptr || results == nullptr || !isValidSensorId(sensorId)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
int value = constrain(results[sensorId].signalQuality + delta, 0, 100);
|
||||||
|
if (value != results[sensorId].signalQuality) {
|
||||||
|
results[sensorId].signalQuality = static_cast<uint8_t>(value);
|
||||||
|
results[sensorId].updatedAt = millis();
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool setAddressById(uint8_t sensorId, const uint8_t* address, const std::function<void()>& onUpdated = nullptr) {
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex);
|
||||||
|
if (settings == nullptr || address == nullptr || !isValidSensorId(sensorId)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (memcmp(settings[sensorId].address, address, sizeof(Settings::address)) == 0) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
memcpy(settings[sensorId].address, address, sizeof(Settings::address));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (onUpdated) {
|
||||||
|
onUpdated();
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool updateConnectionStatusById(uint8_t sensorId, unsigned long wiredTimeout, unsigned long wirelessTimeout) {
|
||||||
|
char name[sizeof(Settings::name)];
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex);
|
||||||
|
if (settings == nullptr || results == nullptr || !isValidSensorId(sensorId) || !results[sensorId].connected) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto& sensor = settings[sensorId];
|
||||||
|
const auto& result = results[sensorId];
|
||||||
|
bool disconnected = !hasEnabledAndValid(sensor);
|
||||||
|
if (!disconnected) {
|
||||||
|
const auto timeout = sensor.type == Type::MANUAL || sensor.type == Type::BLUETOOTH
|
||||||
|
? wirelessTimeout
|
||||||
|
: wiredTimeout;
|
||||||
|
disconnected = millis() - result.activityAt > timeout;
|
||||||
|
}
|
||||||
|
if (!disconnected) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
applyConnectionStatus(sensorId, false, false);
|
||||||
|
memcpy(name, sensor.name, sizeof(name));
|
||||||
|
}
|
||||||
|
logConnectionStatus(sensorId, name, false);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static float getMeanValueByPurpose(Purpose purpose, const ValueType valueType, const AverageType avgType = AverageType::MEAN, const bool onlyConnected = true, const float defaultValue = NAN) {
|
||||||
|
std::lock_guard<std::mutex> lock(mutex);
|
||||||
|
if (settings == nullptr || results == nullptr) {
|
||||||
|
return defaultValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t valueId = (uint8_t) valueType;
|
||||||
|
if (!isValidValueId(valueId)) {
|
||||||
|
return defaultValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
float value = 0.0f;
|
||||||
|
uint8_t amount = 0;
|
||||||
|
|
||||||
|
if (avgType == AverageType::MEAN) {
|
||||||
|
float sum = 0.0f;
|
||||||
|
for (uint8_t id = 0; id <= getMaxSensorId(); id++) {
|
||||||
|
auto& sSensor = settings[id];
|
||||||
|
auto& rSensor = results[id];
|
||||||
|
|
||||||
|
if (sSensor.purpose == purpose && (!onlyConnected || rSensor.connected)) {
|
||||||
|
sum += rSensor.values[valueId];
|
||||||
|
amount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
value = amount == 1 ? sum : (sum / amount);
|
||||||
|
|
||||||
|
} else if (avgType == AverageType::MINIMUM) {
|
||||||
|
for (uint8_t id = 0; id <= getMaxSensorId(); id++) {
|
||||||
|
auto& sSensor = settings[id];
|
||||||
|
auto& rSensor = results[id];
|
||||||
|
|
||||||
|
if (sSensor.purpose == purpose && (!onlyConnected || rSensor.connected)) {
|
||||||
|
if (amount == 0 || rSensor.values[valueId] < value) {
|
||||||
|
value = rSensor.values[valueId];
|
||||||
|
amount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} else if (avgType == AverageType::MAXIMUM) {
|
||||||
|
for (uint8_t id = 0; id <= getMaxSensorId(); id++) {
|
||||||
|
auto& sSensor = settings[id];
|
||||||
|
auto& rSensor = results[id];
|
||||||
|
|
||||||
|
if (sSensor.purpose == purpose && (!onlyConnected || rSensor.connected)) {
|
||||||
|
if (amount == 0 || rSensor.values[valueId] > value) {
|
||||||
|
value = rSensor.values[valueId];
|
||||||
|
amount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return amount > 0 ? value : defaultValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool existsConnectedSensorsByPurpose(Purpose purpose) {
|
||||||
|
std::lock_guard<std::mutex> lock(mutex);
|
||||||
|
if (settings == nullptr || results == nullptr) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (uint8_t id = 0; id <= getMaxSensorId(); id++) {
|
||||||
|
if (settings[id].purpose == purpose && results[id].connected) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::string& cleanName(std::string& value, char space = ' ') {
|
||||||
|
for (char& symbol : value) {
|
||||||
|
if (symbol >= '0' && symbol <= '9') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (symbol >= 'A' && symbol <= 'Z') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (symbol >= 'a' && symbol <= 'z') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (symbol == '_' || symbol == '-' || symbol == space) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
symbol = space;
|
||||||
|
}
|
||||||
|
|
||||||
|
// trim
|
||||||
|
const auto first = value.find_first_not_of(" \t\r\n\f\v");
|
||||||
|
if (first == std::string::npos) {
|
||||||
|
value.clear();
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
value.erase(value.find_last_not_of(" \t\r\n\f\v") + 1);
|
||||||
|
value.erase(0, first);
|
||||||
|
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::string cleanName(std::string_view value, char space = ' ') {
|
||||||
|
std::string result(value);
|
||||||
|
cleanName(result, space);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::string& makeSlug(std::string& result, std::string_view value, char separator = '_') {
|
||||||
|
result.assign(value);
|
||||||
|
cleanName(result);
|
||||||
|
for (char& symbol : result) {
|
||||||
|
if (symbol >= 'A' && symbol <= 'Z') {
|
||||||
|
symbol += 'a' - 'A';
|
||||||
|
}
|
||||||
|
if (symbol == ' ') {
|
||||||
|
symbol = separator;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::string makeSlug(std::string_view value, char separator = '_') {
|
||||||
|
std::string result;
|
||||||
|
makeSlug(result, value, separator);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint8_t bluetoothRssiToQuality(int rssi) {
|
||||||
|
return constrain(map(rssi, -110, -50, 0, 100), 0, 100);;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
// The caller holds mutex; the status log is emitted after it is released.
|
||||||
|
static bool applyConnectionStatus(uint8_t sensorId, bool status, bool updateActivityAt) {
|
||||||
|
auto& result = results[sensorId];
|
||||||
|
const bool changed = result.connected != status;
|
||||||
|
result.connected = status;
|
||||||
|
if (changed || updateActivityAt) {
|
||||||
|
const auto now = millis();
|
||||||
|
result.updatedAt = now;
|
||||||
|
if (updateActivityAt) {
|
||||||
|
result.activityAt = now;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return changed;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void logConnectionStatus(uint8_t sensorId, const char* name, bool status) {
|
||||||
|
ESP_LOGI(
|
||||||
|
L_SENSORS, "#%hhu '%s' new status: %s",
|
||||||
|
sensorId, name, status ? "CONNECTED" : "DISCONNECTED"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static constexpr bool isDigit(const char* value) {
|
||||||
|
if (value == nullptr || *value == '\0') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (*value != '\0') {
|
||||||
|
if (*value < '0' || *value > '9') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
value++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
inline uint8_t Sensors::maxSensors = 0;
|
||||||
|
inline Sensors::Settings* Sensors::settings = nullptr;
|
||||||
|
inline Sensors::Result* Sensors::results = nullptr;
|
||||||
|
inline std::mutex Sensors::mutex;
|
||||||
@@ -0,0 +1,390 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <esp_log.h>
|
||||||
|
#include <atomic>
|
||||||
|
|
||||||
|
#include "macros.h"
|
||||||
|
#include "types.h"
|
||||||
|
#include "Sensors.h"
|
||||||
|
|
||||||
|
struct NetworkSettings {
|
||||||
|
char hostname[25] = DEFAULT_HOSTNAME;
|
||||||
|
bool useDhcp = true;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
char ip[16] = "192.168.0.100";
|
||||||
|
char gateway[16] = "192.168.0.1";
|
||||||
|
char subnet[16] = "255.255.255.0";
|
||||||
|
char dns[16] = "192.168.0.1";
|
||||||
|
} staticConfig;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
char ssid[33] = DEFAULT_AP_SSID;
|
||||||
|
char password[65] = DEFAULT_AP_PASSWORD;
|
||||||
|
uint8_t channel = 6;
|
||||||
|
} ap;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
char ssid[33] = DEFAULT_STA_SSID;
|
||||||
|
char password[65] = DEFAULT_STA_PASSWORD;
|
||||||
|
uint8_t channel = 0;
|
||||||
|
} sta;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct SystemSettings {
|
||||||
|
esp_log_level_t logLevel = static_cast<esp_log_level_t>(DEFAULT_LOG_LEVEL);
|
||||||
|
|
||||||
|
struct {
|
||||||
|
bool enabled = DEFAULT_SERIAL_ENABLED;
|
||||||
|
unsigned int baudrate = DEFAULT_SERIAL_BAUD;
|
||||||
|
} serial;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
bool enabled = DEFAULT_WEBSERIAL_ENABLED;
|
||||||
|
} webSerial;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
char server[49] = "pool.ntp.org";
|
||||||
|
char timezone[49] = "UTC0";
|
||||||
|
} ntp;
|
||||||
|
|
||||||
|
UnitSystem unitSystem = UnitSystem::METRIC;
|
||||||
|
uint8_t statusLedGpio = DEFAULT_STATUS_LED_GPIO;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct PortalSettings {
|
||||||
|
bool auth = false;
|
||||||
|
char login[13] = DEFAULT_PORTAL_LOGIN;
|
||||||
|
char password[33] = DEFAULT_PORTAL_PASSWORD;
|
||||||
|
bool mdns = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct OpenThermSettings {
|
||||||
|
uint8_t inGpio = DEFAULT_OT_IN_GPIO;
|
||||||
|
uint8_t outGpio = DEFAULT_OT_OUT_GPIO;
|
||||||
|
uint8_t rxLedGpio = DEFAULT_OT_RX_LED_GPIO;
|
||||||
|
uint8_t memberId = 0;
|
||||||
|
uint8_t flags = 0;
|
||||||
|
ChannelDisablingAction heatingDisablingAction = ChannelDisablingAction::OFF_AND_ZERO_SETPOINT;
|
||||||
|
ChannelDisablingAction dhwDisablingAction = ChannelDisablingAction::OFF_AND_ZERO_SETPOINT;
|
||||||
|
ChannelDisablingAction ch2DisablingAction = ChannelDisablingAction::OFF_AND_ZERO_SETPOINT;
|
||||||
|
float minPower = 0.0f;
|
||||||
|
float maxPower = 0.0f;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
bool dhwSupport = true;
|
||||||
|
bool coolingSupport = false;
|
||||||
|
bool summerWinterMode = false;
|
||||||
|
bool heatingStateToSummerWinterMode = false;
|
||||||
|
bool ch2AlwaysEnabled = true;
|
||||||
|
bool heatingToCh2 = false;
|
||||||
|
bool dhwToCh2 = false;
|
||||||
|
bool dhwBlocking = false;
|
||||||
|
bool dhwStateAsDhwBlocking = false;
|
||||||
|
bool maxTempSyncWithTargetTemp = true;
|
||||||
|
bool getMinMaxTemp = true;
|
||||||
|
bool ignoreDiagState = false;
|
||||||
|
bool autoFaultReset = false;
|
||||||
|
bool autoDiagReset = false;
|
||||||
|
bool setDateAndTime = false;
|
||||||
|
bool alwaysSendIndoorTemp = true;
|
||||||
|
bool nativeOTC = false;
|
||||||
|
bool immergasFix = false;
|
||||||
|
} options;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct MqttSettings {
|
||||||
|
bool enabled = DEFAULT_MQTT_ENABLED;
|
||||||
|
char server[81] = DEFAULT_MQTT_SERVER;
|
||||||
|
unsigned short port = DEFAULT_MQTT_PORT;
|
||||||
|
char user[33] = DEFAULT_MQTT_USER;
|
||||||
|
char password[33] = DEFAULT_MQTT_PASSWORD;
|
||||||
|
char prefix[33] = DEFAULT_MQTT_PREFIX;
|
||||||
|
unsigned short interval = 5;
|
||||||
|
bool homeAssistantDiscovery = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct EmergencySettings {
|
||||||
|
float target = DEFAULT_HEATING_TARGET_TEMP;
|
||||||
|
unsigned short thresholdTime = 120;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct HeatingSettings {
|
||||||
|
bool enabled = true;
|
||||||
|
bool turbo = false;
|
||||||
|
float target = DEFAULT_HEATING_TARGET_TEMP;
|
||||||
|
float turboFactor = 7.5f;
|
||||||
|
uint8_t minTemp = DEFAULT_HEATING_MIN_TEMP;
|
||||||
|
uint8_t maxTemp = DEFAULT_HEATING_MAX_TEMP;
|
||||||
|
uint8_t maxModulation = 100;
|
||||||
|
Sensors::AverageType indoorTempAvgType = Sensors::AverageType::MEAN;
|
||||||
|
Sensors::AverageType outdoorTempAvgType = Sensors::AverageType::MEAN;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
bool enabled = true;
|
||||||
|
float value = 0.5f;
|
||||||
|
} hysteresis;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
uint8_t highTemp = 95;
|
||||||
|
uint8_t lowTemp = 90;
|
||||||
|
} overheatProtection;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
uint8_t highTemp = 15;
|
||||||
|
uint8_t lowTemp = 10;
|
||||||
|
} freezeProtection;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct DhwSettings {
|
||||||
|
bool enabled = true;
|
||||||
|
float target = DEFAULT_DHW_TARGET_TEMP;
|
||||||
|
uint8_t minTemp = DEFAULT_DHW_MIN_TEMP;
|
||||||
|
uint8_t maxTemp = DEFAULT_DHW_MAX_TEMP;
|
||||||
|
uint8_t maxModulation = 100;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
uint8_t highTemp = 95;
|
||||||
|
uint8_t lowTemp = 90;
|
||||||
|
} overheatProtection;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct PidSettings {
|
||||||
|
bool enabled = false;
|
||||||
|
float p_factor = 2.0f;
|
||||||
|
float i_factor = 0.002f;
|
||||||
|
float d_factor = 0.0f;
|
||||||
|
unsigned short dt = 300;
|
||||||
|
short minTemp = 0;
|
||||||
|
short maxTemp = DEFAULT_HEATING_MAX_TEMP;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
bool enabled = true;
|
||||||
|
float p_multiplier = 1.0f;
|
||||||
|
float i_multiplier = 0.05f;
|
||||||
|
float d_multiplier = 1.0f;
|
||||||
|
float thresholdHigh = 0.5f;
|
||||||
|
float thresholdLow = 1.0f;
|
||||||
|
} deadband;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct EquithermSettings {
|
||||||
|
bool enabled = false;
|
||||||
|
float slope = 0.7f;
|
||||||
|
float exponent = 1.3f;
|
||||||
|
float shift = 0.0f;
|
||||||
|
float targetDiffFactor = 2.0f;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ExternalPumpSettings {
|
||||||
|
bool use = false;
|
||||||
|
uint8_t gpio = DEFAULT_EXT_PUMP_GPIO;
|
||||||
|
bool invertState = false;
|
||||||
|
unsigned short postCirculationTime = 600;
|
||||||
|
unsigned int antiStuckInterval = 2592000;
|
||||||
|
unsigned short antiStuckTime = 300;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct CascadeControlSettings {
|
||||||
|
struct {
|
||||||
|
bool enabled = false;
|
||||||
|
uint8_t gpio = GPIO_IS_NOT_CONFIGURED;
|
||||||
|
bool invertState = false;
|
||||||
|
unsigned short thresholdTime = 60;
|
||||||
|
} input;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
bool enabled = false;
|
||||||
|
uint8_t gpio = GPIO_IS_NOT_CONFIGURED;
|
||||||
|
bool invertState = false;
|
||||||
|
unsigned short thresholdTime = 60;
|
||||||
|
bool onFault = true;
|
||||||
|
bool onLossConnection = true;
|
||||||
|
bool onEnabledHeating = false;
|
||||||
|
} output;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Settings {
|
||||||
|
SystemSettings system;
|
||||||
|
PortalSettings portal;
|
||||||
|
OpenThermSettings opentherm;
|
||||||
|
MqttSettings mqtt;
|
||||||
|
EmergencySettings emergency;
|
||||||
|
HeatingSettings heating;
|
||||||
|
DhwSettings dhw;
|
||||||
|
PidSettings pid;
|
||||||
|
EquithermSettings equitherm;
|
||||||
|
ExternalPumpSettings externalPump;
|
||||||
|
CascadeControlSettings cascadeControl;
|
||||||
|
|
||||||
|
char validationValue[8] = SETTINGS_VALID_VALUE;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Variables {
|
||||||
|
struct {
|
||||||
|
int8_t rssi = 0;
|
||||||
|
} network;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
bool state = false;
|
||||||
|
} emergency;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
bool state = false;
|
||||||
|
unsigned long lastEnabledTime = 0;
|
||||||
|
} externalPump;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
bool input = false;
|
||||||
|
bool output = false;
|
||||||
|
} cascadeControl;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
uint8_t memberId = 0;
|
||||||
|
uint8_t flags = 0;
|
||||||
|
uint8_t type = 0x01;
|
||||||
|
uint8_t appVersion = 0x3F;
|
||||||
|
float protocolVersion = 2.2f;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
bool blocking = false;
|
||||||
|
bool enabled = false;
|
||||||
|
bool smartControl = false;
|
||||||
|
bool overheat = false;
|
||||||
|
bool freezing = false;
|
||||||
|
float setpointTemp = 0.0f;
|
||||||
|
float targetTemp = 0.0f;
|
||||||
|
float currentTemp = 0.0f;
|
||||||
|
float returnTemp = 0.0f;
|
||||||
|
float indoorTemp = 0.0f;
|
||||||
|
float outdoorTemp = 0.0f;
|
||||||
|
float minTemp = 0.0f;
|
||||||
|
float maxTemp = 0.0f;
|
||||||
|
} heating;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
bool enabled = false;
|
||||||
|
bool overheat = false;
|
||||||
|
float targetTemp = 0.0f;
|
||||||
|
float currentTemp = 0.0f;
|
||||||
|
float returnTemp = 0.0f;
|
||||||
|
} dhw;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
bool enabled = false;
|
||||||
|
float targetTemp = 0.0f;
|
||||||
|
} ch2;
|
||||||
|
} master;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
uint8_t memberId = 0;
|
||||||
|
uint8_t flags = 0;
|
||||||
|
uint8_t type = 0;
|
||||||
|
uint8_t appVersion = 0;
|
||||||
|
float protocolVersion = 0.0f;
|
||||||
|
|
||||||
|
bool connected = false;
|
||||||
|
bool flame = false;
|
||||||
|
float pressure = 0.0f;
|
||||||
|
float heatExchangerTemp = 0.0f;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
bool active = false;
|
||||||
|
uint8_t setpoint = 0;
|
||||||
|
} cooling;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
bool active = false;
|
||||||
|
uint8_t code = 0;
|
||||||
|
} fault;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
bool active = false;
|
||||||
|
uint16_t code = 0;
|
||||||
|
} diag;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
uint8_t current = 0;
|
||||||
|
uint8_t min = 0;
|
||||||
|
uint8_t max = 100;
|
||||||
|
} modulation;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
float current = 0.0f;
|
||||||
|
float min = 0.0f;
|
||||||
|
float max = 0.0f;
|
||||||
|
} power;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
float temp = 0.0f;
|
||||||
|
uint16_t co2 = 0;
|
||||||
|
uint16_t fanSpeed = 0;
|
||||||
|
} exhaust;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
float storage = 0.0f;
|
||||||
|
float collector = 0.0f;
|
||||||
|
} solar;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
uint8_t setpoint = 0;
|
||||||
|
uint8_t current = 0;
|
||||||
|
uint16_t supply = 0;
|
||||||
|
} fanSpeed;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
uint16_t burnerStarts = 0;
|
||||||
|
uint16_t dhwBurnerStarts = 0;
|
||||||
|
uint16_t heatingPumpStarts = 0;
|
||||||
|
uint16_t dhwPumpStarts = 0;
|
||||||
|
uint16_t coolingHours = 0;
|
||||||
|
uint16_t burnerHours = 0;
|
||||||
|
uint16_t dhwBurnerHours = 0;
|
||||||
|
uint16_t heatingPumpHours = 0;
|
||||||
|
uint16_t dhwPumpHours = 0;
|
||||||
|
} stats;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
bool active = false;
|
||||||
|
bool enabled = false;
|
||||||
|
float targetTemp = 0.0f;
|
||||||
|
float roomTargetTemp = 0.0f;
|
||||||
|
float currentTemp = 0.0f;
|
||||||
|
float returnTemp = 0.0f;
|
||||||
|
float indoorTemp = 0.0f;
|
||||||
|
float outdoorTemp = 0.0f;
|
||||||
|
uint8_t minTemp = DEFAULT_HEATING_MIN_TEMP;
|
||||||
|
uint8_t maxTemp = DEFAULT_HEATING_MAX_TEMP;
|
||||||
|
} heating;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
bool active = false;
|
||||||
|
bool enabled = false;
|
||||||
|
float targetTemp = 0.0f;
|
||||||
|
float currentTemp = 0.0f;
|
||||||
|
float currentTemp2 = 0.0f;
|
||||||
|
float returnTemp = 0.0f;
|
||||||
|
float flowRate = 0.0f;
|
||||||
|
uint8_t minTemp = DEFAULT_DHW_MIN_TEMP;
|
||||||
|
uint8_t maxTemp = DEFAULT_DHW_MAX_TEMP;
|
||||||
|
} dhw;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
bool active = false;
|
||||||
|
bool enabled = false;
|
||||||
|
float targetTemp = 0.0f;
|
||||||
|
float roomTargetTemp = 0.0f;
|
||||||
|
float currentTemp = 0.0f;
|
||||||
|
float indoorTemp = 0.0f;
|
||||||
|
} ch2;
|
||||||
|
} slave;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
bool resetFault = false;
|
||||||
|
bool resetDiagnostic = false;
|
||||||
|
} actions;
|
||||||
|
|
||||||
|
struct {
|
||||||
|
std::atomic<bool> upgrading{false};
|
||||||
|
} states;
|
||||||
|
};
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include <ArduinoJson.h>
|
||||||
|
#include <MycilaHADiscovery.h>
|
||||||
|
#include <MycilaTaskManager.h>
|
||||||
|
#include <esp_log.h>
|
||||||
|
#include <functional>
|
||||||
|
#include <initializer_list>
|
||||||
|
#include <mutex>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
|
||||||
|
#include "macros.h"
|
||||||
|
#include "types.h"
|
||||||
|
#include "strings_shared.h"
|
||||||
|
#include "Settings.h"
|
||||||
|
#include "utils.h"
|
||||||
|
|
||||||
|
using namespace Mycila;
|
||||||
|
|
||||||
|
class AsyncWebServer;
|
||||||
|
class WebSerial;
|
||||||
|
|
||||||
|
// Configuration
|
||||||
|
extern NetworkSettings networkSettings;
|
||||||
|
extern Settings settings;
|
||||||
|
extern Sensors::Settings sensorsSettings[SENSORS_AMOUNT];
|
||||||
|
void initConfig();
|
||||||
|
void saveSettingsNow();
|
||||||
|
void requestSaveNetworkSettings();
|
||||||
|
void requestSaveSettings();
|
||||||
|
// Call after releasing lifecycle, MQTT queue and Sensors data locks.
|
||||||
|
void requestSaveSensorsSettings();
|
||||||
|
|
||||||
|
JsonVariant toJson(const NetworkSettings& src, JsonVariant dst);
|
||||||
|
JsonVariant toJson(const SystemSettings& src, JsonVariant dst);
|
||||||
|
JsonVariant toJson(const PortalSettings& src, JsonVariant dst);
|
||||||
|
JsonVariant toJson(const OpenThermSettings& src, JsonVariant dst);
|
||||||
|
JsonVariant toJson(const MqttSettings& src, JsonVariant dst);
|
||||||
|
JsonVariant toJson(const EmergencySettings& src, JsonVariant dst);
|
||||||
|
JsonVariant toJson(const HeatingSettings& src, JsonVariant dst);
|
||||||
|
JsonVariant toJson(const DhwSettings& src, JsonVariant dst);
|
||||||
|
JsonVariant toJson(const PidSettings& src, JsonVariant dst);
|
||||||
|
JsonVariant toJson(const EquithermSettings& src, JsonVariant dst);
|
||||||
|
JsonVariant toJson(const ExternalPumpSettings& src, JsonVariant dst);
|
||||||
|
JsonVariant toJson(const CascadeControlSettings& src, JsonVariant dst);
|
||||||
|
SettingResult fromJson(JsonVariantConst src, NetworkSettings& dst);
|
||||||
|
SettingResult fromJson(JsonVariantConst src, SystemSettings& dst);
|
||||||
|
SettingResult fromJson(JsonVariantConst src, PortalSettings& dst);
|
||||||
|
SettingResult fromJson(JsonVariantConst src, OpenThermSettings& dst);
|
||||||
|
SettingResult fromJson(JsonVariantConst src, MqttSettings& dst);
|
||||||
|
SettingResult fromJson(JsonVariantConst src, EmergencySettings& dst);
|
||||||
|
SettingResult fromJson(JsonVariantConst src, HeatingSettings& dst);
|
||||||
|
SettingResult fromJson(JsonVariantConst src, DhwSettings& dst);
|
||||||
|
SettingResult fromJson(JsonVariantConst src, PidSettings& dst);
|
||||||
|
SettingResult fromJson(JsonVariantConst src, EquithermSettings& dst);
|
||||||
|
SettingResult fromJson(JsonVariantConst src, ExternalPumpSettings& dst);
|
||||||
|
SettingResult fromJson(JsonVariantConst src, CascadeControlSettings& dst);
|
||||||
|
SettingResult applySetting(Settings& dst, std::string_view path, bool value);
|
||||||
|
SettingResult applySetting(Settings& dst, std::string_view path, float value);
|
||||||
|
bool normalizeSettings(Settings& dst);
|
||||||
|
JsonVariant toJson(const uint8_t sensorId, const Sensors::Settings& src, JsonVariant dst);
|
||||||
|
// Caller holds Sensors::mutex while accessing shared settings and checking slug uniqueness.
|
||||||
|
SettingResult fromJson(const JsonVariantConst src, Sensors::Settings& dst);
|
||||||
|
JsonVariant toJson(const Sensors::Settings& sensor, const Sensors::Result& result, JsonVariant dst);
|
||||||
|
JsonVariant toJson(const uint8_t sensorId, JsonVariant dst);
|
||||||
|
JsonVariant toJson(const Variables& src, JsonVariant dst);
|
||||||
|
SettingResult fromJson(const JsonVariantConst src, Variables& dst);
|
||||||
|
bool applyAction(std::string_view action, bool value);
|
||||||
|
|
||||||
|
// Application state and task managers
|
||||||
|
extern Variables vars;
|
||||||
|
extern TaskManager coreTaskManager;
|
||||||
|
extern TaskManager systemTaskManager;
|
||||||
|
extern TaskManager openthermTaskManager;
|
||||||
|
extern TaskManager sensorsTaskManager;
|
||||||
|
// Schedule once with resume(delay); scheduled() also covers the delay before restart.
|
||||||
|
// Request only outside OTA and while the task is not already scheduled.
|
||||||
|
extern Task restartTask;
|
||||||
|
void initSystem();
|
||||||
|
|
||||||
|
std::string getResetReason();
|
||||||
|
|
||||||
|
// Control and regulation
|
||||||
|
void initControl();
|
||||||
|
void initRegulator();
|
||||||
|
void initLeds();
|
||||||
|
|
||||||
|
// Sensors
|
||||||
|
void initSensors();
|
||||||
|
|
||||||
|
// OpenTherm
|
||||||
|
extern Task writeRoomTemperatureTask;
|
||||||
|
extern Task writeRoomTemperatureCh2Task;
|
||||||
|
void initOpenTherm();
|
||||||
|
|
||||||
|
// Logging
|
||||||
|
extern WebSerial* webSerial;
|
||||||
|
extern Task configureLoggingTask;
|
||||||
|
bool initLogging();
|
||||||
|
void drainLoggingSerial();
|
||||||
|
|
||||||
|
// Web server and MQTT
|
||||||
|
extern AsyncWebServer* webServer;
|
||||||
|
void initPortal();
|
||||||
|
extern Task mqttConfigureTask;
|
||||||
|
// Protect MQTT client and task pointers while checking and using them.
|
||||||
|
extern std::mutex mqttMutex;
|
||||||
|
extern Task* mqttPublishSettingsTask;
|
||||||
|
extern Task* mqttPublishStateTask;
|
||||||
|
extern Task* mqttPublishSensorsTask;
|
||||||
|
void initMqtt();
|
||||||
|
void stopMqtt(bool destroy);
|
||||||
|
bool isMqttConnected();
|
||||||
|
void requestReconfigureMqtt();
|
||||||
|
void requestReconfigureMqttSensor(uint8_t sensorId, std::optional<Sensors::Settings> previousSettings = std::nullopt);
|
||||||
|
void requestPublishMqttSensor(uint8_t sensorId);
|
||||||
|
std::string mqttTopic(std::initializer_list<std::string_view> parts);
|
||||||
|
template <typename... Parts>
|
||||||
|
std::string mqttTopic(const Parts&... parts) {
|
||||||
|
return mqttTopic({std::string_view(parts)...});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Home Assistant discovery
|
||||||
|
extern HA::Discovery haDiscovery;
|
||||||
|
void publishHaEntity(HaEntity entityId, bool remove);
|
||||||
|
void publishDynamicSensor(
|
||||||
|
const Sensors::Settings& sensor,
|
||||||
|
Sensors::ValueType valueType = Sensors::ValueType::PRIMARY, bool enabledByDefault = true
|
||||||
|
);
|
||||||
|
void publishDynamicManualSensor(const Sensors::Settings& sensor, bool enabledByDefault = true);
|
||||||
|
void deleteDynamicSensor(const Sensors::Settings& sensor, Sensors::ValueType valueType = Sensors::ValueType::PRIMARY);
|
||||||
|
void publishConnectionDynamicSensor(const Sensors::Settings& sensor, bool enabledByDefault = true);
|
||||||
|
void deleteConnectionDynamicSensor(const Sensors::Settings& sensor);
|
||||||
|
void publishSignalQualityDynamicSensor(const Sensors::Settings& sensor, bool enabledByDefault = false);
|
||||||
|
void deleteSignalQualityDynamicSensor(const Sensors::Settings& sensor);
|
||||||
|
|
||||||
|
// Network
|
||||||
|
void initNetwork();
|
||||||
|
// Register during setup, before starting systemTaskManager.
|
||||||
|
// Callbacks run on the system worker: only signal client owners, without blocking.
|
||||||
|
void onNetworkEvent(NetworkEventCallback callback);
|
||||||
|
void onNetworkStateChange(NetworkStateCallback callback);
|
||||||
|
NetworkState getNetworkState(NetworkMode mode = NetworkMode::STA);
|
||||||
|
NetworkMode getNetworkMode();
|
||||||
|
bool isNetworkInterfaceStarted(NetworkMode mode);
|
||||||
|
// Last state published by the system worker, including during event callbacks.
|
||||||
|
bool isNetworkConnected();
|
||||||
|
void reconnectNetwork();
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include <driver/gpio.h>
|
||||||
|
|
||||||
|
#define PROJECT_NAME "OpenTherm Gateway"
|
||||||
|
#define PROJECT_REPO "https://github.com/Laxilef/OTGateway"
|
||||||
|
|
||||||
|
#define MQTT_RECONNECT_INTERVAL 15000
|
||||||
|
#define MQTT_SENSOR_REPUBLISH_INTERVAL 300000u
|
||||||
|
#define SETTINGS_VALID_VALUE "stvalid" // only 8 chars!
|
||||||
|
#define GPIO_IS_NOT_CONFIGURED 0xff
|
||||||
|
|
||||||
|
#define DEFAULT_HEATING_TARGET_TEMP 40
|
||||||
|
#define DEFAULT_HEATING_MIN_TEMP 20
|
||||||
|
#define DEFAULT_HEATING_MAX_TEMP 90
|
||||||
|
|
||||||
|
#define DEFAULT_DHW_TARGET_TEMP 40
|
||||||
|
#define DEFAULT_DHW_MIN_TEMP 30
|
||||||
|
#define DEFAULT_DHW_MAX_TEMP 60
|
||||||
|
|
||||||
|
#define THERMOSTAT_INDOOR_DEFAULT_TEMP 20
|
||||||
|
#define THERMOSTAT_INDOOR_MIN_TEMP 5
|
||||||
|
#define THERMOSTAT_INDOOR_MAX_TEMP 40
|
||||||
|
|
||||||
|
#define DEFAULT_NTC_NOMINAL_RESISTANCE 10000.0f
|
||||||
|
#define DEFAULT_NTC_NOMINAL_TEMP 25.0f
|
||||||
|
#define DEFAULT_NTC_REF_RESISTANCE 10000.0f
|
||||||
|
#define DEFAULT_NTC_BETA_FACTOR 3950.0f
|
||||||
|
#define DEFAULT_NTC_VREF 3300.0f
|
||||||
|
#define DEFAULT_NTC_VLOW_THRESHOLD 25.0f
|
||||||
|
#define DEFAULT_NTC_VHIGH_THRESHOLD 3298.0f
|
||||||
|
|
||||||
|
#ifndef BUILD_VERSION
|
||||||
|
#define BUILD_VERSION "0.0.0"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef BUILD_COMMIT
|
||||||
|
#define BUILD_COMMIT "undefined"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef BUILD_ENV
|
||||||
|
#define BUILD_ENV "undefined"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef LOGGING_QUEUE_SIZE
|
||||||
|
#define LOGGING_QUEUE_SIZE 4096
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef DEFAULT_SERIAL_ENABLED
|
||||||
|
#define DEFAULT_SERIAL_ENABLED true
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef DEFAULT_SERIAL_BAUD
|
||||||
|
#define DEFAULT_SERIAL_BAUD 115200
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef DEFAULT_WEBSERIAL_ENABLED
|
||||||
|
#define DEFAULT_WEBSERIAL_ENABLED true
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef USE_BLE
|
||||||
|
#define USE_BLE false
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef DEFAULT_HOSTNAME
|
||||||
|
#define DEFAULT_HOSTNAME ""
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef DEFAULT_AP_SSID
|
||||||
|
#define DEFAULT_AP_SSID "OpenTherm Gateway"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef DEFAULT_AP_PASSWORD
|
||||||
|
#define DEFAULT_AP_PASSWORD "otgateway123456"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef DEFAULT_STA_SSID
|
||||||
|
#define DEFAULT_STA_SSID ""
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef DEFAULT_STA_PASSWORD
|
||||||
|
#define DEFAULT_STA_PASSWORD ""
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef DEFAULT_LOG_LEVEL
|
||||||
|
#define DEFAULT_LOG_LEVEL ESP_LOG_VERBOSE
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef DEFAULT_STATUS_LED_GPIO
|
||||||
|
#define DEFAULT_STATUS_LED_GPIO GPIO_IS_NOT_CONFIGURED
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef DEFAULT_PORTAL_LOGIN
|
||||||
|
#define DEFAULT_PORTAL_LOGIN ""
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef DEFAULT_PORTAL_PASSWORD
|
||||||
|
#define DEFAULT_PORTAL_PASSWORD ""
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef DEFAULT_MQTT_ENABLED
|
||||||
|
#define DEFAULT_MQTT_ENABLED false
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef DEFAULT_MQTT_SERVER
|
||||||
|
#define DEFAULT_MQTT_SERVER ""
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef DEFAULT_MQTT_PORT
|
||||||
|
#define DEFAULT_MQTT_PORT 1883
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef DEFAULT_MQTT_USER
|
||||||
|
#define DEFAULT_MQTT_USER ""
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef DEFAULT_MQTT_PASSWORD
|
||||||
|
#define DEFAULT_MQTT_PASSWORD ""
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef DEFAULT_MQTT_PREFIX
|
||||||
|
#define DEFAULT_MQTT_PREFIX ""
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef DEFAULT_OT_IN_GPIO
|
||||||
|
#define DEFAULT_OT_IN_GPIO GPIO_IS_NOT_CONFIGURED
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef DEFAULT_OT_OUT_GPIO
|
||||||
|
#define DEFAULT_OT_OUT_GPIO GPIO_IS_NOT_CONFIGURED
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef DEFAULT_OT_RX_LED_GPIO
|
||||||
|
#define DEFAULT_OT_RX_LED_GPIO GPIO_IS_NOT_CONFIGURED
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef DEFAULT_OT_FAULT_STATE_GPIO
|
||||||
|
#define DEFAULT_OT_FAULT_STATE_GPIO GPIO_IS_NOT_CONFIGURED
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef DEFAULT_SENSOR_OUTDOOR_GPIO
|
||||||
|
#define DEFAULT_SENSOR_OUTDOOR_GPIO GPIO_IS_NOT_CONFIGURED
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef DEFAULT_SENSOR_INDOOR_GPIO
|
||||||
|
#define DEFAULT_SENSOR_INDOOR_GPIO GPIO_IS_NOT_CONFIGURED
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef SENSORS_AMOUNT
|
||||||
|
#define SENSORS_AMOUNT 20
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef DEFAULT_EXT_PUMP_GPIO
|
||||||
|
#define DEFAULT_EXT_PUMP_GPIO GPIO_IS_NOT_CONFIGURED
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef GPIO_IS_VALID_OUTPUT_GPIO
|
||||||
|
#define GPIO_IS_VALID_OUTPUT_GPIO(gpio_num) ((gpio_num) >= 0 && (gpio_num) < SOC_GPIO_PIN_COUNT && \
|
||||||
|
(((1ULL << (gpio_num)) & SOC_GPIO_VALID_OUTPUT_GPIO_MASK) != 0))
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef GPIO_IS_VALID_INPUT_GPIO
|
||||||
|
// ESP-IDF uses the general GPIO mask for digital input capability.
|
||||||
|
#define GPIO_IS_VALID_INPUT_GPIO(gpio_num) GPIO_IS_VALID_GPIO(gpio_num)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define GPIO_IS_VALID(gpioNum) ((gpioNum) != GPIO_IS_NOT_CONFIGURED && GPIO_IS_VALID_GPIO(gpioNum))
|
||||||
|
#define GPIO_IS_VALID_INPUT(gpioNum) ((gpioNum) != GPIO_IS_NOT_CONFIGURED && GPIO_IS_VALID_INPUT_GPIO(gpioNum))
|
||||||
|
#define GPIO_IS_VALID_OUTPUT(gpioNum) ((gpioNum) != GPIO_IS_NOT_CONFIGURED && GPIO_IS_VALID_OUTPUT_GPIO(gpioNum))
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include <esp_arduino_version.h>
|
||||||
|
#include <esp_heap_caps.h>
|
||||||
|
#include <esp_timer.h>
|
||||||
|
#include <mutex>
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
struct HeapMetrics : multi_heap_info_t {
|
||||||
|
size_t total;
|
||||||
|
size_t minLargestBlock = SIZE_MAX;
|
||||||
|
uint8_t fragmentation;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct MemoryMetrics {
|
||||||
|
bool captured;
|
||||||
|
uint64_t uptime;
|
||||||
|
HeapMetrics heap;
|
||||||
|
HeapMetrics psram;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct CrashMetrics {
|
||||||
|
bool captured;
|
||||||
|
uint32_t core;
|
||||||
|
uint64_t uptime;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct CoreDumpBuildInfo {
|
||||||
|
char version[sizeof(BUILD_VERSION)] = BUILD_VERSION;
|
||||||
|
char date[sizeof("Mmm dd yyyy hh:mm:ss")];
|
||||||
|
char commit[sizeof(BUILD_COMMIT)] = BUILD_COMMIT;
|
||||||
|
char env[sizeof(BUILD_ENV)] = BUILD_ENV;
|
||||||
|
char core[sizeof(ESP_ARDUINO_VERSION_STR)];
|
||||||
|
char sdk[64];
|
||||||
|
char chipModel[16];
|
||||||
|
uint16_t chipRevision;
|
||||||
|
uint8_t chipCores;
|
||||||
|
uint32_t cpuFreqMHz;
|
||||||
|
uint32_t flashChipSize;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Keep one shared instance of each record in the native core dump.
|
||||||
|
inline COREDUMP_DRAM_ATTR MemoryMetrics memoryMetrics __attribute__((used)) = {};
|
||||||
|
inline COREDUMP_DRAM_ATTR CrashMetrics crashMetrics __attribute__((used)) = {};
|
||||||
|
inline COREDUMP_DRAM_ATTR CoreDumpBuildInfo coreDumpBuildInfo __attribute__((used)) = {};
|
||||||
|
inline std::mutex memoryMetricsMutex;
|
||||||
|
|
||||||
|
// Refresh and copy under the same lock: System and HTTP run on different tasks.
|
||||||
|
inline MemoryMetrics getMemoryMetrics() {
|
||||||
|
std::lock_guard<std::mutex> lock(memoryMetricsMutex);
|
||||||
|
|
||||||
|
// A panic during the update must not report partially written statistics.
|
||||||
|
__atomic_store_n(&memoryMetrics.captured, false, __ATOMIC_SEQ_CST);
|
||||||
|
heap_caps_get_info(&memoryMetrics.heap, MALLOC_CAP_INTERNAL);
|
||||||
|
|
||||||
|
if (memoryMetrics.psram.total) {
|
||||||
|
heap_caps_get_info(&memoryMetrics.psram, MALLOC_CAP_SPIRAM);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (memoryMetrics.heap.largest_free_block < memoryMetrics.heap.minLargestBlock) {
|
||||||
|
memoryMetrics.heap.minLargestBlock = memoryMetrics.heap.largest_free_block;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (memoryMetrics.psram.largest_free_block < memoryMetrics.psram.minLargestBlock) {
|
||||||
|
memoryMetrics.psram.minLargestBlock = memoryMetrics.psram.largest_free_block;
|
||||||
|
}
|
||||||
|
|
||||||
|
memoryMetrics.heap.fragmentation = memoryMetrics.heap.total_free_bytes
|
||||||
|
? 100 - memoryMetrics.heap.largest_free_block * 100.0 / memoryMetrics.heap.total_free_bytes
|
||||||
|
: 0;
|
||||||
|
memoryMetrics.psram.fragmentation = memoryMetrics.psram.total_free_bytes
|
||||||
|
? 100 - memoryMetrics.psram.largest_free_block * 100.0 / memoryMetrics.psram.total_free_bytes
|
||||||
|
: 0;
|
||||||
|
memoryMetrics.uptime = esp_timer_get_time() / 1000;
|
||||||
|
__atomic_store_n(&memoryMetrics.captured, true, __ATOMIC_RELEASE);
|
||||||
|
return memoryMetrics;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void IRAM_ATTR captureCoreDumpMetrics(arduino_panic_info_t* info, void*) {
|
||||||
|
crashMetrics.core = info->core;
|
||||||
|
crashMetrics.uptime = esp_timer_get_time() / 1000;
|
||||||
|
__atomic_store_n(&crashMetrics.captured, true, __ATOMIC_RELEASE);
|
||||||
|
}
|
||||||
|
|
||||||
|
static inline void initCoreDumpMetrics() {
|
||||||
|
// Keep the timestamp local to the calling translation unit, outside shared types.
|
||||||
|
strlcpy(coreDumpBuildInfo.date, __DATE__ " " __TIME__, sizeof(coreDumpBuildInfo.date));
|
||||||
|
strlcpy(coreDumpBuildInfo.core, ESP.getCoreVersion(), sizeof(coreDumpBuildInfo.core));
|
||||||
|
strlcpy(coreDumpBuildInfo.sdk, ESP.getSdkVersion(), sizeof(coreDumpBuildInfo.sdk));
|
||||||
|
strlcpy(coreDumpBuildInfo.chipModel, ESP.getChipModel(), sizeof(coreDumpBuildInfo.chipModel));
|
||||||
|
|
||||||
|
coreDumpBuildInfo.chipRevision = ESP.getChipRevision();
|
||||||
|
coreDumpBuildInfo.chipCores = ESP.getChipCores();
|
||||||
|
coreDumpBuildInfo.cpuFreqMHz = ESP.getCpuFreqMHz();
|
||||||
|
coreDumpBuildInfo.flashChipSize = ESP.getFlashChipSize();
|
||||||
|
|
||||||
|
// Arduino has registered the memory regions before this one-time initialization.
|
||||||
|
memoryMetrics.heap.total = heap_caps_get_total_size(MALLOC_CAP_INTERNAL);
|
||||||
|
memoryMetrics.psram.total = psramFound() ? heap_caps_get_total_size(MALLOC_CAP_SPIRAM) : 0;
|
||||||
|
|
||||||
|
getMemoryMetrics();
|
||||||
|
set_arduino_panic_handler(captureCoreDumpMetrics, nullptr);
|
||||||
|
}
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
inline const char L_SETTINGS[] = "SETTINGS";
|
||||||
|
inline const char L_SETTINGS_OT[] = "SETTINGS.OT";
|
||||||
|
inline const char L_SETTINGS_DHW[] = "SETTINGS.DHW";
|
||||||
|
inline const char L_SETTINGS_HEATING[] = "SETTINGS.HEATING";
|
||||||
|
inline const char L_NETWORK[] = "NETWORK";
|
||||||
|
inline const char L_NETWORK_SETTINGS[] = "NETWORK.SETTINGS";
|
||||||
|
inline const char L_PORTAL_WEBSERVER[] = "PORTAL.WEBSERVER";
|
||||||
|
inline const char L_PORTAL_DNSSERVER[] = "PORTAL.DNSSERVER";
|
||||||
|
inline const char L_PORTAL_CAPTIVE[] = "PORTAL.CAPTIVE";
|
||||||
|
inline const char L_PORTAL_OTA[] = "PORTAL.OTA";
|
||||||
|
inline const char L_MAIN[] = "MAIN";
|
||||||
|
inline const char L_MQTT[] = "MQTT";
|
||||||
|
inline const char L_MQTT_MSG[] = "MQTT.MSG";
|
||||||
|
inline const char L_OT[] = "OT";
|
||||||
|
inline const char L_OT_DHW[] = "OT.DHW";
|
||||||
|
inline const char L_OT_HEATING[] = "OT.HEATING";
|
||||||
|
inline const char L_OT_CH2[] = "OT.CH2";
|
||||||
|
inline const char L_SENSORS[] = "SENSORS";
|
||||||
|
inline const char L_SENSORS_SETTINGS[] = "SENSORS.SETTINGS";
|
||||||
|
inline const char L_SENSORS_DALLAS[] = "SENSORS.DALLAS";
|
||||||
|
inline const char L_SENSORS_DHT[] = "SENSORS.DHT";
|
||||||
|
inline const char L_SENSORS_NTC[] = "SENSORS.NTC";
|
||||||
|
inline const char L_SENSORS_BLE[] = "SENSORS.BLE";
|
||||||
|
inline const char L_REGULATOR[] = "REGULATOR";
|
||||||
|
inline const char L_REGULATOR_PID[] = "REGULATOR.PID";
|
||||||
|
inline const char L_REGULATOR_EQUITHERM[] = "REGULATOR.EQUITHERM";
|
||||||
|
inline const char L_CASCADE_INPUT[] = "CASCADE.INPUT";
|
||||||
|
inline const char L_CASCADE_OUTPUT[] = "CASCADE.OUTPUT";
|
||||||
|
inline const char L_EXTPUMP[] = "EXTPUMP";
|
||||||
|
|
||||||
|
|
||||||
|
inline const char S_ACTIONS[] = "actions";
|
||||||
|
inline const char S_ACTIVE[] = "active";
|
||||||
|
inline const char S_ADDRESS[] = "address";
|
||||||
|
inline const char S_ANTI_STUCK_INTERVAL[] = "antistuck_interval";
|
||||||
|
inline const char S_ANTI_STUCK_TIME[] = "antistuck_time";
|
||||||
|
inline const char S_AP[] = "ap";
|
||||||
|
inline const char S_APP_VERSION[] = "app_version";
|
||||||
|
inline const char S_AUTH[] = "auth";
|
||||||
|
inline const char S_AUTO_DIAG_RESET[] = "auto_diag_reset";
|
||||||
|
inline const char S_AUTO_FAULT_RESET[] = "auto_fault_reset";
|
||||||
|
inline const char S_BATTERY[] = "battery";
|
||||||
|
inline const char S_BAUDRATE[] = "baudrate";
|
||||||
|
inline const char S_BLOCKING[] = "blocking";
|
||||||
|
inline const char S_BSSID[] = "bssid";
|
||||||
|
inline const char S_BUILD[] = "build";
|
||||||
|
inline const char S_CASCADE_CONTROL[] = "cascade_control";
|
||||||
|
inline const char S_CHANNEL[] = "channel";
|
||||||
|
inline const char S_CH2_ALWAYS_ENABLED[] = "ch2_always_enabled";
|
||||||
|
inline const char S_CH2_DISABLING_ACTION[] = "ch2_disabling_action";
|
||||||
|
inline const char S_CHIP[] = "chip";
|
||||||
|
inline const char S_CODE[] = "code";
|
||||||
|
inline const char S_COMMIT[] = "commit";
|
||||||
|
inline const char S_CONNECTED[] = "connected";
|
||||||
|
inline const char S_COOLING[] = "cooling";
|
||||||
|
inline const char S_COOLING_SUPPORT[] = "cooling_support";
|
||||||
|
inline const char S_CORE[] = "core";
|
||||||
|
inline const char S_CORES[] = "cores";
|
||||||
|
inline const char S_CURRENT_TEMP[] = "current_temp";
|
||||||
|
inline const char S_DATE[] = "date";
|
||||||
|
inline const char S_DEADBAND[] = "deadband";
|
||||||
|
inline const char S_DHW[] = "dhw";
|
||||||
|
inline const char S_DHW_BLOCKING[] = "dhw_blocking";
|
||||||
|
inline const char S_DHW_DISABLING_ACTION[] = "dhw_disabling_action";
|
||||||
|
inline const char S_DHW_STATE_AS_DHW_BLOCKING[] = "dhw_state_as_dhw_blocking";
|
||||||
|
inline const char S_DHW_SUPPORT[] = "dhw_support";
|
||||||
|
inline const char S_DHW_TO_CH2[] = "dhw_to_ch2";
|
||||||
|
inline const char S_DIAG[] = "diag";
|
||||||
|
inline const char S_DNS[] = "dns";
|
||||||
|
inline const char S_DT[] = "dt";
|
||||||
|
inline const char S_D_FACTOR[] = "d_factor";
|
||||||
|
inline const char S_D_MULTIPLIER[] = "d_multiplier";
|
||||||
|
inline const char S_EMERGENCY[] = "emergency";
|
||||||
|
inline const char S_ENABLED[] = "enabled";
|
||||||
|
inline const char S_ENV[] = "env";
|
||||||
|
inline const char S_EQUITHERM[] = "equitherm";
|
||||||
|
inline const char S_EXPONENT[] = "exponent";
|
||||||
|
inline const char S_EXTERNAL_PUMP[] = "ext_pump";
|
||||||
|
inline const char S_FACTOR[] = "factor";
|
||||||
|
inline const char S_FALSE[] = "false";
|
||||||
|
inline const char S_FAULT[] = "fault";
|
||||||
|
inline const char S_FREEZE_PROTECTION[] = "freeze_protection";
|
||||||
|
inline const char S_FREEZING[] = "freezing";
|
||||||
|
inline const char S_FILTERING[] = "filtering";
|
||||||
|
inline const char S_FILTERING_FACTOR[] = "filtering_factor";
|
||||||
|
inline const char S_FLAGS[] = "flags";
|
||||||
|
inline const char S_FLAME[] = "flame";
|
||||||
|
inline const char S_FLASH[] = "flash";
|
||||||
|
inline const char S_FREE[] = "free";
|
||||||
|
inline const char S_FREQ[] = "freq";
|
||||||
|
inline const char S_GATEWAY[] = "gateway";
|
||||||
|
inline const char S_GET_MIN_MAX_TEMP[] = "get_min_max_temp";
|
||||||
|
inline const char S_GPIO[] = "gpio";
|
||||||
|
inline const char S_HEAP[] = "heap";
|
||||||
|
inline const char S_HEATING[] = "heating";
|
||||||
|
inline const char S_HEATING_DISABLING_ACTION[] = "heating_disabling_action";
|
||||||
|
inline const char S_HEATING_TO_CH2[] = "heating_to_ch2";
|
||||||
|
inline const char S_HEATING_STATE_TO_SUMMER_WINTER_MODE[] = "heating_state_to_summer_winter_mode";
|
||||||
|
inline const char S_HIDDEN[] = "hidden";
|
||||||
|
inline const char S_HIGH_TEMP[] = "high_temp";
|
||||||
|
inline const char S_HOME_ASSISTANT_DISCOVERY[] = "ha_discovery";
|
||||||
|
inline const char S_HOSTNAME[] = "hostname";
|
||||||
|
inline const char S_HUMIDITY[] = "humidity";
|
||||||
|
inline const char S_HYSTERESIS[] = "hysteresis";
|
||||||
|
inline const char S_ID[] = "id";
|
||||||
|
inline const char S_IGNORE_DIAG_STATE[] = "ignore_diag_state";
|
||||||
|
inline const char S_IMMERGAS_FIX[] = "immergas_fix";
|
||||||
|
inline const char S_ALWAYS_SEND_INDOOR_TEMP[] = "always_send_indoor_temp";
|
||||||
|
inline const char S_INDOOR_TEMP[] = "indoor_temp";
|
||||||
|
inline const char S_INDOOR_TEMP_AVG_TYPE[] = "indoor_temp_avg_type";
|
||||||
|
inline const char S_IN_GPIO[] = "in_gpio";
|
||||||
|
inline const char S_INPUT[] = "input";
|
||||||
|
inline const char S_INTERVAL[] = "interval";
|
||||||
|
inline const char S_INVERT_STATE[] = "invert_state";
|
||||||
|
inline const char S_IP[] = "ip";
|
||||||
|
inline const char S_I_FACTOR[] = "i_factor";
|
||||||
|
inline const char S_I_MULTIPLIER[] = "i_multiplier";
|
||||||
|
inline const char S_LOGIN[] = "login";
|
||||||
|
inline const char S_LOG_LEVEL[] = "loglevel";
|
||||||
|
inline const char S_LOW_TEMP[] = "low_temp";
|
||||||
|
inline const char S_MAC[] = "mac";
|
||||||
|
inline const char S_MASTER[] = "master";
|
||||||
|
inline const char S_MAX[] = "max";
|
||||||
|
inline const char S_MAX_FREE_BLOCK[] = "max_free_block";
|
||||||
|
inline const char S_MAX_MODULATION[] = "max_modulation";
|
||||||
|
inline const char S_MAX_POWER[] = "max_power";
|
||||||
|
inline const char S_MAX_TEMP[] = "max_temp";
|
||||||
|
inline const char S_MAX_TEMP_SYNC_WITH_TARGET_TEMP[] = "max_temp_sync_with_target_temp";
|
||||||
|
inline const char S_MDNS[] = "mdns";
|
||||||
|
inline const char S_MEMBER_ID[] = "member_id";
|
||||||
|
inline const char S_MIN[] = "min";
|
||||||
|
inline const char S_MIN_FREE[] = "min_free";
|
||||||
|
inline const char S_MIN_MAX_FREE_BLOCK[] = "min_max_free_block";
|
||||||
|
inline const char S_MIN_POWER[] = "min_power";
|
||||||
|
inline const char S_MIN_TEMP[] = "min_temp";
|
||||||
|
inline const char S_MODEL[] = "model";
|
||||||
|
inline const char S_MODULATION[] = "modulation";
|
||||||
|
inline const char S_MQTT[] = "mqtt";
|
||||||
|
inline const char S_NAME[] = "name";
|
||||||
|
inline const char S_SLUG[] = "slug";
|
||||||
|
inline const char S_NATIVE_OTC[] = "native_otc";
|
||||||
|
inline const char S_NETWORK[] = "network";
|
||||||
|
inline const char S_NTP[] = "ntp";
|
||||||
|
inline const char S_OFFSET[] = "offset";
|
||||||
|
inline const char S_ON_ENABLED_HEATING[] = "on_enabled_heating";
|
||||||
|
inline const char S_ON_FAULT[] = "on_fault";
|
||||||
|
inline const char S_ON_LOSS_CONNECTION[] = "on_loss_connection";
|
||||||
|
inline const char S_OPENTHERM[] = "opentherm";
|
||||||
|
inline const char S_OPTIONS[] = "options";
|
||||||
|
inline const char S_OUTDOOR_TEMP[] = "outdoor_temp";
|
||||||
|
inline const char S_OUTDOOR_TEMP_AVG_TYPE[] = "outdoor_temp_avg_type";
|
||||||
|
inline const char S_OUT_GPIO[] = "out_gpio";
|
||||||
|
inline const char S_OUTPUT[] = "output";
|
||||||
|
inline const char S_OVERHEAT[] = "overheat";
|
||||||
|
inline const char S_OVERHEAT_PROTECTION[] = "overheat_protection";
|
||||||
|
inline const char S_PASSWORD[] = "password";
|
||||||
|
inline const char S_PID[] = "pid";
|
||||||
|
inline const char S_PORT[] = "port";
|
||||||
|
inline const char S_PORTAL[] = "portal";
|
||||||
|
inline const char S_POST_CIRCULATION_TIME[] = "post_circulation_time";
|
||||||
|
inline const char S_POWER[] = "power";
|
||||||
|
inline const char S_PREFIX[] = "prefix";
|
||||||
|
inline const char S_PROTOCOL_VERSION[] = "protocol_version";
|
||||||
|
inline const char S_PURPOSE[] = "purpose";
|
||||||
|
inline const char S_PSRAM[] = "psram";
|
||||||
|
inline const char S_P_FACTOR[] = "p_factor";
|
||||||
|
inline const char S_P_MULTIPLIER[] = "p_multiplier";
|
||||||
|
inline const char S_RESET_DIAGNOSTIC[] = "reset_diagnostic";
|
||||||
|
inline const char S_RESET_FAULT[] = "reset_fault";
|
||||||
|
inline const char S_RESET_REASON[] = "reset_reason";
|
||||||
|
inline const char S_RESTART[] = "restart";
|
||||||
|
inline const char S_RETURN_TEMP[] = "return_temp";
|
||||||
|
inline const char S_REV[] = "rev";
|
||||||
|
inline const char S_RSSI[] = "rssi";
|
||||||
|
inline const char S_RX_LED_GPIO[] = "rx_led_gpio";
|
||||||
|
inline const char S_SDK[] = "sdk";
|
||||||
|
inline const char S_SENSORS[] = "sensors";
|
||||||
|
inline const char S_SERIAL[] = "serial";
|
||||||
|
inline const char S_SERVER[] = "server";
|
||||||
|
inline const char S_SETTINGS[] = "settings";
|
||||||
|
inline const char S_SET_DATE_AND_TIME[] = "set_date_and_time";
|
||||||
|
inline const char S_SHIFT[] = "shift";
|
||||||
|
inline const char S_SIGNAL_QUALITY[] = "signal_quality";
|
||||||
|
inline const char S_SIZE[] = "size";
|
||||||
|
inline const char S_SLAVE[] = "slave";
|
||||||
|
inline const char S_SLOPE[] = "slope";
|
||||||
|
inline const char S_SMART_CONTROL[] = "smart_control";
|
||||||
|
inline const char S_SSID[] = "ssid";
|
||||||
|
inline const char S_STA[] = "sta";
|
||||||
|
inline const char S_STATE[] = "state";
|
||||||
|
inline const char S_STATIC_CONFIG[] = "static_config";
|
||||||
|
inline const char S_STATUS_LED_GPIO[] = "status_led_gpio";
|
||||||
|
inline const char S_SETPOINT[] = "setpoint";
|
||||||
|
inline const char S_SETPOINT_TEMP[] = "setpoint_temp";
|
||||||
|
inline const char S_SUBNET[] = "subnet";
|
||||||
|
inline const char S_SUMMER_WINTER_MODE[] = "summer_winter_mode";
|
||||||
|
inline const char S_SYSTEM[] = "system";
|
||||||
|
inline const char S_TARGET[] = "target";
|
||||||
|
inline const char S_TARGET_DIFF_FACTOR[] = "target_diff_factor";
|
||||||
|
inline const char S_TARGET_TEMP[] = "target_temp";
|
||||||
|
inline const char S_TEMPERATURE[] = "temperature";
|
||||||
|
inline const char S_THRESHOLD_HIGH[] = "threshold_high";
|
||||||
|
inline const char S_THRESHOLD_LOW[] = "threshold_low";
|
||||||
|
inline const char S_THRESHOLD_TIME[] = "threshold_time";
|
||||||
|
inline const char S_TIMEZONE[] = "timezone";
|
||||||
|
inline const char S_TOTAL[] = "total";
|
||||||
|
inline const char S_TRUE[] = "true";
|
||||||
|
inline const char S_TURBO[] = "turbo";
|
||||||
|
inline const char S_TURBO_FACTOR[] = "turbo_factor";
|
||||||
|
inline const char S_TYPE[] = "type";
|
||||||
|
inline const char S_UNIT_SYSTEM[] = "unit_system";
|
||||||
|
inline const char S_UPTIME[] = "uptime";
|
||||||
|
inline const char S_USE[] = "use";
|
||||||
|
inline const char S_USE_DHCP[] = "use_dhcp";
|
||||||
|
inline const char S_USER[] = "user";
|
||||||
|
inline const char S_VALUE[] = "value";
|
||||||
|
inline const char S_VERSION[] = "version";
|
||||||
|
inline const char S_WEBSERIAL[] = "web_serial";
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <functional>
|
||||||
|
|
||||||
|
enum class UnitSystem : uint8_t {
|
||||||
|
METRIC = 0,
|
||||||
|
IMPERIAL = 1
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class ChannelDisablingAction : uint8_t {
|
||||||
|
OFF = 0,
|
||||||
|
ZERO_SETPOINT = 1,
|
||||||
|
OFF_AND_ZERO_SETPOINT = 2
|
||||||
|
};
|
||||||
|
|
||||||
|
struct SettingResult {
|
||||||
|
bool changed = false;
|
||||||
|
bool accepted = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
enum HaEntity : uint8_t {
|
||||||
|
HA_ENTITY_HEATING_TURBO,
|
||||||
|
HA_ENTITY_HEATING_HYSTERESIS_ENABLED,
|
||||||
|
HA_ENTITY_HEATING_HYSTERESIS_VALUE,
|
||||||
|
HA_ENTITY_HEATING_TURBO_FACTOR,
|
||||||
|
HA_ENTITY_HEATING_MIN_TEMP,
|
||||||
|
HA_ENTITY_HEATING_MAX_TEMP,
|
||||||
|
HA_ENTITY_PID_ENABLED,
|
||||||
|
HA_ENTITY_PID_P_FACTOR,
|
||||||
|
HA_ENTITY_PID_I_FACTOR,
|
||||||
|
HA_ENTITY_PID_D_FACTOR,
|
||||||
|
HA_ENTITY_PID_DT,
|
||||||
|
HA_ENTITY_PID_MIN_TEMP,
|
||||||
|
HA_ENTITY_PID_MAX_TEMP,
|
||||||
|
HA_ENTITY_EQUITHERM_ENABLED,
|
||||||
|
HA_ENTITY_EQUITHERM_SLOPE,
|
||||||
|
HA_ENTITY_EQUITHERM_EXPONENT,
|
||||||
|
HA_ENTITY_EQUITHERM_SHIFT,
|
||||||
|
HA_ENTITY_EQUITHERM_TARGET_DIFF_FACTOR,
|
||||||
|
HA_ENTITY_STATUS,
|
||||||
|
HA_ENTITY_EMERGENCY,
|
||||||
|
HA_ENTITY_OPENTHERM_STATUS,
|
||||||
|
HA_ENTITY_HEATING,
|
||||||
|
HA_ENTITY_FLAME,
|
||||||
|
HA_ENTITY_FAULT,
|
||||||
|
HA_ENTITY_DIAGNOSTIC,
|
||||||
|
HA_ENTITY_EXTERNAL_PUMP,
|
||||||
|
HA_ENTITY_FAULT_CODE,
|
||||||
|
HA_ENTITY_DIAGNOSTIC_CODE,
|
||||||
|
HA_ENTITY_RSSI,
|
||||||
|
HA_ENTITY_UPTIME,
|
||||||
|
HA_ENTITY_RESTART,
|
||||||
|
HA_ENTITY_RESET_FAULT,
|
||||||
|
HA_ENTITY_RESET_DIAGNOSTIC,
|
||||||
|
HA_ENTITY_HEATING_CLIMATE,
|
||||||
|
HA_ENTITY_DHW_MIN_TEMP,
|
||||||
|
HA_ENTITY_DHW_MAX_TEMP,
|
||||||
|
HA_ENTITY_DHW,
|
||||||
|
HA_ENTITY_DHW_CLIMATE,
|
||||||
|
HA_ENTITY_HEATING_BLOCKING,
|
||||||
|
HA_ENTITY_HEATING_OVERHEAT,
|
||||||
|
HA_ENTITY_HEATING_FREEZING,
|
||||||
|
HA_ENTITY_DHW_OVERHEAT,
|
||||||
|
HA_ENTITY_CASCADE_CONTROL_INPUT,
|
||||||
|
HA_ENTITY_CASCADE_CONTROL_OUTPUT,
|
||||||
|
HA_ENTITY_COUNT
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class NetworkEvent : uint8_t {
|
||||||
|
CONNECTED,
|
||||||
|
DISCONNECTED,
|
||||||
|
STA_STARTED,
|
||||||
|
STA_STOPPED,
|
||||||
|
STA_CONNECTED,
|
||||||
|
STA_DISCONNECTED,
|
||||||
|
STA_GOT_IP,
|
||||||
|
STA_LOST_IP,
|
||||||
|
STA_GOT_IP6,
|
||||||
|
AP_STARTED,
|
||||||
|
AP_STOPPED,
|
||||||
|
AP_CLIENT_CONNECTED,
|
||||||
|
AP_CLIENT_DISCONNECTED,
|
||||||
|
AP_CLIENT_GOT_IP,
|
||||||
|
AP_GOT_IP6,
|
||||||
|
PORTAL_STARTED,
|
||||||
|
PORTAL_STOPPED,
|
||||||
|
MDNS_STARTED,
|
||||||
|
MDNS_STOPPED,
|
||||||
|
EVENTS_OVERFLOW
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class NetworkState : uint8_t {
|
||||||
|
NETWORK_DISABLED,
|
||||||
|
NETWORK_ENABLED,
|
||||||
|
NETWORK_CONNECTING,
|
||||||
|
NETWORK_TIMEOUT,
|
||||||
|
NETWORK_CONNECTED,
|
||||||
|
NETWORK_DISCONNECTED,
|
||||||
|
NETWORK_RECONNECTING,
|
||||||
|
AP_STARTING,
|
||||||
|
AP_STARTED,
|
||||||
|
PORTAL_STARTING,
|
||||||
|
PORTAL_STARTED,
|
||||||
|
PORTAL_COMPLETE,
|
||||||
|
PORTAL_TIMEOUT
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class NetworkMode : uint8_t {
|
||||||
|
NONE,
|
||||||
|
AP,
|
||||||
|
STA,
|
||||||
|
ETH
|
||||||
|
};
|
||||||
|
|
||||||
|
using NetworkEventCallback = void (*)(NetworkEvent);
|
||||||
|
using NetworkStateCallback = std::function<void(NetworkMode mode, NetworkState previous, NetworkState state)>;
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include <cmath>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <string>
|
||||||
|
#include <string.h>
|
||||||
|
#include <time.h>
|
||||||
|
|
||||||
|
#include "types.h"
|
||||||
|
|
||||||
|
inline std::string getChipId(const char* prefix = nullptr, const char* suffix = nullptr) {
|
||||||
|
std::string chipId;
|
||||||
|
chipId.reserve(
|
||||||
|
6
|
||||||
|
+ (prefix != nullptr ? strlen(prefix) : 0)
|
||||||
|
+ (suffix != nullptr ? strlen(suffix) : 0)
|
||||||
|
);
|
||||||
|
|
||||||
|
if (prefix != nullptr) {
|
||||||
|
chipId += prefix;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t cid = 0;
|
||||||
|
// https://github.com/espressif/arduino-esp32/blob/master/libraries/ESP32/examples/ChipID/GetChipID/GetChipID.ino
|
||||||
|
for (uint8_t i = 0; i < 17; i = i + 8) {
|
||||||
|
cid |= ((ESP.getEfuseMac() >> (40 - i)) & 0xff) << i;
|
||||||
|
}
|
||||||
|
|
||||||
|
char hexId[7];
|
||||||
|
snprintf(hexId, sizeof(hexId), "%lx", static_cast<unsigned long>(cid));
|
||||||
|
chipId += hexId;
|
||||||
|
|
||||||
|
if (suffix != nullptr) {
|
||||||
|
chipId += suffix;
|
||||||
|
}
|
||||||
|
|
||||||
|
chipId.erase(chipId.find_last_not_of(" \t\n\r\f\v") + 1);
|
||||||
|
chipId.erase(0, chipId.find_first_not_of(" \t\n\r\f\v"));
|
||||||
|
return chipId;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline float liter2gallon(float value) {
|
||||||
|
return value / 3.785411784f;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline float gallon2liter(float value) {
|
||||||
|
return value * 3.785411784f;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline float convertVolume(float value, const UnitSystem unitFrom, const UnitSystem unitTo) {
|
||||||
|
if (unitFrom == UnitSystem::METRIC && unitTo == UnitSystem::IMPERIAL) {
|
||||||
|
value = liter2gallon(value);
|
||||||
|
|
||||||
|
} else if (unitFrom == UnitSystem::IMPERIAL && unitTo == UnitSystem::METRIC) {
|
||||||
|
value = gallon2liter(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline float bar2psi(float value) {
|
||||||
|
return value * 14.5038f;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline float psi2bar(float value) {
|
||||||
|
return value / 14.5038f;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline float convertPressure(float value, const UnitSystem unitFrom, const UnitSystem unitTo) {
|
||||||
|
if (unitFrom == UnitSystem::METRIC && unitTo == UnitSystem::IMPERIAL) {
|
||||||
|
value = bar2psi(value);
|
||||||
|
|
||||||
|
} else if (unitFrom == UnitSystem::IMPERIAL && unitTo == UnitSystem::METRIC) {
|
||||||
|
value = psi2bar(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline float c2f(float value) {
|
||||||
|
return (9.0f / 5.0f) * value + 32.0f;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline float f2c(float value) {
|
||||||
|
return (value - 32.0f) * 5.0f / 9.0f;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline float convertTemp(float value, const UnitSystem unitFrom, const UnitSystem unitTo) {
|
||||||
|
if (unitFrom == UnitSystem::METRIC && unitTo == UnitSystem::IMPERIAL) {
|
||||||
|
value = c2f(value);
|
||||||
|
|
||||||
|
} else if (unitFrom == UnitSystem::IMPERIAL && unitTo == UnitSystem::METRIC) {
|
||||||
|
value = f2c(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool isValidTemp(const float value, UnitSystem unit, const float min = 0.1f, const float max = 99.9f, const UnitSystem minMaxUnit = UnitSystem::METRIC) {
|
||||||
|
return value >= convertTemp(min, minMaxUnit, unit) && value <= convertTemp(max, minMaxUnit, unit);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool isFloatDifferent(float first, float second, float tolerance) {
|
||||||
|
return fabsf(first - second) > tolerance;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline float roundf(float value, uint8_t decimals = 2) {
|
||||||
|
if (decimals == 0) {
|
||||||
|
return std::round(value);
|
||||||
|
|
||||||
|
} else if (abs(value) < 0.00000001f) {
|
||||||
|
return 0.0f;
|
||||||
|
}
|
||||||
|
|
||||||
|
const float multiplier = pow10(decimals);
|
||||||
|
const float scaled = value * multiplier;
|
||||||
|
return std::isfinite(scaled) ? std::round(scaled) / multiplier : value;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline uint8_t rssiToSignalQuality(int16_t rssi) {
|
||||||
|
return constrain(map(rssi, -100, -50, 0, 100), 0, 100);
|
||||||
|
}
|
||||||
@@ -1,85 +0,0 @@
|
|||||||
class BufferedWebServer {
|
|
||||||
public:
|
|
||||||
BufferedWebServer(WebServer* webServer, size_t bufferSize = 64) {
|
|
||||||
this->webServer = webServer;
|
|
||||||
this->bufferSize = bufferSize;
|
|
||||||
this->buffer = (uint8_t*)malloc(bufferSize * sizeof(*this->buffer));
|
|
||||||
}
|
|
||||||
|
|
||||||
~BufferedWebServer() {
|
|
||||||
free(this->buffer);
|
|
||||||
}
|
|
||||||
|
|
||||||
void send(int code, const char* contentType, JsonDocument& content) {
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
if (!this->webServer->chunkedResponseModeStart(code, contentType)) {
|
|
||||||
this->webServer->send(505, F("text/html"), F("HTTP1.1 required"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this->webServer->setContentLength(measureJson(content));
|
|
||||||
#else
|
|
||||||
this->webServer->setContentLength(CONTENT_LENGTH_UNKNOWN);
|
|
||||||
this->webServer->sendHeader(F("Content-Length"), String(measureJson(content)));
|
|
||||||
this->webServer->send(code, contentType, emptyString);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
serializeJson(content, *this);
|
|
||||||
this->flush();
|
|
||||||
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
this->webServer->chunkedResponseFinalize();
|
|
||||||
#else
|
|
||||||
this->webServer->sendContent(emptyString);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t write(uint8_t c) {
|
|
||||||
this->buffer[this->bufferPos++] = c;
|
|
||||||
|
|
||||||
if (this->bufferPos >= this->bufferSize) {
|
|
||||||
this->flush();
|
|
||||||
}
|
|
||||||
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t write(const uint8_t* buffer, size_t length) {
|
|
||||||
size_t written = 0;
|
|
||||||
while (written < length) {
|
|
||||||
size_t copySize = this->bufferSize - this->bufferPos;
|
|
||||||
if (written + copySize > length) {
|
|
||||||
copySize = length - written;
|
|
||||||
}
|
|
||||||
|
|
||||||
memcpy(this->buffer + this->bufferPos, buffer + written, copySize);
|
|
||||||
this->bufferPos += copySize;
|
|
||||||
|
|
||||||
if (this->bufferPos >= this->bufferSize) {
|
|
||||||
this->flush();
|
|
||||||
}
|
|
||||||
|
|
||||||
written += copySize;
|
|
||||||
}
|
|
||||||
|
|
||||||
return written;
|
|
||||||
}
|
|
||||||
|
|
||||||
void flush() {
|
|
||||||
if (this->bufferPos == 0) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this->webServer->sendContent((const char*)this->buffer, this->bufferPos);
|
|
||||||
this->bufferPos = 0;
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
::delay(0);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
protected:
|
|
||||||
WebServer* webServer = nullptr;
|
|
||||||
uint8_t* buffer;
|
|
||||||
size_t bufferSize = 64;
|
|
||||||
size_t bufferPos = 0;
|
|
||||||
};
|
|
||||||
@@ -1,189 +0,0 @@
|
|||||||
#include <Arduino.h>
|
|
||||||
#include <OpenTherm.h>
|
|
||||||
|
|
||||||
class CustomOpenTherm : public OpenTherm {
|
|
||||||
public:
|
|
||||||
typedef std::function<void()> YieldCallback;
|
|
||||||
typedef std::function<void(unsigned long, byte)> BeforeSendRequestCallback;
|
|
||||||
typedef std::function<void(unsigned long, unsigned long, OpenThermResponseStatus, byte)> AfterSendRequestCallback;
|
|
||||||
|
|
||||||
CustomOpenTherm(int inPin = 4, int outPin = 5, bool isSlave = false) : OpenTherm(inPin, outPin, isSlave) {}
|
|
||||||
|
|
||||||
CustomOpenTherm* setYieldCallback(YieldCallback callback = nullptr) {
|
|
||||||
this->yieldCallback = callback;
|
|
||||||
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
CustomOpenTherm* setBeforeSendRequestCallback(BeforeSendRequestCallback callback = nullptr) {
|
|
||||||
this->beforeSendRequestCallback = callback;
|
|
||||||
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
CustomOpenTherm* setAfterSendRequestCallback(AfterSendRequestCallback callback = nullptr) {
|
|
||||||
this->afterSendRequestCallback = callback;
|
|
||||||
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
unsigned long sendRequest(unsigned long request, byte attempts = 5, byte _attempt = 0) {
|
|
||||||
_attempt++;
|
|
||||||
|
|
||||||
while (!this->isReady()) {
|
|
||||||
if (this->yieldCallback) {
|
|
||||||
this->yieldCallback();
|
|
||||||
} else {
|
|
||||||
::yield();
|
|
||||||
}
|
|
||||||
|
|
||||||
this->process();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this->beforeSendRequestCallback) {
|
|
||||||
this->beforeSendRequestCallback(request, _attempt);
|
|
||||||
}
|
|
||||||
|
|
||||||
unsigned long _response;
|
|
||||||
OpenThermResponseStatus _responseStatus = OpenThermResponseStatus::NONE;
|
|
||||||
if (!this->sendRequestAync(request)) {
|
|
||||||
_response = 0;
|
|
||||||
|
|
||||||
} else {
|
|
||||||
while (true) {
|
|
||||||
this->process();
|
|
||||||
|
|
||||||
if (this->status == OpenThermStatus::READY || this->status == OpenThermStatus::DELAY) {
|
|
||||||
break;
|
|
||||||
} else if (this->yieldCallback) {
|
|
||||||
this->yieldCallback();
|
|
||||||
} else {
|
|
||||||
::yield();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
_response = this->getLastResponse();
|
|
||||||
_responseStatus = this->getLastResponseStatus();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this->afterSendRequestCallback) {
|
|
||||||
this->afterSendRequestCallback(request, _response, _responseStatus, _attempt);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (_responseStatus == OpenThermResponseStatus::SUCCESS || _responseStatus == OpenThermResponseStatus::INVALID || _attempt >= attempts) {
|
|
||||||
return _response;
|
|
||||||
|
|
||||||
} else {
|
|
||||||
return this->sendRequest(request, attempts, _attempt);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
unsigned long setBoilerStatus(bool enableCentralHeating, bool enableHotWater, bool enableCooling, bool enableOutsideTemperatureCompensation, bool enableCentralHeating2, bool summerWinterMode, bool dhwBlocking) {
|
|
||||||
unsigned int data = enableCentralHeating
|
|
||||||
| (enableHotWater << 1)
|
|
||||||
| (enableCooling << 2)
|
|
||||||
| (enableOutsideTemperatureCompensation << 3)
|
|
||||||
| (enableCentralHeating2 << 4)
|
|
||||||
| (summerWinterMode << 5)
|
|
||||||
| (dhwBlocking << 6);
|
|
||||||
data <<= 8;
|
|
||||||
|
|
||||||
return this->sendRequest(this->buildRequest(
|
|
||||||
OpenThermMessageType::READ_DATA,
|
|
||||||
OpenThermMessageID::Status,
|
|
||||||
data
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
bool setHeatingCh1Temp(float temperature) {
|
|
||||||
unsigned long response = this->sendRequest(this->buildRequest(
|
|
||||||
OpenThermMessageType::WRITE_DATA,
|
|
||||||
OpenThermMessageID::TSet,
|
|
||||||
this->temperatureToData(temperature)
|
|
||||||
));
|
|
||||||
|
|
||||||
return isValidResponse(response);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool setHeatingCh2Temp(float temperature) {
|
|
||||||
unsigned long response = this->sendRequest(this->buildRequest(
|
|
||||||
OpenThermMessageType::WRITE_DATA,
|
|
||||||
OpenThermMessageID::TsetCH2,
|
|
||||||
this->temperatureToData(temperature)
|
|
||||||
));
|
|
||||||
|
|
||||||
return isValidResponse(response);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool setDhwTemp(float temperature) {
|
|
||||||
unsigned long response = this->sendRequest(this->buildRequest(
|
|
||||||
OpenThermMessageType::WRITE_DATA,
|
|
||||||
OpenThermMessageID::TdhwSet,
|
|
||||||
this->temperatureToData(temperature)
|
|
||||||
));
|
|
||||||
|
|
||||||
return isValidResponse(response);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool sendBoilerReset() {
|
|
||||||
unsigned int data = 1;
|
|
||||||
data <<= 8;
|
|
||||||
unsigned long response = this->sendRequest(this->buildRequest(
|
|
||||||
OpenThermMessageType::WRITE_DATA,
|
|
||||||
OpenThermMessageID::Command,
|
|
||||||
data
|
|
||||||
));
|
|
||||||
|
|
||||||
return isValidResponse(response);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool sendServiceReset() {
|
|
||||||
unsigned int data = 10;
|
|
||||||
data <<= 8;
|
|
||||||
unsigned long response = this->sendRequest(this->buildRequest(
|
|
||||||
OpenThermMessageType::WRITE_DATA,
|
|
||||||
OpenThermMessageID::Command,
|
|
||||||
data
|
|
||||||
));
|
|
||||||
|
|
||||||
return isValidResponse(response);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool sendWaterFilling() {
|
|
||||||
unsigned int data = 2;
|
|
||||||
data <<= 8;
|
|
||||||
unsigned long response = this->sendRequest(this->buildRequest(
|
|
||||||
OpenThermMessageType::WRITE_DATA,
|
|
||||||
OpenThermMessageID::Command,
|
|
||||||
data
|
|
||||||
));
|
|
||||||
|
|
||||||
return isValidResponse(response);
|
|
||||||
}
|
|
||||||
|
|
||||||
// converters
|
|
||||||
float fromF88(unsigned long response) {
|
|
||||||
const byte valueLB = response & 0xFF;
|
|
||||||
const byte valueHB = (response >> 8) & 0xFF;
|
|
||||||
|
|
||||||
float value = (int8_t)valueHB;
|
|
||||||
return value + (float)valueLB / 256.0;
|
|
||||||
}
|
|
||||||
|
|
||||||
template <class T> unsigned int toF88(T val) {
|
|
||||||
return (unsigned int)(val * 256);
|
|
||||||
}
|
|
||||||
|
|
||||||
int16_t fromS16(unsigned long response) {
|
|
||||||
const byte valueLB = response & 0xFF;
|
|
||||||
const byte valueHB = (response >> 8) & 0xFF;
|
|
||||||
|
|
||||||
int16_t value = valueHB;
|
|
||||||
return ((value << 8) + valueLB);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected:
|
|
||||||
YieldCallback yieldCallback;
|
|
||||||
BeforeSendRequestCallback beforeSendRequestCallback;
|
|
||||||
AfterSendRequestCallback afterSendRequestCallback;
|
|
||||||
};
|
|
||||||
@@ -1,63 +0,0 @@
|
|||||||
#include <Arduino.h>
|
|
||||||
|
|
||||||
#if defined(EQUITHERM_INTEGER)
|
|
||||||
// расчёты с целыми числами
|
|
||||||
typedef int datatype;
|
|
||||||
#else
|
|
||||||
// расчёты с float числами
|
|
||||||
typedef float datatype;
|
|
||||||
#endif
|
|
||||||
|
|
||||||
class Equitherm {
|
|
||||||
public:
|
|
||||||
datatype targetTemp = 0;
|
|
||||||
datatype indoorTemp = 0;
|
|
||||||
datatype outdoorTemp = 0;
|
|
||||||
float Kn = 0.0;
|
|
||||||
float Kk = 0.0;
|
|
||||||
float Kt = 0.0;
|
|
||||||
|
|
||||||
Equitherm() = default;
|
|
||||||
|
|
||||||
// kn, kk, kt
|
|
||||||
Equitherm(float new_kn, float new_kk, float new_kt) {
|
|
||||||
Kn = new_kn;
|
|
||||||
Kk = new_kk;
|
|
||||||
Kt = new_kt;
|
|
||||||
}
|
|
||||||
|
|
||||||
// лимит выходной величины
|
|
||||||
void setLimits(int min_output, int max_output) {
|
|
||||||
_minOut = min_output;
|
|
||||||
_maxOut = max_output;
|
|
||||||
}
|
|
||||||
|
|
||||||
// возвращает новое значение при вызове
|
|
||||||
datatype getResult() {
|
|
||||||
datatype output = getResultN() + getResultK() + getResultT();
|
|
||||||
output = constrain(output, _minOut, _maxOut); // ограничиваем выход
|
|
||||||
return output;
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
int _minOut = 20, _maxOut = 90;
|
|
||||||
|
|
||||||
// температура контура отопления в зависимости от наружной температуры
|
|
||||||
datatype getResultN() {
|
|
||||||
float a = (-0.21 * Kn) - 0.06; // a = -0,21k — 0,06
|
|
||||||
float b = (6.04 * Kn) + 1.98; // b = 6,04k + 1,98
|
|
||||||
float c = (-5.06 * Kn) + 18.06; // с = -5,06k + 18,06
|
|
||||||
float x = (-0.2 * outdoorTemp) + 5; // x = -0.2*t1 + 5
|
|
||||||
return (a * x * x) + (b * x) + c; // Tn = ax2 + bx + c
|
|
||||||
}
|
|
||||||
|
|
||||||
// поправка на желаемую комнатную температуру
|
|
||||||
datatype getResultK() {
|
|
||||||
return (targetTemp - 20) * Kk;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Расчет поправки (ошибки) термостата
|
|
||||||
datatype getResultT() {
|
|
||||||
return constrain((targetTemp - indoorTemp), -2, 2) * Kt;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,145 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <Arduino.h>
|
|
||||||
#include "strings.h"
|
|
||||||
|
|
||||||
class HomeAssistantHelper {
|
|
||||||
public:
|
|
||||||
typedef std::function<void(const char*, bool)> PublishEventCallback;
|
|
||||||
|
|
||||||
HomeAssistantHelper() = default;
|
|
||||||
|
|
||||||
void setWriter() {
|
|
||||||
this->writer = nullptr;
|
|
||||||
}
|
|
||||||
|
|
||||||
void setWriter(MqttWriter* writer) {
|
|
||||||
this->writer = writer;
|
|
||||||
}
|
|
||||||
|
|
||||||
void setPublishEventCallback(PublishEventCallback callback) {
|
|
||||||
this->publishEventCallback = callback;
|
|
||||||
}
|
|
||||||
|
|
||||||
void setDevicePrefix(const char* value) {
|
|
||||||
this->devicePrefix = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
void setDeviceVersion(const char* value) {
|
|
||||||
this->deviceVersion = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
void setDeviceManufacturer(const char* value) {
|
|
||||||
this->deviceManufacturer = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
void setDeviceModel(const char* value) {
|
|
||||||
this->deviceModel = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
void setDeviceName(const char* value) {
|
|
||||||
this->deviceName = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
void setDeviceConfigUrl(const char* value) {
|
|
||||||
this->deviceConfigUrl = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool publish(const char* topic, JsonDocument& doc) {
|
|
||||||
if (this->writer == nullptr) {
|
|
||||||
if (this->publishEventCallback) {
|
|
||||||
this->publishEventCallback(topic, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
doc[FPSTR(HA_DEVICE)][FPSTR(HA_IDENTIFIERS)][0] = this->devicePrefix;
|
|
||||||
doc[FPSTR(HA_DEVICE)][FPSTR(HA_SW_VERSION)] = this->deviceVersion;
|
|
||||||
|
|
||||||
if (this->deviceManufacturer != nullptr) {
|
|
||||||
doc[FPSTR(HA_DEVICE)][FPSTR(HA_MANUFACTURER)] = this->deviceManufacturer;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this->deviceModel != nullptr) {
|
|
||||||
doc[FPSTR(HA_DEVICE)][FPSTR(HA_MODEL)] = this->deviceModel;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this->deviceName != nullptr) {
|
|
||||||
doc[FPSTR(HA_DEVICE)][FPSTR(HA_NAME)] = this->deviceName;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this->deviceConfigUrl != nullptr) {
|
|
||||||
doc[FPSTR(HA_DEVICE)][FPSTR(HA_CONF_URL)] = this->deviceConfigUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool result = this->writer->publish(topic, doc, true);
|
|
||||||
doc.clear();
|
|
||||||
doc.shrinkToFit();
|
|
||||||
|
|
||||||
if (this->publishEventCallback) {
|
|
||||||
this->publishEventCallback(topic, result);
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool publish(const char* topic) {
|
|
||||||
if (this->writer == nullptr) {
|
|
||||||
if (this->publishEventCallback) {
|
|
||||||
this->publishEventCallback(topic, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool result = writer->publish(topic, nullptr, 0, true);
|
|
||||||
if (this->publishEventCallback) {
|
|
||||||
this->publishEventCallback(topic, result);
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
template <class T>
|
|
||||||
String getTopic(T category, T name, char nameSeparator = '/') {
|
|
||||||
String topic = "";
|
|
||||||
topic.concat(this->prefix);
|
|
||||||
topic.concat('/');
|
|
||||||
topic.concat(category);
|
|
||||||
topic.concat('/');
|
|
||||||
topic.concat(this->devicePrefix);
|
|
||||||
topic.concat(nameSeparator);
|
|
||||||
topic.concat(name);
|
|
||||||
topic.concat("/config");
|
|
||||||
return topic;
|
|
||||||
}
|
|
||||||
|
|
||||||
template <class T>
|
|
||||||
String getDeviceTopic(T value, char separator = '/') {
|
|
||||||
String topic = "";
|
|
||||||
topic.concat(this->devicePrefix);
|
|
||||||
topic.concat(separator);
|
|
||||||
topic.concat(value);
|
|
||||||
return topic;
|
|
||||||
}
|
|
||||||
|
|
||||||
template <class T>
|
|
||||||
String getObjectId(T value, char separator = '_') {
|
|
||||||
String topic = "";
|
|
||||||
topic.concat(this->devicePrefix);
|
|
||||||
topic.concat(separator);
|
|
||||||
topic.concat(value);
|
|
||||||
return topic;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected:
|
|
||||||
PublishEventCallback publishEventCallback;
|
|
||||||
MqttWriter* writer = nullptr;
|
|
||||||
const char* prefix = "homeassistant";
|
|
||||||
const char* devicePrefix = "";
|
|
||||||
const char* deviceVersion = "1.0";
|
|
||||||
const char* deviceManufacturer = nullptr;
|
|
||||||
const char* deviceModel = nullptr;
|
|
||||||
const char* deviceName = nullptr;
|
|
||||||
const char* deviceConfigUrl = nullptr;
|
|
||||||
};
|
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#ifndef PROGMEM
|
|
||||||
#define PROGMEM
|
|
||||||
#endif
|
|
||||||
|
|
||||||
const char HA_ENTITY_BINARY_SENSOR[] PROGMEM = "binary_sensor";
|
|
||||||
const char HA_ENTITY_BUTTON[] PROGMEM = "button";
|
|
||||||
const char HA_ENTITY_FAN[] PROGMEM = "fan";
|
|
||||||
const char HA_ENTITY_CLIMATE[] PROGMEM = "climate";
|
|
||||||
const char HA_ENTITY_NUMBER[] PROGMEM = "number";
|
|
||||||
const char HA_ENTITY_SELECT[] PROGMEM = "select";
|
|
||||||
const char HA_ENTITY_SENSOR[] PROGMEM = "sensor";
|
|
||||||
const char HA_ENTITY_SWITCH[] PROGMEM = "switch";
|
|
||||||
|
|
||||||
const char HA_DEVICE[] PROGMEM = "device";
|
|
||||||
const char HA_IDENTIFIERS[] PROGMEM = "identifiers";
|
|
||||||
const char HA_SW_VERSION[] PROGMEM = "sw_version";
|
|
||||||
const char HA_MANUFACTURER[] PROGMEM = "manufacturer";
|
|
||||||
const char HA_MODEL[] PROGMEM = "model";
|
|
||||||
const char HA_NAME[] PROGMEM = "name";
|
|
||||||
const char HA_CONF_URL[] PROGMEM = "configuration_url";
|
|
||||||
const char HA_COMMAND_TOPIC[] PROGMEM = "command_topic";
|
|
||||||
const char HA_COMMAND_TEMPLATE[] PROGMEM = "command_template";
|
|
||||||
const char HA_ENABLED_BY_DEFAULT[] PROGMEM = "enabled_by_default";
|
|
||||||
const char HA_UNIQUE_ID[] PROGMEM = "unique_id";
|
|
||||||
const char HA_OBJECT_ID[] PROGMEM = "object_id";
|
|
||||||
const char HA_ENTITY_CATEGORY[] PROGMEM = "entity_category";
|
|
||||||
const char HA_STATE_TOPIC[] PROGMEM = "state_topic";
|
|
||||||
const char HA_VALUE_TEMPLATE[] PROGMEM = "value_template";
|
|
||||||
const char HA_OPTIONS[] PROGMEM = "options";
|
|
||||||
const char HA_AVAILABILITY[] PROGMEM = "availability";
|
|
||||||
const char HA_AVAILABILITY_MODE[] PROGMEM = "availability_mode";
|
|
||||||
const char HA_TOPIC[] PROGMEM = "topic";
|
|
||||||
const char HA_DEVICE_CLASS[] PROGMEM = "device_class";
|
|
||||||
const char HA_UNIT_OF_MEASUREMENT[] PROGMEM = "unit_of_measurement";
|
|
||||||
const char HA_ICON[] PROGMEM = "icon";
|
|
||||||
const char HA_MIN[] PROGMEM = "min";
|
|
||||||
const char HA_MAX[] PROGMEM = "max";
|
|
||||||
const char HA_STEP[] PROGMEM = "step";
|
|
||||||
const char HA_MODE[] PROGMEM = "mode";
|
|
||||||
const char HA_STATE_ON[] PROGMEM = "state_on";
|
|
||||||
const char HA_STATE_OFF[] PROGMEM = "state_off";
|
|
||||||
const char HA_PAYLOAD_ON[] PROGMEM = "payload_on";
|
|
||||||
const char HA_PAYLOAD_OFF[] PROGMEM = "payload_off";
|
|
||||||
const char HA_STATE_CLASS[] PROGMEM = "state_class";
|
|
||||||
const char HA_EXPIRE_AFTER[] PROGMEM = "expire_after";
|
|
||||||
const char HA_CURRENT_TEMPERATURE_TOPIC[] PROGMEM = "current_temperature_topic";
|
|
||||||
const char HA_CURRENT_TEMPERATURE_TEMPLATE[] PROGMEM = "current_temperature_template";
|
|
||||||
const char HA_TEMPERATURE_COMMAND_TOPIC[] PROGMEM = "temperature_command_topic";
|
|
||||||
const char HA_TEMPERATURE_COMMAND_TEMPLATE[] PROGMEM = "temperature_command_template";
|
|
||||||
const char HA_TEMPERATURE_STATE_TOPIC[] PROGMEM = "temperature_state_topic";
|
|
||||||
const char HA_TEMPERATURE_STATE_TEMPLATE[] PROGMEM = "temperature_state_template";
|
|
||||||
const char HA_MODE_COMMAND_TOPIC[] PROGMEM = "mode_command_topic";
|
|
||||||
const char HA_MODE_COMMAND_TEMPLATE[] PROGMEM = "mode_command_template";
|
|
||||||
const char HA_MODE_STATE_TOPIC[] PROGMEM = "mode_state_topic";
|
|
||||||
const char HA_MODE_STATE_TEMPLATE[] PROGMEM = "mode_state_template";
|
|
||||||
const char HA_MODES[] PROGMEM = "modes";
|
|
||||||
const char HA_ACTION_TOPIC[] PROGMEM = "action_topic";
|
|
||||||
const char HA_ACTION_TEMPLATE[] PROGMEM = "action_template";
|
|
||||||
const char HA_MIN_TEMP[] PROGMEM = "min_temp";
|
|
||||||
const char HA_MAX_TEMP[] PROGMEM = "max_temp";
|
|
||||||
const char HA_TEMP_STEP[] PROGMEM = "temp_step";
|
|
||||||
const char HA_PRESET_MODE_COMMAND_TOPIC[] PROGMEM = "preset_mode_command_topic";
|
|
||||||
const char HA_PRESET_MODE_COMMAND_TEMPLATE[] PROGMEM = "preset_mode_command_template";
|
|
||||||
const char HA_PRESET_MODE_STATE_TOPIC[] PROGMEM = "preset_mode_state_topic";
|
|
||||||
const char HA_PRESET_MODE_VALUE_TEMPLATE[] PROGMEM = "preset_mode_value_template";
|
|
||||||
const char HA_PRESET_MODES[] PROGMEM = "preset_modes";
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
#include <WiFiClient.h>
|
|
||||||
|
|
||||||
class MqttWiFiClient : public WiFiClient {
|
|
||||||
public:
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
void flush() override {
|
|
||||||
if (this->connected()) {
|
|
||||||
WiFiClient::flush(0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void stop() override {
|
|
||||||
this->abort();
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifdef ARDUINO_ARCH_ESP32
|
|
||||||
void setSync(bool) {}
|
|
||||||
|
|
||||||
bool getSync() {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
};
|
|
||||||
@@ -1,220 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <Arduino.h>
|
|
||||||
#include <MqttClient.h>
|
|
||||||
#ifdef ARDUINO_ARCH_ESP32
|
|
||||||
#include <mutex>
|
|
||||||
#endif
|
|
||||||
|
|
||||||
|
|
||||||
class MqttWriter {
|
|
||||||
public:
|
|
||||||
typedef std::function<void()> YieldCallback;
|
|
||||||
typedef std::function<void(const char*, size_t, size_t, bool)> PublishEventCallback;
|
|
||||||
typedef std::function<void(size_t, size_t)> FlushEventCallback;
|
|
||||||
|
|
||||||
MqttWriter(MqttClient* client, size_t bufferSize = 64) {
|
|
||||||
this->client = client;
|
|
||||||
this->bufferSize = bufferSize;
|
|
||||||
this->buffer = (uint8_t*) malloc(bufferSize * sizeof(*this->buffer));
|
|
||||||
|
|
||||||
#ifdef ARDUINO_ARCH_ESP32
|
|
||||||
this->mutex = new std::mutex();
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
~MqttWriter() {
|
|
||||||
free(this->buffer);
|
|
||||||
|
|
||||||
#ifdef ARDUINO_ARCH_ESP32
|
|
||||||
delete this->mutex;
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
MqttWriter* setYieldCallback(YieldCallback callback = nullptr) {
|
|
||||||
this->yieldCallback = callback;
|
|
||||||
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
MqttWriter* setPublishEventCallback(PublishEventCallback callback) {
|
|
||||||
this->publishEventCallback = callback;
|
|
||||||
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
MqttWriter* setFlushEventCallback(FlushEventCallback callback) {
|
|
||||||
this->flushEventCallback = callback;
|
|
||||||
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool lock() {
|
|
||||||
#ifdef ARDUINO_ARCH_ESP32
|
|
||||||
if (!this->mutex->try_lock()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
#else
|
|
||||||
if (this->isLocked()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
this->locked = true;
|
|
||||||
this->writeAfterLock = 0;
|
|
||||||
this->lockedTime = millis();
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool isLocked() {
|
|
||||||
return this->locked;
|
|
||||||
}
|
|
||||||
|
|
||||||
void unlock() {
|
|
||||||
this->locked = false;
|
|
||||||
#if defined(ARDUINO_ARCH_ESP32)
|
|
||||||
this->mutex->unlock();
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
bool publish(const char* topic, JsonDocument& doc, bool retained = false) {
|
|
||||||
if (!this->client->connected()) {
|
|
||||||
this->bufferPos = 0;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
while (!this->lock()) {
|
|
||||||
if (this->yieldCallback) {
|
|
||||||
this->yieldCallback();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
this->bufferPos = 0;
|
|
||||||
size_t docSize = measureJson(doc);
|
|
||||||
size_t written = 0;
|
|
||||||
if (this->client->beginMessage(topic, docSize, retained)) {
|
|
||||||
serializeJson(doc, *this);
|
|
||||||
this->flush();
|
|
||||||
this->client->endMessage();
|
|
||||||
|
|
||||||
written = this->writeAfterLock;
|
|
||||||
}
|
|
||||||
this->unlock();
|
|
||||||
|
|
||||||
if (this->publishEventCallback) {
|
|
||||||
this->publishEventCallback(topic, written, docSize, written == docSize);
|
|
||||||
}
|
|
||||||
|
|
||||||
return written == docSize;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool publish(const char* topic, const char* buffer, bool retained = false) {
|
|
||||||
return this->publish(topic, (const uint8_t*) buffer, strlen(buffer), retained);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool publish(const char* topic, const uint8_t* buffer, size_t length, bool retained = false) {
|
|
||||||
if (!this->client->connected()) {
|
|
||||||
this->bufferPos = 0;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
while (!this->lock()) {
|
|
||||||
if (this->yieldCallback) {
|
|
||||||
this->yieldCallback();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
this->bufferPos = 0;
|
|
||||||
size_t written = 0;
|
|
||||||
bool result = false;
|
|
||||||
if (!length || buffer == nullptr) {
|
|
||||||
result = this->client->beginMessage(topic, retained) && this->client->endMessage();
|
|
||||||
|
|
||||||
} else if (this->client->beginMessage(topic, length, retained)) {
|
|
||||||
this->write(buffer, length);
|
|
||||||
this->flush();
|
|
||||||
this->client->endMessage();
|
|
||||||
|
|
||||||
written = this->writeAfterLock;
|
|
||||||
result = written == length;
|
|
||||||
}
|
|
||||||
this->unlock();
|
|
||||||
|
|
||||||
if (this->publishEventCallback) {
|
|
||||||
this->publishEventCallback(topic, written, length, result);
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t write(uint8_t c) {
|
|
||||||
this->buffer[this->bufferPos++] = c;
|
|
||||||
|
|
||||||
if (this->bufferPos >= this->bufferSize) {
|
|
||||||
this->flush();
|
|
||||||
}
|
|
||||||
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t write(const uint8_t* buffer, size_t length) {
|
|
||||||
size_t written = 0;
|
|
||||||
while (written < length) {
|
|
||||||
size_t copySize = this->bufferSize - this->bufferPos;
|
|
||||||
if (written + copySize > length) {
|
|
||||||
copySize = length - written;
|
|
||||||
}
|
|
||||||
|
|
||||||
memcpy(this->buffer + this->bufferPos, buffer + written, copySize);
|
|
||||||
this->bufferPos += copySize;
|
|
||||||
|
|
||||||
if (this->bufferPos >= this->bufferSize) {
|
|
||||||
this->flush();
|
|
||||||
}
|
|
||||||
|
|
||||||
written += copySize;
|
|
||||||
}
|
|
||||||
|
|
||||||
return written;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool flush() {
|
|
||||||
if (this->bufferPos == 0) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!this->client->connected()) {
|
|
||||||
this->bufferPos = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t length = this->bufferPos;
|
|
||||||
size_t written = this->client->write(this->buffer, length);
|
|
||||||
this->client->flush();
|
|
||||||
this->bufferPos = 0;
|
|
||||||
|
|
||||||
if (this->isLocked()) {
|
|
||||||
this->writeAfterLock += written;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this->flushEventCallback) {
|
|
||||||
this->flushEventCallback(written, length);
|
|
||||||
}
|
|
||||||
|
|
||||||
return written == length;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected:
|
|
||||||
YieldCallback yieldCallback;
|
|
||||||
PublishEventCallback publishEventCallback;
|
|
||||||
FlushEventCallback flushEventCallback;
|
|
||||||
MqttClient* client;
|
|
||||||
uint8_t* buffer;
|
|
||||||
size_t bufferSize = 64;
|
|
||||||
size_t bufferPos = 0;
|
|
||||||
bool locked = false;
|
|
||||||
#ifdef ARDUINO_ARCH_ESP32
|
|
||||||
mutable std::mutex* mutex;
|
|
||||||
#endif
|
|
||||||
unsigned long lockedTime = 0;
|
|
||||||
size_t writeAfterLock = 0;
|
|
||||||
};
|
|
||||||
@@ -1,150 +0,0 @@
|
|||||||
#include "NetworkConnection.h"
|
|
||||||
using namespace Network;
|
|
||||||
|
|
||||||
void Connection::setup(bool useDhcp) {
|
|
||||||
setUseDhcp(useDhcp);
|
|
||||||
|
|
||||||
#if defined(ARDUINO_ARCH_ESP8266)
|
|
||||||
wifi_set_event_handler_cb(Connection::onEvent);
|
|
||||||
#elif defined(ARDUINO_ARCH_ESP32)
|
|
||||||
WiFi.onEvent(Connection::onEvent);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
void Connection::reset() {
|
|
||||||
status = Status::NONE;
|
|
||||||
disconnectReason = DisconnectReason::NONE;
|
|
||||||
}
|
|
||||||
|
|
||||||
void Connection::setUseDhcp(bool value) {
|
|
||||||
useDhcp = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
Connection::Status Connection::getStatus() {
|
|
||||||
return status;
|
|
||||||
}
|
|
||||||
|
|
||||||
Connection::DisconnectReason Connection::getDisconnectReason() {
|
|
||||||
return disconnectReason;
|
|
||||||
}
|
|
||||||
|
|
||||||
#if defined(ARDUINO_ARCH_ESP8266)
|
|
||||||
void Connection::onEvent(System_Event_t *event) {
|
|
||||||
switch (event->event) {
|
|
||||||
case EVENT_STAMODE_CONNECTED:
|
|
||||||
status = useDhcp ? Status::CONNECTING : Status::CONNECTED;
|
|
||||||
disconnectReason = DisconnectReason::NONE;
|
|
||||||
|
|
||||||
break;
|
|
||||||
|
|
||||||
case EVENT_STAMODE_GOT_IP:
|
|
||||||
status = Status::CONNECTED;
|
|
||||||
disconnectReason = DisconnectReason::NONE;
|
|
||||||
break;
|
|
||||||
|
|
||||||
case EVENT_STAMODE_DHCP_TIMEOUT:
|
|
||||||
status = Status::DISCONNECTED;
|
|
||||||
disconnectReason = DisconnectReason::DHCP_TIMEOUT;
|
|
||||||
break;
|
|
||||||
|
|
||||||
case EVENT_STAMODE_DISCONNECTED:
|
|
||||||
status = Status::DISCONNECTED;
|
|
||||||
disconnectReason = convertDisconnectReason(event->event_info.disconnected.reason);
|
|
||||||
|
|
||||||
// https://github.com/esp8266/Arduino/blob/d5eb265f78bff9deb7063d10030a02d021c8c66c/libraries/ESP8266WiFi/src/ESP8266WiFiGeneric.cpp#L231
|
|
||||||
if ((wifi_station_get_connect_status() == STATION_GOT_IP) && !wifi_station_get_reconnect_policy()) {
|
|
||||||
wifi_station_disconnect();
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
case EVENT_STAMODE_AUTHMODE_CHANGE:
|
|
||||||
// https://github.com/esp8266/Arduino/blob/d5eb265f78bff9deb7063d10030a02d021c8c66c/libraries/ESP8266WiFi/src/ESP8266WiFiGeneric.cpp#L241
|
|
||||||
{
|
|
||||||
auto& src = event->event_info.auth_change;
|
|
||||||
if ((src.old_mode != AUTH_OPEN) && (src.new_mode == AUTH_OPEN)) {
|
|
||||||
status = Status::DISCONNECTED;
|
|
||||||
disconnectReason = DisconnectReason::OTHER;
|
|
||||||
|
|
||||||
wifi_station_disconnect();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#elif defined(ARDUINO_ARCH_ESP32)
|
|
||||||
void Connection::onEvent(WiFiEvent_t event, WiFiEventInfo_t info) {
|
|
||||||
switch (event) {
|
|
||||||
case ARDUINO_EVENT_WIFI_STA_CONNECTED:
|
|
||||||
status = useDhcp ? Status::CONNECTING : Status::CONNECTED;
|
|
||||||
disconnectReason = DisconnectReason::NONE;
|
|
||||||
|
|
||||||
break;
|
|
||||||
|
|
||||||
case ARDUINO_EVENT_WIFI_STA_GOT_IP:
|
|
||||||
case ARDUINO_EVENT_WIFI_STA_GOT_IP6:
|
|
||||||
status = Status::CONNECTED;
|
|
||||||
disconnectReason = DisconnectReason::NONE;
|
|
||||||
break;
|
|
||||||
|
|
||||||
case ARDUINO_EVENT_WIFI_STA_LOST_IP:
|
|
||||||
status = Status::DISCONNECTED;
|
|
||||||
disconnectReason = DisconnectReason::DHCP_TIMEOUT;
|
|
||||||
break;
|
|
||||||
|
|
||||||
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
|
|
||||||
status = Status::DISCONNECTED;
|
|
||||||
disconnectReason = convertDisconnectReason(info.wifi_sta_disconnected.reason);
|
|
||||||
|
|
||||||
break;
|
|
||||||
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
Connection::DisconnectReason Connection::convertDisconnectReason(uint8_t reason) {
|
|
||||||
switch (reason) {
|
|
||||||
#if defined(ARDUINO_ARCH_ESP8266)
|
|
||||||
case REASON_BEACON_TIMEOUT:
|
|
||||||
return DisconnectReason::BEACON_TIMEOUT;
|
|
||||||
|
|
||||||
case REASON_NO_AP_FOUND:
|
|
||||||
return DisconnectReason::NO_AP_FOUND;
|
|
||||||
|
|
||||||
case REASON_AUTH_FAIL:
|
|
||||||
return DisconnectReason::AUTH_FAIL;
|
|
||||||
|
|
||||||
case REASON_ASSOC_FAIL:
|
|
||||||
return DisconnectReason::ASSOC_FAIL;
|
|
||||||
|
|
||||||
case REASON_HANDSHAKE_TIMEOUT:
|
|
||||||
return DisconnectReason::HANDSHAKE_TIMEOUT;
|
|
||||||
#elif defined(ARDUINO_ARCH_ESP32)
|
|
||||||
case WIFI_REASON_BEACON_TIMEOUT:
|
|
||||||
return DisconnectReason::BEACON_TIMEOUT;
|
|
||||||
|
|
||||||
case WIFI_REASON_NO_AP_FOUND:
|
|
||||||
return DisconnectReason::NO_AP_FOUND;
|
|
||||||
|
|
||||||
case WIFI_REASON_AUTH_FAIL:
|
|
||||||
return DisconnectReason::AUTH_FAIL;
|
|
||||||
|
|
||||||
case WIFI_REASON_ASSOC_FAIL:
|
|
||||||
return DisconnectReason::ASSOC_FAIL;
|
|
||||||
|
|
||||||
case WIFI_REASON_HANDSHAKE_TIMEOUT:
|
|
||||||
return DisconnectReason::HANDSHAKE_TIMEOUT;
|
|
||||||
#endif
|
|
||||||
|
|
||||||
default:
|
|
||||||
return DisconnectReason::OTHER;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bool Connection::useDhcp = false;
|
|
||||||
Connection::Status Connection::status = Status::NONE;
|
|
||||||
Connection::DisconnectReason Connection::disconnectReason = DisconnectReason::NONE;
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
#if defined(ARDUINO_ARCH_ESP8266)
|
|
||||||
#include <ESP8266WiFi.h>
|
|
||||||
#include "lwip/etharp.h"
|
|
||||||
#elif defined(ARDUINO_ARCH_ESP32)
|
|
||||||
#include <WiFi.h>
|
|
||||||
#endif
|
|
||||||
|
|
||||||
namespace Network {
|
|
||||||
struct Connection {
|
|
||||||
enum class Status {
|
|
||||||
CONNECTED,
|
|
||||||
CONNECTING,
|
|
||||||
DISCONNECTED,
|
|
||||||
NONE
|
|
||||||
};
|
|
||||||
|
|
||||||
enum class DisconnectReason {
|
|
||||||
BEACON_TIMEOUT,
|
|
||||||
NO_AP_FOUND,
|
|
||||||
AUTH_FAIL,
|
|
||||||
ASSOC_FAIL,
|
|
||||||
HANDSHAKE_TIMEOUT,
|
|
||||||
DHCP_TIMEOUT,
|
|
||||||
OTHER,
|
|
||||||
NONE
|
|
||||||
};
|
|
||||||
|
|
||||||
static Status status;
|
|
||||||
static DisconnectReason disconnectReason;
|
|
||||||
|
|
||||||
static void setup(bool useDhcp);
|
|
||||||
static void setUseDhcp(bool value);
|
|
||||||
static void reset();
|
|
||||||
static Status getStatus();
|
|
||||||
static DisconnectReason getDisconnectReason();
|
|
||||||
#if defined(ARDUINO_ARCH_ESP8266)
|
|
||||||
static void onEvent(System_Event_t *evt);
|
|
||||||
#elif defined(ARDUINO_ARCH_ESP32)
|
|
||||||
static void onEvent(WiFiEvent_t event, WiFiEventInfo_t info);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
protected:
|
|
||||||
static DisconnectReason convertDisconnectReason(uint8_t reason);
|
|
||||||
static bool useDhcp;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,438 +0,0 @@
|
|||||||
#if defined(ARDUINO_ARCH_ESP8266)
|
|
||||||
#include <ESP8266WiFi.h>
|
|
||||||
#include "lwip/etharp.h"
|
|
||||||
#elif defined(ARDUINO_ARCH_ESP32)
|
|
||||||
#include <WiFi.h>
|
|
||||||
#include <esp_wifi.h>
|
|
||||||
#endif
|
|
||||||
#include <NetworkConnection.h>
|
|
||||||
|
|
||||||
namespace Network {
|
|
||||||
class Manager {
|
|
||||||
public:
|
|
||||||
typedef std::function<void()> YieldCallback;
|
|
||||||
typedef std::function<void(unsigned int)> DelayCallback;
|
|
||||||
|
|
||||||
Manager() {
|
|
||||||
Connection::setup(this->useDhcp);
|
|
||||||
this->resetWifi();
|
|
||||||
}
|
|
||||||
|
|
||||||
Manager* setYieldCallback(YieldCallback callback = nullptr) {
|
|
||||||
this->yieldCallback = callback;
|
|
||||||
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
Manager* setDelayCallback(DelayCallback callback = nullptr) {
|
|
||||||
this->delayCallback = callback;
|
|
||||||
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
Manager* setHostname(const char* value) {
|
|
||||||
this->hostname = value;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
Manager* setApCredentials(const char* ssid, const char* password = nullptr, byte channel = 0) {
|
|
||||||
this->apName = ssid;
|
|
||||||
this->apPassword = password;
|
|
||||||
this->apChannel = channel;
|
|
||||||
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
Manager* setStaCredentials(const char* ssid = nullptr, const char* password = nullptr, byte channel = 0) {
|
|
||||||
this->staSsid = ssid;
|
|
||||||
this->staPassword = password;
|
|
||||||
this->staChannel = channel;
|
|
||||||
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
Manager* setUseDhcp(bool value) {
|
|
||||||
this->useDhcp = value;
|
|
||||||
Connection::setup(this->useDhcp);
|
|
||||||
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
Manager* setStaticConfig(const char* ip, const char* gateway, const char* subnet, const char* dns) {
|
|
||||||
this->staticIp.fromString(ip);
|
|
||||||
this->staticGateway.fromString(gateway);
|
|
||||||
this->staticSubnet.fromString(subnet);
|
|
||||||
this->staticDns.fromString(dns);
|
|
||||||
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
Manager* setStaticConfig(IPAddress &ip, IPAddress &gateway, IPAddress &subnet, IPAddress &dns) {
|
|
||||||
this->staticIp = ip;
|
|
||||||
this->staticGateway = gateway;
|
|
||||||
this->staticSubnet = subnet;
|
|
||||||
this->staticDns = dns;
|
|
||||||
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool hasStaCredentials() {
|
|
||||||
return this->staSsid != nullptr;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool isConnected() {
|
|
||||||
return this->isStaEnabled() && Connection::getStatus() == Connection::Status::CONNECTED;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool isConnecting() {
|
|
||||||
return this->isStaEnabled() && Connection::getStatus() == Connection::Status::CONNECTING;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool isStaEnabled() {
|
|
||||||
return (WiFi.getMode() & WIFI_STA) != 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool isApEnabled() {
|
|
||||||
return (WiFi.getMode() & WIFI_AP) != 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool hasApClients() {
|
|
||||||
if (!this->isApEnabled()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return WiFi.softAPgetStationNum() > 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
short int getRssi() {
|
|
||||||
return WiFi.RSSI();
|
|
||||||
}
|
|
||||||
|
|
||||||
IPAddress getApIp() {
|
|
||||||
return WiFi.softAPIP();
|
|
||||||
}
|
|
||||||
|
|
||||||
IPAddress getStaIp() {
|
|
||||||
return WiFi.localIP();
|
|
||||||
}
|
|
||||||
|
|
||||||
IPAddress getStaSubnet() {
|
|
||||||
return WiFi.subnetMask();
|
|
||||||
}
|
|
||||||
|
|
||||||
IPAddress getStaGateway() {
|
|
||||||
return WiFi.gatewayIP();
|
|
||||||
}
|
|
||||||
|
|
||||||
IPAddress getStaDns() {
|
|
||||||
return WiFi.dnsIP();
|
|
||||||
}
|
|
||||||
|
|
||||||
String getStaMac() {
|
|
||||||
return WiFi.macAddress();
|
|
||||||
}
|
|
||||||
|
|
||||||
const char* getStaSsid() {
|
|
||||||
return this->staSsid;
|
|
||||||
}
|
|
||||||
|
|
||||||
const char* getStaPassword() {
|
|
||||||
return this->staPassword;
|
|
||||||
}
|
|
||||||
|
|
||||||
byte getStaChannel() {
|
|
||||||
return this->staChannel;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool resetWifi() {
|
|
||||||
// set policy manual for work 13 ch
|
|
||||||
{
|
|
||||||
wifi_country_t country = {"CN", 1, 13, WIFI_COUNTRY_POLICY_MANUAL};
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
wifi_set_country(&country);
|
|
||||||
#elif defined(ARDUINO_ARCH_ESP32)
|
|
||||||
esp_wifi_set_country(&country);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
WiFi.persistent(false);
|
|
||||||
WiFi.setAutoConnect(false);
|
|
||||||
WiFi.setAutoReconnect(false);
|
|
||||||
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
WiFi.setSleepMode(WIFI_NONE_SLEEP);
|
|
||||||
#elif defined(ARDUINO_ARCH_ESP32)
|
|
||||||
WiFi.setSleep(USE_BLE ? WIFI_PS_MIN_MODEM : WIFI_PS_NONE);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
WiFi.softAPdisconnect();
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
/*if (wifi_softap_dhcps_status() == DHCP_STARTED) {
|
|
||||||
wifi_softap_dhcps_stop();
|
|
||||||
}*/
|
|
||||||
#endif
|
|
||||||
|
|
||||||
WiFi.disconnect(false, true);
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
/*if (wifi_station_dhcpc_status() == DHCP_STARTED) {
|
|
||||||
wifi_station_dhcpc_stop();
|
|
||||||
}*/
|
|
||||||
|
|
||||||
wifi_station_dhcpc_set_maxtry(5);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
return WiFi.mode(WIFI_OFF);
|
|
||||||
}
|
|
||||||
|
|
||||||
void reconnect() {
|
|
||||||
this->reconnectFlag = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool connect(bool force = false, unsigned int timeout = 1000u) {
|
|
||||||
if (this->isConnected() && !force) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (force && !this->isApEnabled()) {
|
|
||||||
this->resetWifi();
|
|
||||||
|
|
||||||
} else {
|
|
||||||
/*#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
if (wifi_station_dhcpc_status() == DHCP_STARTED) {
|
|
||||||
wifi_station_dhcpc_stop();
|
|
||||||
}
|
|
||||||
#endif*/
|
|
||||||
|
|
||||||
WiFi.disconnect(false, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!this->hasStaCredentials()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
this->delayCallback(200);
|
|
||||||
|
|
||||||
#ifdef ARDUINO_ARCH_ESP32
|
|
||||||
if (this->setWifiHostname(this->hostname)) {
|
|
||||||
Log.straceln(FPSTR(L_NETWORK), F("Set hostname '%s': success"), this->hostname);
|
|
||||||
|
|
||||||
} else {
|
|
||||||
Log.serrorln(FPSTR(L_NETWORK), F("Set hostname '%s': fail"), this->hostname);
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
if (!WiFi.mode((WiFiMode_t)(WiFi.getMode() | WIFI_STA))) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
this->delayCallback(200);
|
|
||||||
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
if (this->setWifiHostname(this->hostname)) {
|
|
||||||
Log.straceln(FPSTR(L_NETWORK), F("Set hostname '%s': success"), this->hostname);
|
|
||||||
|
|
||||||
} else {
|
|
||||||
Log.serrorln(FPSTR(L_NETWORK), F("Set hostname '%s': fail"), this->hostname);
|
|
||||||
}
|
|
||||||
|
|
||||||
this->delayCallback(200);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
if (!this->useDhcp) {
|
|
||||||
WiFi.config(this->staticIp, this->staticGateway, this->staticSubnet, this->staticDns);
|
|
||||||
}
|
|
||||||
|
|
||||||
WiFi.begin(this->staSsid, this->staPassword, this->staChannel);
|
|
||||||
|
|
||||||
unsigned long beginConnectionTime = millis();
|
|
||||||
while (millis() - beginConnectionTime < timeout) {
|
|
||||||
this->delayCallback(100);
|
|
||||||
|
|
||||||
Connection::Status status = Connection::getStatus();
|
|
||||||
if (status != Connection::Status::CONNECTING && status != Connection::Status::NONE) {
|
|
||||||
return status == Connection::Status::CONNECTED;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
void loop() {
|
|
||||||
if (this->isConnected() && !this->hasStaCredentials()) {
|
|
||||||
Log.sinfoln(FPSTR(L_NETWORK), F("Reset"));
|
|
||||||
this->resetWifi();
|
|
||||||
Connection::reset();
|
|
||||||
this->delayCallback(200);
|
|
||||||
|
|
||||||
} else if (this->isConnected() && !this->reconnectFlag) {
|
|
||||||
if (!this->connected) {
|
|
||||||
this->connectedTime = millis();
|
|
||||||
this->connected = true;
|
|
||||||
|
|
||||||
Log.sinfoln(
|
|
||||||
FPSTR(L_NETWORK),
|
|
||||||
F("Connected, downtime: %lu s., IP: %s, RSSI: %hhd"),
|
|
||||||
(millis() - this->disconnectedTime) / 1000,
|
|
||||||
WiFi.localIP().toString().c_str(),
|
|
||||||
WiFi.RSSI()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this->isApEnabled() && millis() - this->connectedTime > this->reconnectInterval && !this->hasApClients()) {
|
|
||||||
Log.sinfoln(FPSTR(L_NETWORK), F("Stop AP because connected, start only STA"));
|
|
||||||
|
|
||||||
WiFi.mode(WIFI_STA);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
if (millis() - this->prevArpGratuitous > 60000) {
|
|
||||||
this->stationKeepAliveNow();
|
|
||||||
this->prevArpGratuitous = millis();
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
} else {
|
|
||||||
if (this->connected) {
|
|
||||||
this->disconnectedTime = millis();
|
|
||||||
this->connected = false;
|
|
||||||
|
|
||||||
Log.sinfoln(
|
|
||||||
FPSTR(L_NETWORK),
|
|
||||||
F("Disconnected, reason: %d, uptime: %lu s."),
|
|
||||||
Connection::getDisconnectReason(),
|
|
||||||
(millis() - this->connectedTime) / 1000
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!this->hasStaCredentials() && !this->isApEnabled()) {
|
|
||||||
Log.sinfoln(FPSTR(L_NETWORK), F("No STA credentials, start AP"));
|
|
||||||
|
|
||||||
WiFi.mode(WIFI_AP_STA);
|
|
||||||
this->delayCallback(250);
|
|
||||||
WiFi.softAP(this->apName, this->apPassword, this->apChannel);
|
|
||||||
|
|
||||||
} else if (!this->isApEnabled() && millis() - this->disconnectedTime > this->failedConnectTimeout) {
|
|
||||||
Log.sinfoln(FPSTR(L_NETWORK), F("Disconnected for a long time, start AP"));
|
|
||||||
|
|
||||||
WiFi.mode(WIFI_AP_STA);
|
|
||||||
this->delayCallback(250);
|
|
||||||
WiFi.softAP(this->apName, this->apPassword, this->apChannel);
|
|
||||||
|
|
||||||
} else if (this->isConnecting() && millis() - this->prevReconnectingTime > this->resetConnectionTimeout) {
|
|
||||||
Log.swarningln(FPSTR(L_NETWORK), F("Connection timeout, reset wifi..."));
|
|
||||||
this->resetWifi();
|
|
||||||
Connection::reset();
|
|
||||||
this->delayCallback(200);
|
|
||||||
|
|
||||||
} else if (!this->isConnecting() && this->hasStaCredentials() && (!this->prevReconnectingTime || millis() - this->prevReconnectingTime > this->reconnectInterval)) {
|
|
||||||
Log.sinfoln(FPSTR(L_NETWORK), F("Try connect..."));
|
|
||||||
|
|
||||||
this->reconnectFlag = false;
|
|
||||||
Connection::reset();
|
|
||||||
if (!this->connect(true, this->connectionTimeout)) {
|
|
||||||
Log.straceln(FPSTR(L_NETWORK), F("Connection failed. Status: %d, reason: %d"), Connection::getStatus(), Connection::getDisconnectReason());
|
|
||||||
}
|
|
||||||
|
|
||||||
this->prevReconnectingTime = millis();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static byte rssiToSignalQuality(short int rssi) {
|
|
||||||
return constrain(map(rssi, -100, -50, 0, 100), 0, 100);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected:
|
|
||||||
const unsigned int reconnectInterval = 5000;
|
|
||||||
const unsigned int failedConnectTimeout = 120000;
|
|
||||||
const unsigned int connectionTimeout = 15000;
|
|
||||||
const unsigned int resetConnectionTimeout = 30000;
|
|
||||||
|
|
||||||
YieldCallback yieldCallback = []() {
|
|
||||||
::yield();
|
|
||||||
};
|
|
||||||
DelayCallback delayCallback = [](unsigned int time) {
|
|
||||||
::delay(time);
|
|
||||||
};
|
|
||||||
|
|
||||||
const char* hostname = "esp";
|
|
||||||
const char* apName = "ESP";
|
|
||||||
const char* apPassword = nullptr;
|
|
||||||
byte apChannel = 1;
|
|
||||||
|
|
||||||
const char* staSsid = nullptr;
|
|
||||||
const char* staPassword = nullptr;
|
|
||||||
byte staChannel = 0;
|
|
||||||
|
|
||||||
bool useDhcp = true;
|
|
||||||
IPAddress staticIp;
|
|
||||||
IPAddress staticGateway;
|
|
||||||
IPAddress staticSubnet;
|
|
||||||
IPAddress staticDns;
|
|
||||||
|
|
||||||
bool connected = false;
|
|
||||||
bool reconnectFlag = false;
|
|
||||||
unsigned long prevArpGratuitous = 0;
|
|
||||||
unsigned long prevReconnectingTime = 0;
|
|
||||||
unsigned long connectedTime = 0;
|
|
||||||
unsigned long disconnectedTime = 0;
|
|
||||||
|
|
||||||
|
|
||||||
bool setWifiHostname(const char* hostname) {
|
|
||||||
if (!this->isHostnameValid(hostname)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (strcmp(WiFi.getHostname(), hostname) == 0) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return WiFi.setHostname(hostname);
|
|
||||||
}
|
|
||||||
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
/**
|
|
||||||
* @brief
|
|
||||||
* https://github.com/arendst/Tasmota/blob/e6515883f0ee5451931b6280ff847b117de5a231/tasmota/tasmota_support/support_wifi.ino#L1196
|
|
||||||
*/
|
|
||||||
static void stationKeepAliveNow(void) {
|
|
||||||
for (netif* interface = netif_list; interface != nullptr; interface = interface->next) {
|
|
||||||
if (
|
|
||||||
(interface->flags & NETIF_FLAG_LINK_UP)
|
|
||||||
&& (interface->flags & NETIF_FLAG_UP)
|
|
||||||
&& interface->num == STATION_IF
|
|
||||||
&& (!ip4_addr_isany_val(*netif_ip4_addr(interface)))
|
|
||||||
) {
|
|
||||||
etharp_gratuitous(interface);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief check RFC compliance
|
|
||||||
*
|
|
||||||
* @param value
|
|
||||||
* @return true
|
|
||||||
* @return false
|
|
||||||
*/
|
|
||||||
static bool isHostnameValid(const char* value) {
|
|
||||||
size_t len = strlen(value);
|
|
||||||
if (len > 24) {
|
|
||||||
return false;
|
|
||||||
} else if (value[len - 1] == '-') {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (size_t i = 0; i < len; i++) {
|
|
||||||
if (!isalnum(value[i]) && value[i] != '-') {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,227 +0,0 @@
|
|||||||
#include <FS.h>
|
|
||||||
|
|
||||||
|
|
||||||
class DynamicPage : public RequestHandler {
|
|
||||||
public:
|
|
||||||
typedef std::function<bool(HTTPMethod, const String&)> CanHandleCallback;
|
|
||||||
typedef std::function<bool()> BeforeSendCallback;
|
|
||||||
typedef std::function<String(const char*)> TemplateCallback;
|
|
||||||
|
|
||||||
DynamicPage(const char* uri, FS* fs, const char* path, const char* cacheHeader = nullptr) {
|
|
||||||
this->uri = uri;
|
|
||||||
this->fs = fs;
|
|
||||||
this->path = path;
|
|
||||||
this->cacheHeader = cacheHeader;
|
|
||||||
}
|
|
||||||
|
|
||||||
DynamicPage* setCanHandleCallback(CanHandleCallback callback = nullptr) {
|
|
||||||
this->canHandleCallback = callback;
|
|
||||||
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
DynamicPage* setBeforeSendCallback(BeforeSendCallback callback = nullptr) {
|
|
||||||
this->beforeSendCallback = callback;
|
|
||||||
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
DynamicPage* setTemplateCallback(TemplateCallback callback = nullptr) {
|
|
||||||
this->templateCallback = callback;
|
|
||||||
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
#if defined(ARDUINO_ARCH_ESP32)
|
|
||||||
bool canHandle(HTTPMethod method, const String uri) override {
|
|
||||||
#else
|
|
||||||
bool canHandle(HTTPMethod method, const String& uri) override {
|
|
||||||
#endif
|
|
||||||
return uri.equals(this->uri) && (!this->canHandleCallback || this->canHandleCallback(method, uri));
|
|
||||||
}
|
|
||||||
|
|
||||||
#if defined(ARDUINO_ARCH_ESP32)
|
|
||||||
bool handle(WebServer& server, HTTPMethod method, const String uri) override {
|
|
||||||
#else
|
|
||||||
bool handle(WebServer& server, HTTPMethod method, const String& uri) override {
|
|
||||||
#endif
|
|
||||||
if (!this->canHandle(method, uri)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this->beforeSendCallback && !this->beforeSendCallback()) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
File file = this->fs->open(this->path, "r");
|
|
||||||
if (!file) {
|
|
||||||
return false;
|
|
||||||
|
|
||||||
} else if (file.isDirectory()) {
|
|
||||||
file.close();
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this->cacheHeader != nullptr) {
|
|
||||||
server.sendHeader("Cache-Control", this->cacheHeader);
|
|
||||||
}
|
|
||||||
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
if (!server.chunkedResponseModeStart(200, F("text/html"))) {
|
|
||||||
server.send(505, F("text/html"), F("HTTP1.1 required"));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
#else
|
|
||||||
server.setContentLength(CONTENT_LENGTH_UNKNOWN);
|
|
||||||
server.send(200, "text/html", emptyString);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
uint8_t* argStartPos = nullptr;
|
|
||||||
uint8_t* argEndPos = nullptr;
|
|
||||||
uint8_t argName[16];
|
|
||||||
size_t sizeArgName = 0;
|
|
||||||
bool argNameProcess = false;
|
|
||||||
while (file.available()) {
|
|
||||||
uint8_t buf[64];
|
|
||||||
size_t length = file.read(buf, sizeof(buf));
|
|
||||||
size_t offset = 0;
|
|
||||||
|
|
||||||
if (argNameProcess) {
|
|
||||||
argEndPos = (uint8_t*) memchr(buf, '}', length);
|
|
||||||
|
|
||||||
if (argEndPos != nullptr) {
|
|
||||||
size_t fullSizeArgName = sizeArgName + (argEndPos - buf);
|
|
||||||
if (fullSizeArgName < sizeof(argName)) {
|
|
||||||
// copy full arg name
|
|
||||||
if (argEndPos - buf > 0) {
|
|
||||||
memcpy(argName + sizeArgName, buf, argEndPos - buf);
|
|
||||||
}
|
|
||||||
argName[fullSizeArgName] = '\0';
|
|
||||||
|
|
||||||
// send arg value
|
|
||||||
String argValue = this->templateCallback((const char*) argName);
|
|
||||||
if (argValue.length()) {
|
|
||||||
server.sendContent(argValue.c_str());
|
|
||||||
|
|
||||||
} else if (fullSizeArgName > 0) {
|
|
||||||
server.sendContent("{");
|
|
||||||
server.sendContent((const char*) argName);
|
|
||||||
server.sendContent("}");
|
|
||||||
}
|
|
||||||
|
|
||||||
offset = size_t(argEndPos - buf + 1);
|
|
||||||
sizeArgName = 0;
|
|
||||||
argNameProcess = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (argNameProcess) {
|
|
||||||
server.sendContent("{");
|
|
||||||
|
|
||||||
if (sizeArgName > 0) {
|
|
||||||
argName[sizeArgName] = '\0';
|
|
||||||
server.sendContent((const char*) argName);
|
|
||||||
}
|
|
||||||
|
|
||||||
argNameProcess = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
do {
|
|
||||||
uint8_t* currentBuf = buf + offset;
|
|
||||||
size_t currentLength = length - offset;
|
|
||||||
|
|
||||||
argStartPos = (uint8_t*) memchr(currentBuf, '{', currentLength);
|
|
||||||
|
|
||||||
// send all content
|
|
||||||
if (argStartPos == nullptr) {
|
|
||||||
if (currentLength > 0) {
|
|
||||||
server.sendContent((const char*) currentBuf, currentLength);
|
|
||||||
}
|
|
||||||
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
argEndPos = (uint8_t*) memchr(argStartPos, '}', length - (argStartPos - buf));
|
|
||||||
if (argEndPos != nullptr) {
|
|
||||||
sizeArgName = argEndPos - argStartPos - 1;
|
|
||||||
|
|
||||||
// send all content if arg len > space
|
|
||||||
if (sizeArgName >= sizeof(argName)) {
|
|
||||||
if (currentLength > 0) {
|
|
||||||
server.sendContent((const char*) currentBuf, currentLength);
|
|
||||||
}
|
|
||||||
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
// arg name
|
|
||||||
memcpy(argName, argStartPos + 1, sizeArgName);
|
|
||||||
argName[sizeArgName] = '\0';
|
|
||||||
|
|
||||||
// send arg value
|
|
||||||
String argValue = this->templateCallback((const char*) argName);
|
|
||||||
if (argValue.length()) {
|
|
||||||
// send content before var
|
|
||||||
if (argStartPos - buf > 0) {
|
|
||||||
server.sendContent((const char*) currentBuf, argStartPos - buf);
|
|
||||||
}
|
|
||||||
|
|
||||||
server.sendContent(argValue.c_str());
|
|
||||||
|
|
||||||
} else {
|
|
||||||
server.sendContent((const char*) currentBuf, argEndPos - currentBuf + 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
offset = size_t(argEndPos - currentBuf + 1);
|
|
||||||
|
|
||||||
} else {
|
|
||||||
sizeArgName = length - size_t(argStartPos - currentBuf) - 1;
|
|
||||||
|
|
||||||
// send all content if arg len > space
|
|
||||||
if (sizeArgName >= sizeof(argName)) {
|
|
||||||
if (currentLength) {
|
|
||||||
server.sendContent((const char*) currentBuf, currentLength);
|
|
||||||
}
|
|
||||||
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
// send content before var
|
|
||||||
if (argStartPos - buf > 0) {
|
|
||||||
server.sendContent((const char*) currentBuf, argStartPos - buf);
|
|
||||||
}
|
|
||||||
|
|
||||||
// copy arg name chunk
|
|
||||||
if (sizeArgName > 0) {
|
|
||||||
memcpy(argName, argStartPos + 1, sizeArgName);
|
|
||||||
}
|
|
||||||
|
|
||||||
argNameProcess = true;
|
|
||||||
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
} while(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
file.close();
|
|
||||||
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
server.chunkedResponseFinalize();
|
|
||||||
#else
|
|
||||||
server.sendContent(emptyString);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected:
|
|
||||||
FS* fs = nullptr;
|
|
||||||
CanHandleCallback canHandleCallback;
|
|
||||||
BeforeSendCallback beforeSendCallback;
|
|
||||||
TemplateCallback templateCallback;
|
|
||||||
String eTag;
|
|
||||||
const char* uri = nullptr;
|
|
||||||
const char* path = nullptr;
|
|
||||||
const char* cacheHeader = nullptr;
|
|
||||||
};
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
#include <FS.h>
|
|
||||||
|
|
||||||
class StaticPage : public RequestHandler {
|
|
||||||
public:
|
|
||||||
typedef std::function<bool(HTTPMethod, const String&)> CanHandleCallback;
|
|
||||||
typedef std::function<bool()> BeforeSendCallback;
|
|
||||||
|
|
||||||
StaticPage(const char* uri, FS* fs, const char* path, const char* cacheHeader = nullptr) {
|
|
||||||
this->uri = uri;
|
|
||||||
this->fs = fs;
|
|
||||||
this->path = path;
|
|
||||||
this->cacheHeader = cacheHeader;
|
|
||||||
}
|
|
||||||
|
|
||||||
StaticPage* setCanHandleCallback(CanHandleCallback callback = nullptr) {
|
|
||||||
this->canHandleCallback = callback;
|
|
||||||
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
StaticPage* setBeforeSendCallback(BeforeSendCallback callback = nullptr) {
|
|
||||||
this->beforeSendCallback = callback;
|
|
||||||
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
#if defined(ARDUINO_ARCH_ESP32)
|
|
||||||
bool canHandle(HTTPMethod method, const String uri) override {
|
|
||||||
#else
|
|
||||||
bool canHandle(HTTPMethod method, const String& uri) override {
|
|
||||||
#endif
|
|
||||||
return method == HTTP_GET && uri.equals(this->uri) && (!this->canHandleCallback || this->canHandleCallback(method, uri));
|
|
||||||
}
|
|
||||||
|
|
||||||
#if defined(ARDUINO_ARCH_ESP32)
|
|
||||||
bool handle(WebServer& server, HTTPMethod method, const String uri) override {
|
|
||||||
#else
|
|
||||||
bool handle(WebServer& server, HTTPMethod method, const String& uri) override {
|
|
||||||
#endif
|
|
||||||
if (!this->canHandle(method, uri)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this->beforeSendCallback && !this->beforeSendCallback()) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
#if defined(ARDUINO_ARCH_ESP8266)
|
|
||||||
if (server._eTagEnabled) {
|
|
||||||
if (server._eTagFunction) {
|
|
||||||
this->eTag = (server._eTagFunction)(*this->fs, this->path);
|
|
||||||
|
|
||||||
} else if (this->eTag.isEmpty()) {
|
|
||||||
this->eTag = esp8266webserver::calcETag(*this->fs, this->path);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (server.header("If-None-Match").equals(this->eTag.c_str())) {
|
|
||||||
server.send(304);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
File file = this->fs->open(this->path, "r");
|
|
||||||
if (!file) {
|
|
||||||
return false;
|
|
||||||
|
|
||||||
} else if (file.isDirectory()) {
|
|
||||||
file.close();
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this->cacheHeader != nullptr) {
|
|
||||||
server.sendHeader("Cache-Control", this->cacheHeader);
|
|
||||||
}
|
|
||||||
|
|
||||||
#if defined(ARDUINO_ARCH_ESP8266)
|
|
||||||
if (server._eTagEnabled && this->eTag.length() > 0) {
|
|
||||||
server.sendHeader("ETag", this->eTag);
|
|
||||||
}
|
|
||||||
|
|
||||||
server.streamFile(file, F("text/html"), method);
|
|
||||||
#else
|
|
||||||
server.streamFile(file, F("text/html"), 200);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected:
|
|
||||||
FS* fs = nullptr;
|
|
||||||
CanHandleCallback canHandleCallback;
|
|
||||||
BeforeSendCallback beforeSendCallback;
|
|
||||||
String eTag;
|
|
||||||
const char* uri = nullptr;
|
|
||||||
const char* path = nullptr;
|
|
||||||
const char* cacheHeader = nullptr;
|
|
||||||
};
|
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
#include <Arduino.h>
|
#include <Arduino.h>
|
||||||
|
#include <esp_log.h>
|
||||||
|
#include <strings_shared.h>
|
||||||
|
|
||||||
class UpgradeHandler : public RequestHandler {
|
class UpgradeHandler : public AsyncWebHandler {
|
||||||
public:
|
public:
|
||||||
enum class UpgradeType {
|
enum class UpgradeType {
|
||||||
FIRMWARE = 0,
|
FIRMWARE = 0,
|
||||||
@@ -12,7 +14,7 @@ public:
|
|||||||
NO_FILE,
|
NO_FILE,
|
||||||
SUCCESS,
|
SUCCESS,
|
||||||
PROHIBITED,
|
PROHIBITED,
|
||||||
ABORTED,
|
SIZE_MISMATCH,
|
||||||
ERROR_ON_START,
|
ERROR_ON_START,
|
||||||
ERROR_ON_WRITE,
|
ERROR_ON_WRITE,
|
||||||
ERROR_ON_FINISH
|
ERROR_ON_FINISH
|
||||||
@@ -22,27 +24,22 @@ public:
|
|||||||
UpgradeType type;
|
UpgradeType type;
|
||||||
UpgradeStatus status;
|
UpgradeStatus status;
|
||||||
String error;
|
String error;
|
||||||
|
size_t progress = 0;
|
||||||
|
size_t size = 0;
|
||||||
} UpgradeResult;
|
} UpgradeResult;
|
||||||
|
|
||||||
typedef std::function<bool(HTTPMethod, const String&)> CanHandleCallback;
|
typedef std::function<bool(AsyncWebServerRequest *request, UpgradeType)> BeforeUpgradeCallback;
|
||||||
typedef std::function<bool(const String&)> CanUploadCallback;
|
// A null request reports an upload disconnected after preparation was accepted.
|
||||||
typedef std::function<bool(UpgradeType)> BeforeUpgradeCallback;
|
typedef std::function<void(AsyncWebServerRequest *request, const UpgradeResult&, const UpgradeResult&)> AfterUpgradeCallback;
|
||||||
typedef std::function<void(const UpgradeResult&, const UpgradeResult&)> AfterUpgradeCallback;
|
|
||||||
|
|
||||||
UpgradeHandler(const char* uri) {
|
explicit UpgradeHandler(AsyncURIMatcher uri) : uri(uri) {}
|
||||||
this->uri = uri;
|
|
||||||
|
bool canHandle(AsyncWebServerRequest *request) const final {
|
||||||
|
if (!request->isHTTP() || request->method() != HTTP_POST) {
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
UpgradeHandler* setCanHandleCallback(CanHandleCallback callback = nullptr) {
|
return this->uri.matches(request);
|
||||||
this->canHandleCallback = callback;
|
|
||||||
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
UpgradeHandler* setCanUploadCallback(CanUploadCallback callback = nullptr) {
|
|
||||||
this->canUploadCallback = callback;
|
|
||||||
|
|
||||||
return this;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
UpgradeHandler* setBeforeUpgradeCallback(BeforeUpgradeCallback callback = nullptr) {
|
UpgradeHandler* setBeforeUpgradeCallback(BeforeUpgradeCallback callback = nullptr) {
|
||||||
@@ -57,162 +54,199 @@ public:
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
#if defined(ARDUINO_ARCH_ESP32)
|
void handleRequest(AsyncWebServerRequest *request) final {
|
||||||
bool canHandle(HTTPMethod method, const String uri) override {
|
if (request->getResponse()) {
|
||||||
#else
|
|
||||||
bool canHandle(HTTPMethod method, const String& uri) override {
|
|
||||||
#endif
|
|
||||||
return method == HTTP_POST && uri.equals(this->uri) && (!this->canHandleCallback || this->canHandleCallback(method, uri));
|
|
||||||
}
|
|
||||||
|
|
||||||
#if defined(ARDUINO_ARCH_ESP32)
|
|
||||||
bool canUpload(const String uri) override {
|
|
||||||
#else
|
|
||||||
bool canUpload(const String& uri) override {
|
|
||||||
#endif
|
|
||||||
return uri.equals(this->uri) && (!this->canUploadCallback || this->canUploadCallback(uri));
|
|
||||||
}
|
|
||||||
|
|
||||||
#if defined(ARDUINO_ARCH_ESP32)
|
|
||||||
bool handle(WebServer& server, HTTPMethod method, const String uri) override {
|
|
||||||
#else
|
|
||||||
bool handle(WebServer& server, HTTPMethod method, const String& uri) override {
|
|
||||||
#endif
|
|
||||||
if (this->afterUpgradeCallback) {
|
|
||||||
this->afterUpgradeCallback(this->firmwareResult, this->filesystemResult);
|
|
||||||
}
|
|
||||||
|
|
||||||
this->firmwareResult.status = UpgradeStatus::NONE;
|
|
||||||
this->firmwareResult.error.clear();
|
|
||||||
|
|
||||||
this->filesystemResult.status = UpgradeStatus::NONE;
|
|
||||||
this->filesystemResult.error.clear();
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
#if defined(ARDUINO_ARCH_ESP32)
|
|
||||||
void upload(WebServer& server, const String uri, HTTPUpload& upload) override {
|
|
||||||
#else
|
|
||||||
void upload(WebServer& server, const String& uri, HTTPUpload& upload) override {
|
|
||||||
#endif
|
|
||||||
UpgradeResult* result;
|
|
||||||
if (upload.name.equals("firmware")) {
|
|
||||||
result = &this->firmwareResult;
|
|
||||||
} else if (upload.name.equals("filesystem")) {
|
|
||||||
result = &this->filesystemResult;
|
|
||||||
} else {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (this->activeRequest != request) {
|
||||||
|
request->send(this->activeRequest ? 409 : 400);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
finishRequest(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
void handleUpload(AsyncWebServerRequest *request, const String &fileName, size_t index, uint8_t *data, size_t dataLength, bool isFinal) final {
|
||||||
|
if (request->getResponse()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (this->activeRequest && this->activeRequest != request) {
|
||||||
|
// Keep the rejection on this request even if the active upload finishes first.
|
||||||
|
request->send(409);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
UpgradeResult* result = nullptr;
|
||||||
|
|
||||||
|
if (!request->hasParam(asyncsrv::T_name, true, true)) {
|
||||||
|
// Missing content-disposition 'name' parameter
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto& pName = request->getParam(asyncsrv::T_name, true, true)->value();
|
||||||
|
if (pName.equals("fw")) {
|
||||||
|
result = &this->firmwareResult;
|
||||||
|
|
||||||
|
if (!index) {
|
||||||
|
result->progress = 0;
|
||||||
|
result->size = request->hasParam("fw_size", true)
|
||||||
|
? request->getParam("fw_size", true)->value().toInt()
|
||||||
|
: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
} else if (pName.equals("fs")) {
|
||||||
|
result = &this->filesystemResult;
|
||||||
|
|
||||||
|
if (!index) {
|
||||||
|
result->progress = 0;
|
||||||
|
result->size = request->hasParam("fs_size", true)
|
||||||
|
? request->getParam("fs_size", true)->value().toInt()
|
||||||
|
: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
} else {
|
||||||
|
// Unknown parameter name
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!this->activeRequest) {
|
||||||
|
this->activeRequest = request;
|
||||||
|
request->onDisconnect([this, request] {
|
||||||
|
if (this->activeRequest == request) {
|
||||||
|
finishRequest(nullptr);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// check result status
|
||||||
if (result->status != UpgradeStatus::NONE) {
|
if (result->status != UpgradeStatus::NONE) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this->beforeUpgradeCallback && !this->beforeUpgradeCallback(result->type)) {
|
if (this->beforeUpgradeCallback && !this->beforeUpgradeCallback(request, result->type)) {
|
||||||
result->status = UpgradeStatus::PROHIBITED;
|
result->status = UpgradeStatus::PROHIBITED;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
this->preparationAccepted = true;
|
||||||
|
|
||||||
if (!upload.filename.length()) {
|
if (!fileName.length()) {
|
||||||
result->status = UpgradeStatus::NO_FILE;
|
result->status = UpgradeStatus::NO_FILE;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (upload.status == UPLOAD_FILE_START) {
|
if (!index) {
|
||||||
// reset
|
// reset
|
||||||
if (Update.isRunning()) {
|
if (Update.isRunning()) {
|
||||||
Update.end(false);
|
Update.end(false);
|
||||||
Update.clearError();
|
Update.clearError();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// try begin
|
||||||
bool begin = false;
|
bool begin = false;
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
Update.runAsync(true);
|
|
||||||
|
|
||||||
if (result->type == UpgradeType::FIRMWARE) {
|
|
||||||
begin = Update.begin((ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000, U_FLASH);
|
|
||||||
|
|
||||||
} else if (result->type == UpgradeType::FILESYSTEM) {
|
|
||||||
close_all_fs();
|
|
||||||
begin = Update.begin((size_t)FS_end - (size_t)FS_start, U_FS);
|
|
||||||
}
|
|
||||||
#elif defined(ARDUINO_ARCH_ESP32)
|
|
||||||
if (result->type == UpgradeType::FIRMWARE) {
|
if (result->type == UpgradeType::FIRMWARE) {
|
||||||
begin = Update.begin(UPDATE_SIZE_UNKNOWN, U_FLASH);
|
begin = Update.begin(UPDATE_SIZE_UNKNOWN, U_FLASH);
|
||||||
|
|
||||||
} else if (result->type == UpgradeType::FILESYSTEM) {
|
} else if (result->type == UpgradeType::FILESYSTEM) {
|
||||||
begin = Update.begin(UPDATE_SIZE_UNKNOWN, U_SPIFFS);
|
begin = Update.begin(UPDATE_SIZE_UNKNOWN, U_SPIFFS);
|
||||||
}
|
}
|
||||||
#endif
|
|
||||||
|
|
||||||
if (!begin || Update.hasError()) {
|
if (!begin || Update.hasError()) {
|
||||||
result->status = UpgradeStatus::ERROR_ON_START;
|
result->status = UpgradeStatus::ERROR_ON_START;
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
result->error = Update.getErrorString();
|
|
||||||
#else
|
|
||||||
result->error = Update.errorString();
|
result->error = Update.errorString();
|
||||||
#endif
|
|
||||||
|
|
||||||
Log.serrorln(FPSTR(L_PORTAL_OTA), F("File '%s', on start: %s"), upload.filename.c_str(), result->error.c_str());
|
ESP_LOGE(L_PORTAL_OTA, "File '%s', on start: %s", fileName.c_str(), result->error.c_str());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
Log.sinfoln(FPSTR(L_PORTAL_OTA), F("File '%s', started"), upload.filename.c_str());
|
ESP_LOGI(L_PORTAL_OTA, "File '%s', started", fileName.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
} else if (upload.status == UPLOAD_FILE_WRITE) {
|
if (dataLength) {
|
||||||
if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
|
if (Update.write(data, dataLength) != dataLength) {
|
||||||
Update.end(false);
|
Update.end(false);
|
||||||
|
|
||||||
result->status = UpgradeStatus::ERROR_ON_WRITE;
|
result->status = UpgradeStatus::ERROR_ON_WRITE;
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
result->error = Update.getErrorString();
|
|
||||||
#else
|
|
||||||
result->error = Update.errorString();
|
result->error = Update.errorString();
|
||||||
#endif
|
|
||||||
|
|
||||||
Log.serrorln(
|
ESP_LOGE(
|
||||||
FPSTR(L_PORTAL_OTA),
|
L_PORTAL_OTA, "File '%s', on write %d bytes, %d of %d bytes",
|
||||||
F("File '%s', on writing %d bytes: %s"),
|
fileName.c_str(),
|
||||||
upload.filename.c_str(), upload.totalSize, result->error
|
dataLength,
|
||||||
|
result->progress + dataLength,
|
||||||
|
result->size
|
||||||
);
|
);
|
||||||
|
return;
|
||||||
} else {
|
|
||||||
Log.sinfoln(FPSTR(L_PORTAL_OTA), F("File '%s', writed %d bytes"), upload.filename.c_str(), upload.totalSize);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
} else if (upload.status == UPLOAD_FILE_END) {
|
result->progress += dataLength;
|
||||||
if (Update.end(true)) {
|
ESP_LOGI(
|
||||||
result->status = UpgradeStatus::SUCCESS;
|
L_PORTAL_OTA, "File '%s', write %d bytes, %d of %d bytes",
|
||||||
|
fileName.c_str(),
|
||||||
Log.sinfoln(FPSTR(L_PORTAL_OTA), F("File '%s': finish"), upload.filename.c_str());
|
dataLength,
|
||||||
|
result->progress,
|
||||||
} else {
|
result->size
|
||||||
result->status = UpgradeStatus::ERROR_ON_FINISH;
|
);
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
result->error = Update.getErrorString();
|
|
||||||
#else
|
|
||||||
result->error = Update.errorString();
|
|
||||||
#endif
|
|
||||||
|
|
||||||
Log.serrorln(FPSTR(L_PORTAL_OTA), F("File '%s', on finish: %s"), upload.filename.c_str(), result->error);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
} else if (upload.status == UPLOAD_FILE_ABORTED) {
|
if (result->size > 0) {
|
||||||
|
if (result->progress > result->size || (isFinal && result->progress < result->size)) {
|
||||||
Update.end(false);
|
Update.end(false);
|
||||||
result->status = UpgradeStatus::ABORTED;
|
result->status = UpgradeStatus::SIZE_MISMATCH;
|
||||||
|
|
||||||
Log.serrorln(FPSTR(L_PORTAL_OTA), F("File '%s': aborted"), upload.filename.c_str());
|
ESP_LOGE(
|
||||||
|
L_PORTAL_OTA, "File '%s', size mismatch: %d of %d bytes",
|
||||||
|
fileName.c_str(),
|
||||||
|
result->progress,
|
||||||
|
result->size
|
||||||
|
);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (isFinal) {
|
||||||
|
if (!Update.end(true)) {
|
||||||
|
result->status = UpgradeStatus::ERROR_ON_FINISH;
|
||||||
|
result->error = Update.errorString();
|
||||||
|
|
||||||
|
ESP_LOGE(L_PORTAL_OTA, "File '%s', on finish: %s", fileName.c_str(), result->error.c_str());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
result->status = UpgradeStatus::SUCCESS;
|
||||||
|
ESP_LOGI(L_PORTAL_OTA, "File '%s': finish", fileName.c_str());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool isRequestHandlerTrivial() const final {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
CanHandleCallback canHandleCallback;
|
void finishRequest(AsyncWebServerRequest *request) {
|
||||||
CanUploadCallback canUploadCallback;
|
if (request) {
|
||||||
|
request->onDisconnect(nullptr);
|
||||||
|
}
|
||||||
|
if (Update.isRunning()) {
|
||||||
|
// Abort only the unfinished file; an earlier successful firmware still needs a restart.
|
||||||
|
Update.abort();
|
||||||
|
}
|
||||||
|
if (this->afterUpgradeCallback && (request || this->preparationAccepted)) {
|
||||||
|
this->afterUpgradeCallback(request, this->firmwareResult, this->filesystemResult);
|
||||||
|
}
|
||||||
|
|
||||||
|
this->activeRequest = nullptr;
|
||||||
|
this->preparationAccepted = false;
|
||||||
|
this->firmwareResult = {UpgradeType::FIRMWARE, UpgradeStatus::NONE};
|
||||||
|
this->filesystemResult = {UpgradeType::FILESYSTEM, UpgradeStatus::NONE};
|
||||||
|
}
|
||||||
|
|
||||||
BeforeUpgradeCallback beforeUpgradeCallback;
|
BeforeUpgradeCallback beforeUpgradeCallback;
|
||||||
AfterUpgradeCallback afterUpgradeCallback;
|
AfterUpgradeCallback afterUpgradeCallback;
|
||||||
const char* uri = nullptr;
|
AsyncURIMatcher uri;
|
||||||
|
|
||||||
|
// Upload, completion and disconnect callbacks share the AsyncTCP worker.
|
||||||
|
AsyncWebServerRequest* activeRequest = nullptr;
|
||||||
|
bool preparationAccepted = false;
|
||||||
UpgradeResult firmwareResult{UpgradeType::FIRMWARE, UpgradeStatus::NONE};
|
UpgradeResult firmwareResult{UpgradeType::FIRMWARE, UpgradeStatus::NONE};
|
||||||
UpgradeResult filesystemResult{UpgradeType::FILESYSTEM, UpgradeStatus::NONE};
|
UpgradeResult filesystemResult{UpgradeType::FILESYSTEM, UpgradeStatus::NONE};
|
||||||
};
|
};
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
/*
|
|
||||||
This file is needed by the Arduino IDE because the ino file needs to be named as the directory name.
|
|
||||||
Don't worry, the Arduino compiler will "merge" all files, including src/main.cpp
|
|
||||||
*/
|
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
{
|
||||||
|
"name": "otgateway",
|
||||||
|
"scripts": {
|
||||||
|
"test": "echo \"Error: no test specified\" && exit 1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"cssnano": "^9.3.2",
|
||||||
|
"cssnano-preset-advanced": "^9.2.2",
|
||||||
|
"gulp": "^5.0.0",
|
||||||
|
"gulp-concat": "^2.6.1",
|
||||||
|
"gulp-gzip": "^1.4.2",
|
||||||
|
"gulp-html-minifier-terser": "^8.0.0",
|
||||||
|
"gulp-jsonminify": "^1.1.0",
|
||||||
|
"gulp-postcss": "^10.0.0",
|
||||||
|
"gulp-terser": "^2.1.0",
|
||||||
|
"gulp-replace": "^1.1.4"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,226 +1,314 @@
|
|||||||
; PlatformIO Project Configuration File
|
|
||||||
;
|
|
||||||
; Build options: build flags, source filter
|
|
||||||
; Upload options: custom upload port, speed and extra flags
|
|
||||||
; Library options: dependencies, extra library storages
|
|
||||||
; Advanced options: extra scripting
|
|
||||||
;
|
|
||||||
; Please visit documentation for the other options and examples
|
|
||||||
; https://docs.platformio.org/page/projectconf.html
|
|
||||||
|
|
||||||
[platformio]
|
[platformio]
|
||||||
;extra_configs = secrets.ini
|
;extra_configs = secrets.ini
|
||||||
extra_configs = secrets.default.ini
|
extra_configs = secrets.default.ini
|
||||||
|
;core_dir = .pio
|
||||||
|
|
||||||
[env]
|
[env]
|
||||||
|
custom_version = 2.0.0-dev
|
||||||
framework = arduino
|
framework = arduino
|
||||||
lib_deps =
|
lib_deps = ESP32Async/AsyncTCP@^3.5.0
|
||||||
bblanchon/ArduinoJson@^7.0.3
|
ESP32Async/ESPAsyncWebServer@^3.12.1
|
||||||
;ihormelnyk/OpenTherm Library@^1.1.4
|
mathieucarbou/MycilaWebSerial@^8.2.3
|
||||||
https://github.com/Laxilef/opentherm_library/archive/refs/heads/fix_start_bit.zip
|
bblanchon/ArduinoJson@^7.4.3
|
||||||
arduino-libraries/ArduinoMqttClient@^0.1.8
|
;ihormelnyk/OpenTherm Library@^1.1.5
|
||||||
lennarthennigs/ESP Telnet@^2.2
|
https://github.com/Laxilef/ESP32OT
|
||||||
gyverlibs/FileData@^1.0.2
|
https://github.com/mathieucarbou/MycilaMQTT
|
||||||
|
https://github.com/mathieucarbou/MycilaHADiscovery/
|
||||||
|
gyverlibs/FileData@^1.0.3
|
||||||
gyverlibs/GyverPID@^3.3.2
|
gyverlibs/GyverPID@^3.3.2
|
||||||
gyverlibs/GyverBlinker@^1.0
|
gyverlibs/GyverBlinker@^1.1.1
|
||||||
milesburton/DallasTemperature@^3.11.0
|
;pstolarz/OneWireNg@^0.14.1
|
||||||
laxilef/TinyLogger@^1.1.0
|
https://github.com/pstolarz/OneWireNg.git
|
||||||
build_flags =
|
milesburton/DallasTemperature@^4.0.6
|
||||||
-D PIO_FRAMEWORK_ARDUINO_LWIP2_LOW_MEMORY
|
https://github.com/Laxilef/esp32DHT#idf5
|
||||||
-D PIO_FRAMEWORK_ARDUINO_ESPRESSIF_SDK305
|
lib_ignore = OneWire
|
||||||
-mtext-section-literals
|
build_type = ${secrets.build_type}
|
||||||
-D MQTT_CLIENT_STD_FUNCTION_CALLBACK=1
|
build_flags = ;-mtext-section-literals
|
||||||
;-D DEBUG_ESP_CORE -D DEBUG_ESP_WIFI -D DEBUG_ESP_PORT=Serial
|
;-D DEBUG_ESP_CORE -D DEBUG_ESP_WIFI -D DEBUG_ESP_HTTP_SERVER -D DEBUG_ESP_PORT=Serial
|
||||||
-D USE_SERIAL=${secrets.use_serial}
|
-D BUILD_VERSION='"${this.custom_version}"'
|
||||||
-D USE_TELNET=${secrets.use_telnet}
|
-D BUILD_ENV='"$PIOENV"'
|
||||||
-D DEBUG_BY_DEFAULT=${secrets.debug}
|
-D DEFAULT_SERIAL_ENABLED=${secrets.serial_enabled}
|
||||||
-D HOSTNAME_DEFAULT='"${secrets.hostname}"'
|
-D DEFAULT_SERIAL_BAUD=${secrets.serial_baud}
|
||||||
-D AP_SSID_DEFAULT='"${secrets.ap_ssid}"'
|
-D DEFAULT_WEBSERIAL_ENABLED=${secrets.webserial_enabled}
|
||||||
-D AP_PASSWORD_DEFAULT='"${secrets.ap_password}"'
|
-D DEFAULT_LOG_LEVEL=${secrets.log_level}
|
||||||
-D STA_SSID_DEFAULT='"${secrets.sta_ssid}"'
|
-D DEFAULT_HOSTNAME='"${secrets.hostname}"'
|
||||||
-D STA_PASSWORD_DEFAULT='"${secrets.sta_password}"'
|
-D DEFAULT_AP_SSID='"${secrets.ap_ssid}"'
|
||||||
-D PORTAL_LOGIN_DEFAULT='"${secrets.portal_login}"'
|
-D DEFAULT_AP_PASSWORD='"${secrets.ap_password}"'
|
||||||
-D PORTAL_PASSWORD_DEFAULT='"${secrets.portal_password}"'
|
-D DEFAULT_STA_SSID='"${secrets.sta_ssid}"'
|
||||||
-D MQTT_SERVER_DEFAULT='"${secrets.mqtt_server}"'
|
-D DEFAULT_STA_PASSWORD='"${secrets.sta_password}"'
|
||||||
-D MQTT_PORT_DEFAULT=${secrets.mqtt_port}
|
-D DEFAULT_PORTAL_LOGIN='"${secrets.portal_login}"'
|
||||||
-D MQTT_USER_DEFAULT='"${secrets.mqtt_user}"'
|
-D DEFAULT_PORTAL_PASSWORD='"${secrets.portal_password}"'
|
||||||
-D MQTT_PASSWORD_DEFAULT='"${secrets.mqtt_password}"'
|
-D DEFAULT_MQTT_ENABLED=${secrets.mqtt_enabled}
|
||||||
-D MQTT_PREFIX_DEFAULT='"${secrets.mqtt_prefix}"'
|
-D DEFAULT_MQTT_SERVER='"${secrets.mqtt_server}"'
|
||||||
|
-D DEFAULT_MQTT_PORT=${secrets.mqtt_port}
|
||||||
|
-D DEFAULT_MQTT_USER='"${secrets.mqtt_user}"'
|
||||||
|
-D DEFAULT_MQTT_PASSWORD='"${secrets.mqtt_password}"'
|
||||||
|
-D DEFAULT_MQTT_PREFIX='"${secrets.mqtt_prefix}"'
|
||||||
upload_speed = 921600
|
upload_speed = 921600
|
||||||
monitor_speed = 115200
|
monitor_speed = 115200
|
||||||
monitor_filters = direct
|
;monitor_filters = direct
|
||||||
|
monitor_filters = esp32_exception_decoder
|
||||||
board_build.flash_mode = dio
|
board_build.flash_mode = dio
|
||||||
board_build.filesystem = littlefs
|
board_build.filesystem = littlefs
|
||||||
version = 1.4.0-rc.15
|
check_tool = ;pvs-studio
|
||||||
|
check_flags = ;pvs-studio: --analysis-mode=4 --exclude-path=./.pio/libdeps
|
||||||
|
|
||||||
; Defaults
|
; Defaults
|
||||||
[esp8266_defaults]
|
|
||||||
platform = espressif8266
|
|
||||||
lib_deps =
|
|
||||||
${env.lib_deps}
|
|
||||||
nrwiersma/ESP8266Scheduler@^1.1
|
|
||||||
lib_ignore =
|
|
||||||
extra_scripts =
|
|
||||||
post:tools/build.py
|
|
||||||
build_flags = ${env.build_flags}
|
|
||||||
board_build.ldscript = eagle.flash.1m256.ld
|
|
||||||
;board_build.ldscript = eagle.flash.4m1m.ld
|
|
||||||
|
|
||||||
[esp32_defaults]
|
[esp32_defaults]
|
||||||
platform = espressif32
|
;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
|
board_build.partitions = esp32_partitions.csv
|
||||||
lib_deps =
|
lib_deps = ${env.lib_deps}
|
||||||
${env.lib_deps}
|
https://github.com/mathieucarbou/MycilaTaskManager#main
|
||||||
laxilef/ESP32Scheduler@^1.0.1
|
nimble_lib = https://github.com/h2zero/NimBLE-Arduino#master
|
||||||
lib_ignore =
|
lib_ignore = ${env.lib_ignore}
|
||||||
extra_scripts =
|
BluetoothSerial
|
||||||
|
SimpleBLE
|
||||||
|
ESP RainMaker
|
||||||
|
RainMaker
|
||||||
|
ESP Insights
|
||||||
|
Insights
|
||||||
|
Zigbee
|
||||||
|
Matter
|
||||||
|
OpenThread
|
||||||
|
dsp
|
||||||
|
; No release includes the stop/reconnect wakeup fix yet (2026-11-21).
|
||||||
|
; With the broker unavailable, stop() can wait for reconnect backoff to expire, delaying OTA/restart.
|
||||||
|
; Fix: https://github.com/espressif/esp-mqtt/commit/c29cdda15f2812207a5740e7ec8f6efdd59d8e77
|
||||||
|
custom_component_add = espressif/mqtt@1.1.0
|
||||||
|
custom_component_remove = espressif/esp_hosted
|
||||||
|
espressif/esp_wifi_remote
|
||||||
|
espressif/esp-dsp
|
||||||
|
espressif/esp_modem
|
||||||
|
espressif/esp_rainmaker
|
||||||
|
espressif/rmaker_common
|
||||||
|
espressif/esp_insights
|
||||||
|
espressif/esp_diag_data_store
|
||||||
|
espressif/esp_diagnostics
|
||||||
|
espressif/libsodium
|
||||||
|
espressif/esp-modbus
|
||||||
|
espressif/esp-cbor
|
||||||
|
espressif/esp-sr
|
||||||
|
espressif/esp32-camera
|
||||||
|
espressif/qrcode
|
||||||
|
espressif/esp-zboss-lib
|
||||||
|
espressif/esp-zigbee-lib
|
||||||
|
chmorgan/esp-libhelix-mp3
|
||||||
|
espressif/cjson
|
||||||
|
extra_scripts = pre:tools/after_build_sdk.py
|
||||||
|
pre:tools/add_build_commit.py
|
||||||
post:tools/esp32.py
|
post:tools/esp32.py
|
||||||
post:tools/build.py
|
post:tools/build.py
|
||||||
build_flags =
|
build_type = ${env.build_type}
|
||||||
${env.build_flags}
|
build_unflags = -fno-lto
|
||||||
-D CORE_DEBUG_LEVEL=0
|
build_flags = ${env.build_flags}
|
||||||
|
-Os
|
||||||
|
-Wno-deprecated-declarations
|
||||||
|
-D WSL_CUSTOM_PAGE
|
||||||
|
; Log transport runs on the System worker instead of producer stacks.
|
||||||
|
-D CONFIG_ASYNC_TCP_STACK_SIZE=5120
|
||||||
|
-D ARDUINOJSON_USE_DOUBLE=0
|
||||||
|
-D ARDUINOJSON_USE_LONG_LONG=0
|
||||||
|
-D DHT_TASK_STACK_SIZE=4096
|
||||||
|
-D MYCILA_TASK_MANAGER_NO_STATS
|
||||||
|
-D MYCILA_MQTT_DEBUG
|
||||||
|
-D MYNEWT_VAL_BLE_MAX_CONNECTIONS=1
|
||||||
|
-D MYNEWT_VAL_BLE_STORE_MAX_BONDS=1
|
||||||
|
; BLE callbacks format logs; System sends them to transports.
|
||||||
|
-D MYNEWT_VAL_NIMBLE_HOST_TASK_STACK_SIZE=4608
|
||||||
|
-D MYNEWT_VAL_BLE_ROLE_CENTRAL=0
|
||||||
|
-D CORE_DEBUG_LEVEL=ESP_LOG_ERROR
|
||||||
|
-D USE_ESP_IDF_LOG
|
||||||
|
-Wl,--wrap=esp_panic_handler
|
||||||
|
-Wl,--wrap=esp_log_format
|
||||||
|
custom_app_flags = -D LOG_LOCAL_LEVEL=ESP_LOG_VERBOSE
|
||||||
|
custom_sdkconfig = '# CONFIG_AUTOSTART_ARDUINO is not set'
|
||||||
|
; Async scalar publications must drain faster than the default 1 s MQTT poll.
|
||||||
|
CONFIG_MQTT_USE_CUSTOM_CONFIG=y
|
||||||
|
CONFIG_MQTT_PROTOCOL_311=y
|
||||||
|
CONFIG_MQTT_POLL_READ_TIMEOUT_MS=5
|
||||||
|
; Initialization now runs on the IDF main task instead of loopTask.
|
||||||
|
CONFIG_ESP_MAIN_TASK_STACK_SIZE=8192
|
||||||
|
'# CONFIG_LOG_VERSION_1 is not set'
|
||||||
|
CONFIG_LOG_VERSION_2=y
|
||||||
|
CONFIG_LOG_VERSION=2
|
||||||
|
CONFIG_LOG_COLORS=y
|
||||||
|
'# CONFIG_LOG_TIMESTAMP_SOURCE_RTOS is not set'
|
||||||
|
CONFIG_LOG_TIMESTAMP_SOURCE_SYSTEM=y
|
||||||
|
'# CONFIG_OPENTHREAD_ENABLED is not set'
|
||||||
|
'# CONFIG_ZB_ENABLED is not set'
|
||||||
|
'# CONFIG_ESP_WIFI_ENTERPRISE_SUPPORT is not set'
|
||||||
|
'# CONFIG_LWIP_IPV6 is not set'
|
||||||
|
'# CONFIG_LWIP_IPV6_AUTOCONFIG is not set'
|
||||||
|
'# CONFIG_LWIP_PPP_SUPPORT is not set'
|
||||||
|
'# CONFIG_MQTT_TRANSPORT_WEBSOCKET is not set'
|
||||||
|
'# CONFIG_LWIP_IP_FORWARD is not set'
|
||||||
|
'# CONFIG_ESP_WIFI_FTM_ENABLE is not set'
|
||||||
|
'# CONFIG_ESP_WIFI_CSI_ENABLED is not set'
|
||||||
|
check_tool = ${env.check_tool}
|
||||||
|
check_flags = ${env.check_flags}
|
||||||
|
|
||||||
|
|
||||||
; Boards
|
; Boards
|
||||||
[env:d1_mini]
|
|
||||||
platform = ${esp8266_defaults.platform}
|
|
||||||
board = d1_mini
|
|
||||||
lib_deps = ${esp8266_defaults.lib_deps}
|
|
||||||
lib_ignore = ${esp8266_defaults.lib_ignore}
|
|
||||||
extra_scripts = ${esp8266_defaults.extra_scripts}
|
|
||||||
board_build.ldscript = ${esp8266_defaults.board_build.ldscript}
|
|
||||||
build_flags =
|
|
||||||
${esp8266_defaults.build_flags}
|
|
||||||
-D OT_IN_PIN_DEFAULT=4
|
|
||||||
-D OT_OUT_PIN_DEFAULT=5
|
|
||||||
-D SENSOR_OUTDOOR_PIN_DEFAULT=12
|
|
||||||
-D SENSOR_INDOOR_PIN_DEFAULT=14
|
|
||||||
-D LED_STATUS_PIN=13
|
|
||||||
-D LED_OT_RX_PIN=15
|
|
||||||
|
|
||||||
[env:d1_mini_lite]
|
|
||||||
platform = ${esp8266_defaults.platform}
|
|
||||||
board = d1_mini_lite
|
|
||||||
lib_deps = ${esp8266_defaults.lib_deps}
|
|
||||||
lib_ignore = ${esp8266_defaults.lib_ignore}
|
|
||||||
extra_scripts = ${esp8266_defaults.extra_scripts}
|
|
||||||
board_build.ldscript = ${esp8266_defaults.board_build.ldscript}
|
|
||||||
build_flags =
|
|
||||||
${esp8266_defaults.build_flags}
|
|
||||||
-D OT_IN_PIN_DEFAULT=4
|
|
||||||
-D OT_OUT_PIN_DEFAULT=5
|
|
||||||
-D SENSOR_OUTDOOR_PIN_DEFAULT=12
|
|
||||||
-D SENSOR_INDOOR_PIN_DEFAULT=14
|
|
||||||
-D LED_STATUS_PIN=13
|
|
||||||
-D LED_OT_RX_PIN=15
|
|
||||||
|
|
||||||
[env:d1_mini_pro]
|
|
||||||
platform = ${esp8266_defaults.platform}
|
|
||||||
board = d1_mini_pro
|
|
||||||
lib_deps = ${esp8266_defaults.lib_deps}
|
|
||||||
lib_ignore = ${esp8266_defaults.lib_ignore}
|
|
||||||
extra_scripts = ${esp8266_defaults.extra_scripts}
|
|
||||||
board_build.ldscript = ${esp8266_defaults.board_build.ldscript}
|
|
||||||
build_flags =
|
|
||||||
${esp8266_defaults.build_flags}
|
|
||||||
-D OT_IN_PIN_DEFAULT=4
|
|
||||||
-D OT_OUT_PIN_DEFAULT=5
|
|
||||||
-D SENSOR_OUTDOOR_PIN_DEFAULT=12
|
|
||||||
-D SENSOR_INDOOR_PIN_DEFAULT=14
|
|
||||||
-D LED_STATUS_PIN=13
|
|
||||||
-D LED_OT_RX_PIN=15
|
|
||||||
|
|
||||||
[env:s2_mini]
|
[env:s2_mini]
|
||||||
platform = ${esp32_defaults.platform}
|
extends = esp32_defaults
|
||||||
board = lolin_s2_mini
|
board = lolin_s2_mini
|
||||||
board_build.partitions = ${esp32_defaults.board_build.partitions}
|
|
||||||
lib_deps = ${esp32_defaults.lib_deps}
|
|
||||||
lib_ignore = ${esp32_defaults.lib_ignore}
|
|
||||||
extra_scripts = ${esp32_defaults.extra_scripts}
|
extra_scripts = ${esp32_defaults.extra_scripts}
|
||||||
build_flags =
|
pre:tools/tinyusb_s2.py
|
||||||
${esp32_defaults.build_flags}
|
custom_sdkconfig = ${esp32_defaults.custom_sdkconfig}
|
||||||
-D OT_IN_PIN_DEFAULT=33
|
'# CONFIG_BT_ENABLED is not set'
|
||||||
-D OT_OUT_PIN_DEFAULT=35
|
CONFIG_TINYUSB_ENABLED=y
|
||||||
-D SENSOR_OUTDOOR_PIN_DEFAULT=9
|
CONFIG_TINYUSB_CDC_ENABLED=y
|
||||||
-D SENSOR_INDOOR_PIN_DEFAULT=7
|
CONFIG_TINYUSB_CDC_MAX_PORTS=2
|
||||||
-D LED_STATUS_PIN=11
|
build_flags = ${esp32_defaults.build_flags}
|
||||||
-D LED_OT_RX_PIN=12
|
-D DEFAULT_OT_IN_GPIO=33
|
||||||
|
-D DEFAULT_OT_OUT_GPIO=35
|
||||||
|
-D DEFAULT_SENSOR_OUTDOOR_GPIO=9
|
||||||
|
-D DEFAULT_SENSOR_INDOOR_GPIO=7
|
||||||
|
-D DEFAULT_STATUS_LED_GPIO=11
|
||||||
|
-D DEFAULT_OT_RX_LED_GPIO=12
|
||||||
|
|
||||||
[env:s3_mini]
|
[env:s3_mini]
|
||||||
platform = ${esp32_defaults.platform}
|
extends = esp32_defaults
|
||||||
board = lolin_s3_mini
|
board = lolin_s3_mini
|
||||||
board_build.partitions = ${esp32_defaults.board_build.partitions}
|
custom_sdkconfig = ${esp32_defaults.custom_sdkconfig}
|
||||||
lib_deps =
|
'# CONFIG_TINYUSB_ENABLED is not set'
|
||||||
${esp32_defaults.lib_deps}
|
lib_deps = ${esp32_defaults.lib_deps}
|
||||||
h2zero/NimBLE-Arduino@^1.4.1
|
${esp32_defaults.nimble_lib}
|
||||||
lib_ignore = ${esp32_defaults.lib_ignore}
|
build_flags = ${esp32_defaults.build_flags}
|
||||||
extra_scripts = ${esp32_defaults.extra_scripts}
|
-D ARDUINO_USB_MODE=1
|
||||||
build_flags =
|
-D ARDUINO_USB_CDC_ON_BOOT=1
|
||||||
${esp32_defaults.build_flags}
|
-D MYNEWT_VAL_BLE_EXT_ADV=1
|
||||||
-D USE_BLE=1
|
-D USE_BLE=1
|
||||||
-D OT_IN_PIN_DEFAULT=35
|
-D DEFAULT_OT_IN_GPIO=35
|
||||||
-D OT_OUT_PIN_DEFAULT=36
|
-D DEFAULT_OT_OUT_GPIO=36
|
||||||
-D SENSOR_OUTDOOR_PIN_DEFAULT=13
|
-D DEFAULT_SENSOR_OUTDOOR_GPIO=13
|
||||||
-D SENSOR_INDOOR_PIN_DEFAULT=12
|
-D DEFAULT_SENSOR_INDOOR_GPIO=12
|
||||||
-D LED_STATUS_PIN=11
|
-D DEFAULT_STATUS_LED_GPIO=11
|
||||||
-D LED_OT_RX_PIN=10
|
-D DEFAULT_OT_RX_LED_GPIO=10
|
||||||
|
|
||||||
|
;[env:s3_mini_no_psram] ; FOR TESTS
|
||||||
|
;extends = env:s3_mini
|
||||||
|
;build_unflags = ${esp32_defaults.build_unflags}
|
||||||
|
; -DBOARD_HAS_PSRAM
|
||||||
|
; -mdisable-hardware-atomics
|
||||||
|
;custom_sdkconfig = ${env:s3_mini.custom_sdkconfig}
|
||||||
|
; '# CONFIG_SPIRAM is not set'
|
||||||
|
|
||||||
[env:c3_mini]
|
[env:c3_mini]
|
||||||
platform = ${esp32_defaults.platform}
|
extends = esp32_defaults
|
||||||
board = lolin_c3_mini
|
board = lolin_c3_mini
|
||||||
board_build.partitions = ${esp32_defaults.board_build.partitions}
|
lib_deps = ${esp32_defaults.lib_deps}
|
||||||
lib_deps =
|
${esp32_defaults.nimble_lib}
|
||||||
${esp32_defaults.lib_deps}
|
build_unflags = ${esp32_defaults.build_unflags}
|
||||||
h2zero/NimBLE-Arduino@^1.4.1
|
-mno-save-restore
|
||||||
lib_ignore = ${esp32_defaults.lib_ignore}
|
custom_link_flags = -msave-restore
|
||||||
extra_scripts = ${esp32_defaults.extra_scripts}
|
build_flags = ${esp32_defaults.build_flags}
|
||||||
build_unflags =
|
-msave-restore
|
||||||
-mtext-section-literals
|
-D MYNEWT_VAL_BLE_EXT_ADV=1
|
||||||
build_flags =
|
|
||||||
${esp32_defaults.build_flags}
|
|
||||||
-D USE_BLE=1
|
-D USE_BLE=1
|
||||||
-D OT_IN_PIN_DEFAULT=8
|
-D DEFAULT_OT_IN_GPIO=8
|
||||||
-D OT_OUT_PIN_DEFAULT=10
|
-D DEFAULT_OT_OUT_GPIO=10
|
||||||
-D SENSOR_OUTDOOR_PIN_DEFAULT=0
|
-D DEFAULT_SENSOR_OUTDOOR_GPIO=0
|
||||||
-D SENSOR_INDOOR_PIN_DEFAULT=1
|
-D DEFAULT_SENSOR_INDOOR_GPIO=1
|
||||||
-D LED_STATUS_PIN=4
|
-D DEFAULT_STATUS_LED_GPIO=4
|
||||||
-D LED_OT_RX_PIN=5
|
-D DEFAULT_OT_RX_LED_GPIO=5
|
||||||
|
custom_sdkconfig = ${esp32_defaults.custom_sdkconfig}
|
||||||
|
CONFIG_COMPILER_SAVE_RESTORE_LIBCALLS=y
|
||||||
|
|
||||||
[env:nodemcu_32s]
|
[env:nodemcu_32]
|
||||||
platform = ${esp32_defaults.platform}
|
extends = esp32_defaults
|
||||||
board = nodemcu-32s
|
board = nodemcu-32s
|
||||||
board_build.partitions = ${esp32_defaults.board_build.partitions}
|
lib_deps = ${esp32_defaults.lib_deps}
|
||||||
lib_deps =
|
${esp32_defaults.nimble_lib}
|
||||||
${esp32_defaults.lib_deps}
|
build_flags = ${esp32_defaults.build_flags}
|
||||||
h2zero/NimBLE-Arduino@^1.4.1
|
|
||||||
lib_ignore = ${esp32_defaults.lib_ignore}
|
|
||||||
extra_scripts = ${esp32_defaults.extra_scripts}
|
|
||||||
build_flags =
|
|
||||||
${esp32_defaults.build_flags}
|
|
||||||
-D USE_BLE=1
|
-D USE_BLE=1
|
||||||
-D OT_IN_PIN_DEFAULT=21
|
-D DEFAULT_OT_IN_GPIO=16
|
||||||
-D OT_OUT_PIN_DEFAULT=22
|
-D DEFAULT_OT_OUT_GPIO=4
|
||||||
-D SENSOR_OUTDOOR_PIN_DEFAULT=12
|
-D DEFAULT_SENSOR_OUTDOOR_GPIO=15
|
||||||
-D SENSOR_INDOOR_PIN_DEFAULT=13
|
-D DEFAULT_SENSOR_INDOOR_GPIO=26
|
||||||
-D LED_STATUS_PIN=2 ; 18
|
-D DEFAULT_STATUS_LED_GPIO=2
|
||||||
-D LED_OT_RX_PIN=19
|
-D DEFAULT_OT_RX_LED_GPIO=19
|
||||||
;-D WOKWI=1
|
|
||||||
|
[env:nodemcu_32_160mhz]
|
||||||
|
extends = env:nodemcu_32
|
||||||
|
board_build.f_cpu = 160000000L ; set frequency to 160MHz
|
||||||
|
|
||||||
[env:d1_mini32]
|
[env:d1_mini32]
|
||||||
platform = ${esp32_defaults.platform}
|
extends = esp32_defaults
|
||||||
board = wemos_d1_mini32
|
board = wemos_d1_mini32
|
||||||
board_build.partitions = ${esp32_defaults.board_build.partitions}
|
lib_deps = ${esp32_defaults.lib_deps}
|
||||||
lib_deps =
|
${esp32_defaults.nimble_lib}
|
||||||
${esp32_defaults.lib_deps}
|
build_flags = ${esp32_defaults.build_flags}
|
||||||
h2zero/NimBLE-Arduino@^1.4.1
|
|
||||||
lib_ignore = ${esp32_defaults.lib_ignore}
|
|
||||||
extra_scripts = ${esp32_defaults.extra_scripts}
|
|
||||||
build_flags =
|
|
||||||
${esp32_defaults.build_flags}
|
|
||||||
-D USE_BLE=1
|
-D USE_BLE=1
|
||||||
-D OT_IN_PIN_DEFAULT=21
|
-D DEFAULT_OT_IN_GPIO=21
|
||||||
-D OT_OUT_PIN_DEFAULT=22
|
-D DEFAULT_OT_OUT_GPIO=22
|
||||||
-D SENSOR_OUTDOOR_PIN_DEFAULT=12
|
-D DEFAULT_SENSOR_OUTDOOR_GPIO=12
|
||||||
-D SENSOR_INDOOR_PIN_DEFAULT=18
|
-D DEFAULT_SENSOR_INDOOR_GPIO=18
|
||||||
-D LED_STATUS_PIN=2
|
-D DEFAULT_STATUS_LED_GPIO=2
|
||||||
-D LED_OT_RX_PIN=19
|
-D DEFAULT_OT_RX_LED_GPIO=19
|
||||||
|
|
||||||
|
[env:esp32_c6]
|
||||||
|
extends = esp32_defaults
|
||||||
|
board = esp32-c6-devkitc-1
|
||||||
|
lib_deps = ${esp32_defaults.lib_deps}
|
||||||
|
${esp32_defaults.nimble_lib}
|
||||||
|
build_unflags = ${esp32_defaults.build_unflags}
|
||||||
|
-mno-save-restore
|
||||||
|
-fexceptions
|
||||||
|
-Os
|
||||||
|
custom_link_flags = -msave-restore
|
||||||
|
-Oz
|
||||||
|
build_flags = ${esp32_defaults.build_flags}
|
||||||
|
-msave-restore
|
||||||
|
-fno-exceptions
|
||||||
|
-Oz
|
||||||
|
-D _GLIBCXX20_CONSTEXPR=__attribute__((cold))constexpr
|
||||||
|
-D _GLIBCXX23_CONSTEXPR=__attribute__((cold))constexpr
|
||||||
|
-D USE_BLE=1
|
||||||
|
-D DEFAULT_OT_IN_GPIO=15
|
||||||
|
-D DEFAULT_OT_OUT_GPIO=23
|
||||||
|
-D DEFAULT_SENSOR_OUTDOOR_GPIO=0
|
||||||
|
-D DEFAULT_SENSOR_INDOOR_GPIO=0
|
||||||
|
-D DEFAULT_STATUS_LED_GPIO=11
|
||||||
|
-D DEFAULT_OT_RX_LED_GPIO=10
|
||||||
|
custom_sdkconfig = ${esp32_defaults.custom_sdkconfig}
|
||||||
|
CONFIG_COMPILER_SAVE_RESTORE_LIBCALLS=y
|
||||||
|
'# CONFIG_LIBC_OPTIMIZED_MISALIGNED_ACCESS is not set'
|
||||||
|
'# CONFIG_COMPILER_CXX_EXCEPTIONS is not set'
|
||||||
|
'# CONFIG_MBEDTLS_TLS_SERVER_AND_CLIENT is not set'
|
||||||
|
'# CONFIG_MBEDTLS_TLS_SERVER_ONLY is not set'
|
||||||
|
CONFIG_MBEDTLS_TLS_CLIENT_ONLY=y
|
||||||
|
'# CONFIG_MBEDTLS_SSL_PROTO_DTLS is not set'
|
||||||
|
'# CONFIG_ESP_HTTPS_SERVER_ENABLE is not set'
|
||||||
|
; Assertions still abort; detailed failure messages are omitted.
|
||||||
|
'# CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_ENABLE is not set'
|
||||||
|
'# CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_DISABLE is not set'
|
||||||
|
CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT=y
|
||||||
|
; Use the compact definitions above instead of spaced native metadata.
|
||||||
|
'# CONFIG_COMPILER_CXX_GLIBCXX_CONSTEXPR_COLD_CONSTEXPR is not set'
|
||||||
|
'# CONFIG_COMPILER_CXX_GLIBCXX_CONSTEXPR_COLD is not set'
|
||||||
|
CONFIG_COMPILER_CXX_GLIBCXX_CONSTEXPR_NO_CHANGE=y
|
||||||
|
|
||||||
|
[env:otthing]
|
||||||
|
extends = esp32_defaults
|
||||||
|
board = lolin_c3_mini
|
||||||
|
lib_deps = ${esp32_defaults.lib_deps}
|
||||||
|
${esp32_defaults.nimble_lib}
|
||||||
|
build_unflags = ${esp32_defaults.build_unflags}
|
||||||
|
-mno-save-restore
|
||||||
|
custom_link_flags = -msave-restore
|
||||||
|
build_flags = ${esp32_defaults.build_flags}
|
||||||
|
-msave-restore
|
||||||
|
-D MYNEWT_VAL_BLE_EXT_ADV=1
|
||||||
|
-D USE_BLE=1
|
||||||
|
-D DEFAULT_OT_IN_GPIO=3
|
||||||
|
-D DEFAULT_OT_OUT_GPIO=1
|
||||||
|
;-D DEFAULT_SENSOR_OUTDOOR_GPIO=0
|
||||||
|
;-D DEFAULT_SENSOR_INDOOR_GPIO=1
|
||||||
|
-D DEFAULT_STATUS_LED_GPIO=8
|
||||||
|
-D DEFAULT_OT_RX_LED_GPIO=2
|
||||||
|
-D OT_BYPASS_RELAY_GPIO=20
|
||||||
|
custom_sdkconfig = ${esp32_defaults.custom_sdkconfig}
|
||||||
|
CONFIG_COMPILER_SAVE_RESTORE_LIBCALLS=y
|
||||||
@@ -1,8 +1,11 @@
|
|||||||
[secrets]
|
[secrets]
|
||||||
use_serial = true
|
build_type = release
|
||||||
use_telnet = true
|
|
||||||
debug = true
|
serial_enabled = true
|
||||||
hostname = opentherm
|
serial_baud = 115200
|
||||||
|
webserial_enabled = true
|
||||||
|
log_level = ESP_LOG_INFO
|
||||||
|
hostname =
|
||||||
|
|
||||||
ap_ssid = OpenTherm Gateway
|
ap_ssid = OpenTherm Gateway
|
||||||
ap_password = otgateway123456
|
ap_password = otgateway123456
|
||||||
@@ -13,8 +16,9 @@ sta_password =
|
|||||||
portal_login = admin
|
portal_login = admin
|
||||||
portal_password = admin
|
portal_password = admin
|
||||||
|
|
||||||
|
mqtt_enabled = false
|
||||||
mqtt_server =
|
mqtt_server =
|
||||||
mqtt_port = 1883
|
mqtt_port = 1883
|
||||||
mqtt_user =
|
mqtt_user =
|
||||||
mqtt_password =
|
mqtt_password =
|
||||||
mqtt_prefix = opentherm
|
mqtt_prefix =
|
||||||
@@ -1,341 +0,0 @@
|
|||||||
#include <Blinker.h>
|
|
||||||
|
|
||||||
extern Network::Manager* network;
|
|
||||||
extern MqttTask* tMqtt;
|
|
||||||
extern OpenThermTask* tOt;
|
|
||||||
extern FileData fsSettings, fsNetworkSettings;
|
|
||||||
extern ESPTelnetStream* telnetStream;
|
|
||||||
|
|
||||||
|
|
||||||
class MainTask : public Task {
|
|
||||||
public:
|
|
||||||
MainTask(bool _enabled = false, unsigned long _interval = 0) : Task(_enabled, _interval) {
|
|
||||||
this->blinker = new Blinker();
|
|
||||||
|
|
||||||
network->setDelayCallback([this](unsigned int time) {
|
|
||||||
this->delay(time);
|
|
||||||
})->setYieldCallback([this]() {
|
|
||||||
this->yield();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
~MainTask() {
|
|
||||||
delete this->blinker;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected:
|
|
||||||
enum class PumpStartReason {NONE, HEATING, ANTISTUCK};
|
|
||||||
|
|
||||||
Blinker* blinker = nullptr;
|
|
||||||
bool blinkerInitialized = false;
|
|
||||||
unsigned long firstFailConnect = 0;
|
|
||||||
unsigned long lastHeapInfo = 0;
|
|
||||||
unsigned int minFreeHeap = 0;
|
|
||||||
unsigned int minMaxFreeBlockHeap = 0;
|
|
||||||
unsigned long restartSignalTime = 0;
|
|
||||||
bool heatingEnabled = false;
|
|
||||||
unsigned long heatingDisabledTime = 0;
|
|
||||||
PumpStartReason extPumpStartReason = PumpStartReason::NONE;
|
|
||||||
unsigned long externalPumpStartTime = 0;
|
|
||||||
bool telnetStarted = false;
|
|
||||||
|
|
||||||
const char* getTaskName() {
|
|
||||||
return "Main";
|
|
||||||
}
|
|
||||||
|
|
||||||
/*int getTaskCore() {
|
|
||||||
return 1;
|
|
||||||
}*/
|
|
||||||
|
|
||||||
int getTaskPriority() {
|
|
||||||
return 3;
|
|
||||||
}
|
|
||||||
|
|
||||||
void setup() {
|
|
||||||
#ifdef LED_STATUS_PIN
|
|
||||||
pinMode(LED_STATUS_PIN, OUTPUT);
|
|
||||||
digitalWrite(LED_STATUS_PIN, LOW);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
if (settings.externalPump.pin != 0) {
|
|
||||||
pinMode(settings.externalPump.pin, OUTPUT);
|
|
||||||
digitalWrite(settings.externalPump.pin, LOW);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void loop() {
|
|
||||||
network->loop();
|
|
||||||
|
|
||||||
if (fsSettings.tick() == FD_WRITE) {
|
|
||||||
Log.sinfoln(FPSTR(L_SETTINGS), F("Updated"));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (fsNetworkSettings.tick() == FD_WRITE) {
|
|
||||||
Log.sinfoln(FPSTR(L_NETWORK_SETTINGS), F("Updated"));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (vars.actions.restart) {
|
|
||||||
vars.actions.restart = false;
|
|
||||||
this->restartSignalTime = millis();
|
|
||||||
|
|
||||||
// save settings
|
|
||||||
fsSettings.updateNow();
|
|
||||||
|
|
||||||
// force save network settings
|
|
||||||
if (fsNetworkSettings.updateNow() == FD_FILE_ERR && LittleFS.begin()) {
|
|
||||||
fsNetworkSettings.write();
|
|
||||||
}
|
|
||||||
|
|
||||||
Log.sinfoln(FPSTR(L_MAIN), F("Restart signal received. Restart after 10 sec."));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!tOt->isEnabled() && settings.opentherm.inPin > 0 && settings.opentherm.outPin > 0 && settings.opentherm.inPin != settings.opentherm.outPin) {
|
|
||||||
tOt->enable();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (network->isConnected()) {
|
|
||||||
vars.sensors.rssi = WiFi.RSSI();
|
|
||||||
|
|
||||||
if (!this->telnetStarted && telnetStream != nullptr) {
|
|
||||||
telnetStream->begin(23, false);
|
|
||||||
this->telnetStarted = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!tMqtt->isEnabled() && strlen(settings.mqtt.server) > 0) {
|
|
||||||
tMqtt->enable();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this->firstFailConnect != 0) {
|
|
||||||
this->firstFailConnect = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ( Log.getLevel() != TinyLogger::Level::INFO && !settings.system.debug ) {
|
|
||||||
Log.setLevel(TinyLogger::Level::INFO);
|
|
||||||
|
|
||||||
} else if ( Log.getLevel() != TinyLogger::Level::VERBOSE && settings.system.debug ) {
|
|
||||||
Log.setLevel(TinyLogger::Level::VERBOSE);
|
|
||||||
}
|
|
||||||
|
|
||||||
} else {
|
|
||||||
if (this->telnetStarted) {
|
|
||||||
telnetStream->stop();
|
|
||||||
this->telnetStarted = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (tMqtt->isEnabled()) {
|
|
||||||
tMqtt->disable();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (settings.emergency.enable && !vars.states.emergency) {
|
|
||||||
if (this->firstFailConnect == 0) {
|
|
||||||
this->firstFailConnect = millis();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (millis() - this->firstFailConnect > EMERGENCY_TIME_TRESHOLD) {
|
|
||||||
vars.states.emergency = true;
|
|
||||||
Log.sinfoln(FPSTR(L_MAIN), F("Emergency mode enabled"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
this->yield();
|
|
||||||
|
|
||||||
|
|
||||||
#ifdef LED_STATUS_PIN
|
|
||||||
this->ledStatus(LED_STATUS_PIN);
|
|
||||||
#endif
|
|
||||||
this->externalPump();
|
|
||||||
this->yield();
|
|
||||||
|
|
||||||
|
|
||||||
// telnet
|
|
||||||
if (this->telnetStarted) {
|
|
||||||
telnetStream->loop();
|
|
||||||
this->yield();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// anti memory leak
|
|
||||||
for (Stream* stream : Log.getStreams()) {
|
|
||||||
while (stream->available() > 0) {
|
|
||||||
stream->read();
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
::delay(0);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// heap info
|
|
||||||
this->heap();
|
|
||||||
|
|
||||||
|
|
||||||
// restart
|
|
||||||
if (this->restartSignalTime > 0 && millis() - this->restartSignalTime > 10000) {
|
|
||||||
this->restartSignalTime = 0;
|
|
||||||
ESP.restart();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void heap() {
|
|
||||||
unsigned int freeHeap = getFreeHeap();
|
|
||||||
unsigned int maxFreeBlockHeap = getMaxFreeBlockHeap();
|
|
||||||
|
|
||||||
if (!this->restartSignalTime && (freeHeap < 2048 || maxFreeBlockHeap < 2048)) {
|
|
||||||
this->restartSignalTime = millis();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!settings.system.debug) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t minFreeHeap = getFreeHeap(true);
|
|
||||||
size_t minFreeHeapDiff = 0;
|
|
||||||
if (minFreeHeap < this->minFreeHeap || this->minFreeHeap == 0) {
|
|
||||||
minFreeHeapDiff = this->minFreeHeap - minFreeHeap;
|
|
||||||
this->minFreeHeap = minFreeHeap;
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t minMaxFreeBlockHeap = getMaxFreeBlockHeap(true);
|
|
||||||
size_t minMaxFreeBlockHeapDiff = 0;
|
|
||||||
if (minMaxFreeBlockHeap < this->minMaxFreeBlockHeap || this->minMaxFreeBlockHeap == 0) {
|
|
||||||
minMaxFreeBlockHeapDiff = this->minMaxFreeBlockHeap - minMaxFreeBlockHeap;
|
|
||||||
this->minMaxFreeBlockHeap = minMaxFreeBlockHeap;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (millis() - this->lastHeapInfo > 20000 || minFreeHeapDiff > 0 || minMaxFreeBlockHeapDiff > 0) {
|
|
||||||
Log.sverboseln(
|
|
||||||
FPSTR(L_MAIN),
|
|
||||||
F("Free heap size: %u of %u bytes (min: %u, diff: %u), max free block: %u (min: %u, diff: %u, frag: %hhu%%)"),
|
|
||||||
freeHeap, getTotalHeap(), this->minFreeHeap, minFreeHeapDiff, maxFreeBlockHeap, this->minMaxFreeBlockHeap, minMaxFreeBlockHeapDiff, getHeapFrag()
|
|
||||||
);
|
|
||||||
this->lastHeapInfo = millis();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void ledStatus(uint8_t ledPin) {
|
|
||||||
uint8_t errors[4];
|
|
||||||
uint8_t errCount = 0;
|
|
||||||
static uint8_t errPos = 0;
|
|
||||||
static unsigned long endBlinkTime = 0;
|
|
||||||
static bool ledOn = false;
|
|
||||||
|
|
||||||
if (!this->blinkerInitialized) {
|
|
||||||
this->blinker->init(ledPin);
|
|
||||||
this->blinkerInitialized = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!network->isConnected()) {
|
|
||||||
errors[errCount++] = 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!vars.states.otStatus) {
|
|
||||||
errors[errCount++] = 3;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (vars.states.fault) {
|
|
||||||
errors[errCount++] = 4;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (vars.states.emergency) {
|
|
||||||
errors[errCount++] = 5;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
if (this->blinker->ready()) {
|
|
||||||
endBlinkTime = millis();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!this->blinker->running() && millis() - endBlinkTime >= 5000) {
|
|
||||||
if (errCount == 0) {
|
|
||||||
if (!ledOn) {
|
|
||||||
digitalWrite(ledPin, HIGH);
|
|
||||||
ledOn = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
|
||||||
|
|
||||||
} else if (ledOn) {
|
|
||||||
digitalWrite(ledPin, LOW);
|
|
||||||
ledOn = false;
|
|
||||||
endBlinkTime = millis();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (errPos >= errCount) {
|
|
||||||
errPos = 0;
|
|
||||||
|
|
||||||
// end of error list
|
|
||||||
this->blinker->blink(10, 50, 50);
|
|
||||||
|
|
||||||
} else {
|
|
||||||
this->blinker->blink(errors[errPos++], 300, 300);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
this->blinker->tick();
|
|
||||||
}
|
|
||||||
|
|
||||||
void externalPump() {
|
|
||||||
if (!vars.states.heating && this->heatingEnabled) {
|
|
||||||
this->heatingEnabled = false;
|
|
||||||
this->heatingDisabledTime = millis();
|
|
||||||
|
|
||||||
} else if (vars.states.heating && !this->heatingEnabled) {
|
|
||||||
this->heatingEnabled = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!settings.externalPump.use || settings.externalPump.pin == 0) {
|
|
||||||
if (vars.states.externalPump) {
|
|
||||||
if (settings.externalPump.pin != 0) {
|
|
||||||
digitalWrite(settings.externalPump.pin, LOW);
|
|
||||||
}
|
|
||||||
|
|
||||||
vars.states.externalPump = false;
|
|
||||||
vars.parameters.extPumpLastEnableTime = millis();
|
|
||||||
|
|
||||||
Log.sinfoln("EXTPUMP", F("Disabled: use = off"));
|
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (vars.states.externalPump && !this->heatingEnabled) {
|
|
||||||
if (this->extPumpStartReason == MainTask::PumpStartReason::HEATING && millis() - this->heatingDisabledTime > (settings.externalPump.postCirculationTime * 1000u)) {
|
|
||||||
digitalWrite(settings.externalPump.pin, LOW);
|
|
||||||
|
|
||||||
vars.states.externalPump = false;
|
|
||||||
vars.parameters.extPumpLastEnableTime = millis();
|
|
||||||
|
|
||||||
Log.sinfoln("EXTPUMP", F("Disabled: expired post circulation time"));
|
|
||||||
|
|
||||||
} else if (this->extPumpStartReason == MainTask::PumpStartReason::ANTISTUCK && millis() - this->externalPumpStartTime >= (settings.externalPump.antiStuckTime * 1000u)) {
|
|
||||||
digitalWrite(settings.externalPump.pin, LOW);
|
|
||||||
|
|
||||||
vars.states.externalPump = false;
|
|
||||||
vars.parameters.extPumpLastEnableTime = millis();
|
|
||||||
|
|
||||||
Log.sinfoln("EXTPUMP", F("Disabled: expired anti stuck time"));
|
|
||||||
}
|
|
||||||
|
|
||||||
} else if (vars.states.externalPump && this->heatingEnabled && this->extPumpStartReason == MainTask::PumpStartReason::ANTISTUCK) {
|
|
||||||
this->extPumpStartReason = MainTask::PumpStartReason::HEATING;
|
|
||||||
|
|
||||||
} else if (!vars.states.externalPump && this->heatingEnabled) {
|
|
||||||
vars.states.externalPump = true;
|
|
||||||
this->externalPumpStartTime = millis();
|
|
||||||
this->extPumpStartReason = MainTask::PumpStartReason::HEATING;
|
|
||||||
|
|
||||||
digitalWrite(settings.externalPump.pin, HIGH);
|
|
||||||
|
|
||||||
Log.sinfoln("EXTPUMP", F("Enabled: heating on"));
|
|
||||||
|
|
||||||
} else if (!vars.states.externalPump && (vars.parameters.extPumpLastEnableTime == 0 || millis() - vars.parameters.extPumpLastEnableTime >= (settings.externalPump.antiStuckInterval * 1000ul))) {
|
|
||||||
vars.states.externalPump = true;
|
|
||||||
this->externalPumpStartTime = millis();
|
|
||||||
this->extPumpStartReason = MainTask::PumpStartReason::ANTISTUCK;
|
|
||||||
|
|
||||||
digitalWrite(settings.externalPump.pin, HIGH);
|
|
||||||
|
|
||||||
Log.sinfoln("EXTPUMP", F("Enabled: anti stuck"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,505 +0,0 @@
|
|||||||
#include <MqttClient.h>
|
|
||||||
#include <MqttWiFiClient.h>
|
|
||||||
#include <MqttWriter.h>
|
|
||||||
#include "HaHelper.h"
|
|
||||||
|
|
||||||
extern FileData fsSettings;
|
|
||||||
|
|
||||||
class MqttTask : public Task {
|
|
||||||
public:
|
|
||||||
MqttTask(bool _enabled = false, unsigned long _interval = 0) : Task(_enabled, _interval) {
|
|
||||||
this->wifiClient = new MqttWiFiClient();
|
|
||||||
this->client = new MqttClient(this->wifiClient);
|
|
||||||
this->writer = new MqttWriter(this->client, 256);
|
|
||||||
this->haHelper = new HaHelper();
|
|
||||||
}
|
|
||||||
|
|
||||||
~MqttTask() {
|
|
||||||
delete this->haHelper;
|
|
||||||
|
|
||||||
if (this->client != nullptr) {
|
|
||||||
if (this->client->connected()) {
|
|
||||||
this->client->stop();
|
|
||||||
}
|
|
||||||
|
|
||||||
delete this->client;
|
|
||||||
}
|
|
||||||
|
|
||||||
delete this->writer;
|
|
||||||
delete this->wifiClient;
|
|
||||||
}
|
|
||||||
|
|
||||||
void disable() {
|
|
||||||
this->client->stop();
|
|
||||||
Task::disable();
|
|
||||||
|
|
||||||
Log.sinfoln(FPSTR(L_MQTT), F("Disabled"));
|
|
||||||
}
|
|
||||||
|
|
||||||
void enable() {
|
|
||||||
Task::enable();
|
|
||||||
|
|
||||||
Log.sinfoln(FPSTR(L_MQTT), F("Enabled"));
|
|
||||||
}
|
|
||||||
|
|
||||||
bool isConnected() {
|
|
||||||
return this->connected;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected:
|
|
||||||
MqttWiFiClient* wifiClient = nullptr;
|
|
||||||
MqttClient* client = nullptr;
|
|
||||||
HaHelper* haHelper = nullptr;
|
|
||||||
MqttWriter* writer = nullptr;
|
|
||||||
unsigned short readyForSendTime = 15000;
|
|
||||||
unsigned long lastReconnectTime = 0;
|
|
||||||
unsigned long connectedTime = 0;
|
|
||||||
unsigned long disconnectedTime = 0;
|
|
||||||
unsigned long prevPubVarsTime = 0;
|
|
||||||
unsigned long prevPubSettingsTime = 0;
|
|
||||||
bool connected = false;
|
|
||||||
bool newConnection = false;
|
|
||||||
|
|
||||||
const char* getTaskName() {
|
|
||||||
return "Mqtt";
|
|
||||||
}
|
|
||||||
|
|
||||||
/*int getTaskCore() {
|
|
||||||
return 1;
|
|
||||||
}*/
|
|
||||||
|
|
||||||
int getTaskPriority() {
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool isReadyForSend() {
|
|
||||||
return millis() - this->connectedTime > this->readyForSendTime;
|
|
||||||
}
|
|
||||||
|
|
||||||
void setup() {
|
|
||||||
Log.sinfoln(FPSTR(L_MQTT), F("Started"));
|
|
||||||
|
|
||||||
// wificlient settings
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
this->wifiClient->setSync(true);
|
|
||||||
this->wifiClient->setNoDelay(true);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// client settings
|
|
||||||
this->client->setKeepAliveInterval(15000);
|
|
||||||
this->client->setTxPayloadSize(256);
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
this->client->setConnectionTimeout(1000);
|
|
||||||
#else
|
|
||||||
this->client->setConnectionTimeout(3000);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
this->client->onMessage([this] (void*, size_t length) {
|
|
||||||
String topic = this->client->messageTopic();
|
|
||||||
if (!length || length > 2048 || !topic.length()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
uint8_t payload[length];
|
|
||||||
for (size_t i = 0; i < length && this->client->available(); i++) {
|
|
||||||
payload[i] = this->client->read();
|
|
||||||
}
|
|
||||||
|
|
||||||
this->onMessage(topic.c_str(), payload, length);
|
|
||||||
});
|
|
||||||
|
|
||||||
// writer settings
|
|
||||||
#ifdef ARDUINO_ARCH_ESP32
|
|
||||||
this->writer->setYieldCallback([this] {
|
|
||||||
this->delay(10);
|
|
||||||
});
|
|
||||||
#endif
|
|
||||||
|
|
||||||
this->writer->setPublishEventCallback([this] (const char* topic, size_t written, size_t length, bool result) {
|
|
||||||
Log.straceln(FPSTR(L_MQTT), F("%s publish %u of %u bytes to topic: %s"), result ? F("Successfully") : F("Failed"), written, length, topic);
|
|
||||||
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
::delay(0);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
//this->client->poll();
|
|
||||||
this->delay(250);
|
|
||||||
});
|
|
||||||
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
this->writer->setFlushEventCallback([this] (size_t, size_t) {
|
|
||||||
::delay(0);
|
|
||||||
|
|
||||||
if (this->wifiClient->connected()) {
|
|
||||||
this->wifiClient->flush();
|
|
||||||
}
|
|
||||||
|
|
||||||
::delay(0);
|
|
||||||
});
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// ha helper settings
|
|
||||||
this->haHelper->setDevicePrefix(settings.mqtt.prefix);
|
|
||||||
this->haHelper->setDeviceVersion(PROJECT_VERSION);
|
|
||||||
this->haHelper->setDeviceModel(PROJECT_NAME);
|
|
||||||
this->haHelper->setDeviceName(PROJECT_NAME);
|
|
||||||
this->haHelper->setWriter(this->writer);
|
|
||||||
|
|
||||||
sprintf(buffer, CONFIG_URL, WiFi.localIP().toString().c_str());
|
|
||||||
this->haHelper->setDeviceConfigUrl(buffer);
|
|
||||||
}
|
|
||||||
|
|
||||||
void loop() {
|
|
||||||
if (settings.mqtt.interval > 120) {
|
|
||||||
settings.mqtt.interval = 5;
|
|
||||||
fsSettings.update();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this->connected && !this->client->connected()) {
|
|
||||||
this->connected = false;
|
|
||||||
this->onDisconnect();
|
|
||||||
|
|
||||||
} else if (!this->connected && millis() - this->lastReconnectTime >= MQTT_RECONNECT_INTERVAL) {
|
|
||||||
Log.sinfoln(FPSTR(L_MQTT), F("Connecting to %s:%u..."), settings.mqtt.server, settings.mqtt.port);
|
|
||||||
|
|
||||||
this->haHelper->setDevicePrefix(settings.mqtt.prefix);
|
|
||||||
this->client->stop();
|
|
||||||
this->client->setId(networkSettings.hostname);
|
|
||||||
this->client->setUsernamePassword(settings.mqtt.user, settings.mqtt.password);
|
|
||||||
this->client->connect(settings.mqtt.server, settings.mqtt.port);
|
|
||||||
this->lastReconnectTime = millis();
|
|
||||||
this->yield();
|
|
||||||
|
|
||||||
} else if (!this->connected && this->client->connected()) {
|
|
||||||
this->connected = true;
|
|
||||||
this->onConnect();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!this->connected && settings.emergency.enable && !vars.states.emergency && millis() - this->disconnectedTime > EMERGENCY_TIME_TRESHOLD) {
|
|
||||||
vars.states.emergency = true;
|
|
||||||
Log.sinfoln(FPSTR(L_MQTT), F("Emergency mode enabled"));
|
|
||||||
|
|
||||||
} else if (this->connected && vars.states.emergency && millis() - this->connectedTime > 10000) {
|
|
||||||
vars.states.emergency = false;
|
|
||||||
Log.sinfoln(FPSTR(L_MQTT), F("Emergency mode disabled"));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!this->connected) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this->client->poll();
|
|
||||||
|
|
||||||
// delay for publish data
|
|
||||||
if (!this->isReadyForSend()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
::delay(0);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// publish variables and status
|
|
||||||
if (this->newConnection || millis() - this->prevPubVarsTime > (settings.mqtt.interval * 1000u)) {
|
|
||||||
this->writer->publish(this->haHelper->getDeviceTopic("status").c_str(), "online", false);
|
|
||||||
this->publishVariables(this->haHelper->getDeviceTopic("state").c_str());
|
|
||||||
this->prevPubVarsTime = millis();
|
|
||||||
}
|
|
||||||
|
|
||||||
// publish settings
|
|
||||||
if (this->newConnection || millis() - this->prevPubSettingsTime > (settings.mqtt.interval * 10000u)) {
|
|
||||||
this->publishSettings(this->haHelper->getDeviceTopic("settings").c_str());
|
|
||||||
this->prevPubSettingsTime = millis();
|
|
||||||
}
|
|
||||||
|
|
||||||
// publish ha entities if not published
|
|
||||||
if (this->newConnection) {
|
|
||||||
this->publishHaEntities();
|
|
||||||
this->publishNonStaticHaEntities(true);
|
|
||||||
this->newConnection = false;
|
|
||||||
|
|
||||||
} else {
|
|
||||||
// publish non static ha entities
|
|
||||||
this->publishNonStaticHaEntities();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void onConnect() {
|
|
||||||
this->connectedTime = millis();
|
|
||||||
this->newConnection = true;
|
|
||||||
unsigned long downtime = (millis() - this->disconnectedTime) / 1000;
|
|
||||||
Log.sinfoln(FPSTR(L_MQTT), F("Connected (downtime: %u s.)"), downtime);
|
|
||||||
|
|
||||||
this->client->subscribe(this->haHelper->getDeviceTopic("settings/set").c_str());
|
|
||||||
this->client->subscribe(this->haHelper->getDeviceTopic("state/set").c_str());
|
|
||||||
}
|
|
||||||
|
|
||||||
void onDisconnect() {
|
|
||||||
this->disconnectedTime = millis();
|
|
||||||
|
|
||||||
unsigned long uptime = (millis() - this->connectedTime) / 1000;
|
|
||||||
Log.swarningln(FPSTR(L_MQTT), F("Disconnected (reason: %d uptime: %u s.)"), this->client->connectError(), uptime);
|
|
||||||
}
|
|
||||||
|
|
||||||
void onMessage(const char* topic, uint8_t* payload, size_t length) {
|
|
||||||
if (!length) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (settings.system.debug) {
|
|
||||||
Log.strace(FPSTR(L_MQTT_MSG), F("Topic: %s\r\n> "), topic);
|
|
||||||
if (Log.lock()) {
|
|
||||||
for (size_t i = 0; i < length; i++) {
|
|
||||||
if (payload[i] == 0) {
|
|
||||||
break;
|
|
||||||
} else if (payload[i] == 13) {
|
|
||||||
continue;
|
|
||||||
} else if (payload[i] == 10) {
|
|
||||||
Log.print("\r\n> ");
|
|
||||||
} else {
|
|
||||||
Log.print((char) payload[i]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Log.print("\r\n\n");
|
|
||||||
Log.flush();
|
|
||||||
Log.unlock();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
JsonDocument doc;
|
|
||||||
DeserializationError dErr = deserializeJson(doc, payload, length);
|
|
||||||
if (dErr != DeserializationError::Ok) {
|
|
||||||
Log.swarningln(FPSTR(L_MQTT_MSG), F("Error on deserialization: %s"), dErr.f_str());
|
|
||||||
return;
|
|
||||||
|
|
||||||
} else if (doc.isNull() || !doc.size()) {
|
|
||||||
Log.swarningln(FPSTR(L_MQTT_MSG), F("Not valid json"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this->haHelper->getDeviceTopic("state/set").equals(topic)) {
|
|
||||||
this->writer->publish(this->haHelper->getDeviceTopic("state/set").c_str(), nullptr, 0, true);
|
|
||||||
this->updateVariables(doc);
|
|
||||||
|
|
||||||
} else if (this->haHelper->getDeviceTopic("settings/set").equals(topic)) {
|
|
||||||
this->writer->publish(this->haHelper->getDeviceTopic("settings/set").c_str(), nullptr, 0, true);
|
|
||||||
this->updateSettings(doc);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
bool updateSettings(JsonDocument& doc) {
|
|
||||||
bool changed = safeJsonToSettings(doc, settings);
|
|
||||||
doc.clear();
|
|
||||||
doc.shrinkToFit();
|
|
||||||
|
|
||||||
if (changed) {
|
|
||||||
this->prevPubSettingsTime = 0;
|
|
||||||
fsSettings.update();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool updateVariables(JsonDocument& doc) {
|
|
||||||
bool changed = jsonToVars(doc, vars);
|
|
||||||
doc.clear();
|
|
||||||
doc.shrinkToFit();
|
|
||||||
|
|
||||||
if (changed) {
|
|
||||||
this->prevPubVarsTime = 0;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
void publishHaEntities() {
|
|
||||||
// emergency
|
|
||||||
this->haHelper->publishSwitchEmergency();
|
|
||||||
this->haHelper->publishNumberEmergencyTarget();
|
|
||||||
this->haHelper->publishSwitchEmergencyUseEquitherm();
|
|
||||||
this->haHelper->publishSwitchEmergencyUsePid();
|
|
||||||
|
|
||||||
// heating
|
|
||||||
this->haHelper->publishSwitchHeating(false);
|
|
||||||
this->haHelper->publishSwitchHeatingTurbo();
|
|
||||||
this->haHelper->publishNumberHeatingHysteresis();
|
|
||||||
this->haHelper->publishSensorHeatingSetpoint(false);
|
|
||||||
this->haHelper->publishSensorBoilerHeatingMinTemp(false);
|
|
||||||
this->haHelper->publishSensorBoilerHeatingMaxTemp(false);
|
|
||||||
this->haHelper->publishNumberHeatingMinTemp(false);
|
|
||||||
this->haHelper->publishNumberHeatingMaxTemp(false);
|
|
||||||
this->haHelper->publishNumberHeatingMaxModulation(false);
|
|
||||||
|
|
||||||
// pid
|
|
||||||
this->haHelper->publishSwitchPid();
|
|
||||||
this->haHelper->publishNumberPidFactorP();
|
|
||||||
this->haHelper->publishNumberPidFactorI();
|
|
||||||
this->haHelper->publishNumberPidFactorD();
|
|
||||||
this->haHelper->publishNumberPidDt(false);
|
|
||||||
this->haHelper->publishNumberPidMinTemp(false);
|
|
||||||
this->haHelper->publishNumberPidMaxTemp(false);
|
|
||||||
|
|
||||||
// equitherm
|
|
||||||
this->haHelper->publishSwitchEquitherm();
|
|
||||||
this->haHelper->publishNumberEquithermFactorN();
|
|
||||||
this->haHelper->publishNumberEquithermFactorK();
|
|
||||||
this->haHelper->publishNumberEquithermFactorT();
|
|
||||||
|
|
||||||
// tuning
|
|
||||||
this->haHelper->publishSwitchTuning();
|
|
||||||
this->haHelper->publishSelectTuningRegulator();
|
|
||||||
|
|
||||||
// states
|
|
||||||
this->haHelper->publishBinSensorStatus();
|
|
||||||
this->haHelper->publishBinSensorOtStatus();
|
|
||||||
this->haHelper->publishBinSensorHeating();
|
|
||||||
this->haHelper->publishBinSensorFlame();
|
|
||||||
this->haHelper->publishBinSensorFault();
|
|
||||||
this->haHelper->publishBinSensorDiagnostic();
|
|
||||||
|
|
||||||
// sensors
|
|
||||||
this->haHelper->publishSensorModulation(false);
|
|
||||||
this->haHelper->publishSensorPressure(false);
|
|
||||||
this->haHelper->publishSensorFaultCode();
|
|
||||||
this->haHelper->publishSensorRssi(false);
|
|
||||||
this->haHelper->publishSensorUptime(false);
|
|
||||||
|
|
||||||
// temperatures
|
|
||||||
this->haHelper->publishNumberIndoorTemp();
|
|
||||||
this->haHelper->publishSensorHeatingTemp();
|
|
||||||
|
|
||||||
// buttons
|
|
||||||
this->haHelper->publishButtonRestart(false);
|
|
||||||
this->haHelper->publishButtonResetFault();
|
|
||||||
this->haHelper->publishButtonResetDiagnostic();
|
|
||||||
}
|
|
||||||
|
|
||||||
bool publishNonStaticHaEntities(bool force = false) {
|
|
||||||
static byte _heatingMinTemp, _heatingMaxTemp, _dhwMinTemp, _dhwMaxTemp = 0;
|
|
||||||
static bool _isStupidMode, _editableOutdoorTemp, _editableIndoorTemp, _dhwPresent = false;
|
|
||||||
|
|
||||||
bool published = false;
|
|
||||||
bool isStupidMode = !settings.pid.enable && !settings.equitherm.enable;
|
|
||||||
byte heatingMinTemp = isStupidMode ? settings.heating.minTemp : 10;
|
|
||||||
byte heatingMaxTemp = isStupidMode ? settings.heating.maxTemp : 30;
|
|
||||||
bool editableOutdoorTemp = settings.sensors.outdoor.type == 1;
|
|
||||||
bool editableIndoorTemp = settings.sensors.indoor.type == 1;
|
|
||||||
|
|
||||||
if (force || _dhwPresent != settings.opentherm.dhwPresent) {
|
|
||||||
_dhwPresent = settings.opentherm.dhwPresent;
|
|
||||||
|
|
||||||
if (_dhwPresent) {
|
|
||||||
this->haHelper->publishSwitchDhw(false);
|
|
||||||
this->haHelper->publishSensorBoilerDhwMinTemp(false);
|
|
||||||
this->haHelper->publishSensorBoilerDhwMaxTemp(false);
|
|
||||||
this->haHelper->publishNumberDhwMinTemp(false);
|
|
||||||
this->haHelper->publishNumberDhwMaxTemp(false);
|
|
||||||
this->haHelper->publishBinSensorDhw();
|
|
||||||
this->haHelper->publishSensorDhwTemp();
|
|
||||||
this->haHelper->publishSensorDhwFlowRate(false);
|
|
||||||
|
|
||||||
} else {
|
|
||||||
this->haHelper->deleteSwitchDhw();
|
|
||||||
this->haHelper->deleteSensorBoilerDhwMinTemp();
|
|
||||||
this->haHelper->deleteSensorBoilerDhwMaxTemp();
|
|
||||||
this->haHelper->deleteNumberDhwMinTemp();
|
|
||||||
this->haHelper->deleteNumberDhwMaxTemp();
|
|
||||||
this->haHelper->deleteBinSensorDhw();
|
|
||||||
this->haHelper->deleteSensorDhwTemp();
|
|
||||||
this->haHelper->deleteNumberDhwTarget();
|
|
||||||
this->haHelper->deleteClimateDhw();
|
|
||||||
this->haHelper->deleteSensorDhwFlowRate();
|
|
||||||
}
|
|
||||||
|
|
||||||
published = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (force || _heatingMinTemp != heatingMinTemp || _heatingMaxTemp != heatingMaxTemp) {
|
|
||||||
if (settings.heating.target < heatingMinTemp || settings.heating.target > heatingMaxTemp) {
|
|
||||||
settings.heating.target = constrain(settings.heating.target, heatingMinTemp, heatingMaxTemp);
|
|
||||||
}
|
|
||||||
|
|
||||||
_heatingMinTemp = heatingMinTemp;
|
|
||||||
_heatingMaxTemp = heatingMaxTemp;
|
|
||||||
_isStupidMode = isStupidMode;
|
|
||||||
|
|
||||||
this->haHelper->publishNumberHeatingTarget(heatingMinTemp, heatingMaxTemp, false);
|
|
||||||
this->haHelper->publishClimateHeating(
|
|
||||||
heatingMinTemp,
|
|
||||||
heatingMaxTemp,
|
|
||||||
isStupidMode ? HaHelper::TEMP_SOURCE_HEATING : HaHelper::TEMP_SOURCE_INDOOR
|
|
||||||
);
|
|
||||||
|
|
||||||
published = true;
|
|
||||||
|
|
||||||
} else if (_isStupidMode != isStupidMode) {
|
|
||||||
_isStupidMode = isStupidMode;
|
|
||||||
this->haHelper->publishClimateHeating(
|
|
||||||
heatingMinTemp,
|
|
||||||
heatingMaxTemp,
|
|
||||||
isStupidMode ? HaHelper::TEMP_SOURCE_HEATING : HaHelper::TEMP_SOURCE_INDOOR
|
|
||||||
);
|
|
||||||
|
|
||||||
published = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (_dhwPresent && (force || _dhwMinTemp != settings.dhw.minTemp || _dhwMaxTemp != settings.dhw.maxTemp)) {
|
|
||||||
_dhwMinTemp = settings.dhw.minTemp;
|
|
||||||
_dhwMaxTemp = settings.dhw.maxTemp;
|
|
||||||
|
|
||||||
this->haHelper->publishNumberDhwTarget(settings.dhw.minTemp, settings.dhw.maxTemp, false);
|
|
||||||
this->haHelper->publishClimateDhw(settings.dhw.minTemp, settings.dhw.maxTemp);
|
|
||||||
|
|
||||||
published = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (force || _editableOutdoorTemp != editableOutdoorTemp) {
|
|
||||||
_editableOutdoorTemp = editableOutdoorTemp;
|
|
||||||
|
|
||||||
if (editableOutdoorTemp) {
|
|
||||||
this->haHelper->deleteSensorOutdoorTemp();
|
|
||||||
this->haHelper->publishNumberOutdoorTemp();
|
|
||||||
} else {
|
|
||||||
this->haHelper->deleteNumberOutdoorTemp();
|
|
||||||
this->haHelper->publishSensorOutdoorTemp();
|
|
||||||
}
|
|
||||||
|
|
||||||
published = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (force || _editableIndoorTemp != editableIndoorTemp) {
|
|
||||||
_editableIndoorTemp = editableIndoorTemp;
|
|
||||||
|
|
||||||
if (editableIndoorTemp) {
|
|
||||||
this->haHelper->deleteSensorIndoorTemp();
|
|
||||||
this->haHelper->publishNumberIndoorTemp();
|
|
||||||
} else {
|
|
||||||
this->haHelper->deleteNumberIndoorTemp();
|
|
||||||
this->haHelper->publishSensorIndoorTemp();
|
|
||||||
}
|
|
||||||
|
|
||||||
published = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return published;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool publishSettings(const char* topic) {
|
|
||||||
JsonDocument doc;
|
|
||||||
safeSettingsToJson(settings, doc);
|
|
||||||
doc.shrinkToFit();
|
|
||||||
|
|
||||||
return this->writer->publish(topic, doc, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool publishVariables(const char* topic) {
|
|
||||||
JsonDocument doc;
|
|
||||||
varsToJson(vars, doc);
|
|
||||||
doc.shrinkToFit();
|
|
||||||
|
|
||||||
return this->writer->publish(topic, doc, true);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,732 +0,0 @@
|
|||||||
#include <CustomOpenTherm.h>
|
|
||||||
|
|
||||||
CustomOpenTherm* ot;
|
|
||||||
extern FileData fsSettings;
|
|
||||||
|
|
||||||
class OpenThermTask : public Task {
|
|
||||||
public:
|
|
||||||
OpenThermTask(bool _enabled = false, unsigned long _interval = 0) : Task(_enabled, _interval) {
|
|
||||||
ot = new CustomOpenTherm(settings.opentherm.inPin, settings.opentherm.outPin);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void IRAM_ATTR handleInterrupt() {
|
|
||||||
ot->handleInterrupt();
|
|
||||||
}
|
|
||||||
|
|
||||||
protected:
|
|
||||||
unsigned short readyTime = 60000;
|
|
||||||
unsigned short dhwSetTempInterval = 60000;
|
|
||||||
unsigned short heatingSetTempInterval = 60000;
|
|
||||||
|
|
||||||
bool pump = true;
|
|
||||||
unsigned long lastSuccessResponse = 0;
|
|
||||||
unsigned long prevUpdateNonEssentialVars = 0;
|
|
||||||
unsigned long startupTime = millis();
|
|
||||||
unsigned long dhwSetTempTime = 0;
|
|
||||||
unsigned long heatingSetTempTime = 0;
|
|
||||||
byte dhwFlowRateMultiplier = 1;
|
|
||||||
byte pressureMultiplier = 1;
|
|
||||||
|
|
||||||
const char* getTaskName() {
|
|
||||||
return "OpenTherm";
|
|
||||||
}
|
|
||||||
|
|
||||||
int getTaskCore() {
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
int getTaskPriority() {
|
|
||||||
return 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
void setup() {
|
|
||||||
Log.sinfoln(FPSTR(L_OT), F("Started. GPIO IN: %hhu, GPIO OUT: %hhu"), settings.opentherm.inPin, settings.opentherm.outPin);
|
|
||||||
|
|
||||||
ot->setAfterSendRequestCallback([this](unsigned long request, unsigned long response, OpenThermResponseStatus status, byte attempt) {
|
|
||||||
Log.straceln(
|
|
||||||
FPSTR(L_OT),
|
|
||||||
F("ID: %4d Request: %8lx Response: %8lx Attempt: %2d Status: %s"),
|
|
||||||
ot->getDataID(request), request, response, attempt, ot->statusToString(status)
|
|
||||||
);
|
|
||||||
|
|
||||||
if (status == OpenThermResponseStatus::SUCCESS) {
|
|
||||||
this->lastSuccessResponse = millis();
|
|
||||||
|
|
||||||
#ifdef LED_OT_RX_PIN
|
|
||||||
{
|
|
||||||
digitalWrite(LED_OT_RX_PIN, HIGH);
|
|
||||||
delayMicroseconds(2000);
|
|
||||||
digitalWrite(LED_OT_RX_PIN, LOW);
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
ot->setYieldCallback([this]() {
|
|
||||||
this->delay(25);
|
|
||||||
});
|
|
||||||
|
|
||||||
ot->setMinWaitTimeForStartBit(20000);
|
|
||||||
ot->begin(OpenThermTask::handleInterrupt);
|
|
||||||
|
|
||||||
#ifdef LED_OT_RX_PIN
|
|
||||||
pinMode(LED_OT_RX_PIN, OUTPUT);
|
|
||||||
digitalWrite(LED_OT_RX_PIN, LOW);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
void initBoiler() {
|
|
||||||
this->dhwFlowRateMultiplier = 1;
|
|
||||||
this->pressureMultiplier = 1;
|
|
||||||
|
|
||||||
// Not all boilers support these, only try once when the boiler becomes connected
|
|
||||||
if (updateSlaveVersion()) {
|
|
||||||
Log.straceln(FPSTR(L_OT), F("Slave version: %u, type: %u"), vars.parameters.slaveVersion, vars.parameters.slaveType);
|
|
||||||
|
|
||||||
} else {
|
|
||||||
Log.swarningln(FPSTR(L_OT), F("Get slave version failed"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// 0x013F
|
|
||||||
if (setMasterVersion(0x3F, 0x01)) {
|
|
||||||
Log.straceln(FPSTR(L_OT), F("Master version: %u, type: %u"), vars.parameters.masterVersion, vars.parameters.masterType);
|
|
||||||
|
|
||||||
} else {
|
|
||||||
Log.swarningln(FPSTR(L_OT), F("Set master version failed"));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (updateSlaveConfig()) {
|
|
||||||
Log.straceln(FPSTR(L_OT), F("Slave member id: %u, flags: %u"), vars.parameters.slaveMemberId, vars.parameters.slaveFlags);
|
|
||||||
|
|
||||||
} else {
|
|
||||||
Log.swarningln(FPSTR(L_OT), F("Get slave config failed"));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (setMasterConfig(settings.opentherm.memberIdCode & 0xFF, (settings.opentherm.memberIdCode & 0xFFFF) >> 8)) {
|
|
||||||
Log.straceln(FPSTR(L_OT), F("Master member id: %u, flags: %u"), vars.parameters.masterMemberId, vars.parameters.masterFlags);
|
|
||||||
|
|
||||||
} else {
|
|
||||||
Log.swarningln(FPSTR(L_OT), F("Set master config failed"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void loop() {
|
|
||||||
static byte currentHeatingTemp, currentDhwTemp = 0;
|
|
||||||
unsigned long localResponse;
|
|
||||||
|
|
||||||
bool heatingEnabled = (vars.states.emergency || settings.heating.enable) && this->pump && isReady();
|
|
||||||
bool heatingCh2Enabled = settings.opentherm.heatingCh2Enabled;
|
|
||||||
if (settings.opentherm.heatingCh1ToCh2) {
|
|
||||||
heatingCh2Enabled = heatingEnabled;
|
|
||||||
|
|
||||||
} else if (settings.opentherm.dhwToCh2) {
|
|
||||||
heatingCh2Enabled = settings.opentherm.dhwPresent && settings.dhw.enable;
|
|
||||||
}
|
|
||||||
|
|
||||||
localResponse = ot->setBoilerStatus(
|
|
||||||
heatingEnabled,
|
|
||||||
settings.opentherm.dhwPresent && settings.dhw.enable,
|
|
||||||
false,
|
|
||||||
false,
|
|
||||||
heatingCh2Enabled,
|
|
||||||
settings.opentherm.summerWinterMode,
|
|
||||||
settings.opentherm.dhwBlocking
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!ot->isValidResponse(localResponse)) {
|
|
||||||
Log.swarningln(FPSTR(L_OT), F("Invalid response after setBoilerStatus: %s"), ot->statusToString(ot->getLastResponseStatus()));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!vars.states.otStatus && millis() - this->lastSuccessResponse < 1150) {
|
|
||||||
Log.sinfoln(FPSTR(L_OT), F("Connected. Initializing"));
|
|
||||||
|
|
||||||
vars.states.otStatus = true;
|
|
||||||
this->initBoiler();
|
|
||||||
|
|
||||||
} else if (vars.states.otStatus && millis() - this->lastSuccessResponse > 1150) {
|
|
||||||
Log.swarningln(FPSTR(L_OT), F("Disconnected"));
|
|
||||||
|
|
||||||
vars.states.otStatus = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// If boiler is disconnected, no need try setting other OT stuff
|
|
||||||
if (!vars.states.otStatus) {
|
|
||||||
vars.states.heating = false;
|
|
||||||
vars.states.dhw = false;
|
|
||||||
vars.states.flame = false;
|
|
||||||
vars.states.fault = false;
|
|
||||||
vars.states.diagnostic = false;
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (vars.parameters.heatingEnabled != heatingEnabled) {
|
|
||||||
this->prevUpdateNonEssentialVars = 0;
|
|
||||||
vars.parameters.heatingEnabled = heatingEnabled;
|
|
||||||
Log.sinfoln(FPSTR(L_OT_HEATING), "%s", heatingEnabled ? F("Enabled") : F("Disabled"));
|
|
||||||
}
|
|
||||||
|
|
||||||
vars.states.heating = ot->isCentralHeatingActive(localResponse);
|
|
||||||
vars.states.dhw = settings.opentherm.dhwPresent ? ot->isHotWaterActive(localResponse) : false;
|
|
||||||
vars.states.flame = ot->isFlameOn(localResponse);
|
|
||||||
vars.states.fault = ot->isFault(localResponse);
|
|
||||||
vars.states.diagnostic = ot->isDiagnostic(localResponse);
|
|
||||||
|
|
||||||
// These parameters will be updated every minute
|
|
||||||
if (millis() - this->prevUpdateNonEssentialVars > 60000) {
|
|
||||||
if (!heatingEnabled && settings.opentherm.modulationSyncWithHeating) {
|
|
||||||
if (setMaxModulationLevel(0)) {
|
|
||||||
Log.snoticeln(FPSTR(L_OT_HEATING), F("Set max modulation 0% (off)"));
|
|
||||||
|
|
||||||
} else {
|
|
||||||
Log.swarningln(FPSTR(L_OT_HEATING), F("Failed set max modulation 0% (off)"));
|
|
||||||
}
|
|
||||||
|
|
||||||
} else {
|
|
||||||
if (setMaxModulationLevel(settings.heating.maxModulation)) {
|
|
||||||
Log.snoticeln(FPSTR(L_OT_HEATING), F("Set max modulation %hhu%%"), settings.heating.maxModulation);
|
|
||||||
|
|
||||||
} else {
|
|
||||||
Log.swarningln(FPSTR(L_OT_HEATING), F("Failed set max modulation %hhu%%"), settings.heating.maxModulation);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Get DHW min/max temp (if necessary)
|
|
||||||
if (settings.opentherm.dhwPresent) {
|
|
||||||
if (updateMinMaxDhwTemp()) {
|
|
||||||
if (settings.dhw.minTemp < vars.parameters.dhwMinTemp) {
|
|
||||||
settings.dhw.minTemp = vars.parameters.dhwMinTemp;
|
|
||||||
fsSettings.update();
|
|
||||||
Log.snoticeln(FPSTR(L_OT_DHW), F("Updated min temp: %hhu"), settings.dhw.minTemp);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (settings.dhw.maxTemp > vars.parameters.dhwMaxTemp) {
|
|
||||||
settings.dhw.maxTemp = vars.parameters.dhwMaxTemp;
|
|
||||||
fsSettings.update();
|
|
||||||
Log.snoticeln(FPSTR(L_OT_DHW), F("Updated max temp: %hhu"), settings.dhw.maxTemp);
|
|
||||||
}
|
|
||||||
|
|
||||||
} else {
|
|
||||||
Log.swarningln(FPSTR(L_OT_DHW), F("Failed get min/max temp"));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (settings.dhw.minTemp >= settings.dhw.maxTemp) {
|
|
||||||
settings.dhw.minTemp = 30;
|
|
||||||
settings.dhw.maxTemp = 60;
|
|
||||||
fsSettings.update();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Get heating min/max temp
|
|
||||||
if (updateMinMaxHeatingTemp()) {
|
|
||||||
if (settings.heating.minTemp < vars.parameters.heatingMinTemp) {
|
|
||||||
settings.heating.minTemp = vars.parameters.heatingMinTemp;
|
|
||||||
fsSettings.update();
|
|
||||||
Log.snoticeln(FPSTR(L_OT_HEATING), F("Updated min temp: %hhu"), settings.heating.minTemp);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (settings.heating.maxTemp > vars.parameters.heatingMaxTemp) {
|
|
||||||
settings.heating.maxTemp = vars.parameters.heatingMaxTemp;
|
|
||||||
fsSettings.update();
|
|
||||||
Log.snoticeln(FPSTR(L_OT_HEATING), F("Updated max temp: %hhu"), settings.heating.maxTemp);
|
|
||||||
}
|
|
||||||
|
|
||||||
} else {
|
|
||||||
Log.swarningln(FPSTR(L_OT_HEATING), F("Failed get min/max temp"));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (settings.heating.minTemp >= settings.heating.maxTemp) {
|
|
||||||
settings.heating.minTemp = 20;
|
|
||||||
settings.heating.maxTemp = 90;
|
|
||||||
fsSettings.update();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Force set max heating temp
|
|
||||||
setMaxHeatingTemp(settings.heating.maxTemp);
|
|
||||||
|
|
||||||
// Get outdoor temp (if necessary)
|
|
||||||
if (settings.sensors.outdoor.type == 0) {
|
|
||||||
updateOutsideTemp();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get fault code (if necessary)
|
|
||||||
if (vars.states.fault) {
|
|
||||||
updateFaultCode();
|
|
||||||
}
|
|
||||||
|
|
||||||
updatePressure();
|
|
||||||
|
|
||||||
this->prevUpdateNonEssentialVars = millis();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Get current modulation level (if necessary)
|
|
||||||
if ((settings.opentherm.dhwPresent && settings.dhw.enable) || settings.heating.enable || heatingEnabled) {
|
|
||||||
updateModulationLevel();
|
|
||||||
|
|
||||||
} else {
|
|
||||||
vars.sensors.modulation = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update DHW sensors (if necessary)
|
|
||||||
if (settings.opentherm.dhwPresent) {
|
|
||||||
updateDhwTemp();
|
|
||||||
updateDhwFlowRate();
|
|
||||||
|
|
||||||
} else {
|
|
||||||
vars.temperatures.dhw = 0.0f;
|
|
||||||
vars.sensors.dhwFlowRate = 0.0f;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get current heating temp
|
|
||||||
updateHeatingTemp();
|
|
||||||
|
|
||||||
|
|
||||||
// Fault reset action
|
|
||||||
if (vars.actions.resetFault) {
|
|
||||||
if (vars.states.fault) {
|
|
||||||
if (ot->sendBoilerReset()) {
|
|
||||||
Log.sinfoln(FPSTR(L_OT), F("Boiler fault reset successfully"));
|
|
||||||
|
|
||||||
} else {
|
|
||||||
Log.serrorln(FPSTR(L_OT), F("Boiler fault reset failed"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
vars.actions.resetFault = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Diag reset action
|
|
||||||
if (vars.actions.resetDiagnostic) {
|
|
||||||
if (vars.states.diagnostic) {
|
|
||||||
if (ot->sendServiceReset()) {
|
|
||||||
Log.sinfoln(FPSTR(L_OT), F("Boiler diagnostic reset successfully"));
|
|
||||||
|
|
||||||
} else {
|
|
||||||
Log.serrorln(FPSTR(L_OT), F("Boiler diagnostic reset failed"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
vars.actions.resetDiagnostic = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Update DHW temp
|
|
||||||
byte newDhwTemp = settings.dhw.target;
|
|
||||||
if (settings.opentherm.dhwPresent && settings.dhw.enable && (needSetDhwTemp() || newDhwTemp != currentDhwTemp)) {
|
|
||||||
if (newDhwTemp < settings.dhw.minTemp || newDhwTemp > settings.dhw.maxTemp) {
|
|
||||||
newDhwTemp = constrain(newDhwTemp, settings.dhw.minTemp, settings.dhw.maxTemp);
|
|
||||||
}
|
|
||||||
|
|
||||||
Log.sinfoln(FPSTR(L_OT_DHW), F("Set temp = %u"), newDhwTemp);
|
|
||||||
|
|
||||||
// Set DHW temp
|
|
||||||
if (ot->setDhwTemp(newDhwTemp)) {
|
|
||||||
currentDhwTemp = newDhwTemp;
|
|
||||||
this->dhwSetTempTime = millis();
|
|
||||||
|
|
||||||
} else {
|
|
||||||
Log.swarningln(FPSTR(L_OT_DHW), F("Failed set temp"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set DHW temp to CH2
|
|
||||||
if (settings.opentherm.dhwToCh2) {
|
|
||||||
if (!ot->setHeatingCh2Temp(newDhwTemp)) {
|
|
||||||
Log.swarningln(FPSTR(L_OT_DHW), F("Failed set ch2 temp"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Update heating temp
|
|
||||||
if (heatingEnabled && (needSetHeatingTemp() || fabs(vars.parameters.heatingSetpoint - currentHeatingTemp) > 0.0001)) {
|
|
||||||
Log.sinfoln(FPSTR(L_OT_HEATING), F("Set temp = %u"), vars.parameters.heatingSetpoint);
|
|
||||||
|
|
||||||
// Set heating temp
|
|
||||||
if (ot->setHeatingCh1Temp(vars.parameters.heatingSetpoint)) {
|
|
||||||
currentHeatingTemp = vars.parameters.heatingSetpoint;
|
|
||||||
this->heatingSetTempTime = millis();
|
|
||||||
|
|
||||||
} else {
|
|
||||||
Log.swarningln(FPSTR(L_OT_HEATING), F("Failed set temp"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set heating temp to CH2
|
|
||||||
if (settings.opentherm.heatingCh1ToCh2) {
|
|
||||||
if (!ot->setHeatingCh2Temp(vars.parameters.heatingSetpoint)) {
|
|
||||||
Log.swarningln(FPSTR(L_OT_HEATING), F("Failed set ch2 temp"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Hysteresis
|
|
||||||
// Only if enabled PID or/and Equitherm
|
|
||||||
if (settings.heating.hysteresis > 0 && (!vars.states.emergency || settings.emergency.usePid) && (settings.equitherm.enable || settings.pid.enable)) {
|
|
||||||
float halfHyst = settings.heating.hysteresis / 2;
|
|
||||||
if (this->pump && vars.temperatures.indoor - settings.heating.target + 0.0001 >= halfHyst) {
|
|
||||||
this->pump = false;
|
|
||||||
|
|
||||||
} else if (!this->pump && vars.temperatures.indoor - settings.heating.target - 0.0001 <= -(halfHyst)) {
|
|
||||||
this->pump = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
} else if (!this->pump) {
|
|
||||||
this->pump = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bool isReady() {
|
|
||||||
return millis() - this->startupTime > this->readyTime;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool needSetDhwTemp() {
|
|
||||||
return millis() - this->dhwSetTempTime > this->dhwSetTempInterval;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool needSetHeatingTemp() {
|
|
||||||
return millis() - this->heatingSetTempTime > this->heatingSetTempInterval;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool updateSlaveConfig() {
|
|
||||||
unsigned long response = ot->sendRequest(ot->buildRequest(
|
|
||||||
OpenThermRequestType::READ_DATA,
|
|
||||||
OpenThermMessageID::SConfigSMemberIDcode,
|
|
||||||
0
|
|
||||||
));
|
|
||||||
|
|
||||||
if (!ot->isValidResponse(response)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
vars.parameters.slaveMemberId = response & 0xFF;
|
|
||||||
vars.parameters.slaveFlags = (response & 0xFFFF) >> 8;
|
|
||||||
|
|
||||||
/*uint8_t flags = (response & 0xFFFF) >> 8;
|
|
||||||
Log.straceln(
|
|
||||||
"OT",
|
|
||||||
F("MasterMemberIdCode:\r\n DHW present: %u\r\n Control type: %u\r\n Cooling configuration: %u\r\n DHW configuration: %u\r\n Pump control: %u\r\n CH2 present: %u\r\n Remote water filling function: %u\r\n Heat/cool mode control: %u\r\n Slave MemberID Code: %u\r\n Raw: %u"),
|
|
||||||
(bool) (flags & 0x01),
|
|
||||||
(bool) (flags & 0x02),
|
|
||||||
(bool) (flags & 0x04),
|
|
||||||
(bool) (flags & 0x08),
|
|
||||||
(bool) (flags & 0x10),
|
|
||||||
(bool) (flags & 0x20),
|
|
||||||
(bool) (flags & 0x40),
|
|
||||||
(bool) (flags & 0x80),
|
|
||||||
response & 0xFF,
|
|
||||||
response
|
|
||||||
);*/
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Set the Master Config
|
|
||||||
* From slave member id code:
|
|
||||||
* id: slave.memberIdCode & 0xFF,
|
|
||||||
* flags: (slave.memberIdCode & 0xFFFF) >> 8
|
|
||||||
* @param id
|
|
||||||
* @param flags
|
|
||||||
* @param force
|
|
||||||
* @return true
|
|
||||||
* @return false
|
|
||||||
*/
|
|
||||||
bool setMasterConfig(uint8_t id, uint8_t flags, bool force = false) {
|
|
||||||
//uint8_t configId = settings.opentherm.memberIdCode & 0xFF;
|
|
||||||
//uint8_t configFlags = (settings.opentherm.memberIdCode & 0xFFFF) >> 8;
|
|
||||||
|
|
||||||
vars.parameters.masterMemberId = (force || id || settings.opentherm.memberIdCode > 65535)
|
|
||||||
? id
|
|
||||||
: vars.parameters.slaveMemberId;
|
|
||||||
|
|
||||||
vars.parameters.masterFlags = (force || flags || settings.opentherm.memberIdCode > 65535)
|
|
||||||
? flags
|
|
||||||
: vars.parameters.slaveFlags;
|
|
||||||
|
|
||||||
unsigned int request = (unsigned int) vars.parameters.masterMemberId | (unsigned int) vars.parameters.masterFlags << 8;
|
|
||||||
// if empty request
|
|
||||||
if (!request) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
unsigned long response = ot->sendRequest(ot->buildRequest(
|
|
||||||
OpenThermRequestType::WRITE_DATA,
|
|
||||||
OpenThermMessageID::MConfigMMemberIDcode,
|
|
||||||
request
|
|
||||||
));
|
|
||||||
|
|
||||||
return ot->isValidResponse(response);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool setMaxModulationLevel(byte value) {
|
|
||||||
unsigned long response = ot->sendRequest(ot->buildRequest(
|
|
||||||
OpenThermRequestType::WRITE_DATA,
|
|
||||||
OpenThermMessageID::MaxRelModLevelSetting,
|
|
||||||
ot->toF88(value)
|
|
||||||
));
|
|
||||||
|
|
||||||
if (!ot->isValidResponse(response)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
vars.parameters.maxModulation = ot->fromF88(response);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool updateSlaveOtVersion() {
|
|
||||||
unsigned long response = ot->sendRequest(ot->buildRequest(
|
|
||||||
OpenThermRequestType::READ_DATA,
|
|
||||||
OpenThermMessageID::OpenThermVersionSlave,
|
|
||||||
0
|
|
||||||
));
|
|
||||||
|
|
||||||
if (!ot->isValidResponse(response)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
vars.parameters.slaveOtVersion = ot->getFloat(response);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool setMasterOtVersion(float version) {
|
|
||||||
unsigned long response = ot->sendRequest(ot->buildRequest(
|
|
||||||
OpenThermRequestType::WRITE_DATA,
|
|
||||||
OpenThermMessageID::OpenThermVersionMaster,
|
|
||||||
ot->toF88(version)
|
|
||||||
));
|
|
||||||
|
|
||||||
if (!ot->isValidResponse(response)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
vars.parameters.masterOtVersion = ot->fromF88(response);
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool updateSlaveVersion() {
|
|
||||||
unsigned long response = ot->sendRequest(ot->buildRequest(
|
|
||||||
OpenThermRequestType::READ_DATA,
|
|
||||||
OpenThermMessageID::SlaveVersion,
|
|
||||||
0
|
|
||||||
));
|
|
||||||
|
|
||||||
if (!ot->isValidResponse(response)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
vars.parameters.slaveVersion = response & 0xFF;
|
|
||||||
vars.parameters.slaveType = (response & 0xFFFF) >> 8;
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool setMasterVersion(uint8_t version, uint8_t type) {
|
|
||||||
unsigned long response = ot->sendRequest(ot->buildRequest(
|
|
||||||
OpenThermRequestType::WRITE_DATA,
|
|
||||||
OpenThermMessageID::MasterVersion,
|
|
||||||
(unsigned int) version | (unsigned int) type << 8
|
|
||||||
));
|
|
||||||
|
|
||||||
if (!ot->isValidResponse(response)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
vars.parameters.masterVersion = response & 0xFF;
|
|
||||||
vars.parameters.masterType = (response & 0xFFFF) >> 8;
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool updateMinMaxDhwTemp() {
|
|
||||||
unsigned long response = ot->sendRequest(ot->buildRequest(
|
|
||||||
OpenThermRequestType::READ_DATA,
|
|
||||||
OpenThermMessageID::TdhwSetUBTdhwSetLB,
|
|
||||||
0
|
|
||||||
));
|
|
||||||
|
|
||||||
if (!ot->isValidResponse(response)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
byte minTemp = response & 0xFF;
|
|
||||||
byte maxTemp = (response & 0xFFFF) >> 8;
|
|
||||||
|
|
||||||
if (minTemp >= 0 && maxTemp > 0 && maxTemp > minTemp) {
|
|
||||||
vars.parameters.dhwMinTemp = minTemp;
|
|
||||||
vars.parameters.dhwMaxTemp = maxTemp;
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool updateMinMaxHeatingTemp() {
|
|
||||||
unsigned long response = ot->sendRequest(ot->buildRequest(
|
|
||||||
OpenThermRequestType::READ_DATA,
|
|
||||||
OpenThermMessageID::MaxTSetUBMaxTSetLB,
|
|
||||||
0
|
|
||||||
));
|
|
||||||
|
|
||||||
if (!ot->isValidResponse(response)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
byte minTemp = response & 0xFF;
|
|
||||||
byte maxTemp = (response & 0xFFFF) >> 8;
|
|
||||||
|
|
||||||
if (minTemp >= 0 && maxTemp > 0 && maxTemp > minTemp) {
|
|
||||||
vars.parameters.heatingMinTemp = minTemp;
|
|
||||||
vars.parameters.heatingMaxTemp = maxTemp;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool setMaxHeatingTemp(byte value) {
|
|
||||||
unsigned long response = ot->sendRequest(ot->buildRequest(
|
|
||||||
OpenThermMessageType::WRITE_DATA,
|
|
||||||
OpenThermMessageID::MaxTSet,
|
|
||||||
ot->temperatureToData(value)
|
|
||||||
));
|
|
||||||
|
|
||||||
return ot->isValidResponse(response);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool updateOutsideTemp() {
|
|
||||||
unsigned long response = ot->sendRequest(ot->buildRequest(
|
|
||||||
OpenThermRequestType::READ_DATA,
|
|
||||||
OpenThermMessageID::Toutside,
|
|
||||||
0
|
|
||||||
));
|
|
||||||
|
|
||||||
if (!ot->isValidResponse(response)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
vars.temperatures.outdoor = ot->getFloat(response) + settings.sensors.outdoor.offset;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool updateHeatingTemp() {
|
|
||||||
unsigned long response = ot->sendRequest(ot->buildRequest(
|
|
||||||
OpenThermMessageType::READ_DATA,
|
|
||||||
OpenThermMessageID::Tboiler,
|
|
||||||
0
|
|
||||||
));
|
|
||||||
|
|
||||||
if (!ot->isValidResponse(response)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
float value = ot->getFloat(response);
|
|
||||||
if (value <= 0) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
vars.temperatures.heating = value;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
bool updateDhwTemp() {
|
|
||||||
unsigned long response = ot->sendRequest(ot->buildRequest(
|
|
||||||
OpenThermMessageType::READ_DATA,
|
|
||||||
OpenThermMessageID::Tdhw,
|
|
||||||
0
|
|
||||||
));
|
|
||||||
|
|
||||||
if (!ot->isValidResponse(response)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
float value = ot->getFloat(response);
|
|
||||||
if (value <= 0) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
vars.temperatures.dhw = value;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool updateDhwFlowRate() {
|
|
||||||
unsigned long response = ot->sendRequest(ot->buildRequest(
|
|
||||||
OpenThermMessageType::READ_DATA,
|
|
||||||
OpenThermMessageID::DHWFlowRate,
|
|
||||||
0
|
|
||||||
));
|
|
||||||
|
|
||||||
if (!ot->isValidResponse(response)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
float value = ot->getFloat(response);
|
|
||||||
if (value > 16 && this->dhwFlowRateMultiplier != 10) {
|
|
||||||
this->dhwFlowRateMultiplier = 10;
|
|
||||||
}
|
|
||||||
vars.sensors.dhwFlowRate = this->dhwFlowRateMultiplier == 1 ? value : value / this->dhwFlowRateMultiplier;
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool updateFaultCode() {
|
|
||||||
unsigned long response = ot->sendRequest(ot->buildRequest(
|
|
||||||
OpenThermRequestType::READ_DATA,
|
|
||||||
OpenThermMessageID::ASFflags,
|
|
||||||
0
|
|
||||||
));
|
|
||||||
|
|
||||||
if (!ot->isValidResponse(response)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
vars.sensors.faultCode = response & 0xFF;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool updateModulationLevel() {
|
|
||||||
unsigned long response = ot->sendRequest(ot->buildRequest(
|
|
||||||
OpenThermRequestType::READ_DATA,
|
|
||||||
OpenThermMessageID::RelModLevel,
|
|
||||||
0
|
|
||||||
));
|
|
||||||
|
|
||||||
if (!ot->isValidResponse(response)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
float modulation = ot->fromF88(response);
|
|
||||||
if (!vars.states.flame) {
|
|
||||||
vars.sensors.modulation = 0;
|
|
||||||
} else {
|
|
||||||
vars.sensors.modulation = modulation;
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool updatePressure() {
|
|
||||||
unsigned long response = ot->sendRequest(ot->buildRequest(
|
|
||||||
OpenThermRequestType::READ_DATA,
|
|
||||||
OpenThermMessageID::CHPressure,
|
|
||||||
0
|
|
||||||
));
|
|
||||||
|
|
||||||
if (!ot->isValidResponse(response)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
float value = ot->getFloat(response);
|
|
||||||
if (value > 5 && this->pressureMultiplier != 10) {
|
|
||||||
this->pressureMultiplier = 10;
|
|
||||||
}
|
|
||||||
vars.sensors.pressure = this->pressureMultiplier == 1 ? value : value / this->pressureMultiplier;
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,647 +0,0 @@
|
|||||||
#define PORTAL_CACHE_TIME "max-age=86400"
|
|
||||||
#define PORTAL_CACHE settings.system.debug ? nullptr : PORTAL_CACHE_TIME
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
#include <ESP8266WebServer.h>
|
|
||||||
#include <Updater.h>
|
|
||||||
using WebServer = ESP8266WebServer;
|
|
||||||
#else
|
|
||||||
#include <WebServer.h>
|
|
||||||
#include <Update.h>
|
|
||||||
#endif
|
|
||||||
#include <BufferedWebServer.h>
|
|
||||||
#include <StaticPage.h>
|
|
||||||
#include <DynamicPage.h>
|
|
||||||
#include <UpgradeHandler.h>
|
|
||||||
#include <DNSServer.h>
|
|
||||||
|
|
||||||
extern Network::Manager* network;
|
|
||||||
extern FileData fsSettings, fsNetworkSettings;
|
|
||||||
extern MqttTask* tMqtt;
|
|
||||||
|
|
||||||
|
|
||||||
class PortalTask : public LeanTask {
|
|
||||||
public:
|
|
||||||
PortalTask(bool _enabled = false, unsigned long _interval = 0) : LeanTask(_enabled, _interval) {
|
|
||||||
this->webServer = new WebServer(80);
|
|
||||||
this->bufferedWebServer = new BufferedWebServer(this->webServer, 32u);
|
|
||||||
this->dnsServer = new DNSServer();
|
|
||||||
}
|
|
||||||
|
|
||||||
~PortalTask() {
|
|
||||||
delete this->bufferedWebServer;
|
|
||||||
|
|
||||||
if (this->webServer != nullptr) {
|
|
||||||
this->stopWebServer();
|
|
||||||
delete this->webServer;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this->dnsServer != nullptr) {
|
|
||||||
this->stopDnsServer();
|
|
||||||
delete this->dnsServer;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
protected:
|
|
||||||
const unsigned int changeStateInterval = 5000;
|
|
||||||
|
|
||||||
WebServer* webServer = nullptr;
|
|
||||||
BufferedWebServer* bufferedWebServer = nullptr;
|
|
||||||
DNSServer* dnsServer = nullptr;
|
|
||||||
|
|
||||||
bool webServerEnabled = false;
|
|
||||||
bool dnsServerEnabled = false;
|
|
||||||
unsigned long webServerChangeState = 0;
|
|
||||||
unsigned long dnsServerChangeState = 0;
|
|
||||||
|
|
||||||
const char* getTaskName() {
|
|
||||||
return "Portal";
|
|
||||||
}
|
|
||||||
|
|
||||||
/*int getTaskCore() {
|
|
||||||
return 1;
|
|
||||||
}*/
|
|
||||||
|
|
||||||
int getTaskPriority() {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
void setup() {
|
|
||||||
this->dnsServer->setTTL(0);
|
|
||||||
this->dnsServer->setErrorReplyCode(DNSReplyCode::NoError);
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
this->webServer->enableETag(true);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// index page
|
|
||||||
/*auto indexPage = (new DynamicPage("/", &LittleFS, "/index.html"))
|
|
||||||
->setTemplateCallback([](const char* var) -> String {
|
|
||||||
String result;
|
|
||||||
|
|
||||||
if (strcmp(var, "ver") == 0) {
|
|
||||||
result = PROJECT_VERSION;
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
});
|
|
||||||
this->webServer->addHandler(indexPage);*/
|
|
||||||
this->webServer->addHandler(new StaticPage("/", &LittleFS, "/index.html", PORTAL_CACHE));
|
|
||||||
|
|
||||||
// restart
|
|
||||||
this->webServer->on("/restart.html", HTTP_GET, [this]() {
|
|
||||||
if (this->isNeedAuth()) {
|
|
||||||
if (!this->webServer->authenticate(settings.portal.login, settings.portal.password)) {
|
|
||||||
this->webServer->send(401);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
vars.actions.restart = true;
|
|
||||||
this->webServer->sendHeader("Location", "/");
|
|
||||||
this->webServer->send(302);
|
|
||||||
});
|
|
||||||
|
|
||||||
// network settings page
|
|
||||||
auto networkPage = (new StaticPage("/network.html", &LittleFS, "/network.html", PORTAL_CACHE))
|
|
||||||
->setBeforeSendCallback([this]() {
|
|
||||||
if (this->isNeedAuth() && !this->webServer->authenticate(settings.portal.login, settings.portal.password)) {
|
|
||||||
this->webServer->requestAuthentication(DIGEST_AUTH);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
this->webServer->addHandler(networkPage);
|
|
||||||
|
|
||||||
// settings page
|
|
||||||
auto settingsPage = (new StaticPage("/settings.html", &LittleFS, "/settings.html", PORTAL_CACHE))
|
|
||||||
->setBeforeSendCallback([this]() {
|
|
||||||
if (this->isNeedAuth() && !this->webServer->authenticate(settings.portal.login, settings.portal.password)) {
|
|
||||||
this->webServer->requestAuthentication(DIGEST_AUTH);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
this->webServer->addHandler(settingsPage);
|
|
||||||
|
|
||||||
// upgrade page
|
|
||||||
auto upgradePage = (new StaticPage("/upgrade.html", &LittleFS, "/upgrade.html", PORTAL_CACHE))
|
|
||||||
->setBeforeSendCallback([this]() {
|
|
||||||
if (this->isNeedAuth() && !this->webServer->authenticate(settings.portal.login, settings.portal.password)) {
|
|
||||||
this->webServer->requestAuthentication(DIGEST_AUTH);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
this->webServer->addHandler(upgradePage);
|
|
||||||
|
|
||||||
// OTA
|
|
||||||
auto upgradeHandler = (new UpgradeHandler("/api/upgrade"))->setCanUploadCallback([this](const String& uri) {
|
|
||||||
if (this->isNeedAuth() && !this->webServer->authenticate(settings.portal.login, settings.portal.password)) {
|
|
||||||
this->webServer->sendHeader("Connection", "close");
|
|
||||||
this->webServer->send(401);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
})->setBeforeUpgradeCallback([](UpgradeHandler::UpgradeType type) -> bool {
|
|
||||||
return true;
|
|
||||||
})->setAfterUpgradeCallback([this](const UpgradeHandler::UpgradeResult& fwResult, const UpgradeHandler::UpgradeResult& fsResult) {
|
|
||||||
unsigned short status = 200;
|
|
||||||
if (fwResult.status == UpgradeHandler::UpgradeStatus::SUCCESS || fsResult.status == UpgradeHandler::UpgradeStatus::SUCCESS) {
|
|
||||||
vars.actions.restart = true;
|
|
||||||
|
|
||||||
} else {
|
|
||||||
status = 400;
|
|
||||||
}
|
|
||||||
|
|
||||||
String response = "{\"firmware\": {\"status\": ";
|
|
||||||
response.concat((short int) fwResult.status);
|
|
||||||
response.concat(", \"error\": \"");
|
|
||||||
response.concat(fwResult.error);
|
|
||||||
response.concat("\"}, \"filesystem\": {\"status\": ");
|
|
||||||
response.concat((short int) fsResult.status);
|
|
||||||
response.concat(", \"error\": \"");
|
|
||||||
response.concat(fsResult.error);
|
|
||||||
response.concat("\"}}");
|
|
||||||
this->webServer->send(status, "application/json", response);
|
|
||||||
});
|
|
||||||
this->webServer->addHandler(upgradeHandler);
|
|
||||||
|
|
||||||
|
|
||||||
// backup
|
|
||||||
this->webServer->on("/api/backup/save", HTTP_GET, [this]() {
|
|
||||||
if (this->isNeedAuth()) {
|
|
||||||
if (!this->webServer->authenticate(settings.portal.login, settings.portal.password)) {
|
|
||||||
return this->webServer->send(401);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
JsonDocument networkSettingsDoc;
|
|
||||||
networkSettingsToJson(networkSettings, networkSettingsDoc);
|
|
||||||
networkSettingsDoc.shrinkToFit();
|
|
||||||
|
|
||||||
JsonDocument settingsDoc;
|
|
||||||
settingsToJson(settings, settingsDoc);
|
|
||||||
settingsDoc.shrinkToFit();
|
|
||||||
|
|
||||||
JsonDocument doc;
|
|
||||||
doc["network"] = networkSettingsDoc;
|
|
||||||
doc["settings"] = settingsDoc;
|
|
||||||
doc.shrinkToFit();
|
|
||||||
|
|
||||||
this->webServer->sendHeader(F("Content-Disposition"), F("attachment; filename=\"backup.json\""));
|
|
||||||
this->bufferedWebServer->send(200, "application/json", doc);
|
|
||||||
});
|
|
||||||
|
|
||||||
this->webServer->on("/api/backup/restore", HTTP_POST, [this]() {
|
|
||||||
if (this->isNeedAuth()) {
|
|
||||||
if (!this->webServer->authenticate(settings.portal.login, settings.portal.password)) {
|
|
||||||
return this->webServer->send(401);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
String plain = this->webServer->arg(0);
|
|
||||||
Log.straceln(FPSTR(L_PORTAL_WEBSERVER), F("Request /api/backup/restore %d bytes: %s"), plain.length(), plain.c_str());
|
|
||||||
|
|
||||||
if (plain.length() < 5) {
|
|
||||||
this->webServer->send(406);
|
|
||||||
return;
|
|
||||||
|
|
||||||
} else if (plain.length() > 2048) {
|
|
||||||
this->webServer->send(413);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
JsonDocument doc;
|
|
||||||
DeserializationError dErr = deserializeJson(doc, plain);
|
|
||||||
plain.clear();
|
|
||||||
|
|
||||||
if (dErr != DeserializationError::Ok || doc.isNull() || !doc.size()) {
|
|
||||||
this->webServer->send(400);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool changed = false;
|
|
||||||
if (doc["settings"] && jsonToSettings(doc["settings"], settings)) {
|
|
||||||
vars.actions.restart = true;
|
|
||||||
fsSettings.update();
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (doc["network"] && jsonToNetworkSettings(doc["network"], networkSettings)) {
|
|
||||||
fsNetworkSettings.update();
|
|
||||||
network->setHostname(networkSettings.hostname)
|
|
||||||
->setStaCredentials(networkSettings.sta.ssid, networkSettings.sta.password, networkSettings.sta.channel)
|
|
||||||
->setUseDhcp(networkSettings.useDhcp)
|
|
||||||
->setStaticConfig(
|
|
||||||
networkSettings.staticConfig.ip,
|
|
||||||
networkSettings.staticConfig.gateway,
|
|
||||||
networkSettings.staticConfig.subnet,
|
|
||||||
networkSettings.staticConfig.dns
|
|
||||||
)
|
|
||||||
->reconnect();
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
doc.clear();
|
|
||||||
doc.shrinkToFit();
|
|
||||||
|
|
||||||
this->webServer->send(changed ? 201 : 200);
|
|
||||||
});
|
|
||||||
|
|
||||||
// network
|
|
||||||
this->webServer->on("/api/network/settings", HTTP_GET, [this]() {
|
|
||||||
if (this->isNeedAuth()) {
|
|
||||||
if (!this->webServer->authenticate(settings.portal.login, settings.portal.password)) {
|
|
||||||
return this->webServer->send(401);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
JsonDocument doc;
|
|
||||||
networkSettingsToJson(networkSettings, doc);
|
|
||||||
doc.shrinkToFit();
|
|
||||||
|
|
||||||
this->bufferedWebServer->send(200, "application/json", doc);
|
|
||||||
});
|
|
||||||
|
|
||||||
this->webServer->on("/api/network/settings", HTTP_POST, [this]() {
|
|
||||||
if (this->isNeedAuth()) {
|
|
||||||
if (!this->webServer->authenticate(settings.portal.login, settings.portal.password)) {
|
|
||||||
return this->webServer->send(401);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
String plain = this->webServer->arg(0);
|
|
||||||
Log.straceln(FPSTR(L_PORTAL_WEBSERVER), F("Request /api/network/settings %d bytes: %s"), plain.length(), plain.c_str());
|
|
||||||
|
|
||||||
if (plain.length() < 5) {
|
|
||||||
this->webServer->send(406);
|
|
||||||
return;
|
|
||||||
|
|
||||||
} else if (plain.length() > 512) {
|
|
||||||
this->webServer->send(413);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
JsonDocument doc;
|
|
||||||
DeserializationError dErr = deserializeJson(doc, plain);
|
|
||||||
plain.clear();
|
|
||||||
|
|
||||||
if (dErr != DeserializationError::Ok || doc.isNull() || !doc.size()) {
|
|
||||||
this->webServer->send(400);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool changed = jsonToNetworkSettings(doc, networkSettings);
|
|
||||||
doc.clear();
|
|
||||||
doc.shrinkToFit();
|
|
||||||
|
|
||||||
if (changed) {
|
|
||||||
this->webServer->send(201);
|
|
||||||
|
|
||||||
fsNetworkSettings.update();
|
|
||||||
network->setHostname(networkSettings.hostname)
|
|
||||||
->setStaCredentials(networkSettings.sta.ssid, networkSettings.sta.password, networkSettings.sta.channel)
|
|
||||||
->setUseDhcp(networkSettings.useDhcp)
|
|
||||||
->setStaticConfig(
|
|
||||||
networkSettings.staticConfig.ip,
|
|
||||||
networkSettings.staticConfig.gateway,
|
|
||||||
networkSettings.staticConfig.subnet,
|
|
||||||
networkSettings.staticConfig.dns
|
|
||||||
)
|
|
||||||
->reconnect();
|
|
||||||
|
|
||||||
} else {
|
|
||||||
this->webServer->send(200);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
this->webServer->on("/api/network/status", HTTP_GET, [this]() {
|
|
||||||
bool isConnected = network->isConnected();
|
|
||||||
|
|
||||||
JsonDocument doc;
|
|
||||||
doc["hostname"] = networkSettings.hostname;
|
|
||||||
doc["mac"] = network->getStaMac();
|
|
||||||
doc["isConnected"] = isConnected;
|
|
||||||
doc["ssid"] = network->getStaSsid();
|
|
||||||
doc["signalQuality"] = isConnected ? Network::Manager::rssiToSignalQuality(network->getRssi()) : 0;
|
|
||||||
doc["channel"] = isConnected ? network->getStaChannel() : 0;
|
|
||||||
doc["ip"] = isConnected ? network->getStaIp().toString() : "";
|
|
||||||
doc["subnet"] = isConnected ? network->getStaSubnet().toString() : "";
|
|
||||||
doc["gateway"] = isConnected ? network->getStaGateway().toString() : "";
|
|
||||||
doc["dns"] = isConnected ? network->getStaDns().toString() : "";
|
|
||||||
doc.shrinkToFit();
|
|
||||||
|
|
||||||
this->bufferedWebServer->send(200, "application/json", doc);
|
|
||||||
});
|
|
||||||
|
|
||||||
this->webServer->on("/api/network/scan", HTTP_GET, [this]() {
|
|
||||||
if (this->isNeedAuth()) {
|
|
||||||
if (!this->webServer->authenticate(settings.portal.login, settings.portal.password)) {
|
|
||||||
this->webServer->send(401);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
auto apCount = WiFi.scanComplete();
|
|
||||||
if (apCount <= 0) {
|
|
||||||
if (apCount != WIFI_SCAN_RUNNING) {
|
|
||||||
WiFi.scanNetworks(true, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
this->webServer->send(404);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
JsonDocument doc;
|
|
||||||
for (short int i = 0; i < apCount; i++) {
|
|
||||||
String ssid = WiFi.SSID(i);
|
|
||||||
doc[i]["ssid"] = ssid;
|
|
||||||
doc[i]["signalQuality"] = Network::Manager::rssiToSignalQuality(WiFi.RSSI(i));
|
|
||||||
doc[i]["channel"] = WiFi.channel(i);
|
|
||||||
doc[i]["hidden"] = !ssid.length();
|
|
||||||
doc[i]["encryptionType"] = WiFi.encryptionType(i);
|
|
||||||
}
|
|
||||||
doc.shrinkToFit();
|
|
||||||
|
|
||||||
this->bufferedWebServer->send(200, "application/json", doc);
|
|
||||||
|
|
||||||
WiFi.scanDelete();
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
// settings
|
|
||||||
this->webServer->on("/api/settings", HTTP_GET, [this]() {
|
|
||||||
if (this->isNeedAuth()) {
|
|
||||||
if (!this->webServer->authenticate(settings.portal.login, settings.portal.password)) {
|
|
||||||
return this->webServer->send(401);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
JsonDocument doc;
|
|
||||||
settingsToJson(settings, doc);
|
|
||||||
doc.shrinkToFit();
|
|
||||||
|
|
||||||
this->bufferedWebServer->send(200, "application/json", doc);
|
|
||||||
});
|
|
||||||
|
|
||||||
this->webServer->on("/api/settings", HTTP_POST, [this]() {
|
|
||||||
if (this->isNeedAuth()) {
|
|
||||||
if (!this->webServer->authenticate(settings.portal.login, settings.portal.password)) {
|
|
||||||
return this->webServer->send(401);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
String plain = this->webServer->arg(0);
|
|
||||||
Log.straceln(FPSTR(L_PORTAL_WEBSERVER), F("Request /api/settings %d bytes: %s"), plain.length(), plain.c_str());
|
|
||||||
|
|
||||||
if (plain.length() < 5) {
|
|
||||||
this->webServer->send(406);
|
|
||||||
return;
|
|
||||||
|
|
||||||
} else if (plain.length() > 2048) {
|
|
||||||
this->webServer->send(413);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
JsonDocument doc;
|
|
||||||
DeserializationError dErr = deserializeJson(doc, plain);
|
|
||||||
plain.clear();
|
|
||||||
|
|
||||||
if (dErr != DeserializationError::Ok || doc.isNull() || !doc.size()) {
|
|
||||||
this->webServer->send(400);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool changed = jsonToSettings(doc, settings);
|
|
||||||
doc.clear();
|
|
||||||
doc.shrinkToFit();
|
|
||||||
|
|
||||||
if (changed) {
|
|
||||||
fsSettings.update();
|
|
||||||
this->webServer->send(201);
|
|
||||||
|
|
||||||
} else {
|
|
||||||
this->webServer->send(200);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
// vars
|
|
||||||
this->webServer->on("/api/vars", HTTP_GET, [this]() {
|
|
||||||
JsonDocument doc;
|
|
||||||
varsToJson(vars, doc);
|
|
||||||
|
|
||||||
doc["system"]["version"] = PROJECT_VERSION;
|
|
||||||
doc["system"]["buildDate"] = __DATE__ " " __TIME__;
|
|
||||||
doc["system"]["uptime"] = millis() / 1000ul;
|
|
||||||
doc["system"]["totalHeap"] = getTotalHeap();
|
|
||||||
doc["system"]["freeHeap"] = getFreeHeap();
|
|
||||||
doc["system"]["minFreeHeap"] = getFreeHeap(true);
|
|
||||||
doc["system"]["maxFreeBlockHeap"] = getMaxFreeBlockHeap();
|
|
||||||
doc["system"]["minMaxFreeBlockHeap"] = getMaxFreeBlockHeap(true);
|
|
||||||
doc["system"]["resetReason"] = getResetReason();
|
|
||||||
doc["system"]["mqttConnected"] = tMqtt->isConnected();
|
|
||||||
doc.shrinkToFit();
|
|
||||||
|
|
||||||
this->bufferedWebServer->send(200, "application/json", doc);
|
|
||||||
});
|
|
||||||
|
|
||||||
this->webServer->on("/api/vars", HTTP_POST, [this]() {
|
|
||||||
if (this->isNeedAuth()) {
|
|
||||||
if (!this->webServer->authenticate(settings.portal.login, settings.portal.password)) {
|
|
||||||
return this->webServer->send(401);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
String plain = this->webServer->arg(0);
|
|
||||||
Log.straceln(FPSTR(L_PORTAL_WEBSERVER), F("Request /api/vars %d bytes: %s"), plain.length(), plain.c_str());
|
|
||||||
|
|
||||||
if (plain.length() < 5) {
|
|
||||||
this->webServer->send(406);
|
|
||||||
return;
|
|
||||||
|
|
||||||
} else if (plain.length() > 1024) {
|
|
||||||
this->webServer->send(413);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
JsonDocument doc;
|
|
||||||
DeserializationError dErr = deserializeJson(doc, plain);
|
|
||||||
plain.clear();
|
|
||||||
|
|
||||||
if (dErr != DeserializationError::Ok || doc.isNull() || !doc.size()) {
|
|
||||||
this->webServer->send(400);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool changed = jsonToVars(doc, vars);
|
|
||||||
doc.clear();
|
|
||||||
doc.shrinkToFit();
|
|
||||||
|
|
||||||
if (changed) {
|
|
||||||
this->webServer->send(201);
|
|
||||||
|
|
||||||
} else {
|
|
||||||
this->webServer->send(200);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
// not found
|
|
||||||
this->webServer->onNotFound([this]() {
|
|
||||||
Log.straceln(FPSTR(L_PORTAL_WEBSERVER), F("Page not found, uri: %s"), this->webServer->uri().c_str());
|
|
||||||
|
|
||||||
const String uri = this->webServer->uri();
|
|
||||||
if (uri.equals("/")) {
|
|
||||||
this->webServer->send(200, "text/plain", F("The file system is not flashed!"));
|
|
||||||
|
|
||||||
} else if (network->isApEnabled()) {
|
|
||||||
this->onCaptivePortal();
|
|
||||||
|
|
||||||
} else {
|
|
||||||
this->webServer->send(404, "text/plain", F("Page not found"));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
this->webServer->serveStatic("/favicon.ico", LittleFS, "/static/favicon.ico", PORTAL_CACHE);
|
|
||||||
this->webServer->serveStatic("/static", LittleFS, "/static", PORTAL_CACHE);
|
|
||||||
}
|
|
||||||
|
|
||||||
void loop() {
|
|
||||||
// web server
|
|
||||||
if (!this->stateWebServer() && (network->isApEnabled() || network->isConnected()) && millis() - this->webServerChangeState >= this->changeStateInterval) {
|
|
||||||
this->startWebServer();
|
|
||||||
Log.straceln(FPSTR(L_PORTAL_WEBSERVER), F("Started: AP up or STA connected"));
|
|
||||||
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
::delay(0);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
} else if (this->stateWebServer() && !network->isApEnabled() && !network->isStaEnabled()) {
|
|
||||||
this->stopWebServer();
|
|
||||||
Log.straceln(FPSTR(L_PORTAL_WEBSERVER), F("Stopped: AP and STA down"));
|
|
||||||
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
::delay(0);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
// dns server
|
|
||||||
if (!this->stateDnsServer() && this->stateWebServer() && network->isApEnabled() && network->hasApClients() && millis() - this->dnsServerChangeState >= this->changeStateInterval) {
|
|
||||||
this->startDnsServer();
|
|
||||||
Log.straceln(FPSTR(L_PORTAL_DNSSERVER), F("Started: AP up"));
|
|
||||||
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
::delay(0);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
} else if (this->stateDnsServer() && (!network->isApEnabled() || !this->stateWebServer())) {
|
|
||||||
this->stopDnsServer();
|
|
||||||
Log.straceln(FPSTR(L_PORTAL_DNSSERVER), F("Stopped: AP down"));
|
|
||||||
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
::delay(0);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this->stateDnsServer()) {
|
|
||||||
this->dnsServer->processNextRequest();
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
::delay(0);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this->stateWebServer()) {
|
|
||||||
this->webServer->handleClient();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bool isNeedAuth() {
|
|
||||||
return !network->isApEnabled() && settings.portal.useAuth && strlen(settings.portal.password);
|
|
||||||
}
|
|
||||||
|
|
||||||
void onCaptivePortal() {
|
|
||||||
const String uri = this->webServer->uri();
|
|
||||||
|
|
||||||
if (uri.equals("/connecttest.txt")) {
|
|
||||||
this->webServer->sendHeader(F("Location"), F("http://logout.net"));
|
|
||||||
this->webServer->send(302);
|
|
||||||
|
|
||||||
Log.straceln(FPSTR(L_PORTAL_CAPTIVE), F("Redirect to http://logout.net with 302 code"));
|
|
||||||
|
|
||||||
} else if (uri.equals("/wpad.dat")) {
|
|
||||||
this->webServer->send(404);
|
|
||||||
|
|
||||||
Log.straceln(FPSTR(L_PORTAL_CAPTIVE), F("Send empty page with 404 code"));
|
|
||||||
|
|
||||||
} else if (uri.equals("/success.txt")) {
|
|
||||||
this->webServer->send(200);
|
|
||||||
|
|
||||||
Log.straceln(FPSTR(L_PORTAL_CAPTIVE), F("Send empty page with 200 code"));
|
|
||||||
|
|
||||||
} else {
|
|
||||||
String portalUrl = "http://" + network->getApIp().toString() + '/';
|
|
||||||
|
|
||||||
this->webServer->sendHeader("Location", portalUrl.c_str());
|
|
||||||
this->webServer->send(302);
|
|
||||||
|
|
||||||
Log.straceln(FPSTR(L_PORTAL_CAPTIVE), F("Redirect to portal page with 302 code"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bool stateWebServer() {
|
|
||||||
return this->webServerEnabled;
|
|
||||||
}
|
|
||||||
|
|
||||||
void startWebServer() {
|
|
||||||
if (this->stateWebServer()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this->webServer->begin();
|
|
||||||
#ifdef ARDUINO_ARCH_ESP8266
|
|
||||||
this->webServer->getServer().setNoDelay(true);
|
|
||||||
#endif
|
|
||||||
this->webServerEnabled = true;
|
|
||||||
this->webServerChangeState = millis();
|
|
||||||
}
|
|
||||||
|
|
||||||
void stopWebServer() {
|
|
||||||
if (!this->stateWebServer()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this->webServer->handleClient();
|
|
||||||
this->webServer->stop();
|
|
||||||
this->webServerEnabled = false;
|
|
||||||
this->webServerChangeState = millis();
|
|
||||||
}
|
|
||||||
|
|
||||||
bool stateDnsServer() {
|
|
||||||
return this->dnsServerEnabled;
|
|
||||||
}
|
|
||||||
|
|
||||||
void startDnsServer() {
|
|
||||||
if (this->stateDnsServer()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this->dnsServer->start(53, "*", network->getApIp());
|
|
||||||
this->dnsServerEnabled = true;
|
|
||||||
this->dnsServerChangeState = millis();
|
|
||||||
}
|
|
||||||
|
|
||||||
void stopDnsServer() {
|
|
||||||
if (!this->stateDnsServer()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this->dnsServer->processNextRequest();
|
|
||||||
this->dnsServer->stop();
|
|
||||||
this->dnsServerEnabled = false;
|
|
||||||
this->dnsServerChangeState = millis();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,346 +0,0 @@
|
|||||||
#include <Equitherm.h>
|
|
||||||
#include <GyverPID.h>
|
|
||||||
#include <PIDtuner.h>
|
|
||||||
|
|
||||||
Equitherm etRegulator;
|
|
||||||
GyverPID pidRegulator(0, 0, 0);
|
|
||||||
PIDtuner pidTuner;
|
|
||||||
|
|
||||||
|
|
||||||
class RegulatorTask : public LeanTask {
|
|
||||||
public:
|
|
||||||
RegulatorTask(bool _enabled = false, unsigned long _interval = 0) : LeanTask(_enabled, _interval) {}
|
|
||||||
|
|
||||||
protected:
|
|
||||||
bool tunerInit = false;
|
|
||||||
byte tunerState = 0;
|
|
||||||
byte tunerRegulator = 0;
|
|
||||||
float prevHeatingTarget = 0;
|
|
||||||
float prevEtResult = 0;
|
|
||||||
float prevPidResult = 0;
|
|
||||||
|
|
||||||
const char* getTaskName() {
|
|
||||||
return "Regulator";
|
|
||||||
}
|
|
||||||
|
|
||||||
/*int getTaskCore() {
|
|
||||||
return 1;
|
|
||||||
}*/
|
|
||||||
|
|
||||||
int getTaskPriority() {
|
|
||||||
return 4;
|
|
||||||
}
|
|
||||||
|
|
||||||
void loop() {
|
|
||||||
byte newTemp = vars.parameters.heatingSetpoint;
|
|
||||||
|
|
||||||
if (vars.states.emergency) {
|
|
||||||
if (settings.heating.turbo) {
|
|
||||||
settings.heating.turbo = false;
|
|
||||||
|
|
||||||
Log.sinfoln(FPSTR(L_REGULATOR), F("Turbo mode auto disabled"));
|
|
||||||
}
|
|
||||||
|
|
||||||
newTemp = getEmergencyModeTemp();
|
|
||||||
|
|
||||||
} else {
|
|
||||||
if (vars.tuning.enable || tunerInit) {
|
|
||||||
if (settings.heating.turbo) {
|
|
||||||
settings.heating.turbo = false;
|
|
||||||
|
|
||||||
Log.sinfoln(FPSTR(L_REGULATOR), F("Turbo mode auto disabled"));
|
|
||||||
}
|
|
||||||
|
|
||||||
newTemp = getTuningModeTemp();
|
|
||||||
|
|
||||||
if (newTemp == 0) {
|
|
||||||
vars.tuning.enable = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!vars.tuning.enable) {
|
|
||||||
if (settings.heating.turbo && (fabs(settings.heating.target - vars.temperatures.indoor) < 1 || !settings.heating.enable || (settings.equitherm.enable && settings.pid.enable))) {
|
|
||||||
settings.heating.turbo = false;
|
|
||||||
|
|
||||||
Log.sinfoln(FPSTR(L_REGULATOR), F("Turbo mode auto disabled"));
|
|
||||||
}
|
|
||||||
|
|
||||||
newTemp = getNormalModeTemp();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ограничиваем, если до этого не ограничило
|
|
||||||
if (newTemp < settings.heating.minTemp || newTemp > settings.heating.maxTemp) {
|
|
||||||
newTemp = constrain(newTemp, settings.heating.minTemp, settings.heating.maxTemp);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (abs(vars.parameters.heatingSetpoint - newTemp) + 0.0001 >= 1) {
|
|
||||||
vars.parameters.heatingSetpoint = newTemp;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
byte getEmergencyModeTemp() {
|
|
||||||
float newTemp = 0;
|
|
||||||
|
|
||||||
// if use equitherm
|
|
||||||
if (settings.emergency.useEquitherm && settings.sensors.outdoor.type != 1) {
|
|
||||||
float etResult = getEquithermTemp(settings.heating.minTemp, settings.heating.maxTemp);
|
|
||||||
|
|
||||||
if (fabs(prevEtResult - etResult) + 0.0001 >= 0.5) {
|
|
||||||
prevEtResult = etResult;
|
|
||||||
newTemp += etResult;
|
|
||||||
|
|
||||||
Log.sinfoln(FPSTR(L_REGULATOR_EQUITHERM), F("New emergency result: %hhu (%.2f)"), (uint8_t) round(etResult), etResult);
|
|
||||||
|
|
||||||
} else {
|
|
||||||
newTemp += prevEtResult;
|
|
||||||
}
|
|
||||||
|
|
||||||
} else if(settings.emergency.usePid && settings.sensors.indoor.type != 1) {
|
|
||||||
if (vars.parameters.heatingEnabled) {
|
|
||||||
float pidResult = getPidTemp(
|
|
||||||
settings.heating.minTemp,
|
|
||||||
settings.heating.maxTemp
|
|
||||||
);
|
|
||||||
|
|
||||||
if (fabs(prevPidResult - pidResult) + 0.0001 >= 0.5) {
|
|
||||||
prevPidResult = pidResult;
|
|
||||||
newTemp += pidResult;
|
|
||||||
|
|
||||||
Log.sinfoln(FPSTR(L_REGULATOR_PID), F("New emergency result: %hhu (%.2f)"), (uint8_t) round(pidResult), pidResult);
|
|
||||||
|
|
||||||
} else {
|
|
||||||
newTemp += prevPidResult;
|
|
||||||
}
|
|
||||||
|
|
||||||
} else if (!vars.parameters.heatingEnabled && prevPidResult != 0) {
|
|
||||||
newTemp += prevPidResult;
|
|
||||||
}
|
|
||||||
|
|
||||||
} else {
|
|
||||||
// default temp, manual mode
|
|
||||||
newTemp = settings.emergency.target;
|
|
||||||
}
|
|
||||||
|
|
||||||
return round(newTemp);
|
|
||||||
}
|
|
||||||
|
|
||||||
byte getNormalModeTemp() {
|
|
||||||
float newTemp = 0;
|
|
||||||
|
|
||||||
if (fabs(prevHeatingTarget - settings.heating.target) > 0.0001) {
|
|
||||||
prevHeatingTarget = settings.heating.target;
|
|
||||||
Log.sinfoln(FPSTR(L_REGULATOR), F("New target: %.2f"), settings.heating.target);
|
|
||||||
|
|
||||||
if (settings.equitherm.enable && settings.pid.enable) {
|
|
||||||
pidRegulator.integral = 0;
|
|
||||||
Log.sinfoln(FPSTR(L_REGULATOR_PID), F("Integral sum has been reset"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// if use equitherm
|
|
||||||
if (settings.equitherm.enable) {
|
|
||||||
float etResult = getEquithermTemp(settings.heating.minTemp, settings.heating.maxTemp);
|
|
||||||
|
|
||||||
if (fabs(prevEtResult - etResult) + 0.0001 >= 0.5) {
|
|
||||||
prevEtResult = etResult;
|
|
||||||
newTemp += etResult;
|
|
||||||
|
|
||||||
Log.sinfoln(FPSTR(L_REGULATOR_EQUITHERM), F("New result: %hhu (%.2f)"), (uint8_t) round(etResult), etResult);
|
|
||||||
|
|
||||||
} else {
|
|
||||||
newTemp += prevEtResult;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// if use pid
|
|
||||||
if (settings.pid.enable) {
|
|
||||||
if (vars.parameters.heatingEnabled) {
|
|
||||||
float pidResult = getPidTemp(
|
|
||||||
settings.equitherm.enable ? (settings.pid.maxTemp * -1) : settings.pid.minTemp,
|
|
||||||
settings.pid.maxTemp
|
|
||||||
);
|
|
||||||
|
|
||||||
if (fabs(prevPidResult - pidResult) + 0.0001 >= 0.5) {
|
|
||||||
prevPidResult = pidResult;
|
|
||||||
newTemp += pidResult;
|
|
||||||
|
|
||||||
Log.sinfoln(FPSTR(L_REGULATOR_PID), F("New result: %hhd (%.2f)"), (int8_t) round(pidResult), pidResult);
|
|
||||||
|
|
||||||
} else {
|
|
||||||
newTemp += prevPidResult;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
newTemp += prevPidResult;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// default temp, manual mode
|
|
||||||
if (!settings.equitherm.enable && !settings.pid.enable) {
|
|
||||||
newTemp = settings.heating.target;
|
|
||||||
}
|
|
||||||
|
|
||||||
newTemp = round(newTemp);
|
|
||||||
newTemp = constrain(newTemp, 0, 100);
|
|
||||||
return newTemp;
|
|
||||||
}
|
|
||||||
|
|
||||||
byte getTuningModeTemp() {
|
|
||||||
if (tunerInit && (!vars.tuning.enable || vars.tuning.regulator != tunerRegulator)) {
|
|
||||||
if (tunerRegulator == 0) {
|
|
||||||
pidTuner.reset();
|
|
||||||
}
|
|
||||||
|
|
||||||
tunerInit = false;
|
|
||||||
tunerRegulator = 0;
|
|
||||||
tunerState = 0;
|
|
||||||
Log.sinfoln("REGULATOR.TUNING", F("Stopped"));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!vars.tuning.enable) {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
if (vars.tuning.regulator == 0) {
|
|
||||||
// @TODO дописать
|
|
||||||
Log.sinfoln("REGULATOR.TUNING.EQUITHERM", F("Not implemented"));
|
|
||||||
return 0;
|
|
||||||
|
|
||||||
} else if (vars.tuning.regulator == 1) {
|
|
||||||
// PID tuner
|
|
||||||
float defaultTemp = settings.equitherm.enable
|
|
||||||
? getEquithermTemp(settings.heating.minTemp, settings.heating.maxTemp)
|
|
||||||
: settings.heating.target;
|
|
||||||
|
|
||||||
if (tunerInit && pidTuner.getState() == 3) {
|
|
||||||
Log.sinfoln("REGULATOR.TUNING.PID", F("Finished"));
|
|
||||||
for (Stream* stream : Log.getStreams()) {
|
|
||||||
pidTuner.debugText(stream);
|
|
||||||
}
|
|
||||||
|
|
||||||
pidTuner.reset();
|
|
||||||
tunerInit = false;
|
|
||||||
tunerRegulator = 0;
|
|
||||||
tunerState = 0;
|
|
||||||
|
|
||||||
if (pidTuner.getAccuracy() < 90) {
|
|
||||||
Log.swarningln("REGULATOR.TUNING.PID", F("Bad result, try again..."));
|
|
||||||
|
|
||||||
} else {
|
|
||||||
settings.pid.p_factor = pidTuner.getPID_p();
|
|
||||||
settings.pid.i_factor = pidTuner.getPID_i();
|
|
||||||
settings.pid.d_factor = pidTuner.getPID_d();
|
|
||||||
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!tunerInit) {
|
|
||||||
Log.sinfoln("REGULATOR.TUNING.PID", F("Start..."));
|
|
||||||
|
|
||||||
float step;
|
|
||||||
if (vars.temperatures.indoor - vars.temperatures.outdoor > 10) {
|
|
||||||
step = ceil(vars.parameters.heatingSetpoint / vars.temperatures.indoor * 2);
|
|
||||||
} else {
|
|
||||||
step = 5.0f;
|
|
||||||
}
|
|
||||||
|
|
||||||
float startTemp = step;
|
|
||||||
Log.sinfoln("REGULATOR.TUNING.PID", F("Started. Start value: %f, step: %f"), startTemp, step);
|
|
||||||
pidTuner.setParameters(NORMAL, startTemp, step, 20 * 60 * 1000, 0.15, 60 * 1000, 10000);
|
|
||||||
tunerInit = true;
|
|
||||||
tunerRegulator = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
pidTuner.setInput(vars.temperatures.indoor);
|
|
||||||
pidTuner.compute();
|
|
||||||
|
|
||||||
if (tunerState > 0 && pidTuner.getState() != tunerState) {
|
|
||||||
Log.sinfoln("REGULATOR.TUNING.PID", F("Log:"));
|
|
||||||
for (Stream* stream : Log.getStreams()) {
|
|
||||||
pidTuner.debugText(stream);
|
|
||||||
}
|
|
||||||
|
|
||||||
tunerState = pidTuner.getState();
|
|
||||||
}
|
|
||||||
|
|
||||||
return round(defaultTemp + pidTuner.getOutput());
|
|
||||||
|
|
||||||
} else {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
float getEquithermTemp(int minTemp, int maxTemp) {
|
|
||||||
if (vars.states.emergency) {
|
|
||||||
etRegulator.Kt = 0;
|
|
||||||
etRegulator.indoorTemp = 0;
|
|
||||||
etRegulator.outdoorTemp = vars.temperatures.outdoor;
|
|
||||||
|
|
||||||
} else if (settings.pid.enable) {
|
|
||||||
etRegulator.Kt = 0;
|
|
||||||
etRegulator.indoorTemp = round(vars.temperatures.indoor);
|
|
||||||
etRegulator.outdoorTemp = round(vars.temperatures.outdoor);
|
|
||||||
|
|
||||||
} else {
|
|
||||||
if (settings.heating.turbo) {
|
|
||||||
etRegulator.Kt = 10;
|
|
||||||
} else {
|
|
||||||
etRegulator.Kt = settings.equitherm.t_factor;
|
|
||||||
}
|
|
||||||
etRegulator.indoorTemp = vars.temperatures.indoor;
|
|
||||||
etRegulator.outdoorTemp = vars.temperatures.outdoor;
|
|
||||||
}
|
|
||||||
|
|
||||||
etRegulator.setLimits(minTemp, maxTemp);
|
|
||||||
etRegulator.Kn = settings.equitherm.n_factor;
|
|
||||||
// etRegulator.Kn = tuneEquithermN(etRegulator.Kn, vars.temperatures.indoor, settings.heating.target, 300, 1800, 0.01, 1);
|
|
||||||
etRegulator.Kk = settings.equitherm.k_factor;
|
|
||||||
etRegulator.targetTemp = vars.states.emergency ? settings.emergency.target : settings.heating.target;
|
|
||||||
|
|
||||||
return etRegulator.getResult();
|
|
||||||
}
|
|
||||||
|
|
||||||
float getPidTemp(int minTemp, int maxTemp) {
|
|
||||||
pidRegulator.Kp = settings.pid.p_factor;
|
|
||||||
pidRegulator.Ki = settings.pid.i_factor;
|
|
||||||
pidRegulator.Kd = settings.pid.d_factor;
|
|
||||||
|
|
||||||
pidRegulator.setLimits(minTemp, maxTemp);
|
|
||||||
pidRegulator.setDt(settings.pid.dt * 1000u);
|
|
||||||
pidRegulator.input = vars.temperatures.indoor;
|
|
||||||
pidRegulator.setpoint = settings.heating.target;
|
|
||||||
|
|
||||||
return pidRegulator.getResultTimer();
|
|
||||||
}
|
|
||||||
|
|
||||||
float tuneEquithermN(float ratio, float currentTemp, float setTemp, unsigned int dirtyInterval = 60, unsigned int accurateInterval = 1800, float accurateStep = 0.01, float accurateStepAfter = 1) {
|
|
||||||
static uint32_t _prevIteration = millis();
|
|
||||||
|
|
||||||
if (abs(currentTemp - setTemp) < accurateStepAfter) {
|
|
||||||
if (millis() - _prevIteration < (accurateInterval * 1000)) {
|
|
||||||
return ratio;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (currentTemp - setTemp > 0.1f) {
|
|
||||||
ratio -= accurateStep;
|
|
||||||
|
|
||||||
} else if (currentTemp - setTemp < -0.1f) {
|
|
||||||
ratio += accurateStep;
|
|
||||||
}
|
|
||||||
|
|
||||||
} else {
|
|
||||||
if (millis() - _prevIteration < (dirtyInterval * 1000)) {
|
|
||||||
return ratio;
|
|
||||||
}
|
|
||||||
|
|
||||||
ratio = ratio * (setTemp / currentTemp);
|
|
||||||
}
|
|
||||||
|
|
||||||
_prevIteration = millis();
|
|
||||||
return ratio;
|
|
||||||
}
|
|
||||||
|
|
||||||
};
|
|
||||||
@@ -1,336 +0,0 @@
|
|||||||
#include <OneWire.h>
|
|
||||||
#include <DallasTemperature.h>
|
|
||||||
|
|
||||||
#if USE_BLE
|
|
||||||
#include <NimBLEDevice.h>
|
|
||||||
#endif
|
|
||||||
|
|
||||||
class SensorsTask : public LeanTask {
|
|
||||||
public:
|
|
||||||
SensorsTask(bool _enabled = false, unsigned long _interval = 0) : LeanTask(_enabled, _interval) {
|
|
||||||
this->oneWireOutdoorSensor = new OneWire();
|
|
||||||
this->outdoorSensor = new DallasTemperature(this->oneWireOutdoorSensor);
|
|
||||||
this->outdoorSensor->setWaitForConversion(false);
|
|
||||||
|
|
||||||
this->oneWireIndoorSensor = new OneWire();
|
|
||||||
this->indoorSensor = new DallasTemperature(this->oneWireIndoorSensor);
|
|
||||||
this->indoorSensor->setWaitForConversion(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
~SensorsTask() {
|
|
||||||
delete this->outdoorSensor;
|
|
||||||
delete this->oneWireOutdoorSensor;
|
|
||||||
delete this->indoorSensor;
|
|
||||||
delete this->oneWireIndoorSensor;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected:
|
|
||||||
OneWire* oneWireOutdoorSensor = nullptr;
|
|
||||||
OneWire* oneWireIndoorSensor = nullptr;
|
|
||||||
|
|
||||||
DallasTemperature* outdoorSensor = nullptr;
|
|
||||||
DallasTemperature* indoorSensor = nullptr;
|
|
||||||
|
|
||||||
bool initOutdoorSensor = false;
|
|
||||||
unsigned long startOutdoorConversionTime = 0;
|
|
||||||
float filteredOutdoorTemp = 0;
|
|
||||||
bool emptyOutdoorTemp = true;
|
|
||||||
|
|
||||||
bool initIndoorSensor = false;
|
|
||||||
unsigned long startIndoorConversionTime = 0;
|
|
||||||
float filteredIndoorTemp = 0;
|
|
||||||
bool emptyIndoorTemp = true;
|
|
||||||
|
|
||||||
#if USE_BLE
|
|
||||||
BLEClient* pBleClient = nullptr;
|
|
||||||
bool initBleSensor = false;
|
|
||||||
bool initBleNotify = false;
|
|
||||||
#endif
|
|
||||||
|
|
||||||
const char* getTaskName() {
|
|
||||||
return "Sensors";
|
|
||||||
}
|
|
||||||
|
|
||||||
/*int getTaskCore() {
|
|
||||||
return 1;
|
|
||||||
}*/
|
|
||||||
|
|
||||||
int getTaskPriority() {
|
|
||||||
return 4;
|
|
||||||
}
|
|
||||||
|
|
||||||
void loop() {
|
|
||||||
if (settings.sensors.outdoor.type == 2 && settings.sensors.outdoor.pin) {
|
|
||||||
outdoorTemperatureSensor();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (settings.sensors.indoor.type == 2 && settings.sensors.indoor.pin) {
|
|
||||||
indoorTemperatureSensor();
|
|
||||||
}
|
|
||||||
|
|
||||||
#if USE_BLE
|
|
||||||
if (settings.sensors.indoor.type == 3) {
|
|
||||||
bluetoothSensor();
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
if (fabs(vars.temperatures.outdoor - this->filteredOutdoorTemp) > 0.099) {
|
|
||||||
vars.temperatures.outdoor = this->filteredOutdoorTemp + settings.sensors.outdoor.offset;
|
|
||||||
Log.sinfoln(FPSTR(L_SENSORS_OUTDOOR), F("New temp: %f"), vars.temperatures.outdoor);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (fabs(vars.temperatures.indoor - this->filteredIndoorTemp) > 0.099) {
|
|
||||||
vars.temperatures.indoor = this->filteredIndoorTemp + settings.sensors.indoor.offset;
|
|
||||||
Log.sinfoln(FPSTR(L_SENSORS_INDOOR), F("New temp: %f"), vars.temperatures.indoor);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#if USE_BLE
|
|
||||||
void bluetoothSensor() {
|
|
||||||
static bool initBleNotify = false;
|
|
||||||
if (!initBleSensor && millis() > 5000) {
|
|
||||||
Log.sinfoln(FPSTR(L_SENSORS_BLE), F("Init BLE"));
|
|
||||||
BLEDevice::init("");
|
|
||||||
|
|
||||||
pBleClient = BLEDevice::createClient();
|
|
||||||
pBleClient->setConnectTimeout(5);
|
|
||||||
|
|
||||||
initBleSensor = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!initBleSensor || pBleClient->isConnected()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reset init notify flag
|
|
||||||
this->initBleNotify = false;
|
|
||||||
|
|
||||||
// Connect to the remote BLE Server.
|
|
||||||
BLEAddress bleServerAddress(settings.sensors.indoor.bleAddresss);
|
|
||||||
if (!pBleClient->connect(bleServerAddress)) {
|
|
||||||
Log.swarningln(FPSTR(L_SENSORS_BLE), "Failed connecting to device at %s", bleServerAddress.toString().c_str());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
Log.sinfoln(FPSTR(L_SENSORS_BLE), "Connected to device at %s", bleServerAddress.toString().c_str());
|
|
||||||
|
|
||||||
NimBLEUUID serviceUUID((uint16_t) 0x181AU);
|
|
||||||
BLERemoteService* pRemoteService = pBleClient->getService(serviceUUID);
|
|
||||||
if (!pRemoteService) {
|
|
||||||
Log.straceln(FPSTR(L_SENSORS_BLE), F("Failed to find service UUID: %s"), serviceUUID.toString().c_str());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
Log.straceln(FPSTR(L_SENSORS_BLE), F("Found service UUID: %s"), serviceUUID.toString().c_str());
|
|
||||||
|
|
||||||
// 0x2A6E - Notify temperature x0.01C (pvvx)
|
|
||||||
if (!this->initBleNotify) {
|
|
||||||
NimBLEUUID charUUID((uint16_t) 0x2A6E);
|
|
||||||
BLERemoteCharacteristic* pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID);
|
|
||||||
if (pRemoteCharacteristic && pRemoteCharacteristic->canNotify()) {
|
|
||||||
Log.straceln(FPSTR(L_SENSORS_BLE), F("Found characteristic UUID: %s"), charUUID.toString().c_str());
|
|
||||||
|
|
||||||
this->initBleNotify = pRemoteCharacteristic->subscribe(true, [this](NimBLERemoteCharacteristic*, uint8_t* pData, size_t length, bool isNotify) {
|
|
||||||
if (length != 2) {
|
|
||||||
Log.swarningln(FPSTR(L_SENSORS_BLE), F("Invalid notification data"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
float rawTemp = ((pData[0] | (pData[1] << 8)) * 0.01);
|
|
||||||
Log.straceln(FPSTR(L_SENSORS_INDOOR), F("Raw temp: %f"), rawTemp);
|
|
||||||
|
|
||||||
if (this->emptyIndoorTemp) {
|
|
||||||
this->filteredIndoorTemp = rawTemp;
|
|
||||||
this->emptyIndoorTemp = false;
|
|
||||||
|
|
||||||
} else {
|
|
||||||
this->filteredIndoorTemp += (rawTemp - this->filteredIndoorTemp) * EXT_SENSORS_FILTER_K;
|
|
||||||
}
|
|
||||||
|
|
||||||
this->filteredIndoorTemp = floor(this->filteredIndoorTemp * 100) / 100;
|
|
||||||
});
|
|
||||||
|
|
||||||
if (this->initBleNotify) {
|
|
||||||
Log.straceln(FPSTR(L_SENSORS_BLE), F("Subscribed to characteristic UUID: %s"), charUUID.toString().c_str());
|
|
||||||
|
|
||||||
} else {
|
|
||||||
Log.swarningln(FPSTR(L_SENSORS_BLE), F("Failed to subscribe to characteristic UUID: %s"), charUUID.toString().c_str());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 0x2A1F - Notify temperature x0.1C (atc1441/pvvx)
|
|
||||||
if (!this->initBleNotify) {
|
|
||||||
NimBLEUUID charUUID((uint16_t) 0x2A1F);
|
|
||||||
BLERemoteCharacteristic* pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID);
|
|
||||||
if (pRemoteCharacteristic && pRemoteCharacteristic->canNotify()) {
|
|
||||||
Log.straceln(FPSTR(L_SENSORS_BLE), F("Found characteristic UUID: %s"), charUUID.toString().c_str());
|
|
||||||
|
|
||||||
this->initBleNotify = pRemoteCharacteristic->subscribe(true, [this](NimBLERemoteCharacteristic*, uint8_t* pData, size_t length, bool isNotify) {
|
|
||||||
if (length != 2) {
|
|
||||||
Log.swarningln(FPSTR(L_SENSORS_BLE), F("Invalid notification data"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
float rawTemp = ((pData[0] | (pData[1] << 8)) * 0.1);
|
|
||||||
Log.straceln(FPSTR(L_SENSORS_INDOOR), F("Raw temp: %f"), rawTemp);
|
|
||||||
|
|
||||||
if (this->emptyIndoorTemp) {
|
|
||||||
this->filteredIndoorTemp = rawTemp;
|
|
||||||
this->emptyIndoorTemp = false;
|
|
||||||
|
|
||||||
} else {
|
|
||||||
this->filteredIndoorTemp += (rawTemp - this->filteredIndoorTemp) * EXT_SENSORS_FILTER_K;
|
|
||||||
}
|
|
||||||
|
|
||||||
this->filteredIndoorTemp = floor(this->filteredIndoorTemp * 100) / 100;
|
|
||||||
});
|
|
||||||
|
|
||||||
if (this->initBleNotify) {
|
|
||||||
Log.straceln(FPSTR(L_SENSORS_BLE), F("Subscribed to characteristic UUID: %s"), charUUID.toString().c_str());
|
|
||||||
|
|
||||||
} else {
|
|
||||||
Log.swarningln(FPSTR(L_SENSORS_BLE), F("Failed to subscribe to characteristic UUID: %s"), charUUID.toString().c_str());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!this->initBleNotify) {
|
|
||||||
Log.swarningln(FPSTR(L_SENSORS_BLE), F("Not found supported characteristics"));
|
|
||||||
pBleClient->disconnect();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
void outdoorTemperatureSensor() {
|
|
||||||
if (!this->initOutdoorSensor) {
|
|
||||||
Log.sinfoln(FPSTR(L_SENSORS_OUTDOOR), F("Starting on gpio %hhu..."), settings.sensors.outdoor.pin);
|
|
||||||
|
|
||||||
this->oneWireOutdoorSensor->begin(settings.sensors.outdoor.pin);
|
|
||||||
this->outdoorSensor->begin();
|
|
||||||
|
|
||||||
Log.straceln(
|
|
||||||
FPSTR(L_SENSORS_OUTDOOR),
|
|
||||||
F("Devices on bus: %hhu, DS18* devices: %hhu"),
|
|
||||||
this->outdoorSensor->getDeviceCount(),
|
|
||||||
this->outdoorSensor->getDS18Count()
|
|
||||||
);
|
|
||||||
|
|
||||||
if (this->outdoorSensor->getDeviceCount() > 0) {
|
|
||||||
this->initOutdoorSensor = true;
|
|
||||||
this->outdoorSensor->setResolution(12);
|
|
||||||
this->outdoorSensor->requestTemperatures();
|
|
||||||
this->startOutdoorConversionTime = millis();
|
|
||||||
|
|
||||||
Log.sinfoln(FPSTR(L_SENSORS_OUTDOOR), F("Started"));
|
|
||||||
|
|
||||||
} else {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
unsigned long estimateConversionTime = millis() - this->startOutdoorConversionTime;
|
|
||||||
if (estimateConversionTime < this->outdoorSensor->millisToWaitForConversion()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool completed = this->outdoorSensor->isConversionComplete();
|
|
||||||
if (!completed && estimateConversionTime >= 1000) {
|
|
||||||
this->initOutdoorSensor = false;
|
|
||||||
|
|
||||||
Log.serrorln(FPSTR(L_SENSORS_OUTDOOR), F("Could not read temperature data (no response)"));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!completed) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
float rawTemp = this->outdoorSensor->getTempCByIndex(0);
|
|
||||||
if (rawTemp == DEVICE_DISCONNECTED_C) {
|
|
||||||
this->initOutdoorSensor = false;
|
|
||||||
|
|
||||||
Log.serrorln(FPSTR(L_SENSORS_OUTDOOR), F("Could not read temperature data (not connected)"));
|
|
||||||
|
|
||||||
} else {
|
|
||||||
Log.straceln(FPSTR(L_SENSORS_OUTDOOR), F("Raw temp: %f"), rawTemp);
|
|
||||||
|
|
||||||
if (this->emptyOutdoorTemp) {
|
|
||||||
this->filteredOutdoorTemp = rawTemp;
|
|
||||||
this->emptyOutdoorTemp = false;
|
|
||||||
|
|
||||||
} else {
|
|
||||||
this->filteredOutdoorTemp += (rawTemp - this->filteredOutdoorTemp) * EXT_SENSORS_FILTER_K;
|
|
||||||
}
|
|
||||||
|
|
||||||
this->filteredOutdoorTemp = floor(this->filteredOutdoorTemp * 100) / 100;
|
|
||||||
this->outdoorSensor->requestTemperatures();
|
|
||||||
this->startOutdoorConversionTime = millis();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void indoorTemperatureSensor() {
|
|
||||||
if (!this->initIndoorSensor) {
|
|
||||||
Log.sinfoln(FPSTR(L_SENSORS_INDOOR), F("Starting on gpio %hhu..."), settings.sensors.indoor.pin);
|
|
||||||
|
|
||||||
this->oneWireIndoorSensor->begin(settings.sensors.indoor.pin);
|
|
||||||
this->indoorSensor->begin();
|
|
||||||
|
|
||||||
Log.straceln(
|
|
||||||
FPSTR(L_SENSORS_INDOOR),
|
|
||||||
F("Devices on bus: %hhu, DS18* devices: %hhu"),
|
|
||||||
this->indoorSensor->getDeviceCount(),
|
|
||||||
this->indoorSensor->getDS18Count()
|
|
||||||
);
|
|
||||||
|
|
||||||
if (this->indoorSensor->getDeviceCount() > 0) {
|
|
||||||
this->initIndoorSensor = true;
|
|
||||||
this->indoorSensor->setResolution(12);
|
|
||||||
this->indoorSensor->requestTemperatures();
|
|
||||||
this->startIndoorConversionTime = millis();
|
|
||||||
|
|
||||||
Log.sinfoln(FPSTR(L_SENSORS_INDOOR), F("Started"));
|
|
||||||
|
|
||||||
} else {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
unsigned long estimateConversionTime = millis() - this->startIndoorConversionTime;
|
|
||||||
if (estimateConversionTime < this->indoorSensor->millisToWaitForConversion()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool completed = this->indoorSensor->isConversionComplete();
|
|
||||||
if (!completed && estimateConversionTime >= 1000) {
|
|
||||||
this->initIndoorSensor = false;
|
|
||||||
|
|
||||||
Log.serrorln(FPSTR(L_SENSORS_INDOOR), F("Could not read temperature data (no response)"));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!completed) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
float rawTemp = this->indoorSensor->getTempCByIndex(0);
|
|
||||||
if (rawTemp == DEVICE_DISCONNECTED_C) {
|
|
||||||
this->initIndoorSensor = false;
|
|
||||||
|
|
||||||
Log.serrorln(FPSTR(L_SENSORS_INDOOR), F("Could not read temperature data (not connected)"));
|
|
||||||
|
|
||||||
} else {
|
|
||||||
Log.straceln(FPSTR(L_SENSORS_INDOOR), F("Raw temp: %f"), rawTemp);
|
|
||||||
|
|
||||||
if (this->emptyIndoorTemp) {
|
|
||||||
this->filteredIndoorTemp = rawTemp;
|
|
||||||
this->emptyIndoorTemp = false;
|
|
||||||
|
|
||||||
} else {
|
|
||||||
this->filteredIndoorTemp += (rawTemp - this->filteredIndoorTemp) * EXT_SENSORS_FILTER_K;
|
|
||||||
}
|
|
||||||
|
|
||||||
this->filteredIndoorTemp = floor(this->filteredIndoorTemp * 100) / 100;
|
|
||||||
this->indoorSensor->requestTemperatures();
|
|
||||||
this->startIndoorConversionTime = millis();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,187 +0,0 @@
|
|||||||
struct NetworkSettings {
|
|
||||||
char hostname[25] = HOSTNAME_DEFAULT;
|
|
||||||
bool useDhcp = true;
|
|
||||||
|
|
||||||
struct {
|
|
||||||
char ip[16] = "192.168.0.100";
|
|
||||||
char gateway[16] = "192.168.0.1";
|
|
||||||
char subnet[16] = "255.255.255.0";
|
|
||||||
char dns[16] = "192.168.0.1";
|
|
||||||
} staticConfig;
|
|
||||||
|
|
||||||
struct {
|
|
||||||
char ssid[33] = AP_SSID_DEFAULT;
|
|
||||||
char password[65] = AP_PASSWORD_DEFAULT;
|
|
||||||
byte channel = 6;
|
|
||||||
} ap;
|
|
||||||
|
|
||||||
struct {
|
|
||||||
char ssid[33] = STA_SSID_DEFAULT;
|
|
||||||
char password[65] = STA_PASSWORD_DEFAULT;
|
|
||||||
byte channel = 0;
|
|
||||||
} sta;
|
|
||||||
} networkSettings;
|
|
||||||
|
|
||||||
struct Settings {
|
|
||||||
struct {
|
|
||||||
bool debug = DEBUG_BY_DEFAULT;
|
|
||||||
bool useSerial = USE_SERIAL;
|
|
||||||
bool useTelnet = USE_TELNET;
|
|
||||||
} system;
|
|
||||||
|
|
||||||
struct {
|
|
||||||
bool useAuth = false;
|
|
||||||
char login[13] = PORTAL_LOGIN_DEFAULT;
|
|
||||||
char password[33] = PORTAL_PASSWORD_DEFAULT;
|
|
||||||
} portal;
|
|
||||||
|
|
||||||
struct {
|
|
||||||
byte inPin = OT_IN_PIN_DEFAULT;
|
|
||||||
byte outPin = OT_OUT_PIN_DEFAULT;
|
|
||||||
unsigned int memberIdCode = 0;
|
|
||||||
bool dhwPresent = true;
|
|
||||||
bool summerWinterMode = false;
|
|
||||||
bool heatingCh2Enabled = true;
|
|
||||||
bool heatingCh1ToCh2 = false;
|
|
||||||
bool dhwToCh2 = false;
|
|
||||||
bool dhwBlocking = false;
|
|
||||||
bool modulationSyncWithHeating = false;
|
|
||||||
} opentherm;
|
|
||||||
|
|
||||||
struct {
|
|
||||||
char server[81] = MQTT_SERVER_DEFAULT;
|
|
||||||
unsigned short port = MQTT_PORT_DEFAULT;
|
|
||||||
char user[33] = MQTT_USER_DEFAULT;
|
|
||||||
char password[33] = MQTT_PASSWORD_DEFAULT;
|
|
||||||
char prefix[33] = MQTT_PREFIX_DEFAULT;
|
|
||||||
unsigned short interval = 5;
|
|
||||||
} mqtt;
|
|
||||||
|
|
||||||
struct {
|
|
||||||
bool enable = true;
|
|
||||||
float target = 40.0f;
|
|
||||||
bool useEquitherm = false;
|
|
||||||
bool usePid = false;
|
|
||||||
} emergency;
|
|
||||||
|
|
||||||
struct {
|
|
||||||
bool enable = true;
|
|
||||||
bool turbo = false;
|
|
||||||
float target = 40.0f;
|
|
||||||
float hysteresis = 0.5f;
|
|
||||||
byte minTemp = DEFAULT_HEATING_MIN_TEMP;
|
|
||||||
byte maxTemp = DEFAULT_HEATING_MAX_TEMP;
|
|
||||||
byte maxModulation = 100;
|
|
||||||
} heating;
|
|
||||||
|
|
||||||
struct {
|
|
||||||
bool enable = true;
|
|
||||||
byte target = 40;
|
|
||||||
byte minTemp = DEFAULT_DHW_MIN_TEMP;
|
|
||||||
byte maxTemp = DEFAULT_DHW_MAX_TEMP;
|
|
||||||
} dhw;
|
|
||||||
|
|
||||||
struct {
|
|
||||||
bool enable = false;
|
|
||||||
float p_factor = 50;
|
|
||||||
float i_factor = 0.006f;
|
|
||||||
float d_factor = 10000;
|
|
||||||
unsigned short dt = 180;
|
|
||||||
byte minTemp = 0;
|
|
||||||
byte maxTemp = DEFAULT_HEATING_MAX_TEMP;
|
|
||||||
} pid;
|
|
||||||
|
|
||||||
struct {
|
|
||||||
bool enable = false;
|
|
||||||
float n_factor = 0.7f;
|
|
||||||
float k_factor = 3.0f;
|
|
||||||
float t_factor = 2.0f;
|
|
||||||
} equitherm;
|
|
||||||
|
|
||||||
struct {
|
|
||||||
struct {
|
|
||||||
// 0 - boiler, 1 - manual, 2 - ds18b20
|
|
||||||
byte type = 0;
|
|
||||||
byte pin = SENSOR_OUTDOOR_PIN_DEFAULT;
|
|
||||||
float offset = 0.0f;
|
|
||||||
} outdoor;
|
|
||||||
|
|
||||||
struct {
|
|
||||||
// 1 - manual, 2 - ds18b20, 3 - ble
|
|
||||||
byte type = 1;
|
|
||||||
byte pin = SENSOR_INDOOR_PIN_DEFAULT;
|
|
||||||
uint8_t bleAddresss[6] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
|
|
||||||
float offset = 0.0f;
|
|
||||||
} indoor;
|
|
||||||
} sensors;
|
|
||||||
|
|
||||||
struct {
|
|
||||||
bool use = false;
|
|
||||||
byte pin = EXT_PUMP_PIN_DEFAULT;
|
|
||||||
unsigned short postCirculationTime = 600;
|
|
||||||
unsigned int antiStuckInterval = 2592000;
|
|
||||||
unsigned short antiStuckTime = 300;
|
|
||||||
} externalPump;
|
|
||||||
|
|
||||||
char validationValue[8] = SETTINGS_VALID_VALUE;
|
|
||||||
} settings;
|
|
||||||
|
|
||||||
struct Variables {
|
|
||||||
struct {
|
|
||||||
bool enable = false;
|
|
||||||
byte regulator = 0;
|
|
||||||
} tuning;
|
|
||||||
|
|
||||||
struct {
|
|
||||||
bool otStatus = false;
|
|
||||||
bool emergency = false;
|
|
||||||
bool heating = false;
|
|
||||||
bool dhw = false;
|
|
||||||
bool flame = false;
|
|
||||||
bool fault = false;
|
|
||||||
bool diagnostic = false;
|
|
||||||
bool externalPump = false;
|
|
||||||
} states;
|
|
||||||
|
|
||||||
struct {
|
|
||||||
float modulation = 0.0f;
|
|
||||||
float pressure = 0.0f;
|
|
||||||
float dhwFlowRate = 0.0f;
|
|
||||||
byte faultCode = 0;
|
|
||||||
int8_t rssi = 0;
|
|
||||||
} sensors;
|
|
||||||
|
|
||||||
struct {
|
|
||||||
float indoor = 0.0f;
|
|
||||||
float outdoor = 0.0f;
|
|
||||||
float heating = 0.0f;
|
|
||||||
float dhw = 0.0f;
|
|
||||||
} temperatures;
|
|
||||||
|
|
||||||
struct {
|
|
||||||
bool heatingEnabled = false;
|
|
||||||
byte heatingMinTemp = DEFAULT_HEATING_MIN_TEMP;
|
|
||||||
byte heatingMaxTemp = DEFAULT_HEATING_MAX_TEMP;
|
|
||||||
byte heatingSetpoint = 0;
|
|
||||||
unsigned long extPumpLastEnableTime = 0;
|
|
||||||
byte dhwMinTemp = DEFAULT_DHW_MIN_TEMP;
|
|
||||||
byte dhwMaxTemp = DEFAULT_DHW_MAX_TEMP;
|
|
||||||
byte maxModulation = 0;
|
|
||||||
uint8_t slaveMemberId = 0;
|
|
||||||
uint8_t slaveFlags = 0;
|
|
||||||
uint8_t slaveType = 0;
|
|
||||||
uint8_t slaveVersion = 0;
|
|
||||||
float slaveOtVersion = 0.0f;
|
|
||||||
uint8_t masterMemberId = 0;
|
|
||||||
uint8_t masterFlags = 0;
|
|
||||||
uint8_t masterType = 0;
|
|
||||||
uint8_t masterVersion = 0;
|
|
||||||
float masterOtVersion = 0;
|
|
||||||
} parameters;
|
|
||||||
|
|
||||||
struct {
|
|
||||||
bool restart = false;
|
|
||||||
bool resetFault = false;
|
|
||||||
bool resetDiagnostic = false;
|
|
||||||
} actions;
|
|
||||||
} vars;
|
|
||||||
@@ -0,0 +1,455 @@
|
|||||||
|
#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE
|
||||||
|
|
||||||
|
#include <app.h>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
|
||||||
|
Variables vars;
|
||||||
|
|
||||||
|
enum class PumpStartReason {NONE, HEATING, ANTISTUCK};
|
||||||
|
|
||||||
|
static bool heatingEnabled = false;
|
||||||
|
static unsigned long heatingDisabledTime = 0;
|
||||||
|
static PumpStartReason extPumpStartReason = PumpStartReason::NONE;
|
||||||
|
static unsigned long externalPumpStartTime = 0;
|
||||||
|
static bool emergencyDetected = false;
|
||||||
|
static unsigned long emergencyFlipTime = 0;
|
||||||
|
|
||||||
|
static Task freezeProtectionTask("Freeze protection", [](void*) {
|
||||||
|
float lowTemp = 255.0f;
|
||||||
|
uint8_t availableSensors = 0;
|
||||||
|
|
||||||
|
if (Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::INDOOR_TEMP)) {
|
||||||
|
auto value = Sensors::getMeanValueByPurpose(Sensors::Purpose::INDOOR_TEMP, Sensors::ValueType::PRIMARY, settings.heating.indoorTempAvgType);
|
||||||
|
if (value < lowTemp) {
|
||||||
|
lowTemp = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
availableSensors++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::HEATING_TEMP)) {
|
||||||
|
auto value = Sensors::getMeanValueByPurpose(Sensors::Purpose::HEATING_TEMP, Sensors::ValueType::PRIMARY);
|
||||||
|
if (value < lowTemp) {
|
||||||
|
lowTemp = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
availableSensors++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::HEATING_RETURN_TEMP)) {
|
||||||
|
auto value = Sensors::getMeanValueByPurpose(Sensors::Purpose::HEATING_RETURN_TEMP, Sensors::ValueType::PRIMARY);
|
||||||
|
if (value < lowTemp) {
|
||||||
|
lowTemp = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
availableSensors++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (availableSensors) {
|
||||||
|
if (vars.master.heating.freezing) {
|
||||||
|
if (lowTemp - static_cast<float>(settings.heating.freezeProtection.highTemp) + 0.0001f >= 0.0f) {
|
||||||
|
vars.master.heating.freezing = false;
|
||||||
|
|
||||||
|
ESP_LOGI(
|
||||||
|
L_MAIN,
|
||||||
|
"No freezing detected. Current low temp: %.2f, threshold (high): %hhu",
|
||||||
|
lowTemp, settings.heating.freezeProtection.highTemp
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
} else {
|
||||||
|
if (static_cast<float>(settings.heating.freezeProtection.lowTemp) - lowTemp + 0.0001f >= 0.0f) {
|
||||||
|
vars.master.heating.freezing = true;
|
||||||
|
|
||||||
|
if (!settings.heating.enabled) {
|
||||||
|
settings.heating.enabled = true;
|
||||||
|
requestSaveSettings();
|
||||||
|
}
|
||||||
|
|
||||||
|
ESP_LOGI(
|
||||||
|
L_MAIN,
|
||||||
|
"Freezing detected! Current low temp: %.2f, threshold (low): %hhu",
|
||||||
|
lowTemp, settings.heating.freezeProtection.lowTemp
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} else if (vars.master.heating.freezing) {
|
||||||
|
vars.master.heating.freezing = false;
|
||||||
|
|
||||||
|
ESP_LOGI(L_MAIN, "No sensors available, freeze protection unavailable!");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
static Task emergencyTask("Emergency mode", [](void*) {
|
||||||
|
// flags
|
||||||
|
uint8_t emergencyFlags = 0b00000000;
|
||||||
|
|
||||||
|
// set outdoor sensor flag
|
||||||
|
if (settings.equitherm.enabled) {
|
||||||
|
if (!Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::OUTDOOR_TEMP)) {
|
||||||
|
emergencyFlags |= 0b00000001;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// set indoor sensor flags
|
||||||
|
if (!Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::INDOOR_TEMP)) {
|
||||||
|
if (!settings.equitherm.enabled && settings.pid.enabled) {
|
||||||
|
emergencyFlags |= 0b00000010;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (settings.opentherm.options.nativeOTC) {
|
||||||
|
emergencyFlags |= 0b00000100;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// if any flags is true
|
||||||
|
if ((emergencyFlags & 0b00001111) != 0) {
|
||||||
|
if (!emergencyDetected) {
|
||||||
|
// flip flag
|
||||||
|
emergencyDetected = true;
|
||||||
|
emergencyFlipTime = millis();
|
||||||
|
|
||||||
|
} else if (emergencyDetected && !vars.emergency.state) {
|
||||||
|
// enable emergency
|
||||||
|
if (millis() - emergencyFlipTime > (settings.emergency.thresholdTime * 1000)) {
|
||||||
|
vars.emergency.state = true;
|
||||||
|
ESP_LOGI(L_MAIN, "Emergency mode enabled (%hhu)", emergencyFlags);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} else {
|
||||||
|
if (emergencyDetected) {
|
||||||
|
// flip flag
|
||||||
|
emergencyDetected = false;
|
||||||
|
emergencyFlipTime = millis();
|
||||||
|
|
||||||
|
} else if (!emergencyDetected && vars.emergency.state) {
|
||||||
|
// disable emergency
|
||||||
|
if (millis() - emergencyFlipTime > (settings.emergency.thresholdTime * 1000)) {
|
||||||
|
vars.emergency.state = false;
|
||||||
|
ESP_LOGI(L_MAIN, "Emergency mode disabled");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
static Task overheatProtectionTask("Overheat protection", [](void*) {
|
||||||
|
// Heating overheat control
|
||||||
|
if (settings.heating.overheatProtection.highTemp > 0 && settings.heating.overheatProtection.lowTemp > 0) {
|
||||||
|
const float highTemp = std::max({
|
||||||
|
vars.slave.heating.currentTemp,
|
||||||
|
vars.slave.heating.returnTemp,
|
||||||
|
vars.slave.heatExchangerTemp
|
||||||
|
});
|
||||||
|
|
||||||
|
if (vars.master.heating.overheat) {
|
||||||
|
if (static_cast<float>(settings.heating.overheatProtection.lowTemp) - highTemp + 0.0001f >= 0.0f) {
|
||||||
|
vars.master.heating.overheat = false;
|
||||||
|
|
||||||
|
ESP_LOGI(
|
||||||
|
L_OT_HEATING, "Overheating not detected. Current high temp: %.2f, threshold (low): %hhu",
|
||||||
|
highTemp, settings.heating.overheatProtection.lowTemp
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
} else if (vars.slave.heating.active) {
|
||||||
|
if (highTemp - static_cast<float>(settings.heating.overheatProtection.highTemp) + 0.0001f >= 0.0f) {
|
||||||
|
vars.master.heating.overheat = true;
|
||||||
|
|
||||||
|
ESP_LOGW(
|
||||||
|
L_OT_HEATING, "Overheating detected! Current high temp: %.2f, threshold (high): %hhu",
|
||||||
|
highTemp, settings.heating.overheatProtection.highTemp
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} else if (vars.master.heating.overheat) {
|
||||||
|
vars.master.heating.overheat = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// DHW overheat control
|
||||||
|
if (settings.dhw.overheatProtection.highTemp > 0 && settings.dhw.overheatProtection.lowTemp > 0) {
|
||||||
|
const float highTemp = std::max({
|
||||||
|
vars.slave.heating.currentTemp,
|
||||||
|
vars.slave.heating.returnTemp,
|
||||||
|
vars.slave.heatExchangerTemp,
|
||||||
|
vars.slave.dhw.currentTemp,
|
||||||
|
vars.slave.dhw.currentTemp2,
|
||||||
|
vars.slave.dhw.returnTemp
|
||||||
|
});
|
||||||
|
|
||||||
|
if (vars.master.dhw.overheat) {
|
||||||
|
if (static_cast<float>(settings.dhw.overheatProtection.lowTemp) - highTemp + 0.0001f >= 0.0f) {
|
||||||
|
vars.master.dhw.overheat = false;
|
||||||
|
|
||||||
|
ESP_LOGI(
|
||||||
|
L_OT_DHW, "Overheating not detected. Current high temp: %.2f, threshold (low): %hhu",
|
||||||
|
highTemp, settings.dhw.overheatProtection.lowTemp
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
} else if (vars.slave.dhw.active) {
|
||||||
|
if (highTemp - static_cast<float>(settings.dhw.overheatProtection.highTemp) + 0.0001f >= 0.0f) {
|
||||||
|
vars.master.dhw.overheat = true;
|
||||||
|
|
||||||
|
ESP_LOGW(
|
||||||
|
L_OT_DHW, "Overheating detected! Current high temp: %.2f, threshold (high): %hhu",
|
||||||
|
highTemp, settings.dhw.overheatProtection.highTemp
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} else if (vars.master.dhw.overheat) {
|
||||||
|
vars.master.dhw.overheat = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
static Task cascadeTask("Cascade", [](void*) {
|
||||||
|
static uint8_t configuredInputGpio = GPIO_IS_NOT_CONFIGURED;
|
||||||
|
static uint8_t configuredOutputGpio = GPIO_IS_NOT_CONFIGURED;
|
||||||
|
static bool pendingInputState = false;
|
||||||
|
static unsigned long inputChangedTime = 0;
|
||||||
|
static bool pendingOutputState = false;
|
||||||
|
static unsigned long outputChangedTime = 0;
|
||||||
|
|
||||||
|
// input
|
||||||
|
if (settings.cascadeControl.input.enabled) {
|
||||||
|
if (settings.cascadeControl.input.gpio != configuredInputGpio) {
|
||||||
|
if (configuredInputGpio != GPIO_IS_NOT_CONFIGURED) {
|
||||||
|
// Keep the old input high-impedance, including input-only GPIOs.
|
||||||
|
pinMode(configuredInputGpio, INPUT);
|
||||||
|
|
||||||
|
ESP_LOGI(L_CASCADE_INPUT, "Deinitialized on GPIO %hhu", configuredInputGpio);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (GPIO_IS_VALID_INPUT(settings.cascadeControl.input.gpio)) {
|
||||||
|
configuredInputGpio = settings.cascadeControl.input.gpio;
|
||||||
|
pinMode(configuredInputGpio, INPUT);
|
||||||
|
|
||||||
|
ESP_LOGI(L_CASCADE_INPUT, "Initialized on GPIO %hhu", configuredInputGpio);
|
||||||
|
|
||||||
|
} else if (configuredInputGpio != GPIO_IS_NOT_CONFIGURED) {
|
||||||
|
configuredInputGpio = GPIO_IS_NOT_CONFIGURED;
|
||||||
|
|
||||||
|
ESP_LOGW(L_CASCADE_INPUT, "Failed initialize: GPIO %hhu is not valid!", configuredInputGpio);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (configuredInputGpio != GPIO_IS_NOT_CONFIGURED) {
|
||||||
|
bool value = (digitalRead(configuredInputGpio) == HIGH) ^ settings.cascadeControl.input.invertState;
|
||||||
|
|
||||||
|
if (value != vars.cascadeControl.input) {
|
||||||
|
if (value != pendingInputState) {
|
||||||
|
pendingInputState = value;
|
||||||
|
inputChangedTime = millis();
|
||||||
|
|
||||||
|
} else if (millis() - inputChangedTime >= settings.cascadeControl.input.thresholdTime * 1000u) {
|
||||||
|
vars.cascadeControl.input = value;
|
||||||
|
|
||||||
|
ESP_LOGI(
|
||||||
|
L_CASCADE_INPUT,
|
||||||
|
"State changed to %s",
|
||||||
|
value ? "TRUE" : "FALSE"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
} else if (value != pendingInputState) {
|
||||||
|
pendingInputState = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!settings.cascadeControl.input.enabled || configuredInputGpio == GPIO_IS_NOT_CONFIGURED) {
|
||||||
|
if (!vars.cascadeControl.input) {
|
||||||
|
vars.cascadeControl.input = true;
|
||||||
|
|
||||||
|
ESP_LOGI(
|
||||||
|
L_CASCADE_INPUT,
|
||||||
|
"Disabled, state changed to %s",
|
||||||
|
vars.cascadeControl.input ? "TRUE" : "FALSE"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// output
|
||||||
|
if (settings.cascadeControl.output.gpio != configuredOutputGpio) {
|
||||||
|
if (configuredOutputGpio != GPIO_IS_NOT_CONFIGURED) {
|
||||||
|
digitalWrite(configuredOutputGpio, LOW);
|
||||||
|
pinMode(configuredOutputGpio, DISABLED);
|
||||||
|
|
||||||
|
ESP_LOGI(L_CASCADE_OUTPUT, "Deinitialized on GPIO %hhu", configuredOutputGpio);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (GPIO_IS_VALID_OUTPUT(settings.cascadeControl.output.gpio)) {
|
||||||
|
configuredOutputGpio = settings.cascadeControl.output.gpio;
|
||||||
|
pinMode(configuredOutputGpio, OUTPUT);
|
||||||
|
|
||||||
|
ESP_LOGI(L_CASCADE_OUTPUT, "Initialized on GPIO %hhu", configuredOutputGpio);
|
||||||
|
|
||||||
|
} else if (configuredOutputGpio != GPIO_IS_NOT_CONFIGURED) {
|
||||||
|
configuredOutputGpio = GPIO_IS_NOT_CONFIGURED;
|
||||||
|
|
||||||
|
ESP_LOGW(L_CASCADE_OUTPUT, "Failed initialize: GPIO %hhu is not valid!", configuredOutputGpio);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (settings.cascadeControl.output.enabled) {
|
||||||
|
if (configuredOutputGpio != GPIO_IS_NOT_CONFIGURED) {
|
||||||
|
bool value = false;
|
||||||
|
if (settings.cascadeControl.output.onFault && vars.slave.fault.active) {
|
||||||
|
value = true;
|
||||||
|
|
||||||
|
} else if (settings.cascadeControl.output.onLossConnection && !vars.slave.connected) {
|
||||||
|
value = true;
|
||||||
|
|
||||||
|
} else if (settings.cascadeControl.output.onEnabledHeating && settings.heating.enabled && vars.cascadeControl.input) {
|
||||||
|
value = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value != vars.cascadeControl.output) {
|
||||||
|
if (value != pendingOutputState) {
|
||||||
|
pendingOutputState = value;
|
||||||
|
outputChangedTime = millis();
|
||||||
|
|
||||||
|
} else if (millis() - outputChangedTime >= settings.cascadeControl.output.thresholdTime * 1000u) {
|
||||||
|
vars.cascadeControl.output = value;
|
||||||
|
|
||||||
|
ESP_LOGI(
|
||||||
|
L_CASCADE_OUTPUT,
|
||||||
|
"State changed to %s",
|
||||||
|
value ? "TRUE" : "FALSE"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
} else if (value != pendingOutputState) {
|
||||||
|
pendingOutputState = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!settings.cascadeControl.output.enabled || configuredOutputGpio == GPIO_IS_NOT_CONFIGURED) {
|
||||||
|
if (vars.cascadeControl.output) {
|
||||||
|
vars.cascadeControl.output = false;
|
||||||
|
|
||||||
|
ESP_LOGI(
|
||||||
|
L_CASCADE_OUTPUT,
|
||||||
|
"Disabled, state changed to %s",
|
||||||
|
vars.cascadeControl.output ? "TRUE" : "FALSE"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (configuredOutputGpio != GPIO_IS_NOT_CONFIGURED) {
|
||||||
|
digitalWrite(
|
||||||
|
configuredOutputGpio,
|
||||||
|
(vars.cascadeControl.output ^ settings.cascadeControl.output.invertState) ? HIGH : LOW
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
static Task externalPumpTask("External pump", [](void*) {
|
||||||
|
static uint8_t configuredGpio = GPIO_IS_NOT_CONFIGURED;
|
||||||
|
|
||||||
|
if (settings.externalPump.gpio != configuredGpio) {
|
||||||
|
if (configuredGpio != GPIO_IS_NOT_CONFIGURED) {
|
||||||
|
digitalWrite(configuredGpio, LOW);
|
||||||
|
pinMode(configuredGpio, DISABLED);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (GPIO_IS_VALID_OUTPUT(settings.externalPump.gpio)) {
|
||||||
|
configuredGpio = settings.externalPump.gpio;
|
||||||
|
pinMode(configuredGpio, OUTPUT);
|
||||||
|
|
||||||
|
} else if (configuredGpio != GPIO_IS_NOT_CONFIGURED) {
|
||||||
|
configuredGpio = GPIO_IS_NOT_CONFIGURED;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (configuredGpio == GPIO_IS_NOT_CONFIGURED) {
|
||||||
|
if (vars.externalPump.state) {
|
||||||
|
vars.externalPump.state = false;
|
||||||
|
vars.externalPump.lastEnabledTime = millis();
|
||||||
|
|
||||||
|
ESP_LOGI(L_EXTPUMP, "Disabled: use = off");
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!vars.master.heating.enabled && heatingEnabled) {
|
||||||
|
heatingEnabled = false;
|
||||||
|
heatingDisabledTime = millis();
|
||||||
|
|
||||||
|
} else if (vars.master.heating.enabled && !heatingEnabled) {
|
||||||
|
heatingEnabled = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!settings.externalPump.use) {
|
||||||
|
if (vars.externalPump.state) {
|
||||||
|
vars.externalPump.state = false;
|
||||||
|
vars.externalPump.lastEnabledTime = millis();
|
||||||
|
|
||||||
|
ESP_LOGI(L_EXTPUMP, "Disabled: use = off");
|
||||||
|
}
|
||||||
|
|
||||||
|
} else if (vars.externalPump.state && !heatingEnabled) {
|
||||||
|
if (extPumpStartReason == PumpStartReason::HEATING && millis() - heatingDisabledTime > (settings.externalPump.postCirculationTime * 1000u)) {
|
||||||
|
vars.externalPump.state = false;
|
||||||
|
vars.externalPump.lastEnabledTime = millis();
|
||||||
|
|
||||||
|
ESP_LOGI(L_EXTPUMP, "Disabled: expired post circulation time");
|
||||||
|
|
||||||
|
} else if (extPumpStartReason == PumpStartReason::ANTISTUCK && millis() - externalPumpStartTime >= (settings.externalPump.antiStuckTime * 1000u)) {
|
||||||
|
vars.externalPump.state = false;
|
||||||
|
vars.externalPump.lastEnabledTime = millis();
|
||||||
|
|
||||||
|
ESP_LOGI(L_EXTPUMP, "Disabled: expired anti stuck time");
|
||||||
|
}
|
||||||
|
|
||||||
|
} else if (vars.externalPump.state && heatingEnabled && extPumpStartReason == PumpStartReason::ANTISTUCK) {
|
||||||
|
extPumpStartReason = PumpStartReason::HEATING;
|
||||||
|
|
||||||
|
} else if (!vars.externalPump.state && heatingEnabled) {
|
||||||
|
vars.externalPump.state = true;
|
||||||
|
externalPumpStartTime = millis();
|
||||||
|
extPumpStartReason = PumpStartReason::HEATING;
|
||||||
|
|
||||||
|
ESP_LOGI(L_EXTPUMP, "Enabled: heating on");
|
||||||
|
|
||||||
|
} else if (!vars.externalPump.state && (vars.externalPump.lastEnabledTime == 0 || millis() - vars.externalPump.lastEnabledTime >= (settings.externalPump.antiStuckInterval * 1000lu))) {
|
||||||
|
vars.externalPump.state = true;
|
||||||
|
externalPumpStartTime = millis();
|
||||||
|
extPumpStartReason = PumpStartReason::ANTISTUCK;
|
||||||
|
|
||||||
|
ESP_LOGI(L_EXTPUMP, "Enabled: anti stuck");
|
||||||
|
}
|
||||||
|
|
||||||
|
digitalWrite(
|
||||||
|
configuredGpio,
|
||||||
|
(vars.externalPump.state ^ settings.externalPump.invertState) ? HIGH : LOW
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
void initControl() {
|
||||||
|
freezeProtectionTask.setInterval(1000);
|
||||||
|
coreTaskManager.addTask(freezeProtectionTask);
|
||||||
|
|
||||||
|
emergencyTask.setInterval(1000);
|
||||||
|
coreTaskManager.addTask(emergencyTask);
|
||||||
|
|
||||||
|
// The OpenTherm loop previously skipped overheat control while disconnected.
|
||||||
|
overheatProtectionTask.setEnabledWhen([] {
|
||||||
|
return vars.slave.connected;
|
||||||
|
});
|
||||||
|
overheatProtectionTask.setInterval(1000);
|
||||||
|
coreTaskManager.addTask(overheatProtectionTask);
|
||||||
|
|
||||||
|
cascadeTask.setInterval(1000);
|
||||||
|
coreTaskManager.addTask(cascadeTask);
|
||||||
|
|
||||||
|
externalPumpTask.setInterval(1000);
|
||||||
|
coreTaskManager.addTask(externalPumpTask);
|
||||||
|
}
|
||||||
@@ -1,115 +0,0 @@
|
|||||||
#define PROJECT_NAME "OpenTherm Gateway"
|
|
||||||
#define PROJECT_VERSION "1.4.0-rc.15"
|
|
||||||
#define PROJECT_REPO "https://github.com/Laxilef/OTGateway"
|
|
||||||
|
|
||||||
#define EMERGENCY_TIME_TRESHOLD 120000
|
|
||||||
#define MQTT_RECONNECT_INTERVAL 15000
|
|
||||||
#define MQTT_KEEPALIVE 30
|
|
||||||
|
|
||||||
#define OPENTHERM_OFFLINE_TRESHOLD 10
|
|
||||||
|
|
||||||
#define EXT_SENSORS_INTERVAL 5000
|
|
||||||
#define EXT_SENSORS_FILTER_K 0.15
|
|
||||||
|
|
||||||
#define CONFIG_URL "http://%s/"
|
|
||||||
#define SETTINGS_VALID_VALUE "stvalid" // only 8 chars!
|
|
||||||
|
|
||||||
#define DEFAULT_HEATING_MIN_TEMP 20
|
|
||||||
#define DEFAULT_HEATING_MAX_TEMP 90
|
|
||||||
#define DEFAULT_DHW_MIN_TEMP 30
|
|
||||||
#define DEFAULT_DHW_MAX_TEMP 60
|
|
||||||
|
|
||||||
|
|
||||||
#ifndef WM_DEBUG_MODE
|
|
||||||
#define WM_DEBUG_MODE WM_DEBUG_NOTIFY
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef USE_SERIAL
|
|
||||||
#define USE_SERIAL true
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef USE_TELNET
|
|
||||||
#define USE_TELNET true
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef USE_BLE
|
|
||||||
#define USE_BLE false
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef HOSTNAME_DEFAULT
|
|
||||||
#define HOSTNAME_DEFAULT "opentherm"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef AP_SSID_DEFAULT
|
|
||||||
#define AP_SSID_DEFAULT "OpenTherm Gateway"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef AP_PASSWORD_DEFAULT
|
|
||||||
#define AP_PASSWORD_DEFAULT "otgateway123456"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef STA_SSID_DEFAULT
|
|
||||||
#define STA_SSID_DEFAULT ""
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef STA_PASSWORD_DEFAULT
|
|
||||||
#define STA_PASSWORD_DEFAULT ""
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef DEBUG_BY_DEFAULT
|
|
||||||
#define DEBUG_BY_DEFAULT false
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef PORTAL_LOGIN_DEFAULT
|
|
||||||
#define PORTAL_LOGIN_DEFAULT ""
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef PORTAL_PASSWORD_DEFAULT
|
|
||||||
#define PORTAL_PASSWORD_DEFAULT ""
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef MQTT_SERVER_DEFAULT
|
|
||||||
#define MQTT_SERVER_DEFAULT ""
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef MQTT_PORT_DEFAULT
|
|
||||||
#define MQTT_PORT_DEFAULT 1883
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef MQTT_USER_DEFAULT
|
|
||||||
#define MQTT_USER_DEFAULT ""
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef MQTT_PASSWORD_DEFAULT
|
|
||||||
#define MQTT_PASSWORD_DEFAULT ""
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef MQTT_PREFIX_DEFAULT
|
|
||||||
#define MQTT_PREFIX_DEFAULT "opentherm"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef OT_IN_PIN_DEFAULT
|
|
||||||
#define OT_IN_PIN_DEFAULT 0
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef OT_OUT_PIN_DEFAULT
|
|
||||||
#define OT_OUT_PIN_DEFAULT 0
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef SENSOR_OUTDOOR_PIN_DEFAULT
|
|
||||||
#define SENSOR_OUTDOOR_PIN_DEFAULT 0
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef SENSOR_INDOOR_PIN_DEFAULT
|
|
||||||
#define SENSOR_INDOOR_PIN_DEFAULT 0
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef EXT_PUMP_PIN_DEFAULT
|
|
||||||
#define EXT_PUMP_PIN_DEFAULT 0
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef PROGMEM
|
|
||||||
#define PROGMEM
|
|
||||||
#endif
|
|
||||||
|
|
||||||
char buffer[255];
|
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE
|
||||||
|
|
||||||
|
#include <app.h>
|
||||||
|
#include <Blinker.h>
|
||||||
|
|
||||||
|
static Blinker blinker;
|
||||||
|
|
||||||
|
static Task ledStatusTask("LED status", [](void*) {
|
||||||
|
uint8_t errors[4];
|
||||||
|
uint8_t errCount = 0;
|
||||||
|
static uint8_t errPos = 0;
|
||||||
|
static unsigned long endBlinkTime = 0;
|
||||||
|
static bool ledOn = false;
|
||||||
|
static uint8_t configuredGpio = GPIO_IS_NOT_CONFIGURED;
|
||||||
|
|
||||||
|
if (settings.system.statusLedGpio != configuredGpio) {
|
||||||
|
if (configuredGpio != GPIO_IS_NOT_CONFIGURED) {
|
||||||
|
digitalWrite(configuredGpio, LOW);
|
||||||
|
pinMode(configuredGpio, DISABLED);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (GPIO_IS_VALID_OUTPUT(settings.system.statusLedGpio)) {
|
||||||
|
configuredGpio = settings.system.statusLedGpio;
|
||||||
|
pinMode(configuredGpio, OUTPUT);
|
||||||
|
digitalWrite(configuredGpio, LOW);
|
||||||
|
blinker.init(configuredGpio);
|
||||||
|
|
||||||
|
} else if (configuredGpio != GPIO_IS_NOT_CONFIGURED) {
|
||||||
|
configuredGpio = GPIO_IS_NOT_CONFIGURED;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (configuredGpio == GPIO_IS_NOT_CONFIGURED) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isNetworkConnected()) {
|
||||||
|
errors[errCount++] = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!vars.slave.connected) {
|
||||||
|
errors[errCount++] = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (vars.slave.fault.active) {
|
||||||
|
errors[errCount++] = 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (vars.emergency.state) {
|
||||||
|
errors[errCount++] = 5;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if (blinker.ready()) {
|
||||||
|
endBlinkTime = millis();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!blinker.running() && millis() - endBlinkTime >= 5000) {
|
||||||
|
if (errCount == 0) {
|
||||||
|
if (!ledOn) {
|
||||||
|
digitalWrite(configuredGpio, HIGH);
|
||||||
|
ledOn = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
|
||||||
|
} else if (ledOn) {
|
||||||
|
digitalWrite(configuredGpio, LOW);
|
||||||
|
ledOn = false;
|
||||||
|
endBlinkTime = millis();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (errPos >= errCount) {
|
||||||
|
errPos = 0;
|
||||||
|
|
||||||
|
// end of error list
|
||||||
|
blinker.blink(10, 50, 50);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
blinker.blink(errors[errPos++], 300, 300);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
blinker.tick();
|
||||||
|
});
|
||||||
|
|
||||||
|
void initLeds() {
|
||||||
|
ledStatusTask.setInterval(100);
|
||||||
|
coreTaskManager.addTask(ledStatusTask);
|
||||||
|
}
|
||||||
@@ -0,0 +1,239 @@
|
|||||||
|
#include <app.h>
|
||||||
|
|
||||||
|
#include <MycilaWebSerial.h>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <atomic>
|
||||||
|
#include <cstdio>
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <cstring>
|
||||||
|
#include <esp_log_color.h>
|
||||||
|
#include <esp_private/log_format.h>
|
||||||
|
#include <esp_private/log_timestamp.h>
|
||||||
|
#include <esp_rom_sys.h>
|
||||||
|
#include <freertos/ringbuf.h>
|
||||||
|
|
||||||
|
static_assert(CONFIG_LOG_VERSION == 2, "OTGateway requires an SDK built with Log v2");
|
||||||
|
static_assert(CONFIG_LOG_DYNAMIC_LEVEL_CONTROL, "Runtime log levels require dynamic level control");
|
||||||
|
|
||||||
|
static std::atomic<RingbufHandle_t> loggingQueue{nullptr};
|
||||||
|
static std::atomic<bool> activeSerial{false};
|
||||||
|
static std::atomic<bool> activeWebSerial{false};
|
||||||
|
static thread_local bool writingOutputs = false;
|
||||||
|
|
||||||
|
// Return the full byte count, like snprintf, so only long records need a second pass.
|
||||||
|
static size_t formatLogRecord(esp_log_msg_t& message, char* buffer, size_t capacity) {
|
||||||
|
const auto& options = message.config.opts;
|
||||||
|
size_t prefixLength = 0;
|
||||||
|
const char* suffix = "";
|
||||||
|
|
||||||
|
if (options.require_formatting) {
|
||||||
|
const auto level = options.log_level;
|
||||||
|
if (level >= ESP_LOG_MAX) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char* color = "";
|
||||||
|
#if ESP_LOG_SUPPORT_COLOR && !ESP_LOG_COLOR_DISABLED
|
||||||
|
static const char* const colors[ESP_LOG_MAX] = {
|
||||||
|
"", LOG_COLOR_E, LOG_COLOR_W, LOG_COLOR_I, LOG_COLOR(LOG_COLOR_CYAN), LOG_COLOR(LOG_COLOR_MAGENTA)
|
||||||
|
};
|
||||||
|
if (!options.dis_color) {
|
||||||
|
color = colors[level];
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
char timestamp[32] = {};
|
||||||
|
if (!options.dis_timestamp) {
|
||||||
|
esp_log_timestamp_str(false, message.timestamp, timestamp);
|
||||||
|
}
|
||||||
|
|
||||||
|
int written = snprintf(
|
||||||
|
buffer, capacity, "%s%s%s%s[%c]%s%s%s ",
|
||||||
|
options.dis_timestamp ? "" : "[",
|
||||||
|
timestamp,
|
||||||
|
options.dis_timestamp ? "" : "]",
|
||||||
|
color,
|
||||||
|
"\0EWIDV"[level],
|
||||||
|
message.tag ? "[" : "",
|
||||||
|
message.tag ? message.tag : "",
|
||||||
|
message.tag ? "]" : ""
|
||||||
|
);
|
||||||
|
if (written < 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
prefixLength = written;
|
||||||
|
suffix = *color ? LOG_RESET_COLOR "\n" : "\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t offset = std::min(prefixLength, capacity - 1);
|
||||||
|
va_list args;
|
||||||
|
va_copy(args, message.args);
|
||||||
|
int bodyLength = vsnprintf(buffer + offset, capacity - offset, message.format, args);
|
||||||
|
va_end(args);
|
||||||
|
if (bodyLength < 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t suffixOffset = prefixLength + bodyLength;
|
||||||
|
size_t length = suffixOffset + strlen(suffix);
|
||||||
|
if (length < capacity) {
|
||||||
|
memcpy(buffer + suffixOffset, suffix, length - suffixOffset + 1);
|
||||||
|
}
|
||||||
|
return length;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void __attribute__((noinline)) enqueueLogRecord(RingbufHandle_t queue, esp_log_msg_t& message) {
|
||||||
|
char local[128];
|
||||||
|
size_t length = formatLogRecord(message, local, sizeof(local));
|
||||||
|
if (length == 0 || length >= xRingbufferGetMaxItemSize(queue)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (length < sizeof(local)) {
|
||||||
|
xRingbufferSend(queue, local, length + 1, 0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
char* buffer = static_cast<char*>(malloc(length + 1));
|
||||||
|
if (buffer != nullptr) {
|
||||||
|
if (formatLogRecord(message, buffer, length + 1) == length) {
|
||||||
|
xRingbufferSend(queue, buffer, length + 1, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
free(buffer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extern "C" {
|
||||||
|
void __real_esp_log_format(esp_log_msg_t* message);
|
||||||
|
|
||||||
|
void IRAM_ATTR __wrap_esp_log_format(esp_log_msg_t* message) {
|
||||||
|
RingbufHandle_t queue = loggingQueue.load(std::memory_order_acquire);
|
||||||
|
if (message->config.opts.constrained_env || writingOutputs || queue == nullptr) {
|
||||||
|
__real_esp_log_format(message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const bool hasOutput = activeSerial.load(std::memory_order_relaxed) ||
|
||||||
|
activeWebSerial.load(std::memory_order_relaxed);
|
||||||
|
|
||||||
|
if (hasOutput) {
|
||||||
|
enqueueLogRecord(queue, *message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void writeOutput(Print& output, const uint8_t* buffer, size_t size) {
|
||||||
|
while (size > 0) {
|
||||||
|
size_t written = output.write(buffer, size);
|
||||||
|
if (written == 0 || written > size) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
buffer += written;
|
||||||
|
size -= written;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void setLoggingLevel(esp_log_level_t level) {
|
||||||
|
esp_log_level_set("*", level);
|
||||||
|
|
||||||
|
// prevents loop with WebSerial in case we reach some error logs in esp_async_ws like WS message queue overflow
|
||||||
|
esp_log_level_set("async_tcp", ESP_LOG_NONE);
|
||||||
|
esp_log_level_set("async_ws", ESP_LOG_NONE);
|
||||||
|
}
|
||||||
|
|
||||||
|
void drainLoggingSerial() {
|
||||||
|
if (activeSerial.load(std::memory_order_relaxed)) {
|
||||||
|
// Drain only the current RX backlog; continuous input must not starve tasks.
|
||||||
|
int available = Serial.available();
|
||||||
|
while (available-- > 0) {
|
||||||
|
Serial.read();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static Task sendLogsTask("Send logs", [](void*) {
|
||||||
|
// Bound each pass so continuous logging cannot starve System tasks.
|
||||||
|
size_t remaining = LOGGING_QUEUE_SIZE;
|
||||||
|
const unsigned long started = millis();
|
||||||
|
RingbufHandle_t queue = loggingQueue.load(std::memory_order_acquire);
|
||||||
|
|
||||||
|
while (remaining > 0 && millis() - started < 10) {
|
||||||
|
size_t size = 0;
|
||||||
|
auto* buffer = static_cast<uint8_t*>(xRingbufferReceive(queue, &size, 0));
|
||||||
|
|
||||||
|
if (buffer == nullptr) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A transport may itself log during a write on this task.
|
||||||
|
writingOutputs = true;
|
||||||
|
if (activeSerial.load(std::memory_order_relaxed)) {
|
||||||
|
writeOutput(Serial, buffer, size - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (activeWebSerial.load(std::memory_order_relaxed) && webSerial != nullptr) {
|
||||||
|
if (webSerial->getConnectionCount() > 0) {
|
||||||
|
writeOutput(*webSerial, buffer, size - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
writingOutputs = false;
|
||||||
|
|
||||||
|
vRingbufferReturnItem(queue, buffer);
|
||||||
|
remaining = size >= remaining ? 0 : remaining - size;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Task configureLoggingTask("Configure logging", Task::Type::ONCE, [](void*) {
|
||||||
|
static unsigned int currentSerialBaudrate = 0;
|
||||||
|
unsigned int newSerialBaudrate = settings.system.serial.enabled ? settings.system.serial.baudrate : 0;
|
||||||
|
if (currentSerialBaudrate != newSerialBaudrate) {
|
||||||
|
if (newSerialBaudrate == 0) {
|
||||||
|
Serial.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (newSerialBaudrate != 0) {
|
||||||
|
#if ARDUINO_USB_CDC_ON_BOOT && ARDUINO_USB_MODE
|
||||||
|
Serial.setTxBufferSize(512);
|
||||||
|
Serial.setTxTimeoutMs(0);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
Serial.begin(newSerialBaudrate);
|
||||||
|
}
|
||||||
|
|
||||||
|
currentSerialBaudrate = newSerialBaudrate;
|
||||||
|
}
|
||||||
|
|
||||||
|
activeSerial.store(currentSerialBaudrate != 0, std::memory_order_relaxed);
|
||||||
|
activeWebSerial.store(settings.system.webSerial.enabled && webSerial != nullptr, std::memory_order_relaxed);
|
||||||
|
|
||||||
|
setLoggingLevel(settings.system.logLevel);
|
||||||
|
});
|
||||||
|
|
||||||
|
bool initLogging() {
|
||||||
|
if (loggingQueue.load(std::memory_order_relaxed) != nullptr) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
RingbufHandle_t queue = xRingbufferCreate(LOGGING_QUEUE_SIZE, RINGBUF_TYPE_NOSPLIT);
|
||||||
|
if (queue == nullptr) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
#if !CONFIG_LOG_API_CONSTRAINED_ENV_SAFE
|
||||||
|
// The native formatter uses the vprintf hook even in an ISR on these SDK builds.
|
||||||
|
esp_log_set_vprintf(esp_rom_vprintf);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
configureLoggingTask.forceRun();
|
||||||
|
loggingQueue.store(queue, std::memory_order_release);
|
||||||
|
systemTaskManager.addTask(configureLoggingTask);
|
||||||
|
|
||||||
|
sendLogsTask.setInterval(10);
|
||||||
|
systemTaskManager.addTask(sendLogsTask);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
@@ -1,168 +1,97 @@
|
|||||||
#include <Arduino.h>
|
#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE
|
||||||
#include "defines.h"
|
|
||||||
#include "strings.h"
|
|
||||||
#include <ArduinoJson.h>
|
|
||||||
#include <FileData.h>
|
|
||||||
#include <LittleFS.h>
|
|
||||||
#include "ESPTelnetStream.h"
|
|
||||||
#include <TinyLogger.h>
|
|
||||||
#include <NetworkManager.h>
|
|
||||||
#include "Settings.h"
|
|
||||||
#include <utils.h>
|
|
||||||
|
|
||||||
#if defined(ARDUINO_ARCH_ESP32)
|
#include <app.h>
|
||||||
#include <ESP32Scheduler.h>
|
#include <metrics.h>
|
||||||
#elif defined(ARDUINO_ARCH_ESP8266)
|
#include <cstdlib>
|
||||||
#include <Scheduler.h>
|
#include <esp_system.h>
|
||||||
#else
|
|
||||||
#error Wrong board. Supported boards: esp8266, esp32
|
#if ARDUINO_USB_CDC_ON_BOOT && !ARDUINO_USB_MODE
|
||||||
|
#include <USB.h>
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#include <Task.h>
|
#ifndef ARDUINO_ARCH_ESP32
|
||||||
#include <LeanTask.h>
|
#error Only ESP32 boards are supported
|
||||||
#include "MqttTask.h"
|
#endif
|
||||||
#include "OpenThermTask.h"
|
|
||||||
#include "SensorsTask.h"
|
#include <LittleFS.h>
|
||||||
#include "RegulatorTask.h"
|
|
||||||
#include "PortalTask.h"
|
|
||||||
#include "MainTask.h"
|
|
||||||
|
|
||||||
// Vars
|
// Vars
|
||||||
FileData fsNetworkSettings(&LittleFS, "/network.conf", 'n', &networkSettings, sizeof(networkSettings), 1000);
|
Sensors::Result sensorsResults[SENSORS_AMOUNT];
|
||||||
FileData fsSettings(&LittleFS, "/settings.conf", 's', &settings, sizeof(settings), 60000);
|
|
||||||
ESPTelnetStream* telnetStream = nullptr;
|
|
||||||
Network::Manager* network = nullptr;
|
|
||||||
|
|
||||||
// Tasks
|
TaskManager coreTaskManager("Core");
|
||||||
MqttTask* tMqtt;
|
TaskManager systemTaskManager("System");
|
||||||
OpenThermTask* tOt;
|
TaskManager openthermTaskManager("OpenTherm");
|
||||||
SensorsTask* tSensors;
|
TaskManager sensorsTaskManager("Sensors");
|
||||||
RegulatorTask* tRegulator;
|
|
||||||
PortalTask* tPortal;
|
|
||||||
MainTask* tMain;
|
|
||||||
|
|
||||||
|
|
||||||
void setup() {
|
extern "C" void app_main() {
|
||||||
|
// https://github.com/espressif/arduino-esp32/blob/master/cores/esp32/main.cpp
|
||||||
|
#if defined(F_XTAL_MHZ) && !CONFIG_IDF_TARGET_ESP32S2
|
||||||
|
rtc_clk_xtal_freq_update((rtc_xtal_freq_t)F_XTAL_MHZ);
|
||||||
|
rtc_clk_cpu_freq_set_xtal();
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef F_CPU
|
||||||
|
setCpuFrequencyMhz(F_CPU / 1000000);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if ARDUINO_USB_DFU_ON_BOOT && !ARDUINO_USB_MODE
|
||||||
|
USB.enableDFU();
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if ARDUINO_USB_ON_BOOT && !ARDUINO_USB_MODE
|
||||||
|
USB.begin();
|
||||||
|
#endif
|
||||||
|
|
||||||
|
initArduino();
|
||||||
|
|
||||||
|
initCoreDumpMetrics();
|
||||||
|
Sensors::setMaxSensors(SENSORS_AMOUNT);
|
||||||
|
Sensors::settings = sensorsSettings;
|
||||||
|
Sensors::results = sensorsResults;
|
||||||
LittleFS.begin();
|
LittleFS.begin();
|
||||||
|
|
||||||
Log.setLevel(TinyLogger::Level::VERBOSE);
|
if (!initLogging()) {
|
||||||
Log.setServiceTemplate("\033[1m[%s]\033[22m");
|
std::abort();
|
||||||
Log.setLevelTemplate("\033[1m[%s]\033[22m");
|
|
||||||
Log.setMsgPrefix("\033[m ");
|
|
||||||
Log.setDateTemplate("\033[1m[%H:%M:%S]\033[22m");
|
|
||||||
Log.setDateCallback([] {
|
|
||||||
unsigned int time = millis() / 1000;
|
|
||||||
int sec = time % 60;
|
|
||||||
int min = time % 3600 / 60;
|
|
||||||
int hour = time / 3600;
|
|
||||||
|
|
||||||
return tm{sec, min, hour};
|
|
||||||
});
|
|
||||||
|
|
||||||
Serial.begin(115200);
|
|
||||||
Log.addStream(&Serial);
|
|
||||||
Log.print("\n\n\r");
|
|
||||||
|
|
||||||
// network settings
|
|
||||||
switch (fsNetworkSettings.read()) {
|
|
||||||
case FD_FS_ERR:
|
|
||||||
Log.swarningln(FPSTR(L_NETWORK_SETTINGS), F("Filesystem error, load default"));
|
|
||||||
break;
|
|
||||||
case FD_FILE_ERR:
|
|
||||||
Log.swarningln(FPSTR(L_NETWORK_SETTINGS), F("Bad data, load default"));
|
|
||||||
break;
|
|
||||||
case FD_WRITE:
|
|
||||||
Log.sinfoln(FPSTR(L_NETWORK_SETTINGS), F("Not found, load default"));
|
|
||||||
break;
|
|
||||||
case FD_ADD:
|
|
||||||
case FD_READ:
|
|
||||||
Log.sinfoln(FPSTR(L_NETWORK_SETTINGS), F("Loaded"));
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// settings
|
initConfig();
|
||||||
switch (fsSettings.read()) {
|
initNetwork();
|
||||||
case FD_FS_ERR:
|
initSensors();
|
||||||
Log.swarningln(FPSTR(L_SETTINGS), F("Filesystem error, load default"));
|
initControl();
|
||||||
break;
|
initRegulator();
|
||||||
case FD_FILE_ERR:
|
initLeds();
|
||||||
Log.swarningln(FPSTR(L_SETTINGS), F("Bad data, load default"));
|
initMqtt();
|
||||||
break;
|
initPortal();
|
||||||
case FD_WRITE:
|
initSystem();
|
||||||
Log.sinfoln(FPSTR(L_SETTINGS), F("Not found, load default"));
|
initOpenTherm();
|
||||||
break;
|
|
||||||
case FD_ADD:
|
|
||||||
case FD_READ:
|
|
||||||
Log.sinfoln(FPSTR(L_SETTINGS), F("Loaded"));
|
|
||||||
|
|
||||||
if (strcmp(SETTINGS_VALID_VALUE, settings.validationValue) != 0) {
|
// RMT has its own worker; this manager schedules synchronous boiler operations.
|
||||||
Log.swarningln(FPSTR(L_SETTINGS), F("Not valid, set default and restart..."));
|
if (!openthermTaskManager.asyncStart(4096, 5, 0, 10, false)) {
|
||||||
fsSettings.reset();
|
esp_system_abort("Failed to start OpenTherm task manager");
|
||||||
::delay(5000);
|
|
||||||
ESP.restart();
|
|
||||||
}
|
}
|
||||||
break;
|
ESP_LOGI(L_MAIN, "Started %s task manager", openthermTaskManager.name());
|
||||||
default:
|
|
||||||
break;
|
// Core runs control and MQTT tasks; poll their intervals every 100 ms.
|
||||||
|
if (!coreTaskManager.asyncStart(4608, 4, tskNO_AFFINITY, 100, false)) {
|
||||||
|
esp_system_abort("Failed to start Core task manager");
|
||||||
}
|
}
|
||||||
|
ESP_LOGI(L_MAIN, "Started %s task manager", coreTaskManager.name());
|
||||||
|
|
||||||
// logs
|
// System keeps maintenance, networking and restart handling active during Core pauses.
|
||||||
if (!settings.system.useSerial) {
|
if (!systemTaskManager.asyncStart(5120, 3, tskNO_AFFINITY, 100, false)) {
|
||||||
Log.clearStreams();
|
esp_system_abort("Failed to start System task manager");
|
||||||
Serial.end();
|
|
||||||
}
|
}
|
||||||
|
ESP_LOGI(L_MAIN, "Started %s task manager", systemTaskManager.name());
|
||||||
|
|
||||||
if (settings.system.useTelnet) {
|
BaseType_t sensorsCore = tskNO_AFFINITY;
|
||||||
telnetStream = new ESPTelnetStream;
|
#if USE_BLE && defined(CONFIG_BT_NIMBLE_PINNED_TO_CORE)
|
||||||
telnetStream->setKeepAliveInterval(500);
|
sensorsCore = CONFIG_BT_NIMBLE_PINNED_TO_CORE;
|
||||||
Log.addStream(telnetStream);
|
|
||||||
}
|
|
||||||
|
|
||||||
Log.setLevel(settings.system.debug ? TinyLogger::Level::VERBOSE : TinyLogger::Level::INFO);
|
|
||||||
|
|
||||||
// network
|
|
||||||
network = (new Network::Manager)
|
|
||||||
->setHostname(networkSettings.hostname)
|
|
||||||
->setStaCredentials(
|
|
||||||
#ifdef WOKWI
|
|
||||||
"Wokwi-GUEST", nullptr, 6
|
|
||||||
#else
|
|
||||||
strlen(networkSettings.sta.ssid) ? networkSettings.sta.ssid : nullptr,
|
|
||||||
strlen(networkSettings.sta.password) ? networkSettings.sta.password : nullptr,
|
|
||||||
networkSettings.sta.channel
|
|
||||||
#endif
|
#endif
|
||||||
)->setApCredentials(
|
|
||||||
strlen(networkSettings.ap.ssid) ? networkSettings.ap.ssid : nullptr,
|
|
||||||
strlen(networkSettings.ap.password) ? networkSettings.ap.password : nullptr,
|
|
||||||
networkSettings.ap.channel
|
|
||||||
);
|
|
||||||
|
|
||||||
// tasks
|
// Keep physical sensor I/O and result processing outside the Core worker.
|
||||||
tMqtt = new MqttTask(false, 500);
|
if (!sensorsTaskManager.asyncStart(4096, 4, sensorsCore, 1000, false)) {
|
||||||
Scheduler.start(tMqtt);
|
esp_system_abort("Failed to start Sensors task manager");
|
||||||
|
}
|
||||||
tOt = new OpenThermTask(false, 750);
|
ESP_LOGI(L_MAIN, "Started %s task manager", sensorsTaskManager.name());
|
||||||
Scheduler.start(tOt);
|
|
||||||
|
|
||||||
tSensors = new SensorsTask(true, EXT_SENSORS_INTERVAL);
|
|
||||||
Scheduler.start(tSensors);
|
|
||||||
|
|
||||||
tRegulator = new RegulatorTask(true, 10000);
|
|
||||||
Scheduler.start(tRegulator);
|
|
||||||
|
|
||||||
tPortal = new PortalTask(true, 0);
|
|
||||||
Scheduler.start(tPortal);
|
|
||||||
|
|
||||||
tMain = new MainTask(true, 100);
|
|
||||||
Scheduler.start(tMain);
|
|
||||||
|
|
||||||
Scheduler.begin();
|
|
||||||
}
|
|
||||||
|
|
||||||
void loop() {
|
|
||||||
#if defined(ARDUINO_ARCH_ESP32)
|
|
||||||
vTaskDelete(NULL);
|
|
||||||
#endif
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,849 @@
|
|||||||
|
#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE
|
||||||
|
|
||||||
|
#include <app.h>
|
||||||
|
|
||||||
|
#include <DNSServer.h>
|
||||||
|
#include <ESPmDNS.h>
|
||||||
|
#include <ESPAsyncWebServer.h>
|
||||||
|
#include <Network.h>
|
||||||
|
#include <WiFi.h>
|
||||||
|
#include <esp_wifi.h>
|
||||||
|
#include <freertos/queue.h>
|
||||||
|
#include <atomic>
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
// Requests and state shared with other workers.
|
||||||
|
static std::atomic<bool> reconnectRequested{false};
|
||||||
|
static std::atomic<bool> staStarted{false};
|
||||||
|
static std::atomic<bool> apStarted{false};
|
||||||
|
static std::atomic<NetworkState> staState{NetworkState::NETWORK_DISABLED};
|
||||||
|
static std::atomic<NetworkState> apState{NetworkState::NETWORK_DISABLED};
|
||||||
|
|
||||||
|
// Subscriptions are fixed before the worker starts.
|
||||||
|
static std::vector<NetworkEventCallback> networkCallbacks;
|
||||||
|
static std::vector<NetworkStateCallback> stateCallbacks;
|
||||||
|
|
||||||
|
// Framework callbacks only copy events. Driver and service operations stay in this worker.
|
||||||
|
struct PendingNetworkEvent {
|
||||||
|
uint32_t value; // IPv4 address for STA_GOT_IP and AP_STARTED.
|
||||||
|
NetworkEvent event;
|
||||||
|
uint8_t reason; // STA disconnect reason.
|
||||||
|
};
|
||||||
|
|
||||||
|
static constexpr size_t NETWORK_EVENT_QUEUE_LENGTH = 32;
|
||||||
|
static StaticQueue_t networkEventQueueStorage;
|
||||||
|
static uint8_t networkEventBuffer[NETWORK_EVENT_QUEUE_LENGTH * sizeof(PendingNetworkEvent)];
|
||||||
|
static QueueHandle_t networkEventQueue = nullptr;
|
||||||
|
static std::atomic<bool> networkEventsOverflowed{false};
|
||||||
|
static std::atomic<bool> networkRecoveryRequested{false};
|
||||||
|
|
||||||
|
// Station state and timers; only the system worker accesses these values.
|
||||||
|
static unsigned long lastConnectionAttempt = 0;
|
||||||
|
static unsigned long connectedTime = 0;
|
||||||
|
static unsigned long disconnectedTime = 0;
|
||||||
|
static unsigned long lastRssiUpdate = 0;
|
||||||
|
static uint32_t connectedIp = 0;
|
||||||
|
static uint8_t disconnectReason = 0;
|
||||||
|
static bool staAssociated = false;
|
||||||
|
static bool connectionPending = false;
|
||||||
|
static bool ntpStarted = false;
|
||||||
|
|
||||||
|
// Fallback access point
|
||||||
|
static unsigned long lastApAttempt = 0;
|
||||||
|
static uint32_t apIp = 0;
|
||||||
|
static uint8_t apClients = 0;
|
||||||
|
|
||||||
|
// Full driver recovery
|
||||||
|
static unsigned long lastNetworkRecoveryAttempt = 0;
|
||||||
|
static bool recoveryPending = false;
|
||||||
|
|
||||||
|
// DNS is asynchronous in the current framework; it needs no polling task.
|
||||||
|
static bool webServerReady = false;
|
||||||
|
static DNSServer dnsServer;
|
||||||
|
static bool dnsStarted = false;
|
||||||
|
static bool mdnsStarted = false;
|
||||||
|
static unsigned long lastDnsAttempt = 0;
|
||||||
|
static unsigned long lastMdnsAttempt = 0;
|
||||||
|
static char mdnsHostname[sizeof(networkSettings.hostname)] = {};
|
||||||
|
|
||||||
|
// Event subscriptions
|
||||||
|
void onNetworkEvent(NetworkEventCallback callback) {
|
||||||
|
if (!callback) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (auto registered : networkCallbacks) {
|
||||||
|
if (registered == callback) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
networkCallbacks.push_back(callback);
|
||||||
|
}
|
||||||
|
|
||||||
|
void onNetworkStateChange(NetworkStateCallback callback) {
|
||||||
|
if (callback) {
|
||||||
|
stateCallbacks.push_back(std::move(callback));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Published interface state
|
||||||
|
NetworkState getNetworkState(NetworkMode mode) {
|
||||||
|
if (mode == NetworkMode::STA) {
|
||||||
|
return staState.load();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mode == NetworkMode::AP) {
|
||||||
|
return apState.load();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ethernet initialization and routing will be implemented separately.
|
||||||
|
return NetworkState::NETWORK_DISABLED;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool isNetworkConnected() {
|
||||||
|
return getNetworkState(NetworkMode::STA) == NetworkState::NETWORK_CONNECTED;
|
||||||
|
}
|
||||||
|
|
||||||
|
NetworkMode getNetworkMode() {
|
||||||
|
if (isNetworkConnected()) {
|
||||||
|
return NetworkMode::STA;
|
||||||
|
}
|
||||||
|
|
||||||
|
return apStarted.load() ? NetworkMode::AP : NetworkMode::NONE;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool isNetworkInterfaceStarted(NetworkMode mode) {
|
||||||
|
if (mode == NetworkMode::STA) {
|
||||||
|
return staStarted.load();
|
||||||
|
}
|
||||||
|
|
||||||
|
return mode == NetworkMode::AP && apStarted.load();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Requests from other tasks; driver operations run in the system worker.
|
||||||
|
void reconnectNetwork() {
|
||||||
|
reconnectRequested.store(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
// State transitions and notifications
|
||||||
|
static void notifyNetworkEvent(NetworkEvent event) {
|
||||||
|
for (auto callback : networkCallbacks) {
|
||||||
|
callback(event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void setNetworkState(NetworkMode mode, NetworkState next) {
|
||||||
|
auto& state = mode == NetworkMode::STA ? staState : apState;
|
||||||
|
const NetworkState previous = state.load();
|
||||||
|
|
||||||
|
if (previous == next) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mode == NetworkMode::STA) {
|
||||||
|
if (previous == NetworkState::NETWORK_CONNECTED) {
|
||||||
|
disconnectedTime = millis();
|
||||||
|
connectedIp = 0;
|
||||||
|
vars.network.rssi = 0;
|
||||||
|
ntpStarted = false;
|
||||||
|
Sensors::setConnectionStatusByType(Sensors::Type::MANUAL, false, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (next == NetworkState::NETWORK_CONNECTED) {
|
||||||
|
connectedTime = millis();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Publish before callbacks so getters and JSON already reflect the new state.
|
||||||
|
state.store(next);
|
||||||
|
for (auto& callback : stateCallbacks) {
|
||||||
|
callback(mode, previous, next);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mode == NetworkMode::STA) {
|
||||||
|
if (next == NetworkState::NETWORK_CONNECTED) {
|
||||||
|
notifyNetworkEvent(NetworkEvent::CONNECTED);
|
||||||
|
|
||||||
|
} else if (previous == NetworkState::NETWORK_CONNECTED) {
|
||||||
|
notifyNetworkEvent(NetworkEvent::DISCONNECTED);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Framework events
|
||||||
|
static void queueNetworkEvent(NetworkEvent event, uint32_t value = 0, uint8_t reason = 0) {
|
||||||
|
const PendingNetworkEvent pending{value, event, reason};
|
||||||
|
|
||||||
|
// Never wait here: this worker can be waiting for the framework inside STA/AP.begin().
|
||||||
|
if (xQueueSend(networkEventQueue, &pending, 0) != pdTRUE) {
|
||||||
|
networkEventsOverflowed.store(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void handleWifiEvent(arduino_event_id_t event, arduino_event_info_t info) {
|
||||||
|
// This callback runs in the Arduino event task; only copy the event data here.
|
||||||
|
switch (event) {
|
||||||
|
// Station
|
||||||
|
case ARDUINO_EVENT_WIFI_STA_START:
|
||||||
|
queueNetworkEvent(NetworkEvent::STA_STARTED);
|
||||||
|
break;
|
||||||
|
case ARDUINO_EVENT_WIFI_STA_STOP:
|
||||||
|
queueNetworkEvent(NetworkEvent::STA_STOPPED);
|
||||||
|
break;
|
||||||
|
case ARDUINO_EVENT_WIFI_STA_CONNECTED:
|
||||||
|
queueNetworkEvent(NetworkEvent::STA_CONNECTED);
|
||||||
|
break;
|
||||||
|
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
|
||||||
|
queueNetworkEvent(NetworkEvent::STA_DISCONNECTED, 0, info.wifi_sta_disconnected.reason);
|
||||||
|
break;
|
||||||
|
case ARDUINO_EVENT_WIFI_STA_GOT_IP:
|
||||||
|
queueNetworkEvent(NetworkEvent::STA_GOT_IP, info.got_ip.ip_info.ip.addr);
|
||||||
|
break;
|
||||||
|
case ARDUINO_EVENT_WIFI_STA_LOST_IP:
|
||||||
|
queueNetworkEvent(NetworkEvent::STA_LOST_IP);
|
||||||
|
break;
|
||||||
|
case ARDUINO_EVENT_WIFI_STA_GOT_IP6:
|
||||||
|
queueNetworkEvent(NetworkEvent::STA_GOT_IP6);
|
||||||
|
break;
|
||||||
|
|
||||||
|
// Access point
|
||||||
|
case ARDUINO_EVENT_WIFI_AP_START:
|
||||||
|
queueNetworkEvent(NetworkEvent::AP_STARTED, static_cast<uint32_t>(WiFi.AP.localIP()));
|
||||||
|
break;
|
||||||
|
case ARDUINO_EVENT_WIFI_AP_STOP:
|
||||||
|
queueNetworkEvent(NetworkEvent::AP_STOPPED);
|
||||||
|
break;
|
||||||
|
case ARDUINO_EVENT_WIFI_AP_STACONNECTED:
|
||||||
|
queueNetworkEvent(NetworkEvent::AP_CLIENT_CONNECTED);
|
||||||
|
break;
|
||||||
|
case ARDUINO_EVENT_WIFI_AP_STADISCONNECTED:
|
||||||
|
queueNetworkEvent(NetworkEvent::AP_CLIENT_DISCONNECTED);
|
||||||
|
break;
|
||||||
|
case ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED:
|
||||||
|
queueNetworkEvent(NetworkEvent::AP_CLIENT_GOT_IP);
|
||||||
|
break;
|
||||||
|
case ARDUINO_EVENT_WIFI_AP_GOT_IP6:
|
||||||
|
queueNetworkEvent(NetworkEvent::AP_GOT_IP6);
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void postInterfaceStopped(arduino_event_id_t type) {
|
||||||
|
// onDisable() can remove the native STOP handler. Keep our notification ordered
|
||||||
|
// after already queued framework START/GOT_IP events and before the next start.
|
||||||
|
arduino_event_t event{};
|
||||||
|
event.event_id = type;
|
||||||
|
if (!Network.postEvent(&event)) {
|
||||||
|
ESP_LOGE(L_NETWORK, "Failed post interface stop, reset WiFi requested");
|
||||||
|
networkRecoveryRequested.store(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WiFi interfaces
|
||||||
|
static void configureWifiRadio() {
|
||||||
|
// Apply the existing channel policy after the WiFi driver has started.
|
||||||
|
const wifi_country_t country = {
|
||||||
|
"JP",
|
||||||
|
1,
|
||||||
|
14,
|
||||||
|
CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER,
|
||||||
|
WIFI_COUNTRY_POLICY_MANUAL
|
||||||
|
};
|
||||||
|
|
||||||
|
esp_wifi_set_country(&country);
|
||||||
|
//WiFi.setSleep(USE_BLE ? WIFI_PS_MIN_MODEM : WIFI_PS_NONE);
|
||||||
|
WiFi.setSleep(WIFI_PS_NONE);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void stopAccessPoint() {
|
||||||
|
if (!WiFi.AP.end()) {
|
||||||
|
ESP_LOGE(L_NETWORK, "Failed stop AP, reset WiFi requested");
|
||||||
|
networkRecoveryRequested.store(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
postInterfaceStopped(ARDUINO_EVENT_WIFI_AP_STOP);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void startAccessPoint() {
|
||||||
|
lastApAttempt = millis();
|
||||||
|
setNetworkState(NetworkMode::AP, NetworkState::AP_STARTING);
|
||||||
|
|
||||||
|
// Keep STA available for scans and retries while the fallback AP is running.
|
||||||
|
WiFi.STA.begin();
|
||||||
|
if (!WiFi.AP.begin()) {
|
||||||
|
// begin() can enable AP but time out before its STARTED event arrives.
|
||||||
|
stopAccessPoint();
|
||||||
|
setNetworkState(NetworkMode::AP, NetworkState::NETWORK_DISABLED);
|
||||||
|
ESP_LOGE(L_NETWORK, "Failed start AP");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
configureWifiRadio();
|
||||||
|
WiFi.AP.setHostname(networkSettings.hostname);
|
||||||
|
if (!WiFi.AP.create(
|
||||||
|
networkSettings.ap.ssid,
|
||||||
|
networkSettings.ap.password[0] ? networkSettings.ap.password : nullptr,
|
||||||
|
networkSettings.ap.channel
|
||||||
|
)) {
|
||||||
|
stopAccessPoint();
|
||||||
|
setNetworkState(NetworkMode::AP, NetworkState::NETWORK_DISABLED);
|
||||||
|
ESP_LOGE(L_NETWORK, "Failed configure AP");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool resetWifi() {
|
||||||
|
const bool restoreAp = WiFi.AP.started();
|
||||||
|
connectionPending = false;
|
||||||
|
|
||||||
|
// A failed driver reset must also respect the retry cooldown.
|
||||||
|
lastConnectionAttempt = millis();
|
||||||
|
if (!WiFi.mode(WIFI_OFF)) {
|
||||||
|
ESP_LOGE(L_NETWORK, "Failed reset WiFi");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
postInterfaceStopped(ARDUINO_EVENT_WIFI_STA_STOP);
|
||||||
|
if (restoreAp) {
|
||||||
|
postInterfaceStopped(ARDUINO_EVENT_WIFI_AP_STOP);
|
||||||
|
}
|
||||||
|
|
||||||
|
lastConnectionAttempt = 0;
|
||||||
|
if (restoreAp) {
|
||||||
|
startAccessPoint();
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool startNetworkConnection() {
|
||||||
|
// Ordinary retries preserve AP. Escalate only if STA cannot be stopped.
|
||||||
|
const bool wasStarted = WiFi.STA.started();
|
||||||
|
|
||||||
|
if (!WiFi.STA.end()) {
|
||||||
|
ESP_LOGW(L_NETWORK, "Failed stop STA, reset WiFi...");
|
||||||
|
if (!resetWifi()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
} else if (wasStarted) {
|
||||||
|
postInterfaceStopped(ARDUINO_EVENT_WIFI_STA_STOP);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!WiFi.STA.begin()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
configureWifiRadio();
|
||||||
|
WiFi.STA.setAutoReconnect(false);
|
||||||
|
WiFi.STA.setScanMethod(WIFI_ALL_CHANNEL_SCAN);
|
||||||
|
WiFi.STA.setSortMethod(WIFI_CONNECT_AP_BY_SIGNAL);
|
||||||
|
|
||||||
|
if (!WiFi.STA.setHostname(networkSettings.hostname)) {
|
||||||
|
ESP_LOGE(L_NETWORK, "Set hostname '%s': fail", networkSettings.hostname);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (networkSettings.useDhcp) {
|
||||||
|
if (!WiFi.STA.config()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
} else {
|
||||||
|
IPAddress ip, gateway, subnet, dns;
|
||||||
|
ip.fromString(networkSettings.staticConfig.ip);
|
||||||
|
gateway.fromString(networkSettings.staticConfig.gateway);
|
||||||
|
subnet.fromString(networkSettings.staticConfig.subnet);
|
||||||
|
dns.fromString(networkSettings.staticConfig.dns);
|
||||||
|
|
||||||
|
if (!WiFi.STA.config(ip, gateway, subnet, dns)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setNetworkState(
|
||||||
|
NetworkMode::STA,
|
||||||
|
connectedTime ? NetworkState::NETWORK_RECONNECTING : NetworkState::NETWORK_CONNECTING
|
||||||
|
);
|
||||||
|
|
||||||
|
return WiFi.STA.connect(
|
||||||
|
networkSettings.sta.ssid,
|
||||||
|
networkSettings.sta.password[0] ? networkSettings.sta.password : nullptr,
|
||||||
|
networkSettings.sta.channel
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Station connection and recovery timeouts
|
||||||
|
static void updateConnection() {
|
||||||
|
if (!networkSettings.sta.ssid[0]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (connectionPending) {
|
||||||
|
if (millis() - lastConnectionAttempt < 10000) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
connectionPending = false;
|
||||||
|
lastConnectionAttempt = millis();
|
||||||
|
setNetworkState(NetworkMode::STA, NetworkState::NETWORK_TIMEOUT);
|
||||||
|
|
||||||
|
ESP_LOGD(
|
||||||
|
L_NETWORK,
|
||||||
|
"Connection attempt timed out. Status: %d",
|
||||||
|
WiFi.STA.status()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Associated without IP: allow DHCP to recover before resetting the whole driver.
|
||||||
|
if (staAssociated) {
|
||||||
|
if (millis() - lastConnectionAttempt > 90000) {
|
||||||
|
ESP_LOGW(L_NETWORK, "Connection timeout, reset WiFi...");
|
||||||
|
resetWifi();
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!lastConnectionAttempt || millis() - lastConnectionAttempt > 15000) {
|
||||||
|
ESP_LOGI(L_NETWORK, "Try connect...");
|
||||||
|
|
||||||
|
connectionPending = startNetworkConnection();
|
||||||
|
lastConnectionAttempt = millis();
|
||||||
|
|
||||||
|
if (!connectionPending) {
|
||||||
|
setNetworkState(NetworkMode::STA, NetworkState::NETWORK_TIMEOUT);
|
||||||
|
ESP_LOGW(L_NETWORK, "Failed start connection");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback access point
|
||||||
|
static void updateAccessPoint() {
|
||||||
|
if (isNetworkConnected()) {
|
||||||
|
if (apStarted.load() && millis() - connectedTime > 15000 && !apClients) {
|
||||||
|
ESP_LOGI(L_NETWORK, "Stop AP because STA connected");
|
||||||
|
stopAccessPoint();
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!apStarted.load() && (!networkSettings.sta.ssid[0] || millis() - disconnectedTime > 185000)) {
|
||||||
|
if (!lastApAttempt || millis() - lastApAttempt > 15000) {
|
||||||
|
ESP_LOGI(L_NETWORK, "Start fallback AP");
|
||||||
|
startAccessPoint();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Captive DNS and mDNS
|
||||||
|
static void stopCaptiveDns(bool complete = false) {
|
||||||
|
if (!dnsStarted) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
dnsServer.stop();
|
||||||
|
dnsStarted = false;
|
||||||
|
lastDnsAttempt = 0;
|
||||||
|
|
||||||
|
if (complete) {
|
||||||
|
setNetworkState(NetworkMode::AP, NetworkState::PORTAL_COMPLETE);
|
||||||
|
}
|
||||||
|
|
||||||
|
setNetworkState(
|
||||||
|
NetworkMode::AP,
|
||||||
|
apStarted.load() ? NetworkState::AP_STARTED : NetworkState::NETWORK_DISABLED
|
||||||
|
);
|
||||||
|
notifyNetworkEvent(NetworkEvent::PORTAL_STOPPED);
|
||||||
|
ESP_LOGD(L_PORTAL_DNSSERVER, "Stopped");
|
||||||
|
}
|
||||||
|
|
||||||
|
static void stopMdns() {
|
||||||
|
if (mdnsStarted) {
|
||||||
|
MDNS.end();
|
||||||
|
mdnsStarted = false;
|
||||||
|
lastMdnsAttempt = 0;
|
||||||
|
notifyNetworkEvent(NetworkEvent::MDNS_STOPPED);
|
||||||
|
ESP_LOGD(L_PORTAL_WEBSERVER, "mDNS disabled");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void updateNetworkServices() {
|
||||||
|
const bool ready = webServerReady;
|
||||||
|
|
||||||
|
// Serve captive DNS only while HTTP is ready and no upstream connection exists.
|
||||||
|
const bool captive = ready
|
||||||
|
&& apStarted.load()
|
||||||
|
&& apIp
|
||||||
|
&& !isNetworkConnected();
|
||||||
|
|
||||||
|
if (!captive) {
|
||||||
|
stopCaptiveDns(isNetworkConnected());
|
||||||
|
|
||||||
|
} else if (!dnsStarted && (!lastDnsAttempt || millis() - lastDnsAttempt >= 5000)) {
|
||||||
|
lastDnsAttempt = millis();
|
||||||
|
setNetworkState(NetworkMode::AP, NetworkState::PORTAL_STARTING);
|
||||||
|
|
||||||
|
if (dnsServer.start(53, "*", IPAddress(apIp))) {
|
||||||
|
dnsStarted = true;
|
||||||
|
setNetworkState(NetworkMode::AP, NetworkState::PORTAL_STARTED);
|
||||||
|
notifyNetworkEvent(NetworkEvent::PORTAL_STARTED);
|
||||||
|
ESP_LOGD(L_PORTAL_DNSSERVER, "Started: AP up");
|
||||||
|
|
||||||
|
} else {
|
||||||
|
dnsServer.stop();
|
||||||
|
setNetworkState(NetworkMode::AP, NetworkState::AP_STARTED);
|
||||||
|
ESP_LOGE(L_PORTAL_DNSSERVER, "Failed start DNS");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Advertise HTTP on either interface, including while the fallback AP is active.
|
||||||
|
const bool enableMdns = ready
|
||||||
|
&& settings.portal.mdns
|
||||||
|
&& (apStarted.load() || isNetworkConnected());
|
||||||
|
|
||||||
|
if (!enableMdns) {
|
||||||
|
stopMdns();
|
||||||
|
|
||||||
|
} else {
|
||||||
|
if (mdnsStarted && strcmp(mdnsHostname, networkSettings.hostname) != 0) {
|
||||||
|
stopMdns();
|
||||||
|
lastMdnsAttempt = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!mdnsStarted && (!lastMdnsAttempt || millis() - lastMdnsAttempt >= 5000)) {
|
||||||
|
lastMdnsAttempt = millis();
|
||||||
|
bool started = MDNS.begin(networkSettings.hostname);
|
||||||
|
|
||||||
|
if (started) {
|
||||||
|
started = MDNS.addService("http", "tcp", 80);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (started) {
|
||||||
|
strcpy(mdnsHostname, networkSettings.hostname);
|
||||||
|
mdnsStarted = true;
|
||||||
|
notifyNetworkEvent(NetworkEvent::MDNS_STARTED);
|
||||||
|
ESP_LOGD(L_PORTAL_WEBSERVER, "mDNS enabled and service added");
|
||||||
|
|
||||||
|
} else {
|
||||||
|
MDNS.end();
|
||||||
|
ESP_LOGE(L_PORTAL_WEBSERVER, "Failed start mDNS");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Event processing and recovery
|
||||||
|
static void processNetworkEvent(const PendingNetworkEvent& pending) {
|
||||||
|
switch (pending.event) {
|
||||||
|
// Station
|
||||||
|
case NetworkEvent::STA_STARTED:
|
||||||
|
// Repeated START must not invalidate an active connection.
|
||||||
|
if (staStarted.exchange(true)) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (connectionPending) {
|
||||||
|
setNetworkState(
|
||||||
|
NetworkMode::STA,
|
||||||
|
connectedTime ? NetworkState::NETWORK_RECONNECTING : NetworkState::NETWORK_CONNECTING
|
||||||
|
);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
setNetworkState(NetworkMode::STA, NetworkState::NETWORK_ENABLED);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case NetworkEvent::STA_STOPPED: {
|
||||||
|
const bool started = staStarted.exchange(false);
|
||||||
|
staAssociated = false;
|
||||||
|
disconnectReason = 0;
|
||||||
|
setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISABLED);
|
||||||
|
if (!started) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case NetworkEvent::STA_CONNECTED:
|
||||||
|
// Association alone does not confirm a usable IP address.
|
||||||
|
staAssociated = true;
|
||||||
|
break;
|
||||||
|
case NetworkEvent::STA_GOT_IP:
|
||||||
|
if (!pending.value) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// GOT_IP confirms both DHCP and configured static IPv4 after association.
|
||||||
|
// IP changes invalidate the previous client session, including A -> B -> A.
|
||||||
|
if (isNetworkConnected() && connectedIp != pending.value) {
|
||||||
|
disconnectReason = 0;
|
||||||
|
setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISCONNECTED);
|
||||||
|
}
|
||||||
|
|
||||||
|
staAssociated = true;
|
||||||
|
connectedIp = pending.value;
|
||||||
|
if (!isNetworkConnected()) {
|
||||||
|
vars.network.rssi = WiFi.STA.RSSI();
|
||||||
|
lastRssiUpdate = millis();
|
||||||
|
setNetworkState(NetworkMode::STA, NetworkState::NETWORK_CONNECTED);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case NetworkEvent::STA_DISCONNECTED:
|
||||||
|
staAssociated = false;
|
||||||
|
disconnectReason = pending.reason;
|
||||||
|
setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISCONNECTED);
|
||||||
|
break;
|
||||||
|
case NetworkEvent::STA_LOST_IP:
|
||||||
|
// Keep association so the DHCP recovery timeout remains active.
|
||||||
|
disconnectReason = 0;
|
||||||
|
setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISCONNECTED);
|
||||||
|
break;
|
||||||
|
|
||||||
|
// Access point
|
||||||
|
case NetworkEvent::AP_STARTED:
|
||||||
|
// Preserve clients and captive portal state on a repeated START.
|
||||||
|
if (apStarted.exchange(true)) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
apIp = pending.value;
|
||||||
|
apClients = 0;
|
||||||
|
setNetworkState(NetworkMode::AP, NetworkState::AP_STARTED);
|
||||||
|
break;
|
||||||
|
case NetworkEvent::AP_STOPPED: {
|
||||||
|
stopCaptiveDns();
|
||||||
|
const bool started = apStarted.exchange(false);
|
||||||
|
apIp = 0;
|
||||||
|
apClients = 0;
|
||||||
|
setNetworkState(NetworkMode::AP, NetworkState::NETWORK_DISABLED);
|
||||||
|
if (!isNetworkConnected()) {
|
||||||
|
stopMdns();
|
||||||
|
}
|
||||||
|
if (!started) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case NetworkEvent::AP_CLIENT_CONNECTED:
|
||||||
|
if (apClients < UINT8_MAX) {
|
||||||
|
++apClients;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case NetworkEvent::AP_CLIENT_DISCONNECTED:
|
||||||
|
if (apClients) {
|
||||||
|
--apClients;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
notifyNetworkEvent(pending.event);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void processNetworkEvents() {
|
||||||
|
const bool overflowed = networkEventsOverflowed.exchange(false);
|
||||||
|
const bool recoveryRequested = networkRecoveryRequested.exchange(false);
|
||||||
|
|
||||||
|
if (overflowed || recoveryRequested) {
|
||||||
|
// Lost events invalidate published state immediately, even during the reset cooldown.
|
||||||
|
xQueueReset(networkEventQueue);
|
||||||
|
stopCaptiveDns();
|
||||||
|
stopMdns();
|
||||||
|
staStarted.store(false);
|
||||||
|
apStarted.store(false);
|
||||||
|
staAssociated = false;
|
||||||
|
setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISABLED);
|
||||||
|
setNetworkState(NetworkMode::AP, NetworkState::NETWORK_DISABLED);
|
||||||
|
|
||||||
|
if (overflowed) {
|
||||||
|
ESP_LOGW(L_NETWORK, "Network event queue overflow, reset WiFi requested");
|
||||||
|
notifyNetworkEvent(NetworkEvent::EVENTS_OVERFLOW);
|
||||||
|
}
|
||||||
|
|
||||||
|
recoveryPending = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (recoveryPending) {
|
||||||
|
// Limit driver resets, but keep the published state offline while waiting.
|
||||||
|
if (lastNetworkRecoveryAttempt && millis() - lastNetworkRecoveryAttempt < 15000) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
lastNetworkRecoveryAttempt = millis();
|
||||||
|
// Keep callbacks nonblocking; recover through the existing full-reset path.
|
||||||
|
ESP_LOGW(L_NETWORK, "Reset WiFi after network event failure...");
|
||||||
|
if (!resetWifi()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
recoveryPending = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bound each pass so event bursts leave time for the rest of the worker.
|
||||||
|
PendingNetworkEvent pending;
|
||||||
|
for (size_t count = 0; count < NETWORK_EVENT_QUEUE_LENGTH; ++count) {
|
||||||
|
if (xQueueReceive(networkEventQueue, &pending, 0) != pdTRUE) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
processNetworkEvent(pending);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Connection services
|
||||||
|
static void updateRssi() {
|
||||||
|
if (isNetworkConnected() && millis() - lastRssiUpdate >= 1000) {
|
||||||
|
vars.network.rssi = WiFi.STA.RSSI();
|
||||||
|
lastRssiUpdate = millis();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void updateNtp() {
|
||||||
|
if (!ntpStarted && settings.system.ntp.server[0]) {
|
||||||
|
configTime(0, 0, settings.system.ntp.server);
|
||||||
|
setenv("TZ", settings.system.ntp.timezone, 1);
|
||||||
|
tzset();
|
||||||
|
ntpStarted = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void logNetworkState(NetworkMode mode, NetworkState previous, NetworkState state) {
|
||||||
|
if (mode != NetworkMode::STA) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state == NetworkState::NETWORK_CONNECTED) {
|
||||||
|
ESP_LOGI(
|
||||||
|
L_NETWORK,
|
||||||
|
"Connected, downtime: %lu s., IP: %s, RSSI: %hhd",
|
||||||
|
(millis() - disconnectedTime) / 1000,
|
||||||
|
IPAddress(connectedIp).toString().c_str(),
|
||||||
|
vars.network.rssi
|
||||||
|
);
|
||||||
|
|
||||||
|
} else if (previous == NetworkState::NETWORK_CONNECTED) {
|
||||||
|
ESP_LOGI(
|
||||||
|
L_NETWORK,
|
||||||
|
"Disconnected, reason: %hhu, uptime: %lu s.",
|
||||||
|
disconnectReason,
|
||||||
|
(millis() - connectedTime) / 1000
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tasks
|
||||||
|
static Task networkStartTask("Start network services", Task::Type::ONCE, [](void*) {
|
||||||
|
if (webServerReady || (!isNetworkInterfaceStarted(NetworkMode::AP) && !isNetworkConnected())) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
webServer->begin();
|
||||||
|
webServerReady = true;
|
||||||
|
configureLoggingTask.resume();
|
||||||
|
ESP_LOGD(L_PORTAL_WEBSERVER, "Started: AP up or STA connected");
|
||||||
|
});
|
||||||
|
|
||||||
|
static Task reconnectTask("Reconnect network", Task::Type::ONCE, [](void*) {
|
||||||
|
ESP_LOGI(L_NETWORK, "Reconnecting...");
|
||||||
|
|
||||||
|
const bool wasStarted = WiFi.STA.started();
|
||||||
|
if (!WiFi.STA.end()) {
|
||||||
|
ESP_LOGW(L_NETWORK, "Failed stop STA, reset WiFi...");
|
||||||
|
resetWifi();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (wasStarted) {
|
||||||
|
postInterfaceStopped(ARDUINO_EVENT_WIFI_STA_STOP);
|
||||||
|
}
|
||||||
|
|
||||||
|
lastConnectionAttempt = 0;
|
||||||
|
connectionPending = false;
|
||||||
|
});
|
||||||
|
|
||||||
|
static Task networkTask("Network", [](void*) {
|
||||||
|
// Delay explicit reconnects so the HTTP handler can finish its response.
|
||||||
|
if (reconnectRequested.exchange(false)) {
|
||||||
|
reconnectTask.resume(5000);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply queued transitions before using the interfaces and services.
|
||||||
|
processNetworkEvents();
|
||||||
|
if (!isNetworkConnected()) {
|
||||||
|
Sensors::setConnectionStatusByType(Sensors::Type::MANUAL, false, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (recoveryPending
|
||||||
|
|| networkRecoveryRequested.load()
|
||||||
|
|| networkEventsOverflowed.load()
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
updateRssi();
|
||||||
|
updateNetworkServices();
|
||||||
|
|
||||||
|
// Continue processing events and services during the reconnect delay.
|
||||||
|
if (!reconnectTask.paused()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isNetworkConnected()) {
|
||||||
|
if (connectionPending) {
|
||||||
|
connectionPending = false;
|
||||||
|
lastConnectionAttempt = millis();
|
||||||
|
}
|
||||||
|
|
||||||
|
updateNtp();
|
||||||
|
updateAccessPoint();
|
||||||
|
|
||||||
|
} else {
|
||||||
|
updateAccessPoint();
|
||||||
|
updateConnection();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Initialization
|
||||||
|
void initNetwork() {
|
||||||
|
// The queue must exist before registering framework callbacks or starting WiFi.
|
||||||
|
networkEventQueue = xQueueCreateStatic(
|
||||||
|
NETWORK_EVENT_QUEUE_LENGTH,
|
||||||
|
sizeof(PendingNetworkEvent),
|
||||||
|
networkEventBuffer,
|
||||||
|
&networkEventQueueStorage
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!networkEventQueue) {
|
||||||
|
ESP_LOGE(L_NETWORK, "Failed create network event queue");
|
||||||
|
std::abort();
|
||||||
|
}
|
||||||
|
|
||||||
|
dnsServer.setTTL(0);
|
||||||
|
dnsServer.setErrorReplyCode(DNSReplyCode::NoError);
|
||||||
|
|
||||||
|
onNetworkEvent([](NetworkEvent event) {
|
||||||
|
if (!webServerReady && (event == NetworkEvent::AP_STARTED || event == NetworkEvent::CONNECTED)) {
|
||||||
|
networkStartTask.resume();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Network.begin();
|
||||||
|
Network.onEvent(handleWifiEvent);
|
||||||
|
onNetworkStateChange(logNetworkState);
|
||||||
|
WiFi.persistent(false);
|
||||||
|
WiFi.STA.setAutoReconnect(false);
|
||||||
|
Network.setHostname(networkSettings.hostname);
|
||||||
|
|
||||||
|
networkTask.setInterval(100);
|
||||||
|
systemTaskManager.addTask(reconnectTask);
|
||||||
|
systemTaskManager.addTask(networkTask);
|
||||||
|
systemTaskManager.addTask(networkStartTask);
|
||||||
|
}
|
||||||
@@ -0,0 +1,985 @@
|
|||||||
|
#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE
|
||||||
|
|
||||||
|
#include <app.h>
|
||||||
|
#include <metrics.h>
|
||||||
|
//#define PORTAL_CACHE "max-age=86400"
|
||||||
|
#define PORTAL_CACHE nullptr
|
||||||
|
|
||||||
|
#include <AsyncTCP.h>
|
||||||
|
#include <ESPAsyncWebServer.h>
|
||||||
|
#include <AsyncJson.h>
|
||||||
|
#include <ArduinoJson.h>
|
||||||
|
#include <LittleFS.h>
|
||||||
|
#include <Update.h>
|
||||||
|
#include <UpgradeHandler.h>
|
||||||
|
#include <WiFi.h>
|
||||||
|
#include <MycilaWebSerial.h>
|
||||||
|
|
||||||
|
#include <esp_core_dump.h>
|
||||||
|
#include <esp_partition.h>
|
||||||
|
|
||||||
|
#include <cstdio>
|
||||||
|
#include <cstring>
|
||||||
|
#include <ctime>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
WebSerial* webSerial = nullptr;
|
||||||
|
|
||||||
|
AsyncWebServer* webServer = nullptr;
|
||||||
|
|
||||||
|
enum class RequestInterface : uint8_t {
|
||||||
|
UNKNOWN,
|
||||||
|
AP,
|
||||||
|
STA,
|
||||||
|
ETH
|
||||||
|
};
|
||||||
|
|
||||||
|
static RequestInterface getRequestInterface(AsyncWebServerRequest* request) {
|
||||||
|
if (request == nullptr || request->client() == nullptr) {
|
||||||
|
return RequestInterface::UNKNOWN;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Classify the connection by its destination address.
|
||||||
|
const IPAddress localIP = request->client()->localIP();
|
||||||
|
if (localIP == IPAddress(0, 0, 0, 0)) {
|
||||||
|
return RequestInterface::UNKNOWN;
|
||||||
|
}
|
||||||
|
|
||||||
|
const IPAddress apIP = WiFi.AP.localIP();
|
||||||
|
const IPAddress staIP = WiFi.STA.localIP();
|
||||||
|
if (localIP == apIP && localIP == staIP) {
|
||||||
|
// Matching AP/STA addresses cannot identify the interface.
|
||||||
|
return RequestInterface::UNKNOWN;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (localIP == apIP) {
|
||||||
|
return RequestInterface::AP;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (localIP == staIP) {
|
||||||
|
return RequestInterface::STA;
|
||||||
|
}
|
||||||
|
|
||||||
|
return RequestInterface::UNKNOWN;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void onCaptivePortal(AsyncWebServerRequest *request) {
|
||||||
|
const auto& url = request->url();
|
||||||
|
|
||||||
|
if (url.equals("/connecttest.txt")) {
|
||||||
|
request->redirect("http://logout.net", 302);
|
||||||
|
|
||||||
|
ESP_LOGD(L_PORTAL_CAPTIVE, "Redirect to http://logout.net with 302 code");
|
||||||
|
|
||||||
|
} else if (url.equals("/wpad.dat")) {
|
||||||
|
request->send(404);
|
||||||
|
|
||||||
|
ESP_LOGD(L_PORTAL_CAPTIVE, "Send empty page with 404 code");
|
||||||
|
|
||||||
|
} else if (url.equals("/success.txt")) {
|
||||||
|
request->send(200);
|
||||||
|
|
||||||
|
ESP_LOGD(L_PORTAL_CAPTIVE, "Send empty page with 200 code");
|
||||||
|
|
||||||
|
} else {
|
||||||
|
std::string portalUrl;
|
||||||
|
portalUrl.reserve(7 + 15 + 1);
|
||||||
|
portalUrl = "http://";
|
||||||
|
portalUrl += WiFi.AP.localIP().toString().c_str();
|
||||||
|
portalUrl += '/';
|
||||||
|
|
||||||
|
request->redirect(portalUrl.c_str(), 302);
|
||||||
|
|
||||||
|
ESP_LOGD(L_PORTAL_CAPTIVE, "Redirect to portal page with 302 code");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool isAuthenticationRequired(AsyncWebServerRequest* request) {
|
||||||
|
if (isNetworkInterfaceStarted(NetworkMode::AP) && getRequestInterface(request) == RequestInterface::AP) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return settings.portal.auth && strlen(settings.portal.password);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void setDownloadFilename(AsyncWebServerResponse* response, const char* type, const char* extension) {
|
||||||
|
const time_t now = time(nullptr);
|
||||||
|
|
||||||
|
tm localNow {};
|
||||||
|
localtime_r(&now, &localNow);
|
||||||
|
|
||||||
|
char localNowValue[20];
|
||||||
|
strftime(localNowValue, sizeof(localNowValue), "%Y-%m-%d-%H-%M-%S", &localNow);
|
||||||
|
|
||||||
|
char contentDisposition[96];
|
||||||
|
snprintf(
|
||||||
|
contentDisposition, sizeof(contentDisposition),
|
||||||
|
"attachment; filename=\"%s_%s_%s.%s\"",
|
||||||
|
networkSettings.hostname, localNowValue, type, extension
|
||||||
|
);
|
||||||
|
response->addHeader("Content-Disposition", contentDisposition);
|
||||||
|
}
|
||||||
|
|
||||||
|
// auth middleware
|
||||||
|
static AsyncMiddlewareFunction authMiddleware([](AsyncWebServerRequest *request, ArMiddlewareNext next) {
|
||||||
|
if (!isAuthenticationRequired(request)) {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request->authenticate(settings.portal.login, settings.portal.password, PROJECT_NAME)) {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
|
||||||
|
return request->requestAuthentication(AsyncAuthType::AUTH_BASIC, PROJECT_NAME, "Authentication failed");
|
||||||
|
});
|
||||||
|
|
||||||
|
static void initWebSerial() {
|
||||||
|
// Register before System starts. Unbuffered WebSerial preserves newlines inside each record.
|
||||||
|
webSerial = new WebSerial();
|
||||||
|
webSerial->begin(webServer, nullptr, "/webserial");
|
||||||
|
|
||||||
|
webServer->addMiddleware([](AsyncWebServerRequest* request, ArMiddlewareNext next) {
|
||||||
|
if (request->url().equals("/webserial")) {
|
||||||
|
if (!settings.system.webSerial.enabled) {
|
||||||
|
request->send(404);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refresh credentials before each handshake, including after re-enabling.
|
||||||
|
if (isAuthenticationRequired(request)) {
|
||||||
|
webSerial->setAuthentication(settings.portal.login, settings.portal.password);
|
||||||
|
} else {
|
||||||
|
webSerial->setAuthentication("", "");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
static void routes() {
|
||||||
|
// index page
|
||||||
|
webServer->on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||||
|
request->redirect("/index.html");
|
||||||
|
});
|
||||||
|
webServer->serveStatic("/index.html", LittleFS, "/pages/index.html", PORTAL_CACHE);
|
||||||
|
|
||||||
|
// dashboard page
|
||||||
|
webServer->serveStatic("/dashboard.html", LittleFS, "/pages/dashboard.html", PORTAL_CACHE)
|
||||||
|
.addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
// network settings page
|
||||||
|
webServer->serveStatic("/network.html", LittleFS, "/pages/network.html", PORTAL_CACHE)
|
||||||
|
.addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
// settings page
|
||||||
|
webServer->serveStatic("/settings.html", LittleFS, "/pages/settings.html", PORTAL_CACHE)
|
||||||
|
.addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
// sensors page
|
||||||
|
webServer->serveStatic("/sensors.html", LittleFS, "/pages/sensors.html", PORTAL_CACHE)
|
||||||
|
.addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
// upgrade page
|
||||||
|
webServer->serveStatic("/upgrade.html", LittleFS, "/pages/upgrade.html", PORTAL_CACHE)
|
||||||
|
.addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
// logs page
|
||||||
|
webServer->serveStatic("/logs.html", LittleFS, "/pages/logs.html", PORTAL_CACHE)
|
||||||
|
.addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
// not found
|
||||||
|
webServer->onNotFound([](AsyncWebServerRequest *request) {
|
||||||
|
const auto& url = request->url();
|
||||||
|
ESP_LOGD(L_PORTAL_WEBSERVER, "Page not found, uri: %s", url.c_str());
|
||||||
|
|
||||||
|
if (url.equals("/index.html")) {
|
||||||
|
request->send(200, "text/plain", "The file system is not flashed!");
|
||||||
|
|
||||||
|
} else if (getNetworkState(NetworkMode::AP) == NetworkState::PORTAL_STARTED && getRequestInterface(request) == RequestInterface::AP) {
|
||||||
|
onCaptivePortal(request);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
request->send(404, "text/plain", "Page not found");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
webServer->serveStatic("/robots.txt", LittleFS, "/static/robots.txt", PORTAL_CACHE);
|
||||||
|
webServer->serveStatic("/favicon.ico", LittleFS, "/static/images/favicon.ico", PORTAL_CACHE);
|
||||||
|
webServer->serveStatic("/static", LittleFS, "/static", PORTAL_CACHE);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void restApi() {
|
||||||
|
// OTA
|
||||||
|
auto upgradeHandler = (new UpgradeHandler("/api/upgrade"))
|
||||||
|
->setBeforeUpgradeCallback([](AsyncWebServerRequest *request, UpgradeHandler::UpgradeType type) -> bool {
|
||||||
|
// Upload callbacks run before middleware; reject before pausing tasks or writing.
|
||||||
|
if (isAuthenticationRequired(request) && !request->authenticate(settings.portal.login, settings.portal.password, PROJECT_NAME)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (restartTask.scheduled() || restartTask.active()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// UpgradeHandler invokes this callback for every upload chunk.
|
||||||
|
if (vars.states.upgrading) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
vars.states.upgrading = true;
|
||||||
|
coreTaskManager.pause();
|
||||||
|
// Core owns MQTT; finish its current callback before stopping the client.
|
||||||
|
if (!coreTaskManager.waitForPaused(5000)) {
|
||||||
|
vars.states.upgrading = false;
|
||||||
|
if (!restartTask.scheduled() && !restartTask.active()) {
|
||||||
|
coreTaskManager.resume();
|
||||||
|
}
|
||||||
|
ESP_LOGW(L_PORTAL_OTA, "Core task manager pause not confirmed, upgrade cancelled");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
stopMqtt(false);
|
||||||
|
|
||||||
|
// An MQTT command already in flight may have scheduled a restart before end().
|
||||||
|
if (restartTask.scheduled() || restartTask.active()) {
|
||||||
|
vars.states.upgrading = false;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
sensorsTaskManager.pause();
|
||||||
|
if (!sensorsTaskManager.waitForPaused(5000)) {
|
||||||
|
requestReconfigureMqtt();
|
||||||
|
vars.states.upgrading = false;
|
||||||
|
if (!restartTask.scheduled() && !restartTask.active()) {
|
||||||
|
coreTaskManager.resume();
|
||||||
|
sensorsTaskManager.resume();
|
||||||
|
}
|
||||||
|
ESP_LOGW(L_PORTAL_OTA, "Sensors task manager pause not confirmed, upgrade cancelled");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
openthermTaskManager.pause();
|
||||||
|
if (!openthermTaskManager.waitForPaused(5000)) {
|
||||||
|
requestReconfigureMqtt();
|
||||||
|
vars.states.upgrading = false;
|
||||||
|
if (!restartTask.scheduled() && !restartTask.active()) {
|
||||||
|
coreTaskManager.resume();
|
||||||
|
sensorsTaskManager.resume();
|
||||||
|
openthermTaskManager.resume();
|
||||||
|
}
|
||||||
|
ESP_LOGW(L_PORTAL_OTA, "OpenTherm task manager pause not confirmed, upgrade cancelled");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
})->setAfterUpgradeCallback([](AsyncWebServerRequest *request, const UpgradeHandler::UpgradeResult& fwResult, const UpgradeHandler::UpgradeResult& fsResult) {
|
||||||
|
if (request && isAuthenticationRequired(request) && !request->authenticate(settings.portal.login, settings.portal.password, PROJECT_NAME)) {
|
||||||
|
return request->requestAuthentication(AsyncAuthType::AUTH_BASIC, PROJECT_NAME, "Authentication failed");
|
||||||
|
}
|
||||||
|
|
||||||
|
unsigned short status = 406;
|
||||||
|
if (fwResult.status == UpgradeHandler::UpgradeStatus::SUCCESS || fsResult.status == UpgradeHandler::UpgradeStatus::SUCCESS) {
|
||||||
|
status = 202;
|
||||||
|
if (!restartTask.scheduled() && !restartTask.active()) {
|
||||||
|
restartTask.resume(15000);
|
||||||
|
}
|
||||||
|
|
||||||
|
} else {
|
||||||
|
requestReconfigureMqtt();
|
||||||
|
}
|
||||||
|
|
||||||
|
vars.states.upgrading = false;
|
||||||
|
if (status != 202 && !restartTask.scheduled() && !restartTask.active()) {
|
||||||
|
coreTaskManager.resume();
|
||||||
|
sensorsTaskManager.resume();
|
||||||
|
openthermTaskManager.resume();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!request) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// make response
|
||||||
|
auto *response = new AsyncJsonResponse();
|
||||||
|
auto& doc = response->getRoot();
|
||||||
|
|
||||||
|
auto fwDoc = doc["firmware"].to<JsonObject>();
|
||||||
|
fwDoc["status"] = static_cast<uint8_t>(fwResult.status);
|
||||||
|
fwDoc["error"] = fwResult.error;
|
||||||
|
|
||||||
|
auto fsDoc = doc["filesystem"].to<JsonObject>();
|
||||||
|
fsDoc["status"] = static_cast<uint8_t>(fsResult.status);
|
||||||
|
fsDoc["error"] = fsResult.error;
|
||||||
|
|
||||||
|
// send response
|
||||||
|
response->setLength();
|
||||||
|
response->setCode(status);
|
||||||
|
request->send(response);
|
||||||
|
});
|
||||||
|
upgradeHandler->addMiddleware(&authMiddleware);
|
||||||
|
webServer->addHandler(upgradeHandler);
|
||||||
|
|
||||||
|
|
||||||
|
// backup
|
||||||
|
webServer->on("/api/backup/save", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||||
|
// make response
|
||||||
|
auto *response = new AsyncJsonResponse();
|
||||||
|
auto& doc = response->getRoot();
|
||||||
|
|
||||||
|
// add network settings
|
||||||
|
auto networkDoc = doc[S_NETWORK].to<JsonObject>();
|
||||||
|
toJson(networkSettings, networkDoc);
|
||||||
|
|
||||||
|
// add main settings
|
||||||
|
auto settingsDoc = doc[S_SETTINGS].to<JsonObject>();
|
||||||
|
toJson(settings.system, settingsDoc[S_SYSTEM].to<JsonObject>());
|
||||||
|
toJson(settings.portal, settingsDoc[S_PORTAL].to<JsonObject>());
|
||||||
|
toJson(settings.opentherm, settingsDoc[S_OPENTHERM].to<JsonObject>());
|
||||||
|
toJson(settings.mqtt, settingsDoc[S_MQTT].to<JsonObject>());
|
||||||
|
toJson(settings.emergency, settingsDoc[S_EMERGENCY].to<JsonObject>());
|
||||||
|
toJson(settings.heating, settingsDoc[S_HEATING].to<JsonObject>());
|
||||||
|
toJson(settings.dhw, settingsDoc[S_DHW].to<JsonObject>());
|
||||||
|
toJson(settings.equitherm, settingsDoc[S_EQUITHERM].to<JsonObject>());
|
||||||
|
toJson(settings.pid, settingsDoc[S_PID].to<JsonObject>());
|
||||||
|
toJson(settings.externalPump, settingsDoc[S_EXTERNAL_PUMP].to<JsonObject>());
|
||||||
|
toJson(settings.cascadeControl, settingsDoc[S_CASCADE_CONTROL].to<JsonObject>());
|
||||||
|
|
||||||
|
// add sensors settings
|
||||||
|
for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) {
|
||||||
|
if (const auto sensor = Sensors::getSettings(sensorId)) {
|
||||||
|
auto sensorsettingsDoc = doc[S_SENSORS][sensorId].to<JsonObject>();
|
||||||
|
toJson(sensorId, *sensor, sensorsettingsDoc);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// send response
|
||||||
|
setDownloadFilename(response, "backup", "json");
|
||||||
|
response->setLength();
|
||||||
|
request->send(response);
|
||||||
|
}).addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
// restart
|
||||||
|
webServer->on("/api/restart", HTTP_POST, [](AsyncWebServerRequest *request) {
|
||||||
|
if (vars.states.upgrading || restartTask.scheduled() || restartTask.active()) {
|
||||||
|
return request->send(503);
|
||||||
|
}
|
||||||
|
|
||||||
|
restartTask.resume(15000);
|
||||||
|
request->send(202);
|
||||||
|
}).addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
// network
|
||||||
|
webServer->on("/api/network/settings", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||||
|
// make response
|
||||||
|
auto *response = new AsyncJsonResponse();
|
||||||
|
auto& doc = response->getRoot();
|
||||||
|
toJson(networkSettings, doc);
|
||||||
|
|
||||||
|
// send response
|
||||||
|
response->setLength();
|
||||||
|
request->send(response);
|
||||||
|
}).addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
auto& nsHandler = webServer->on("/api/network/settings", HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) {
|
||||||
|
if (vars.states.upgrading || restartTask.scheduled() || restartTask.active()) {
|
||||||
|
return request->send(503);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (requestDoc.isNull() || !requestDoc.size()) {
|
||||||
|
return request->send(400);
|
||||||
|
}
|
||||||
|
|
||||||
|
// prepare request
|
||||||
|
const auto result = fromJson(requestDoc, networkSettings);
|
||||||
|
if (result.changed) {
|
||||||
|
requestSaveNetworkSettings();
|
||||||
|
}
|
||||||
|
requestDoc.clear();
|
||||||
|
|
||||||
|
if (request->hasParam("noresponse")) {
|
||||||
|
request->send(result.changed ? 201 : 200);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
// make response
|
||||||
|
auto *response = new AsyncJsonResponse();
|
||||||
|
auto& responseDoc = response->getRoot();
|
||||||
|
toJson(networkSettings, responseDoc);
|
||||||
|
|
||||||
|
// send response
|
||||||
|
response->setLength();
|
||||||
|
response->setCode(result.changed ? 201 : 200);
|
||||||
|
request->send(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.changed && !request->hasParam("noreconnect")) {
|
||||||
|
// Queue the response before a network reset can disconnect this request.
|
||||||
|
reconnectNetwork();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
nsHandler.setMaxContentLength(512);
|
||||||
|
nsHandler.addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
webServer->on("/api/network/scan", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||||
|
auto apCount = WiFi.scanComplete();
|
||||||
|
|
||||||
|
switch (apCount) {
|
||||||
|
case WIFI_SCAN_FAILED:
|
||||||
|
WiFi.scanNetworks(true, true, true);
|
||||||
|
request->send(404);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case WIFI_SCAN_RUNNING:
|
||||||
|
request->send(202);
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
// make respponse
|
||||||
|
auto *response = new AsyncJsonResponse(true);
|
||||||
|
auto& doc = response->getRoot();
|
||||||
|
for (short int i = 0; i < apCount; i++) {
|
||||||
|
doc[i][S_SSID] = WiFi.SSID(i);
|
||||||
|
doc[i][S_BSSID] = WiFi.BSSIDstr(i);
|
||||||
|
doc[i][S_SIGNAL_QUALITY] = rssiToSignalQuality(WiFi.RSSI(i));
|
||||||
|
doc[i][S_CHANNEL] = WiFi.channel(i);
|
||||||
|
doc[i][S_HIDDEN] = !WiFi.SSID(i).length();
|
||||||
|
doc[i][S_AUTH] = WiFi.encryptionType(i);
|
||||||
|
}
|
||||||
|
|
||||||
|
// send response
|
||||||
|
response->setLength();
|
||||||
|
request->send(response);
|
||||||
|
|
||||||
|
// clear
|
||||||
|
WiFi.scanDelete();
|
||||||
|
}
|
||||||
|
}).addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
|
||||||
|
// settings
|
||||||
|
webServer->on(AsyncURIMatcher::prefix("/api/settings/"), HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||||
|
const auto& url = request->url();
|
||||||
|
const auto section = std::string_view(url.c_str(), url.length())
|
||||||
|
.substr(sizeof("/api/settings/") - 1);
|
||||||
|
auto *response = new AsyncJsonResponse();
|
||||||
|
auto& doc = response->getRoot();
|
||||||
|
|
||||||
|
if (section == S_SYSTEM) {
|
||||||
|
toJson(settings.system, doc);
|
||||||
|
|
||||||
|
} else if (section == S_PORTAL) {
|
||||||
|
toJson(settings.portal, doc);
|
||||||
|
|
||||||
|
} else if (section == S_OPENTHERM) {
|
||||||
|
toJson(settings.opentherm, doc);
|
||||||
|
|
||||||
|
} else if (section == S_MQTT) {
|
||||||
|
toJson(settings.mqtt, doc);
|
||||||
|
|
||||||
|
} else if (section == S_EMERGENCY) {
|
||||||
|
toJson(settings.emergency, doc);
|
||||||
|
|
||||||
|
} else if (section == S_HEATING) {
|
||||||
|
toJson(settings.heating, doc);
|
||||||
|
|
||||||
|
} else if (section == S_DHW) {
|
||||||
|
toJson(settings.dhw, doc);
|
||||||
|
|
||||||
|
} else if (section == S_PID) {
|
||||||
|
toJson(settings.pid, doc);
|
||||||
|
|
||||||
|
} else if (section == S_EQUITHERM) {
|
||||||
|
toJson(settings.equitherm, doc);
|
||||||
|
|
||||||
|
} else if (section == S_EXTERNAL_PUMP) {
|
||||||
|
toJson(settings.externalPump, doc);
|
||||||
|
|
||||||
|
} else if (section == S_CASCADE_CONTROL) {
|
||||||
|
toJson(settings.cascadeControl, doc);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
delete response;
|
||||||
|
return request->send(404);
|
||||||
|
}
|
||||||
|
|
||||||
|
response->setLength();
|
||||||
|
request->send(response);
|
||||||
|
}).addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
auto& settingsHandler = webServer->on(AsyncURIMatcher::prefix("/api/settings/"), HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) {
|
||||||
|
if (vars.states.upgrading || restartTask.scheduled() || restartTask.active()) {
|
||||||
|
request->send(503);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!requestDoc.is<JsonObjectConst>() || !requestDoc.size()) {
|
||||||
|
request->send(400);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto& url = request->url();
|
||||||
|
const auto section = std::string_view(url.c_str(), url.length())
|
||||||
|
.substr(sizeof("/api/settings/") - 1);
|
||||||
|
SettingResult result;
|
||||||
|
bool mqttChanged = false;
|
||||||
|
|
||||||
|
if (section == S_SYSTEM) {
|
||||||
|
result = fromJson(requestDoc, settings.system);
|
||||||
|
|
||||||
|
} else if (section == S_PORTAL) {
|
||||||
|
result = fromJson(requestDoc, settings.portal);
|
||||||
|
|
||||||
|
} else if (section == S_OPENTHERM) {
|
||||||
|
result = fromJson(requestDoc, settings.opentherm);
|
||||||
|
|
||||||
|
} else if (section == S_MQTT) {
|
||||||
|
const auto previousMqtt = settings.mqtt;
|
||||||
|
result = fromJson(requestDoc, settings.mqtt);
|
||||||
|
mqttChanged = previousMqtt.enabled != settings.mqtt.enabled
|
||||||
|
|| previousMqtt.port != settings.mqtt.port
|
||||||
|
|| previousMqtt.interval != settings.mqtt.interval
|
||||||
|
|| strcmp(previousMqtt.server, settings.mqtt.server) != 0
|
||||||
|
|| strcmp(previousMqtt.user, settings.mqtt.user) != 0
|
||||||
|
|| strcmp(previousMqtt.password, settings.mqtt.password) != 0
|
||||||
|
|| strcmp(previousMqtt.prefix, settings.mqtt.prefix) != 0;
|
||||||
|
|
||||||
|
} else if (section == S_EMERGENCY) {
|
||||||
|
result = fromJson(requestDoc, settings.emergency);
|
||||||
|
|
||||||
|
} else if (section == S_HEATING) {
|
||||||
|
result = fromJson(requestDoc, settings.heating);
|
||||||
|
|
||||||
|
} else if (section == S_DHW) {
|
||||||
|
result = fromJson(requestDoc, settings.dhw);
|
||||||
|
|
||||||
|
} else if (section == S_PID) {
|
||||||
|
result = fromJson(requestDoc, settings.pid);
|
||||||
|
|
||||||
|
} else if (section == S_EQUITHERM) {
|
||||||
|
result = fromJson(requestDoc, settings.equitherm);
|
||||||
|
|
||||||
|
} else if (section == S_EXTERNAL_PUMP) {
|
||||||
|
result = fromJson(requestDoc, settings.externalPump);
|
||||||
|
|
||||||
|
} else if (section == S_CASCADE_CONTROL) {
|
||||||
|
result = fromJson(requestDoc, settings.cascadeControl);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
return request->send(404);
|
||||||
|
}
|
||||||
|
|
||||||
|
result.changed = normalizeSettings(settings) || result.changed;
|
||||||
|
if (result.changed) {
|
||||||
|
requestSaveSettings();
|
||||||
|
configureLoggingTask.resume();
|
||||||
|
if (mqttChanged) {
|
||||||
|
requestReconfigureMqtt();
|
||||||
|
}
|
||||||
|
|
||||||
|
// If busy, the periodic task will publish the current settings.
|
||||||
|
std::unique_lock<std::mutex> lock(mqttMutex, std::try_to_lock);
|
||||||
|
if (lock.owns_lock() && mqttPublishSettingsTask) {
|
||||||
|
mqttPublishSettingsTask->requestEarlyRun();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
requestDoc.clear();
|
||||||
|
|
||||||
|
if (request->hasParam("noresponse")) {
|
||||||
|
return request->send(result.changed ? 201 : 200);
|
||||||
|
}
|
||||||
|
|
||||||
|
auto *response = new AsyncJsonResponse();
|
||||||
|
auto& responseDoc = response->getRoot();
|
||||||
|
|
||||||
|
if (section == S_SYSTEM) {
|
||||||
|
toJson(settings.system, responseDoc);
|
||||||
|
|
||||||
|
} else if (section == S_PORTAL) {
|
||||||
|
toJson(settings.portal, responseDoc);
|
||||||
|
|
||||||
|
} else if (section == S_OPENTHERM) {
|
||||||
|
toJson(settings.opentherm, responseDoc);
|
||||||
|
|
||||||
|
} else if (section == S_MQTT) {
|
||||||
|
toJson(settings.mqtt, responseDoc);
|
||||||
|
|
||||||
|
} else if (section == S_EMERGENCY) {
|
||||||
|
toJson(settings.emergency, responseDoc);
|
||||||
|
|
||||||
|
} else if (section == S_HEATING) {
|
||||||
|
toJson(settings.heating, responseDoc);
|
||||||
|
|
||||||
|
} else if (section == S_DHW) {
|
||||||
|
toJson(settings.dhw, responseDoc);
|
||||||
|
|
||||||
|
} else if (section == S_PID) {
|
||||||
|
toJson(settings.pid, responseDoc);
|
||||||
|
|
||||||
|
} else if (section == S_EQUITHERM) {
|
||||||
|
toJson(settings.equitherm, responseDoc);
|
||||||
|
|
||||||
|
} else if (section == S_EXTERNAL_PUMP) {
|
||||||
|
toJson(settings.externalPump, responseDoc);
|
||||||
|
|
||||||
|
} else if (section == S_CASCADE_CONTROL) {
|
||||||
|
toJson(settings.cascadeControl, responseDoc);
|
||||||
|
}
|
||||||
|
|
||||||
|
response->setLength();
|
||||||
|
response->setCode(result.changed ? 201 : 200);
|
||||||
|
request->send(response);
|
||||||
|
});
|
||||||
|
settingsHandler.setMaxContentLength(3072);
|
||||||
|
settingsHandler.addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
|
||||||
|
// sensors list
|
||||||
|
webServer->on("/api/sensors", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||||
|
// make response
|
||||||
|
bool detailed = request->hasParam("detailed");
|
||||||
|
auto *response = new AsyncJsonResponse(true);
|
||||||
|
auto& responseDoc = response->getRoot();
|
||||||
|
|
||||||
|
// add sensors
|
||||||
|
for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) {
|
||||||
|
if (detailed) {
|
||||||
|
if (const auto snapshot = Sensors::getSnapshot(sensorId)) {
|
||||||
|
responseDoc[sensorId][S_ENABLED] = snapshot->settings.enabled;
|
||||||
|
responseDoc[sensorId][S_NAME] = static_cast<const char*>(snapshot->settings.name);
|
||||||
|
responseDoc[sensorId][S_SLUG] = static_cast<const char*>(snapshot->settings.slug);
|
||||||
|
responseDoc[sensorId][S_PURPOSE] = static_cast<uint8_t>(snapshot->settings.purpose);
|
||||||
|
toJson(snapshot->settings, snapshot->result, responseDoc[sensorId]);
|
||||||
|
}
|
||||||
|
|
||||||
|
} else if (const auto sensor = Sensors::getSettings(sensorId)) {
|
||||||
|
responseDoc[sensorId] = static_cast<const char*>(sensor->name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// send response
|
||||||
|
response->setLength();
|
||||||
|
request->send(response);
|
||||||
|
}).addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
// sensor settings
|
||||||
|
webServer->on(AsyncURIMatcher::exact("/api/sensor"), HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||||
|
if (!request->hasParam("id")) {
|
||||||
|
return request->send(400);
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto& id = request->getParam("id")->value();
|
||||||
|
const auto sensorId = Sensors::parseId(id.c_str());
|
||||||
|
if (!sensorId) {
|
||||||
|
return request->send(404);
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto sensor = Sensors::getSettings(*sensorId);
|
||||||
|
if (!sensor) {
|
||||||
|
return request->send(404);
|
||||||
|
}
|
||||||
|
auto *response = new AsyncJsonResponse();
|
||||||
|
auto& doc = response->getRoot();
|
||||||
|
toJson(*sensorId, *sensor, doc);
|
||||||
|
|
||||||
|
response->setLength();
|
||||||
|
request->send(response);
|
||||||
|
}).addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
auto& ssHandler = webServer->on(AsyncURIMatcher::exact("/api/sensor"), HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) {
|
||||||
|
if (vars.states.upgrading || restartTask.scheduled() || restartTask.active()) {
|
||||||
|
return request->send(503);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (requestDoc.isNull() || !requestDoc.size()) {
|
||||||
|
return request->send(400);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!request->hasParam("id")) {
|
||||||
|
return request->send(400);
|
||||||
|
}
|
||||||
|
|
||||||
|
auto& id = request->getParam("id")->value();
|
||||||
|
const auto sensorId = Sensors::parseId(id.c_str());
|
||||||
|
if (!sensorId) {
|
||||||
|
return request->send(404);
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto previousSettings = Sensors::getSettings(*sensorId);
|
||||||
|
if (!previousSettings) {
|
||||||
|
return request->send(404);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool isDifferent = false;
|
||||||
|
SettingResult result;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(Sensors::mutex);
|
||||||
|
auto& sensor = Sensors::settings[*sensorId];
|
||||||
|
|
||||||
|
result = fromJson(requestDoc, sensor);
|
||||||
|
if (result.changed) {
|
||||||
|
isDifferent |= previousSettings->enabled != sensor.enabled;
|
||||||
|
isDifferent |= strcmp(previousSettings->name, sensor.name) != 0;
|
||||||
|
isDifferent |= strcmp(previousSettings->slug, sensor.slug) != 0;
|
||||||
|
isDifferent |= previousSettings->purpose != sensor.purpose;
|
||||||
|
isDifferent |= previousSettings->type != sensor.type;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.changed) {
|
||||||
|
if (isDifferent) {
|
||||||
|
requestReconfigureMqttSensor(*sensorId, *previousSettings);
|
||||||
|
}
|
||||||
|
|
||||||
|
requestSaveSensorsSettings();
|
||||||
|
}
|
||||||
|
requestDoc.clear();
|
||||||
|
|
||||||
|
if (request->hasParam("noresponse")) {
|
||||||
|
return request->send(result.changed ? 201 : 200);
|
||||||
|
}
|
||||||
|
|
||||||
|
// make response
|
||||||
|
auto *response = new AsyncJsonResponse();
|
||||||
|
auto& responseDoc = response->getRoot();
|
||||||
|
|
||||||
|
if (const auto sensor = Sensors::getSettings(*sensorId)) {
|
||||||
|
toJson(*sensorId, *sensor, responseDoc);
|
||||||
|
}
|
||||||
|
|
||||||
|
// send response
|
||||||
|
response->setLength();
|
||||||
|
response->setCode(result.changed ? 201 : 200);
|
||||||
|
request->send(response);
|
||||||
|
});
|
||||||
|
ssHandler.setMaxContentLength(1024);
|
||||||
|
ssHandler.addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
|
||||||
|
// sensor measurements
|
||||||
|
webServer->on(AsyncURIMatcher::exact("/api/sensor/value"), HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||||
|
if (!request->hasParam("id")) {
|
||||||
|
return request->send(400);
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto& id = request->getParam("id")->value();
|
||||||
|
const auto sensorId = Sensors::parseId(id.c_str());
|
||||||
|
if (!sensorId) {
|
||||||
|
return request->send(404);
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto sensor = Sensors::getSnapshot(*sensorId);
|
||||||
|
if (!sensor) {
|
||||||
|
return request->send(404);
|
||||||
|
}
|
||||||
|
|
||||||
|
auto *response = new AsyncJsonResponse();
|
||||||
|
auto& doc = response->getRoot();
|
||||||
|
toJson(sensor->settings, sensor->result, doc);
|
||||||
|
response->setLength();
|
||||||
|
request->send(response);
|
||||||
|
}).addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
auto& sensorValueHandler = webServer->on(AsyncURIMatcher::exact("/api/sensor/value"), HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) {
|
||||||
|
if (vars.states.upgrading || restartTask.scheduled() || restartTask.active()) {
|
||||||
|
return request->send(503);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!requestDoc.is<JsonObjectConst>() || !requestDoc.size()) {
|
||||||
|
return request->send(400);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!request->hasParam("id")) {
|
||||||
|
return request->send(400);
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto& id = request->getParam("id")->value();
|
||||||
|
const auto sensorId = Sensors::parseId(id.c_str());
|
||||||
|
if (!sensorId) {
|
||||||
|
return request->send(404);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!requestDoc[S_VALUE].is<float>()) {
|
||||||
|
return request->send(400);
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto value = requestDoc[S_VALUE].as<float>();
|
||||||
|
requestDoc.clear();
|
||||||
|
if (!Sensors::setManualValueById(*sensorId, value, settings.system.unitSystem)) {
|
||||||
|
return request->send(400);
|
||||||
|
}
|
||||||
|
|
||||||
|
requestPublishMqttSensor(*sensorId);
|
||||||
|
|
||||||
|
if (request->hasParam("noresponse")) {
|
||||||
|
return request->send(201);
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto sensor = Sensors::getSnapshot(*sensorId);
|
||||||
|
if (!sensor) {
|
||||||
|
return request->send(404);
|
||||||
|
}
|
||||||
|
|
||||||
|
auto *response = new AsyncJsonResponse();
|
||||||
|
auto& responseDoc = response->getRoot();
|
||||||
|
toJson(sensor->settings, sensor->result, responseDoc);
|
||||||
|
response->setLength();
|
||||||
|
response->setCode(201);
|
||||||
|
request->send(response);
|
||||||
|
});
|
||||||
|
sensorValueHandler.setMaxContentLength(1024);
|
||||||
|
sensorValueHandler.addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
|
||||||
|
// vars
|
||||||
|
webServer->on("/api/vars", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||||
|
// make response
|
||||||
|
auto *response = new AsyncJsonResponse();
|
||||||
|
auto& doc = response->getRoot();
|
||||||
|
toJson(vars, doc);
|
||||||
|
|
||||||
|
// send response
|
||||||
|
response->setLength();
|
||||||
|
request->send(response);
|
||||||
|
});
|
||||||
|
|
||||||
|
auto& vHandler = webServer->on("/api/vars", HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) {
|
||||||
|
if (vars.states.upgrading || restartTask.scheduled() || restartTask.active()) {
|
||||||
|
return request->send(503);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (requestDoc.isNull() || !requestDoc.size()) {
|
||||||
|
return request->send(400);
|
||||||
|
}
|
||||||
|
|
||||||
|
// prepare request
|
||||||
|
const auto result = fromJson(requestDoc, vars);
|
||||||
|
requestDoc.clear();
|
||||||
|
|
||||||
|
// make response
|
||||||
|
auto *response = new AsyncJsonResponse();
|
||||||
|
auto& responseDoc = response->getRoot();
|
||||||
|
toJson(vars, responseDoc);
|
||||||
|
|
||||||
|
// send response
|
||||||
|
response->setLength();
|
||||||
|
response->setCode(result.changed ? 201 : 200);
|
||||||
|
request->send(response);
|
||||||
|
|
||||||
|
if (result.changed) {
|
||||||
|
// If busy, the periodic task will publish the current state.
|
||||||
|
std::unique_lock<std::mutex> lock(mqttMutex, std::try_to_lock);
|
||||||
|
if (lock.owns_lock() && mqttPublishStateTask) {
|
||||||
|
mqttPublishStateTask->requestEarlyRun();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
vHandler.setMaxContentLength(1536);
|
||||||
|
vHandler.addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
webServer->on("/api/info", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||||
|
// make response
|
||||||
|
auto *response = new AsyncJsonResponse();
|
||||||
|
auto& doc = response->getRoot();
|
||||||
|
|
||||||
|
auto docSystem = doc[S_SYSTEM].to<JsonObject>();
|
||||||
|
docSystem[S_RESET_REASON] = getResetReason();
|
||||||
|
docSystem[S_UPTIME] = millis() / 1000;
|
||||||
|
|
||||||
|
bool isConnected = isNetworkConnected();
|
||||||
|
auto docNetwork = doc[S_NETWORK].to<JsonObject>();
|
||||||
|
docNetwork[S_HOSTNAME] = networkSettings.hostname;
|
||||||
|
docNetwork[S_MAC] = WiFi.STA.macAddress();
|
||||||
|
docNetwork[S_CONNECTED] = isConnected;
|
||||||
|
docNetwork[S_SSID] = strlen(networkSettings.sta.ssid) ? networkSettings.sta.ssid : nullptr;
|
||||||
|
docNetwork[S_SIGNAL_QUALITY] = isConnected ? rssiToSignalQuality(WiFi.STA.RSSI()) : 0;
|
||||||
|
docNetwork[S_CHANNEL] = isConnected ? networkSettings.sta.channel : 0;
|
||||||
|
docNetwork[S_IP] = isConnected ? WiFi.STA.localIP().toString() : "";
|
||||||
|
docNetwork[S_SUBNET] = isConnected ? WiFi.STA.subnetMask().toString() : "";
|
||||||
|
docNetwork[S_GATEWAY] = isConnected ? WiFi.STA.gatewayIP().toString() : "";
|
||||||
|
docNetwork[S_DNS] = isConnected ? WiFi.STA.dnsIP().toString() : "";
|
||||||
|
|
||||||
|
auto docBuild = doc[S_BUILD].to<JsonObject>();
|
||||||
|
docBuild[S_VERSION] = BUILD_VERSION;
|
||||||
|
docBuild[S_COMMIT] = BUILD_COMMIT;
|
||||||
|
docBuild[S_DATE] = __DATE__ " " __TIME__;
|
||||||
|
docBuild[S_ENV] = BUILD_ENV;
|
||||||
|
docBuild[S_CORE] = ESP.getCoreVersion();
|
||||||
|
docBuild[S_SDK] = ESP.getSdkVersion();
|
||||||
|
|
||||||
|
const auto memory = getMemoryMetrics();
|
||||||
|
auto docHeap = doc[S_HEAP].to<JsonObject>();
|
||||||
|
docHeap[S_TOTAL] = memory.heap.total;
|
||||||
|
docHeap[S_FREE] = memory.heap.total_free_bytes;
|
||||||
|
docHeap[S_MIN_FREE] = memory.heap.minimum_free_bytes;
|
||||||
|
docHeap[S_MAX_FREE_BLOCK] = memory.heap.largest_free_block;
|
||||||
|
docHeap[S_MIN_MAX_FREE_BLOCK] = memory.heap.minLargestBlock;
|
||||||
|
|
||||||
|
auto docPsram = doc[S_PSRAM].to<JsonObject>();
|
||||||
|
docPsram[S_TOTAL] = memory.psram.total;
|
||||||
|
docPsram[S_FREE] = memory.psram.total_free_bytes;
|
||||||
|
docPsram[S_MIN_FREE] = memory.psram.minimum_free_bytes;
|
||||||
|
docPsram[S_MAX_FREE_BLOCK] = memory.psram.largest_free_block;
|
||||||
|
|
||||||
|
auto docChip = doc[S_CHIP].to<JsonObject>();
|
||||||
|
docChip[S_MODEL] = ESP.getChipModel();
|
||||||
|
docChip[S_REV] = ESP.getChipRevision();
|
||||||
|
docChip[S_CORES] = ESP.getChipCores();
|
||||||
|
docChip[S_FREQ] = ESP.getCpuFreqMHz();
|
||||||
|
|
||||||
|
auto docFlash = doc[S_FLASH].to<JsonObject>();
|
||||||
|
docFlash[S_SIZE] = ESP.getFlashChipSize();
|
||||||
|
|
||||||
|
// send response
|
||||||
|
response->setLength();
|
||||||
|
request->send(response);
|
||||||
|
});
|
||||||
|
|
||||||
|
webServer->on("/api/coredump", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||||
|
size_t address = 0;
|
||||||
|
size_t size = 0;
|
||||||
|
|
||||||
|
const esp_err_t image = esp_core_dump_image_get(&address, &size);
|
||||||
|
if (image != ESP_OK) {
|
||||||
|
request->send(image == ESP_ERR_NOT_FOUND ? 404 : 500);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (esp_core_dump_image_check() != ESP_OK) {
|
||||||
|
request->send(500);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const esp_partition_t* partition = esp_partition_find_first(
|
||||||
|
ESP_PARTITION_TYPE_DATA,
|
||||||
|
ESP_PARTITION_SUBTYPE_DATA_COREDUMP,
|
||||||
|
nullptr
|
||||||
|
);
|
||||||
|
if (partition == nullptr || partition->address != address || size > partition->size) {
|
||||||
|
request->send(500);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto* response = request->beginResponse("application/octet-stream", size,
|
||||||
|
[partition, size](uint8_t* buffer, size_t maximum, size_t index) -> size_t {
|
||||||
|
if (index >= size) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const size_t remaining = size - index;
|
||||||
|
const size_t count = remaining < maximum ? remaining : maximum;
|
||||||
|
if (esp_partition_read(partition, index, buffer, count) != ESP_OK) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return count;
|
||||||
|
});
|
||||||
|
setDownloadFilename(response, "coredump", "bin");
|
||||||
|
request->send(response);
|
||||||
|
}).addMiddleware(&authMiddleware);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initialization
|
||||||
|
void initPortal() {
|
||||||
|
webServer = new AsyncWebServer(80);
|
||||||
|
initWebSerial();
|
||||||
|
routes();
|
||||||
|
restApi();
|
||||||
|
}
|
||||||
@@ -0,0 +1,242 @@
|
|||||||
|
#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE
|
||||||
|
|
||||||
|
#include <app.h>
|
||||||
|
|
||||||
|
#include <cmath>
|
||||||
|
#include <GyverPID.h>
|
||||||
|
|
||||||
|
static GyverPID pidRegulator(0, 0, 0);
|
||||||
|
|
||||||
|
static float prevHeatingTarget = 0.0f;
|
||||||
|
static float equithermResult = 0.0f;
|
||||||
|
static float pidResult = 0.0f;
|
||||||
|
static bool indoorSensorsConnected = false;
|
||||||
|
|
||||||
|
static Task equithermTask("Equitherm", Task::Type::ONCE, [](void*) {
|
||||||
|
float etResult = settings.heating.target + settings.equitherm.shift;
|
||||||
|
|
||||||
|
if (settings.heating.maxTemp > settings.heating.target) {
|
||||||
|
float tempDelta = settings.heating.target - vars.master.heating.outdoorTemp;
|
||||||
|
float maxPoint = settings.heating.target - (
|
||||||
|
settings.heating.maxTemp - settings.heating.target
|
||||||
|
) / settings.equitherm.slope;
|
||||||
|
|
||||||
|
float sf = (settings.heating.maxTemp - settings.heating.target) / pow(
|
||||||
|
settings.heating.target - maxPoint,
|
||||||
|
1.0f / settings.equitherm.exponent
|
||||||
|
);
|
||||||
|
etResult = settings.heating.target + settings.equitherm.shift + sf * (
|
||||||
|
tempDelta >= 0
|
||||||
|
? pow(tempDelta, 1.0f / settings.equitherm.exponent)
|
||||||
|
: -(pow(-(tempDelta), 1.0f / settings.equitherm.exponent))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (indoorSensorsConnected && !settings.pid.enabled && !settings.heating.turbo) {
|
||||||
|
etResult += constrain(
|
||||||
|
settings.heating.target - vars.master.heating.indoorTemp,
|
||||||
|
-3.0f,
|
||||||
|
3.0f
|
||||||
|
) * settings.equitherm.targetDiffFactor;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!std::isfinite(etResult)) {
|
||||||
|
etResult = settings.heating.target + settings.equitherm.shift;
|
||||||
|
}
|
||||||
|
|
||||||
|
etResult = constrain(etResult, settings.heating.minTemp, settings.heating.maxTemp);
|
||||||
|
|
||||||
|
if (isFloatDifferent(equithermResult, etResult, 0.09f)) {
|
||||||
|
equithermResult = etResult;
|
||||||
|
ESP_LOGI(L_REGULATOR_EQUITHERM, "New result: %.2f", etResult);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
static Task pidTask("PID", Task::Type::FOREVER, [](void*) {
|
||||||
|
pidRegulator.Kp = settings.heating.turbo ? 0.0f : settings.pid.p_factor;
|
||||||
|
pidRegulator.Ki = settings.pid.i_factor;
|
||||||
|
pidRegulator.Kd = settings.pid.d_factor;
|
||||||
|
|
||||||
|
pidRegulator.setLimits(settings.pid.minTemp, settings.pid.maxTemp);
|
||||||
|
// Use the same period for scheduling and the integral/derivative terms.
|
||||||
|
pidRegulator.setDt(pidTask.interval());
|
||||||
|
pidRegulator.input = vars.master.heating.indoorTemp;
|
||||||
|
pidRegulator.setpoint = settings.heating.target;
|
||||||
|
|
||||||
|
float error = pidRegulator.setpoint - pidRegulator.input;
|
||||||
|
bool hasDeadband = settings.pid.deadband.enabled
|
||||||
|
&& (error > -(settings.pid.deadband.thresholdHigh))
|
||||||
|
&& (error < settings.pid.deadband.thresholdLow);
|
||||||
|
|
||||||
|
if (hasDeadband) {
|
||||||
|
pidRegulator.Kp *= settings.pid.deadband.p_multiplier;
|
||||||
|
pidRegulator.Ki *= settings.pid.deadband.i_multiplier;
|
||||||
|
pidRegulator.Kd *= settings.pid.deadband.d_multiplier;
|
||||||
|
}
|
||||||
|
|
||||||
|
float result = pidRegulator.getResult();
|
||||||
|
if (isFloatDifferent(pidResult, result, 0.09f)) {
|
||||||
|
pidResult = result;
|
||||||
|
ESP_LOGI(L_REGULATOR_PID, "New result: %.2f", result);
|
||||||
|
ESP_LOGD(L_REGULATOR_PID, "Integral: %.2f", pidRegulator.integral);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
static void turbo() {
|
||||||
|
if (settings.heating.turbo) {
|
||||||
|
if (!settings.heating.enabled || vars.emergency.state || !indoorSensorsConnected) {
|
||||||
|
settings.heating.turbo = false;
|
||||||
|
|
||||||
|
} else if (!settings.pid.enabled && !settings.equitherm.enabled) {
|
||||||
|
settings.heating.turbo = false;
|
||||||
|
|
||||||
|
} else if (fabsf(settings.heating.target - vars.master.heating.indoorTemp) <= 1.0f) {
|
||||||
|
settings.heating.turbo = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!settings.heating.turbo) {
|
||||||
|
ESP_LOGI(L_REGULATOR, "Turbo mode auto disabled");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void hysteresis() {
|
||||||
|
// Hysteresis also clears blocking when it is no longer applicable.
|
||||||
|
const bool useHysteresis = settings.heating.hysteresis.enabled && indoorSensorsConnected
|
||||||
|
&& (settings.equitherm.enabled || settings.pid.enabled || settings.opentherm.options.nativeOTC);
|
||||||
|
|
||||||
|
if (useHysteresis) {
|
||||||
|
if (!vars.master.heating.blocking && vars.master.heating.indoorTemp - settings.heating.target + 0.0001f >= settings.heating.hysteresis.value) {
|
||||||
|
vars.master.heating.blocking = true;
|
||||||
|
|
||||||
|
} else if (vars.master.heating.blocking && vars.master.heating.indoorTemp - settings.heating.target - 0.0001f <= -(settings.heating.hysteresis.value)) {
|
||||||
|
vars.master.heating.blocking = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
} else if (vars.master.heating.blocking) {
|
||||||
|
vars.master.heating.blocking = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static inline float getHeatingMinSetpointTemp() {
|
||||||
|
return settings.opentherm.options.nativeOTC
|
||||||
|
? vars.master.heating.minTemp
|
||||||
|
: settings.heating.minTemp;
|
||||||
|
}
|
||||||
|
|
||||||
|
static inline float getHeatingMaxSetpointTemp() {
|
||||||
|
return settings.opentherm.options.nativeOTC
|
||||||
|
? vars.master.heating.maxTemp
|
||||||
|
: settings.heating.maxTemp;
|
||||||
|
}
|
||||||
|
|
||||||
|
static float getHeatingSetpointTemp() {
|
||||||
|
if (isFloatDifferent(prevHeatingTarget, settings.heating.target, 0.0001f)) {
|
||||||
|
prevHeatingTarget = settings.heating.target;
|
||||||
|
ESP_LOGI(L_REGULATOR, "New target: %.2f", settings.heating.target);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (vars.emergency.state) {
|
||||||
|
return settings.emergency.target;
|
||||||
|
|
||||||
|
} else if (settings.opentherm.options.nativeOTC) {
|
||||||
|
return settings.heating.target;
|
||||||
|
}
|
||||||
|
|
||||||
|
float setpoint = settings.heating.target;
|
||||||
|
if (settings.equitherm.enabled || settings.pid.enabled) {
|
||||||
|
setpoint = 0.0f;
|
||||||
|
|
||||||
|
if (settings.equitherm.enabled) {
|
||||||
|
equithermTask.forceRun();
|
||||||
|
setpoint += equithermResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keep the last PID result when heating or the indoor sensor is unavailable.
|
||||||
|
if (settings.pid.enabled) {
|
||||||
|
setpoint += pidResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (settings.heating.turbo) {
|
||||||
|
setpoint += constrain(
|
||||||
|
settings.heating.target - vars.master.heating.indoorTemp,
|
||||||
|
-3.0f,
|
||||||
|
3.0f
|
||||||
|
) * settings.heating.turboFactor;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (vars.master.heating.freezing) {
|
||||||
|
setpoint = fmaxf(
|
||||||
|
setpoint,
|
||||||
|
static_cast<float>(settings.heating.freezeProtection.lowTemp)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return setpoint;
|
||||||
|
}
|
||||||
|
|
||||||
|
static Task regulatorTask("Regulator", [](void*) {
|
||||||
|
indoorSensorsConnected = Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::INDOOR_TEMP);
|
||||||
|
|
||||||
|
if (pidTask.enabled()) {
|
||||||
|
const uint32_t pidInterval = settings.pid.dt * 1000u;
|
||||||
|
|
||||||
|
if (pidTask.interval() != pidInterval) {
|
||||||
|
pidTask.setInterval(pidInterval);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (settings.equitherm.enabled || settings.pid.enabled || settings.opentherm.options.nativeOTC) {
|
||||||
|
vars.master.heating.smartControl = true;
|
||||||
|
vars.master.heating.minTemp = THERMOSTAT_INDOOR_MIN_TEMP;
|
||||||
|
vars.master.heating.maxTemp = THERMOSTAT_INDOOR_MAX_TEMP;
|
||||||
|
|
||||||
|
} else {
|
||||||
|
vars.master.heating.smartControl = false;
|
||||||
|
vars.master.heating.minTemp = settings.heating.minTemp;
|
||||||
|
vars.master.heating.maxTemp = settings.heating.maxTemp;
|
||||||
|
}
|
||||||
|
|
||||||
|
// This must still run when the PID calculation task is disabled.
|
||||||
|
if (!settings.pid.enabled && fabsf(pidRegulator.integral) > 0.01f) {
|
||||||
|
pidRegulator.integral = 0.0f;
|
||||||
|
ESP_LOGI(L_REGULATOR_PID, "Integral sum has been reset");
|
||||||
|
}
|
||||||
|
|
||||||
|
turbo();
|
||||||
|
hysteresis();
|
||||||
|
|
||||||
|
vars.master.heating.targetTemp = settings.heating.target;
|
||||||
|
|
||||||
|
const float setpointTemp = getHeatingSetpointTemp();
|
||||||
|
vars.master.heating.setpointTemp = roundf(constrain(
|
||||||
|
setpointTemp,
|
||||||
|
getHeatingMinSetpointTemp(),
|
||||||
|
getHeatingMaxSetpointTemp()
|
||||||
|
), 0);
|
||||||
|
|
||||||
|
Sensors::setValueByType(
|
||||||
|
Sensors::Type::HEATING_SETPOINT_TEMP, vars.master.heating.setpointTemp,
|
||||||
|
Sensors::ValueType::PRIMARY, true, true
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
void initRegulator() {
|
||||||
|
regulatorTask.setInterval(10000);
|
||||||
|
|
||||||
|
// Sensor availability is refreshed by the regulator before checking PID eligibility.
|
||||||
|
pidTask.setEnabledWhen([] {
|
||||||
|
return settings.pid.enabled && settings.heating.enabled
|
||||||
|
&& !vars.emergency.state && !settings.opentherm.options.nativeOTC
|
||||||
|
&& indoorSensorsConnected;
|
||||||
|
});
|
||||||
|
pidTask.setInterval(10000);
|
||||||
|
pidTask.resume(pidTask.interval());
|
||||||
|
|
||||||
|
// Apply mode changes and turbo auto-disable before a PID calculation due on the same pass.
|
||||||
|
coreTaskManager.addTask(regulatorTask);
|
||||||
|
coreTaskManager.addTask(pidTask);
|
||||||
|
coreTaskManager.addTask(equithermTask);
|
||||||
|
equithermTask.pause();
|
||||||
|
}
|
||||||
@@ -0,0 +1,990 @@
|
|||||||
|
#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE
|
||||||
|
|
||||||
|
#include <app.h>
|
||||||
|
#include <atomic>
|
||||||
|
#include <optional>
|
||||||
|
#include <unordered_map>
|
||||||
|
#include <OneWire.h>
|
||||||
|
#include <DallasTemperature.h>
|
||||||
|
#include <esp32DHT.h>
|
||||||
|
#include <math.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#if USE_BLE
|
||||||
|
#include <NimBLEDevice.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if USE_BLE
|
||||||
|
class BluetoothScanCallbacks : public NimBLEScanCallbacks {
|
||||||
|
public:
|
||||||
|
void onDiscovered(const NimBLEAdvertisedDevice* device) override {
|
||||||
|
auto& deviceAddress = device->getAddress();
|
||||||
|
|
||||||
|
bool found = false;
|
||||||
|
uint8_t sensorId;
|
||||||
|
std::optional<Sensors::Settings> sSensor;
|
||||||
|
for (sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) {
|
||||||
|
sSensor = Sensors::getSettings(sensorId);
|
||||||
|
if (!sSensor) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!sSensor->enabled || sSensor->type != Sensors::Type::BLUETOOTH || sSensor->purpose == Sensors::Purpose::NOT_CONFIGURED) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto sensorAddress = NimBLEAddress(sSensor->address, deviceAddress.getType());
|
||||||
|
if (sensorAddress.isNull() || sensorAddress != deviceAddress) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
found = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!found) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto deviceName = device->getName();
|
||||||
|
auto deviceRssi = device->getRSSI();
|
||||||
|
|
||||||
|
ESP_LOGI(
|
||||||
|
L_SENSORS_BLE, "Sensor #%hhu '%s': discovered device %s, name: %s, RSSI: %hhd",
|
||||||
|
sensorId, sSensor->name,
|
||||||
|
deviceAddress.toString().c_str(), deviceName.c_str(), deviceRssi
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!device->haveServiceData()) {
|
||||||
|
ESP_LOGW(
|
||||||
|
L_SENSORS_BLE, "Sensor #%hhu '%s': not found service data!",
|
||||||
|
sensorId, sSensor->name
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto serviceDataCount = device->getServiceDataCount();
|
||||||
|
ESP_LOGD(
|
||||||
|
L_SENSORS_BLE, "Sensor #%hhu '%s': found %hhu service data",
|
||||||
|
sensorId, sSensor->name, serviceDataCount
|
||||||
|
);
|
||||||
|
|
||||||
|
if (parseAtcData(device, sensorId) || parsePvvxData(device, sensorId) || parseBTHomeData(device, sensorId)) {
|
||||||
|
// update rssi
|
||||||
|
Sensors::setValueById(sensorId, deviceRssi, Sensors::ValueType::RSSI, false, false);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
ESP_LOGW(
|
||||||
|
L_SENSORS_BLE, "Sensor #%hhu '%s': unsupported data format!",
|
||||||
|
sensorId, sSensor->name
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool parseAtcData(const NimBLEAdvertisedDevice* device, uint8_t sensorId) {
|
||||||
|
NimBLEUUID serviceUuid(static_cast<uint16_t>(0x181A));
|
||||||
|
|
||||||
|
auto serviceData = device->getServiceData(serviceUuid);
|
||||||
|
if (!serviceData.size()) {
|
||||||
|
ESP_LOGD(
|
||||||
|
L_SENSORS_BLE, "Sensor #%hhu, service %s: not found ATC1441 data",
|
||||||
|
sensorId, serviceUuid.toString().c_str()
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
|
||||||
|
} else if (serviceData.size() != 13) {
|
||||||
|
ESP_LOGD(
|
||||||
|
L_SENSORS_BLE, "Sensor #%hhu, service %s: not in ATC1441 format",
|
||||||
|
sensorId, serviceUuid.toString().c_str()
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
ESP_LOGI(
|
||||||
|
L_SENSORS_BLE, "Sensor #%hhu, service %s: found ATC1441 format",
|
||||||
|
sensorId, serviceUuid.toString().c_str()
|
||||||
|
);
|
||||||
|
|
||||||
|
// Temperature (2 bytes, signed, big-endian)
|
||||||
|
float temperature = static_cast<int16_t>(
|
||||||
|
(static_cast<uint8_t>(serviceData[6]) << 8) |
|
||||||
|
static_cast<uint8_t>(serviceData[7])
|
||||||
|
) * 0.1f;
|
||||||
|
Sensors::setValueById(
|
||||||
|
sensorId, temperature,
|
||||||
|
Sensors::ValueType::TEMPERATURE, true, true
|
||||||
|
);
|
||||||
|
|
||||||
|
// Humidity (1 byte)
|
||||||
|
float humidity = static_cast<uint8_t>(serviceData[8]);
|
||||||
|
Sensors::setValueById(sensorId, humidity, Sensors::ValueType::HUMIDITY, true, true);
|
||||||
|
|
||||||
|
// Battery level (1 byte)
|
||||||
|
uint8_t batteryLevel = static_cast<uint8_t>(serviceData[9]);
|
||||||
|
Sensors::setValueById(sensorId, batteryLevel, Sensors::ValueType::BATTERY, true, true);
|
||||||
|
|
||||||
|
// Battery mV (2 bytes, big-endian)
|
||||||
|
uint16_t batteryMv = (static_cast<uint8_t>(serviceData[10]) << 8) | static_cast<uint8_t>(serviceData[11]);
|
||||||
|
|
||||||
|
// Log
|
||||||
|
ESP_LOGI(
|
||||||
|
L_SENSORS_BLE,
|
||||||
|
"Sensor #%hhu, received temp: %.2f; humidity: %.2f, battery voltage: %hu, battery level: %hhu",
|
||||||
|
sensorId, temperature, humidity, batteryMv, batteryLevel
|
||||||
|
);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool parsePvvxData(const NimBLEAdvertisedDevice* device, uint8_t sensorId) {
|
||||||
|
NimBLEUUID serviceUuid(static_cast<uint16_t>(0x181A));
|
||||||
|
|
||||||
|
auto serviceData = device->getServiceData(serviceUuid);
|
||||||
|
if (!serviceData.size()) {
|
||||||
|
ESP_LOGD(
|
||||||
|
L_SENSORS_BLE, "Sensor #%hhu, service %s: not found PVVX data",
|
||||||
|
sensorId, serviceUuid.toString().c_str()
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
|
||||||
|
} else if (serviceData.size() != 14 && serviceData.size() != 15) {
|
||||||
|
ESP_LOGD(
|
||||||
|
L_SENSORS_BLE, "Sensor #%hhu, service %s: not in PVVX format",
|
||||||
|
sensorId, serviceUuid.toString().c_str()
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
ESP_LOGI(
|
||||||
|
L_SENSORS_BLE, "Sensor #%hhu, service %s: found PVVX format",
|
||||||
|
sensorId, serviceUuid.toString().c_str()
|
||||||
|
);
|
||||||
|
|
||||||
|
// Temperature (2 bytes, signed, little-endian)
|
||||||
|
float temperature = static_cast<int16_t>(
|
||||||
|
(static_cast<uint8_t>(serviceData[7]) << 8) |
|
||||||
|
static_cast<uint8_t>(serviceData[6])
|
||||||
|
) * 0.01f;
|
||||||
|
Sensors::setValueById(
|
||||||
|
sensorId, temperature,
|
||||||
|
Sensors::ValueType::TEMPERATURE, true, true
|
||||||
|
);
|
||||||
|
|
||||||
|
// Humidity (2 bytes, little-endian)
|
||||||
|
float humidity = (
|
||||||
|
(static_cast<uint8_t>(serviceData[9]) << 8) | static_cast<uint8_t>(serviceData[8])
|
||||||
|
) * 0.01f;
|
||||||
|
Sensors::setValueById(sensorId, humidity, Sensors::ValueType::HUMIDITY, true, true);
|
||||||
|
|
||||||
|
// Battery level (1 byte)
|
||||||
|
uint8_t batteryLevel = static_cast<uint8_t>(serviceData[12]);
|
||||||
|
Sensors::setValueById(sensorId, batteryLevel, Sensors::ValueType::BATTERY, true, true);
|
||||||
|
|
||||||
|
// Battery mV (2 bytes, little-endian)
|
||||||
|
uint16_t batteryMv = (static_cast<uint8_t>(serviceData[11]) << 8) | static_cast<uint8_t>(serviceData[10]);
|
||||||
|
|
||||||
|
// Log
|
||||||
|
ESP_LOGI(
|
||||||
|
L_SENSORS_BLE,
|
||||||
|
"Sensor #%hhu, received temp: %.2f; humidity: %.2f, battery voltage: %hu, battery level: %hhu",
|
||||||
|
sensorId, temperature, humidity, batteryMv, batteryLevel
|
||||||
|
);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool parseBTHomeData(const NimBLEAdvertisedDevice* device, uint8_t sensorId) {
|
||||||
|
NimBLEUUID serviceUuid(static_cast<uint16_t>(0xFCD2));
|
||||||
|
|
||||||
|
auto serviceData = device->getServiceData(serviceUuid);
|
||||||
|
if (!serviceData.size()) {
|
||||||
|
ESP_LOGD(
|
||||||
|
L_SENSORS_BLE, "Sensor #%hhu, service %s: not found BTHome data",
|
||||||
|
sensorId, serviceUuid.toString().c_str()
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
|
||||||
|
} else if ((serviceData[0] & 0xE0) != 0x40) {
|
||||||
|
ESP_LOGD(
|
||||||
|
L_SENSORS_BLE, "Sensor #%hhu, service %s: unsupported BTHome version",
|
||||||
|
sensorId, serviceUuid.toString().c_str()
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
|
||||||
|
} else if ((serviceData[0] & 0x01) != 0) {
|
||||||
|
ESP_LOGD(
|
||||||
|
L_SENSORS_BLE, "Sensor #%hhu, service %s: unsupported BTHome encrypted data",
|
||||||
|
sensorId, serviceUuid.toString().c_str()
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
ESP_LOGI(
|
||||||
|
L_SENSORS_BLE, "Sensor #%hhu, service %s: found BTHome format",
|
||||||
|
sensorId, serviceUuid.toString().c_str()
|
||||||
|
);
|
||||||
|
|
||||||
|
bool foundData = false;
|
||||||
|
size_t serviceDataPos = 1;
|
||||||
|
while (serviceDataPos < serviceData.size()) {
|
||||||
|
uint8_t objectId = serviceData[serviceDataPos++];
|
||||||
|
|
||||||
|
switch (objectId) {
|
||||||
|
// Packet ID (1 byte)
|
||||||
|
case 0x00:
|
||||||
|
if (serviceDataPos + 1 > serviceData.size()) {
|
||||||
|
return foundData;
|
||||||
|
}
|
||||||
|
|
||||||
|
serviceDataPos += 1;
|
||||||
|
break;
|
||||||
|
|
||||||
|
// Battery (1 byte)
|
||||||
|
case 0x01: {
|
||||||
|
if (serviceDataPos + 1 > serviceData.size()) {
|
||||||
|
return foundData;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t batteryLevel = static_cast<uint8_t>(serviceData[serviceDataPos]);
|
||||||
|
Sensors::setValueById(sensorId, batteryLevel, Sensors::ValueType::BATTERY, true, true);
|
||||||
|
serviceDataPos += 1;
|
||||||
|
foundData = true;
|
||||||
|
|
||||||
|
ESP_LOGI(
|
||||||
|
L_SENSORS_BLE, "Sensor #%hhu, received battery level: %hhu",
|
||||||
|
sensorId, batteryLevel
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Temperature (2 bytes, signed, little-endian)
|
||||||
|
case 0x02: {
|
||||||
|
if (serviceDataPos + 2 > serviceData.size()) {
|
||||||
|
return foundData;
|
||||||
|
}
|
||||||
|
|
||||||
|
int16_t rawTemperature = (static_cast<uint8_t>(serviceData[serviceDataPos + 1]) << 8)
|
||||||
|
| static_cast<uint8_t>(serviceData[serviceDataPos]);
|
||||||
|
float temperature = static_cast<float>(rawTemperature) * 0.01f;
|
||||||
|
Sensors::setValueById(
|
||||||
|
sensorId, temperature,
|
||||||
|
Sensors::ValueType::TEMPERATURE, true, true
|
||||||
|
);
|
||||||
|
serviceDataPos += 2;
|
||||||
|
foundData = true;
|
||||||
|
|
||||||
|
ESP_LOGI(
|
||||||
|
L_SENSORS_BLE, "Sensor #%hhu, received temp: %.2f",
|
||||||
|
sensorId, temperature
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Humidity (2 bytes, little-endian)
|
||||||
|
case 0x03: {
|
||||||
|
if (serviceDataPos + 2 > serviceData.size()) {
|
||||||
|
return foundData;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint16_t rawHumidity = (static_cast<uint16_t>(serviceData[serviceDataPos + 1]) << 8)
|
||||||
|
| static_cast<uint8_t>(serviceData[serviceDataPos]);
|
||||||
|
float humidity = static_cast<float>(rawHumidity) * 0.01f;
|
||||||
|
Sensors::setValueById(sensorId, humidity, Sensors::ValueType::HUMIDITY, true, true);
|
||||||
|
serviceDataPos += 2;
|
||||||
|
foundData = true;
|
||||||
|
|
||||||
|
ESP_LOGI(
|
||||||
|
L_SENSORS_BLE, "Sensor #%hhu, received humidity: %.2f",
|
||||||
|
sensorId, humidity
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Voltage (2 bytes, little-endian)
|
||||||
|
case 0x0C: {
|
||||||
|
if (serviceDataPos + 2 > serviceData.size()) {
|
||||||
|
return foundData;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint16_t batteryMv = (static_cast<uint16_t>(serviceData[serviceDataPos + 1]) << 8)
|
||||||
|
| static_cast<uint8_t>(serviceData[serviceDataPos]);
|
||||||
|
serviceDataPos += 2;
|
||||||
|
foundData = true;
|
||||||
|
|
||||||
|
ESP_LOGI(
|
||||||
|
L_SENSORS_BLE, "Sensor #%hhu, received battery voltage: %hu",
|
||||||
|
sensorId, batteryMv
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
return foundData;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return foundData;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
static BluetoothScanCallbacks bluetoothScanCallbacks;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
static const unsigned int wiredDisconnectTimeout = 180000u;
|
||||||
|
static const unsigned int wirelessDisconnectTimeout = 600000u;
|
||||||
|
static const unsigned short dallasSearchInterval = 60000u;
|
||||||
|
static const unsigned short dallasPollingInterval = 10000u;
|
||||||
|
static const unsigned short dhtPollingInterval = 15000;
|
||||||
|
|
||||||
|
// OneWire
|
||||||
|
static std::unordered_map<uint8_t, OneWire> owInstances;
|
||||||
|
static std::unordered_map<uint8_t, DallasTemperature> dallasInstances;
|
||||||
|
static std::unordered_map<uint8_t, unsigned long> dallasSearchTime;
|
||||||
|
static std::unordered_map<uint8_t, unsigned long> dallasLastPollingTime;
|
||||||
|
static std::unordered_map<uint8_t, bool> dallasPolling;
|
||||||
|
|
||||||
|
#if USE_BLE
|
||||||
|
static NimBLEScan* pBLEScan = nullptr;
|
||||||
|
static bool activeScanBle = false;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
static bool isEqualAddress(const uint8_t *addr1, const uint8_t *addr2, const uint8_t length = 8) {
|
||||||
|
return memcmp(addr1, addr2, length) == 0;
|
||||||
|
/*bool result = true;
|
||||||
|
|
||||||
|
for (uint8_t i = 0; i < length; i++) {
|
||||||
|
if (addr1[i] != addr2[i]) {
|
||||||
|
result = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;*/
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool isEmptyAddress(const uint8_t *addr, const uint8_t length = 8) {
|
||||||
|
bool result = true;
|
||||||
|
|
||||||
|
for (uint8_t i = 0; i < length; i++) {
|
||||||
|
if (addr[i] != 0) {
|
||||||
|
result = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void updateMasterValues() {
|
||||||
|
const float previousIndoorTemp = vars.master.heating.indoorTemp;
|
||||||
|
vars.master.heating.indoorTemp = Sensors::getMeanValueByPurpose(
|
||||||
|
Sensors::Purpose::INDOOR_TEMP,
|
||||||
|
Sensors::ValueType::PRIMARY,
|
||||||
|
settings.heating.indoorTempAvgType,
|
||||||
|
true,
|
||||||
|
0.0f
|
||||||
|
);
|
||||||
|
|
||||||
|
if (previousIndoorTemp != vars.master.heating.indoorTemp) {
|
||||||
|
writeRoomTemperatureTask.requestEarlyRun();
|
||||||
|
writeRoomTemperatureCh2Task.requestEarlyRun();
|
||||||
|
}
|
||||||
|
|
||||||
|
vars.master.heating.outdoorTemp = Sensors::getMeanValueByPurpose(
|
||||||
|
Sensors::Purpose::OUTDOOR_TEMP,
|
||||||
|
Sensors::ValueType::PRIMARY,
|
||||||
|
settings.heating.outdoorTempAvgType,
|
||||||
|
true,
|
||||||
|
0.0f
|
||||||
|
);
|
||||||
|
|
||||||
|
vars.master.heating.currentTemp = Sensors::getMeanValueByPurpose(
|
||||||
|
Sensors::Purpose::HEATING_TEMP,
|
||||||
|
Sensors::ValueType::PRIMARY,
|
||||||
|
Sensors::AverageType::MEAN,
|
||||||
|
true,
|
||||||
|
0.0f
|
||||||
|
);
|
||||||
|
vars.master.heating.returnTemp = Sensors::getMeanValueByPurpose(
|
||||||
|
Sensors::Purpose::HEATING_RETURN_TEMP,
|
||||||
|
Sensors::ValueType::PRIMARY,
|
||||||
|
Sensors::AverageType::MEAN,
|
||||||
|
true,
|
||||||
|
0.0f
|
||||||
|
);
|
||||||
|
|
||||||
|
vars.master.dhw.currentTemp = Sensors::getMeanValueByPurpose(
|
||||||
|
Sensors::Purpose::DHW_TEMP,
|
||||||
|
Sensors::ValueType::PRIMARY,
|
||||||
|
Sensors::AverageType::MEAN,
|
||||||
|
true,
|
||||||
|
0.0f
|
||||||
|
);
|
||||||
|
vars.master.dhw.returnTemp = Sensors::getMeanValueByPurpose(
|
||||||
|
Sensors::Purpose::DHW_RETURN_TEMP,
|
||||||
|
Sensors::ValueType::PRIMARY,
|
||||||
|
Sensors::AverageType::MEAN,
|
||||||
|
true,
|
||||||
|
0.0f
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void makeDallasInstances() {
|
||||||
|
for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) {
|
||||||
|
const auto sSensor = Sensors::getSettings(sensorId);
|
||||||
|
if (!sSensor) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!sSensor->enabled || sSensor->type != Sensors::Type::DALLAS_TEMP || sSensor->purpose == Sensors::Purpose::NOT_CONFIGURED) {
|
||||||
|
continue;
|
||||||
|
|
||||||
|
} else if (dallasInstances.count(sSensor->gpio)) {
|
||||||
|
// no need to make instances
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto& owInstance = owInstances[sSensor->gpio];
|
||||||
|
owInstance.begin(sSensor->gpio);
|
||||||
|
owInstance.reset();
|
||||||
|
|
||||||
|
dallasSearchTime[sSensor->gpio] = 0;
|
||||||
|
dallasPolling[sSensor->gpio] = false;
|
||||||
|
dallasLastPollingTime[sSensor->gpio] = 0;
|
||||||
|
|
||||||
|
auto& instance = dallasInstances[sSensor->gpio];
|
||||||
|
instance.setOneWire(&owInstance);
|
||||||
|
instance.setWaitForConversion(false);
|
||||||
|
|
||||||
|
ESP_LOGI(L_SENSORS_DALLAS, "Started on GPIO %hhu", sSensor->gpio);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void cleanDallasInstances() {
|
||||||
|
// for (auto& [gpio, instance] : dallasInstances) {
|
||||||
|
auto it = dallasInstances.begin();
|
||||||
|
while (it != dallasInstances.end()) {
|
||||||
|
auto gpio = it->first;
|
||||||
|
bool instanceUsed = false;
|
||||||
|
|
||||||
|
for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) {
|
||||||
|
const auto sSensor = Sensors::getSettings(sensorId);
|
||||||
|
if (!sSensor) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!sSensor->enabled || sSensor->type != Sensors::Type::DALLAS_TEMP || sSensor->purpose == Sensors::Purpose::NOT_CONFIGURED) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sSensor->gpio == gpio) {
|
||||||
|
instanceUsed = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!instanceUsed) {
|
||||||
|
it = dallasInstances.erase(it);
|
||||||
|
owInstances.erase(gpio);
|
||||||
|
dallasSearchTime.erase(gpio);
|
||||||
|
dallasPolling.erase(gpio);
|
||||||
|
dallasLastPollingTime.erase(gpio);
|
||||||
|
|
||||||
|
ESP_LOGI(L_SENSORS_DALLAS, "Stopped on GPIO %hhu", gpio);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
it++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void searchDallasSensors() {
|
||||||
|
// search sensors on bus
|
||||||
|
for (auto& [gpio, instance] : dallasInstances) {
|
||||||
|
// do not search if polling!
|
||||||
|
if (dallasPolling[gpio]) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (millis() - dallasSearchTime[gpio] < dallasSearchInterval) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
dallasSearchTime[gpio] = millis();
|
||||||
|
owInstances[gpio].reset();
|
||||||
|
instance.begin();
|
||||||
|
|
||||||
|
ESP_LOGD(
|
||||||
|
L_SENSORS_DALLAS,
|
||||||
|
"GPIO %hhu, devices on bus: %hhu, DS18* devices: %hhu",
|
||||||
|
gpio, instance.getDeviceCount(), instance.getDS18Count()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void fillingAddressesDallasSensors() {
|
||||||
|
// check & filling sensors address
|
||||||
|
for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) {
|
||||||
|
const auto sSensor = Sensors::getSettings(sensorId);
|
||||||
|
if (!sSensor) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!sSensor->enabled || sSensor->type != Sensors::Type::DALLAS_TEMP || sSensor->purpose == Sensors::Purpose::NOT_CONFIGURED) {
|
||||||
|
continue;
|
||||||
|
|
||||||
|
} else if (!dallasInstances.count(sSensor->gpio)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// do nothing if address not empty
|
||||||
|
if (!isEmptyAddress(sSensor->address)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// do nothing if polling
|
||||||
|
if (dallasPolling[sSensor->gpio]) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto& instance = dallasInstances[sSensor->gpio];
|
||||||
|
DeviceAddress devAddr;
|
||||||
|
for (uint8_t devId = 0; devId < instance.getDeviceCount(); devId++) {
|
||||||
|
if (!instance.getAddress(devAddr, devId)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool freeAddress = true;
|
||||||
|
|
||||||
|
// checking address usage
|
||||||
|
for (uint8_t checkingSensorId = 0; checkingSensorId <= Sensors::getMaxSensorId(); checkingSensorId++) {
|
||||||
|
const auto sCheckingSensor = Sensors::getSettings(checkingSensorId);
|
||||||
|
if (!sCheckingSensor) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (sCheckingSensor->type != Sensors::Type::DALLAS_TEMP || checkingSensorId == sensorId) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sCheckingSensor->gpio != sSensor->gpio || isEmptyAddress(sCheckingSensor->address)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isEqualAddress(sCheckingSensor->address, devAddr)) {
|
||||||
|
freeAddress = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// address already in use
|
||||||
|
if (!freeAddress) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const bool addressSet = Sensors::setAddressById(sensorId, devAddr, [sensorId] {
|
||||||
|
requestReconfigureMqttSensor(sensorId);
|
||||||
|
requestSaveSensorsSettings();
|
||||||
|
});
|
||||||
|
if (!addressSet) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
ESP_LOGD(
|
||||||
|
L_SENSORS_DALLAS, "GPIO %hhu, sensor #%hhu '%s', set address: %hhX:%hhX:%hhX:%hhX:%hhX:%hhX:%hhX:%hhX",
|
||||||
|
sSensor->gpio, sensorId, sSensor->name,
|
||||||
|
devAddr[0], devAddr[1], devAddr[2], devAddr[3],
|
||||||
|
devAddr[4], devAddr[5], devAddr[6], devAddr[7]
|
||||||
|
);
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool isPollingDallasSensors() {
|
||||||
|
for (auto& [gpio, instance] : dallasInstances) {
|
||||||
|
if (dallasPolling.count(gpio) && dallasPolling[gpio]) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void pollingDallasSensors(bool newPolling = true) {
|
||||||
|
for (auto& [gpio, instance] : dallasInstances) {
|
||||||
|
unsigned long ts = millis();
|
||||||
|
|
||||||
|
if (dallasPolling[gpio]) {
|
||||||
|
unsigned long minPollingTime = instance.millisToWaitForConversion(12) * 2;
|
||||||
|
unsigned long estimatePollingTime = ts - dallasLastPollingTime[gpio];
|
||||||
|
|
||||||
|
// check conversion time
|
||||||
|
// isConversionComplete does not work with chinese clones!
|
||||||
|
if (estimatePollingTime < minPollingTime) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// read sensors data for current instance
|
||||||
|
for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) {
|
||||||
|
const auto sSensor = Sensors::getSettings(sensorId);
|
||||||
|
if (!sSensor) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// only target & valid sensors
|
||||||
|
if (!sSensor->enabled || sSensor->type != Sensors::Type::DALLAS_TEMP || sSensor->purpose == Sensors::Purpose::NOT_CONFIGURED) {
|
||||||
|
continue;
|
||||||
|
|
||||||
|
} else if (sSensor->gpio != gpio || isEmptyAddress(sSensor->address)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
float value = instance.getTempC(sSensor->address);
|
||||||
|
if (value == DEVICE_DISCONNECTED_C) {
|
||||||
|
ESP_LOGW(
|
||||||
|
L_SENSORS_DALLAS, "GPIO %hhu, sensor #%hhu '%s': failed receiving data",
|
||||||
|
sSensor->gpio, sensorId, sSensor->name
|
||||||
|
);
|
||||||
|
|
||||||
|
Sensors::adjustSignalQuality(sensorId, -1);
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
ESP_LOGD(
|
||||||
|
L_SENSORS_DALLAS, "GPIO %hhu, sensor #%hhu '%s', received data: %.2f",
|
||||||
|
sSensor->gpio, sensorId, sSensor->name, value
|
||||||
|
);
|
||||||
|
|
||||||
|
Sensors::adjustSignalQuality(sensorId, 1);
|
||||||
|
|
||||||
|
// set sensor value
|
||||||
|
Sensors::setValueById(
|
||||||
|
sensorId, value,
|
||||||
|
Sensors::ValueType::TEMPERATURE, true, true
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// reset polling flag
|
||||||
|
dallasPolling[gpio] = false;
|
||||||
|
|
||||||
|
} else if (newPolling) {
|
||||||
|
auto estimateLastPollingTime = ts - dallasLastPollingTime[gpio];
|
||||||
|
|
||||||
|
// check last polling time
|
||||||
|
if (estimateLastPollingTime < dallasPollingInterval) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// start polling
|
||||||
|
instance.setResolution(12);
|
||||||
|
instance.requestTemperatures();
|
||||||
|
dallasPolling[gpio] = true;
|
||||||
|
dallasLastPollingTime[gpio] = ts;
|
||||||
|
|
||||||
|
ESP_LOGD(L_SENSORS_DALLAS, "GPIO %hhu, polling...", gpio);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#if USE_BLE
|
||||||
|
static void scanBleSensors() {
|
||||||
|
if (!Sensors::getAmountByType(Sensors::Type::BLUETOOTH, true)) {
|
||||||
|
if (NimBLEDevice::isInitialized()) {
|
||||||
|
if (pBLEScan != nullptr) {
|
||||||
|
if (pBLEScan->isScanning()) {
|
||||||
|
pBLEScan->stop();
|
||||||
|
|
||||||
|
} else {
|
||||||
|
pBLEScan = nullptr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pBLEScan == nullptr) {
|
||||||
|
if (NimBLEDevice::deinit(true)) {
|
||||||
|
ESP_LOGI(L_SENSORS_BLE, "Deinitialized");
|
||||||
|
|
||||||
|
} else {
|
||||||
|
ESP_LOGW(L_SENSORS_BLE, "Unable to deinitialize!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!NimBLEDevice::isInitialized() && millis() > 5000) {
|
||||||
|
if (NimBLEDevice::init(PROJECT_NAME)) {
|
||||||
|
ESP_LOGI(L_SENSORS_BLE, "Initialized");
|
||||||
|
|
||||||
|
#ifdef ESP_PWR_LVL_P20
|
||||||
|
NimBLEDevice::setPower(ESP_PWR_LVL_P20);
|
||||||
|
#elifdef ESP_PWR_LVL_P9
|
||||||
|
NimBLEDevice::setPower(ESP_PWR_LVL_P9);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
} else {
|
||||||
|
ESP_LOGW(L_SENSORS_BLE, "Unable to initialize!");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pBLEScan == nullptr) {
|
||||||
|
pBLEScan = NimBLEDevice::getScan();
|
||||||
|
pBLEScan->setCallbacks(bluetoothScanCallbacks);
|
||||||
|
#if MYNEWT_VAL(BLE_EXT_ADV)
|
||||||
|
pBLEScan->setPhy(NimBLEScan::Phy::SCAN_ALL);
|
||||||
|
#endif
|
||||||
|
pBLEScan->setDuplicateFilter(false);
|
||||||
|
pBLEScan->setMaxResults(0);
|
||||||
|
pBLEScan->setInterval(10000);
|
||||||
|
pBLEScan->setWindow(10000);
|
||||||
|
|
||||||
|
ESP_LOGI(L_SENSORS_BLE, "Scanning initialized");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!pBLEScan->isScanning()) {
|
||||||
|
activeScanBle = !activeScanBle;
|
||||||
|
pBLEScan->setActiveScan(activeScanBle);
|
||||||
|
|
||||||
|
if (pBLEScan->start(30000, false, false)) {
|
||||||
|
ESP_LOGI(
|
||||||
|
L_SENSORS_BLE,
|
||||||
|
"%s scanning started",
|
||||||
|
activeScanBle ? "Active" : "Passive"
|
||||||
|
);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
ESP_LOGI(L_SENSORS_BLE, "Unable to start scanning");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
static void updateConnectionStatus() {
|
||||||
|
for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) {
|
||||||
|
Sensors::updateConnectionStatusById(sensorId, wiredDisconnectTimeout, wirelessDisconnectTimeout);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool canRunSensors() {
|
||||||
|
return !vars.states.upgrading && !restartTask.scheduled() && !restartTask.active();
|
||||||
|
}
|
||||||
|
|
||||||
|
static Task readDallasSensorsTask("Read Dallas sensors", [](void*) {
|
||||||
|
pollingDallasSensors(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
static Task pollDhtSensorsTask("Poll DHT sensors", [](void*) {
|
||||||
|
static DHT instance;
|
||||||
|
static uint8_t lastPollingSensorId{0};
|
||||||
|
static std::unordered_map<uint8_t, unsigned long> lastPollingTime(2);
|
||||||
|
|
||||||
|
if (instance.isPolling()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) {
|
||||||
|
const auto sSensor = Sensors::getSettings(sensorId);
|
||||||
|
if (!sSensor) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!sSensor->enabled || sSensor->purpose == Sensors::Purpose::NOT_CONFIGURED) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sSensor->type != Sensors::Type::DHT11 && sSensor->type != Sensors::Type::DHT22) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (lastPollingTime.count(sSensor->gpio) && millis() - lastPollingTime[sSensor->gpio] < dhtPollingInterval) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto sensorGpio = static_cast<gpio_num_t>(sSensor->gpio);
|
||||||
|
DHT::Type sensorType = DHT::Type::DHT22;
|
||||||
|
if (sSensor->type == Sensors::Type::DHT11) {
|
||||||
|
sensorType = DHT::Type::DHT11;
|
||||||
|
|
||||||
|
} else if (sSensor->type == Sensors::Type::DHT22) {
|
||||||
|
sensorType = DHT::Type::DHT22;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (lastPollingSensorId != sensorId || instance.getGpio() != sensorGpio || instance.getType() != sensorType) {
|
||||||
|
instance.reset();
|
||||||
|
instance.onData([sensorId, gpio = sSensor->gpio](float humidity, float temperature) {
|
||||||
|
const auto sSensor = Sensors::getSettings(sensorId);
|
||||||
|
if (!sSensor) {
|
||||||
|
lastPollingTime[gpio] = millis();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
ESP_LOGD(
|
||||||
|
L_SENSORS_DHT, "GPIO %hhu, sensor #%hhu '%s', temp: %.2f, humidity: %.2f%%",
|
||||||
|
sSensor->gpio, sensorId, sSensor->name, temperature, humidity
|
||||||
|
);
|
||||||
|
|
||||||
|
// set temperature
|
||||||
|
Sensors::setValueById(
|
||||||
|
sensorId, temperature,
|
||||||
|
Sensors::ValueType::TEMPERATURE, true, true
|
||||||
|
);
|
||||||
|
|
||||||
|
// set humidity
|
||||||
|
Sensors::setValueById(sensorId, humidity, Sensors::ValueType::HUMIDITY, true, true);
|
||||||
|
|
||||||
|
Sensors::adjustSignalQuality(sensorId, 1);
|
||||||
|
lastPollingTime[gpio] = millis();
|
||||||
|
});
|
||||||
|
|
||||||
|
instance.onError([sensorId, gpio = sSensor->gpio](DHT::Status status) {
|
||||||
|
const auto sSensor = Sensors::getSettings(sensorId);
|
||||||
|
if (!sSensor) {
|
||||||
|
lastPollingTime[gpio] = millis();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
ESP_LOGW(
|
||||||
|
L_SENSORS_DHT, "GPIO %hhu, sensor #%hhu '%s': failed receiving data (err: %s)",
|
||||||
|
sSensor->gpio, sensorId, sSensor->name, DHT::statusToString(instance.getStatus())
|
||||||
|
);
|
||||||
|
|
||||||
|
Sensors::adjustSignalQuality(sensorId, -1);
|
||||||
|
lastPollingTime[gpio] = millis();
|
||||||
|
});
|
||||||
|
|
||||||
|
if (instance.setup(sensorGpio, sensorType)) {
|
||||||
|
ESP_LOGI(L_SENSORS_DHT, "Started on GPIO %hhu", sSensor->gpio);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
ESP_LOGW(
|
||||||
|
L_SENSORS_DHT, "Failed to start on GPIO %hhu (err: %s)",
|
||||||
|
sSensor->gpio, DHT::statusToString(instance.getStatus())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
lastPollingSensorId = sensorId;
|
||||||
|
if (!instance.poll()) {
|
||||||
|
lastPollingTime[sSensor->gpio] = millis();
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
static Task maintainDallasSensorsTask("Maintain Dallas sensors", [](void*) {
|
||||||
|
cleanDallasInstances();
|
||||||
|
makeDallasInstances();
|
||||||
|
searchDallasSensors();
|
||||||
|
fillingAddressesDallasSensors();
|
||||||
|
pollingDallasSensors();
|
||||||
|
});
|
||||||
|
|
||||||
|
static Task readNtcSensorsTask("Read NTC sensors", [](void*) {
|
||||||
|
for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) {
|
||||||
|
const auto sSensor = Sensors::getSettings(sensorId);
|
||||||
|
if (!sSensor) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!sSensor->enabled || sSensor->type != Sensors::Type::NTC_10K_TEMP || sSensor->purpose == Sensors::Purpose::NOT_CONFIGURED) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto value = analogReadMilliVolts(sSensor->gpio);
|
||||||
|
if (value < DEFAULT_NTC_VLOW_THRESHOLD || value > DEFAULT_NTC_VHIGH_THRESHOLD) {
|
||||||
|
Sensors::setConnectionStatusById(sensorId, false, false);
|
||||||
|
|
||||||
|
ESP_LOGW(
|
||||||
|
L_SENSORS_NTC, "GPIO %hhu, sensor #%hhu '%s', voltage is out of threshold: %.3f",
|
||||||
|
sSensor->gpio, sensorId, sSensor->name, (value / 1000.0f)
|
||||||
|
);
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const float sensorResistance = value > 1
|
||||||
|
? DEFAULT_NTC_REF_RESISTANCE / (DEFAULT_NTC_VREF / static_cast<float>(value) - 1.0f)
|
||||||
|
: 0.0f;
|
||||||
|
const float rawTemp = 1.0f / (
|
||||||
|
1.0f / (DEFAULT_NTC_NOMINAL_TEMP + 273.15f) +
|
||||||
|
log(sensorResistance / DEFAULT_NTC_NOMINAL_RESISTANCE) / DEFAULT_NTC_BETA_FACTOR
|
||||||
|
) - 273.15f;
|
||||||
|
|
||||||
|
ESP_LOGD(
|
||||||
|
L_SENSORS_NTC, "GPIO %hhu, sensor #%hhu '%s', raw temp: %.2f, raw voltage: %.3f, raw resistance: %.2f",
|
||||||
|
sSensor->gpio, sensorId, sSensor->name, rawTemp, (value / 1000.0f), sensorResistance
|
||||||
|
);
|
||||||
|
|
||||||
|
// set temp
|
||||||
|
Sensors::setValueById(
|
||||||
|
sensorId, rawTemp,
|
||||||
|
Sensors::ValueType::TEMPERATURE, true, true
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
#if USE_BLE
|
||||||
|
static Task scanBleSensorsTask("Scan BLE sensors", [](void*) {
|
||||||
|
scanBleSensors();
|
||||||
|
});
|
||||||
|
#endif
|
||||||
|
|
||||||
|
static Task updateSensorsTask("Update sensor states", [](void*) {
|
||||||
|
updateConnectionStatus();
|
||||||
|
updateMasterValues();
|
||||||
|
});
|
||||||
|
|
||||||
|
void initSensors() {
|
||||||
|
dallasLastPollingTime.reserve(2);
|
||||||
|
owInstances.reserve(2);
|
||||||
|
dallasInstances.reserve(2);
|
||||||
|
dallasSearchTime.reserve(2);
|
||||||
|
dallasPolling.reserve(2);
|
||||||
|
|
||||||
|
readDallasSensorsTask.setInterval(1000)
|
||||||
|
.setEnabledWhen([] {
|
||||||
|
return canRunSensors() && isPollingDallasSensors();
|
||||||
|
});
|
||||||
|
sensorsTaskManager.addTask(readDallasSensorsTask);
|
||||||
|
|
||||||
|
pollDhtSensorsTask.setInterval(1000)
|
||||||
|
.setEnabledWhen([] {
|
||||||
|
return canRunSensors() && (
|
||||||
|
Sensors::getAmountByType(Sensors::Type::DHT11, true) ||
|
||||||
|
Sensors::getAmountByType(Sensors::Type::DHT22, true)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
sensorsTaskManager.addTask(pollDhtSensorsTask);
|
||||||
|
|
||||||
|
maintainDallasSensorsTask.setEnabledWhen([] {
|
||||||
|
return canRunSensors() && (
|
||||||
|
!dallasInstances.empty() ||
|
||||||
|
Sensors::getAmountByType(Sensors::Type::DALLAS_TEMP, true)
|
||||||
|
);
|
||||||
|
})
|
||||||
|
.resume(15000);
|
||||||
|
sensorsTaskManager.addTask(maintainDallasSensorsTask);
|
||||||
|
|
||||||
|
readNtcSensorsTask.setEnabledWhen([] {
|
||||||
|
return canRunSensors() && Sensors::getAmountByType(Sensors::Type::NTC_10K_TEMP, true);
|
||||||
|
})
|
||||||
|
.resume(15000);
|
||||||
|
sensorsTaskManager.addTask(readNtcSensorsTask);
|
||||||
|
|
||||||
|
#if USE_BLE
|
||||||
|
scanBleSensorsTask.setEnabledWhen([] {
|
||||||
|
return canRunSensors() && (
|
||||||
|
NimBLEDevice::isInitialized() ||
|
||||||
|
Sensors::getAmountByType(Sensors::Type::BLUETOOTH, true)
|
||||||
|
);
|
||||||
|
})
|
||||||
|
.resume(15000);
|
||||||
|
sensorsTaskManager.addTask(scanBleSensorsTask);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
updateSensorsTask.setInterval(1000)
|
||||||
|
.setEnabledWhen(canRunSensors);
|
||||||
|
sensorsTaskManager.addTask(updateSensorsTask);
|
||||||
|
}
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#ifndef PROGMEM
|
|
||||||
#define PROGMEM
|
|
||||||
#endif
|
|
||||||
|
|
||||||
const char L_SETTINGS[] PROGMEM = "SETTINGS";
|
|
||||||
const char L_NETWORK[] PROGMEM = "NETWORK";
|
|
||||||
const char L_NETWORK_SETTINGS[] PROGMEM = "NETWORK.SETTINGS";
|
|
||||||
const char L_PORTAL_WEBSERVER[] PROGMEM = "PORTAL.WEBSERVER";
|
|
||||||
const char L_PORTAL_DNSSERVER[] PROGMEM = "PORTAL.DNSSERVER";
|
|
||||||
const char L_PORTAL_CAPTIVE[] PROGMEM = "PORTAL.CAPTIVE";
|
|
||||||
const char L_PORTAL_OTA[] PROGMEM = "PORTAL.OTA";
|
|
||||||
const char L_MAIN[] PROGMEM = "MAIN";
|
|
||||||
const char L_MQTT[] PROGMEM = "MQTT";
|
|
||||||
const char L_MQTT_MSG[] PROGMEM = "MQTT.MSG";
|
|
||||||
const char L_OT[] PROGMEM = "OT";
|
|
||||||
const char L_OT_DHW[] PROGMEM = "OT.DHW";
|
|
||||||
const char L_OT_HEATING[] PROGMEM = "OT.HEATING";
|
|
||||||
const char L_SENSORS_OUTDOOR[] PROGMEM = "SENSORS.OUTDOOR";
|
|
||||||
const char L_SENSORS_INDOOR[] PROGMEM = "SENSORS.INDOOR";
|
|
||||||
const char L_SENSORS_BLE[] PROGMEM = "SENSORS.BLE";
|
|
||||||
const char L_REGULATOR[] PROGMEM = "REGULATOR";
|
|
||||||
const char L_REGULATOR_PID[] PROGMEM = "REGULATOR.PID";
|
|
||||||
const char L_REGULATOR_EQUITHERM[] PROGMEM = "REGULATOR.EQUITHERM";
|
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE
|
||||||
|
|
||||||
|
#include <app.h>
|
||||||
|
#include <metrics.h>
|
||||||
|
#include <esp_system.h>
|
||||||
|
|
||||||
|
|
||||||
|
std::string getResetReason() {
|
||||||
|
std::string value;
|
||||||
|
|
||||||
|
switch (esp_reset_reason()) {
|
||||||
|
case ESP_RST_POWERON:
|
||||||
|
value = "Reset due to power-on event";
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ESP_RST_EXT:
|
||||||
|
value = "Reset by external pin";
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ESP_RST_SW:
|
||||||
|
value = "Software reset via esp_restart";
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ESP_RST_PANIC:
|
||||||
|
value = "Software reset due to exception/panic";
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ESP_RST_INT_WDT:
|
||||||
|
value = "Reset (software or hardware) due to interrupt watchdog";
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ESP_RST_TASK_WDT:
|
||||||
|
value = "Reset due to task watchdog";
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ESP_RST_WDT:
|
||||||
|
value = "Reset due to other watchdogs";
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ESP_RST_DEEPSLEEP:
|
||||||
|
value = "Reset after exiting deep sleep mode";
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ESP_RST_BROWNOUT:
|
||||||
|
value = "Brownout reset (software or hardware)";
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ESP_RST_SDIO:
|
||||||
|
value = "Reset over SDIO";
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ESP_RST_UNKNOWN:
|
||||||
|
default:
|
||||||
|
value = "unknown";
|
||||||
|
break;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
static unsigned long lastHeapInfo = 0;
|
||||||
|
static unsigned int minFreeHeap = 0;
|
||||||
|
static unsigned int minLargestFreeBlock = 0;
|
||||||
|
|
||||||
|
Task restartTask("Restart", Task::Type::ONCE, [](void*) {
|
||||||
|
ESP_LOGI(L_MAIN, "Restart preparation started");
|
||||||
|
coreTaskManager.pause();
|
||||||
|
sensorsTaskManager.pause();
|
||||||
|
openthermTaskManager.pause();
|
||||||
|
|
||||||
|
// Finish application callbacks and onDone before saving, including with critical heap.
|
||||||
|
coreTaskManager.waitForPaused();
|
||||||
|
sensorsTaskManager.waitForPaused();
|
||||||
|
openthermTaskManager.waitForPaused();
|
||||||
|
saveSettingsNow();
|
||||||
|
|
||||||
|
// Yield to FreeRTOS/IDF tasks before resetting the device.
|
||||||
|
::delay(250);
|
||||||
|
ESP.restart();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Maintenance
|
||||||
|
static Task maintenanceTask("System maintenance", [](void*) {
|
||||||
|
getMemoryMetrics();
|
||||||
|
|
||||||
|
drainLoggingSerial();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Heap monitoring remains active while the core manager is paused.
|
||||||
|
static Task heapTask("Heap monitoring", [](void*) {
|
||||||
|
const auto memory = getMemoryMetrics();
|
||||||
|
unsigned int freeHeap = memory.heap.total_free_bytes;
|
||||||
|
unsigned int maxFreeBlockHeap = memory.heap.largest_free_block;
|
||||||
|
|
||||||
|
/*if (freeHeap < 2048 || maxFreeBlockHeap < 2048) {
|
||||||
|
if (!vars.states.upgrading) {
|
||||||
|
esp_system_abort("OTGateway: low internal heap");
|
||||||
|
}
|
||||||
|
}*/
|
||||||
|
|
||||||
|
if (esp_log_level_get(L_MAIN) < ESP_LOG_VERBOSE) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t currentMinFreeHeap = memory.heap.minimum_free_bytes;
|
||||||
|
size_t minFreeHeapDiff = 0;
|
||||||
|
if (currentMinFreeHeap < minFreeHeap || minFreeHeap == 0) {
|
||||||
|
minFreeHeapDiff = minFreeHeap ? minFreeHeap - currentMinFreeHeap : 0;
|
||||||
|
minFreeHeap = currentMinFreeHeap;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t currentMinLargestFreeBlock = memory.heap.minLargestBlock;
|
||||||
|
size_t minLargestFreeBlockDiff = 0;
|
||||||
|
if (currentMinLargestFreeBlock < minLargestFreeBlock || minLargestFreeBlock == 0) {
|
||||||
|
minLargestFreeBlockDiff = minLargestFreeBlock ? minLargestFreeBlock - currentMinLargestFreeBlock : 0;
|
||||||
|
minLargestFreeBlock = currentMinLargestFreeBlock;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (millis() - lastHeapInfo > 20000 || minFreeHeapDiff > 0 || minLargestFreeBlockDiff > 0) {
|
||||||
|
ESP_LOGV(
|
||||||
|
L_MAIN,
|
||||||
|
"Free heap size: %u of %u bytes (min: %u, diff: %u), max free block: %u (min: %u, diff: %u, frag: %hhu%%)",
|
||||||
|
freeHeap, memory.heap.total, minFreeHeap, minFreeHeapDiff,
|
||||||
|
maxFreeBlockHeap, minLargestFreeBlock, minLargestFreeBlockDiff, memory.heap.fragmentation
|
||||||
|
);
|
||||||
|
lastHeapInfo = millis();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Initialization
|
||||||
|
void initSystem() {
|
||||||
|
systemTaskManager.addTask(restartTask);
|
||||||
|
|
||||||
|
maintenanceTask.setInterval(100);
|
||||||
|
systemTaskManager.addTask(maintenanceTask);
|
||||||
|
|
||||||
|
heapTask.setInterval(100);
|
||||||
|
systemTaskManager.addTask(heapTask);
|
||||||
|
}
|
||||||
@@ -1,993 +0,0 @@
|
|||||||
#include <Arduino.h>
|
|
||||||
|
|
||||||
double roundd(double value, uint8_t decimals = 2) {
|
|
||||||
if (decimals == 0) {
|
|
||||||
return (int)(value + 0.5);
|
|
||||||
|
|
||||||
} else if (abs(value) < 0.00000001) {
|
|
||||||
return 0.0;
|
|
||||||
}
|
|
||||||
|
|
||||||
double multiplier = pow10(decimals);
|
|
||||||
value += 0.5 / multiplier * (value < 0 ? -1 : 1);
|
|
||||||
return (int)(value * multiplier) / multiplier;
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t getTotalHeap() {
|
|
||||||
#if defined(ARDUINO_ARCH_ESP32)
|
|
||||||
return ESP.getHeapSize();
|
|
||||||
#elif defined(ARDUINO_ARCH_ESP8266)
|
|
||||||
return 81920;
|
|
||||||
#else
|
|
||||||
return 99999;
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t getFreeHeap(bool getMinValue = false) {
|
|
||||||
#if defined(ARDUINO_ARCH_ESP32)
|
|
||||||
return getMinValue ? ESP.getMinFreeHeap() : ESP.getFreeHeap();
|
|
||||||
|
|
||||||
#elif defined(ARDUINO_ARCH_ESP8266)
|
|
||||||
static size_t minValue = 0;
|
|
||||||
size_t value = ESP.getFreeHeap();
|
|
||||||
|
|
||||||
if (value < minValue || minValue == 0) {
|
|
||||||
minValue = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
return getMinValue ? minValue : value;
|
|
||||||
#else
|
|
||||||
return 0;
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t getMaxFreeBlockHeap(bool getMinValue = false) {
|
|
||||||
static size_t minValue = 0;
|
|
||||||
size_t value = 0;
|
|
||||||
|
|
||||||
#if defined(ARDUINO_ARCH_ESP32)
|
|
||||||
value = ESP.getMaxAllocHeap();
|
|
||||||
|
|
||||||
size_t minHeapValue = getFreeHeap(true);
|
|
||||||
if (minHeapValue < minValue || minValue == 0) {
|
|
||||||
minValue = minHeapValue;
|
|
||||||
}
|
|
||||||
#elif defined(ARDUINO_ARCH_ESP8266)
|
|
||||||
value = ESP.getMaxFreeBlockSize();
|
|
||||||
#endif
|
|
||||||
|
|
||||||
if (value < minValue || minValue == 0) {
|
|
||||||
minValue = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
return getMinValue ? minValue : value;
|
|
||||||
}
|
|
||||||
|
|
||||||
uint8_t getHeapFrag() {
|
|
||||||
return 100 - getMaxFreeBlockHeap() * 100.0 / getFreeHeap();
|
|
||||||
}
|
|
||||||
|
|
||||||
String getResetReason() {
|
|
||||||
String value;
|
|
||||||
|
|
||||||
#if defined(ARDUINO_ARCH_ESP8266)
|
|
||||||
value = ESP.getResetReason();
|
|
||||||
#elif defined(ARDUINO_ARCH_ESP32)
|
|
||||||
switch(esp_reset_reason()) {
|
|
||||||
case ESP_RST_POWERON:
|
|
||||||
value = F("Reset due to power-on event");
|
|
||||||
break;
|
|
||||||
|
|
||||||
case ESP_RST_EXT:
|
|
||||||
value = F("Reset by external pin");
|
|
||||||
break;
|
|
||||||
|
|
||||||
case ESP_RST_SW:
|
|
||||||
value = F("Software reset via esp_restart");
|
|
||||||
break;
|
|
||||||
|
|
||||||
case ESP_RST_PANIC:
|
|
||||||
value = F("Software reset due to exception/panic");
|
|
||||||
break;
|
|
||||||
|
|
||||||
case ESP_RST_INT_WDT:
|
|
||||||
value = F("Reset (software or hardware) due to interrupt watchdog");
|
|
||||||
break;
|
|
||||||
|
|
||||||
case ESP_RST_TASK_WDT:
|
|
||||||
value = F("Reset due to task watchdog");
|
|
||||||
break;
|
|
||||||
|
|
||||||
case ESP_RST_WDT:
|
|
||||||
value = F("Reset due to other watchdogs");
|
|
||||||
break;
|
|
||||||
|
|
||||||
case ESP_RST_DEEPSLEEP:
|
|
||||||
value = F("Reset after exiting deep sleep mode");
|
|
||||||
break;
|
|
||||||
|
|
||||||
case ESP_RST_BROWNOUT:
|
|
||||||
value = F("Brownout reset (software or hardware)");
|
|
||||||
break;
|
|
||||||
|
|
||||||
case ESP_RST_SDIO:
|
|
||||||
value = F("Reset over SDIO");
|
|
||||||
break;
|
|
||||||
|
|
||||||
case ESP_RST_UNKNOWN:
|
|
||||||
default:
|
|
||||||
value = F("unknown");
|
|
||||||
break;
|
|
||||||
|
|
||||||
}
|
|
||||||
#else
|
|
||||||
value = F("unknown");
|
|
||||||
#endif
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
void networkSettingsToJson(const NetworkSettings& src, JsonVariant dst) {
|
|
||||||
dst["hostname"] = src.hostname;
|
|
||||||
|
|
||||||
dst["useDhcp"] = src.useDhcp;
|
|
||||||
dst["staticConfig"]["ip"] = src.staticConfig.ip;
|
|
||||||
dst["staticConfig"]["gateway"] = src.staticConfig.gateway;
|
|
||||||
dst["staticConfig"]["subnet"] = src.staticConfig.subnet;
|
|
||||||
dst["staticConfig"]["dns"] = src.staticConfig.dns;
|
|
||||||
|
|
||||||
dst["ap"]["ssid"] = src.ap.ssid;
|
|
||||||
dst["ap"]["password"] = src.ap.password;
|
|
||||||
dst["ap"]["channel"] = src.ap.channel;
|
|
||||||
|
|
||||||
dst["sta"]["ssid"] = src.sta.ssid;
|
|
||||||
dst["sta"]["password"] = src.sta.password;
|
|
||||||
dst["sta"]["channel"] = src.sta.channel;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool jsonToNetworkSettings(const JsonVariantConst src, NetworkSettings& dst) {
|
|
||||||
bool changed = false;
|
|
||||||
|
|
||||||
// hostname
|
|
||||||
if (!src["hostname"].isNull()) {
|
|
||||||
String value = src["hostname"].as<String>();
|
|
||||||
|
|
||||||
if (value.length() < sizeof(dst.hostname)) {
|
|
||||||
strcpy(dst.hostname, value.c_str());
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// use dhcp
|
|
||||||
if (src["useDhcp"].is<bool>()) {
|
|
||||||
dst.useDhcp = src["useDhcp"].as<bool>();
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// static config
|
|
||||||
if (!src["staticConfig"]["ip"].isNull()) {
|
|
||||||
String value = src["staticConfig"]["ip"].as<String>();
|
|
||||||
|
|
||||||
if (value.length() < sizeof(dst.staticConfig.ip)) {
|
|
||||||
strcpy(dst.staticConfig.ip, value.c_str());
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["staticConfig"]["gateway"].isNull()) {
|
|
||||||
String value = src["staticConfig"]["gateway"].as<String>();
|
|
||||||
|
|
||||||
if (value.length() < sizeof(dst.staticConfig.gateway)) {
|
|
||||||
strcpy(dst.staticConfig.gateway, value.c_str());
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["staticConfig"]["subnet"].isNull()) {
|
|
||||||
String value = src["staticConfig"]["subnet"].as<String>();
|
|
||||||
|
|
||||||
if (value.length() < sizeof(dst.staticConfig.subnet)) {
|
|
||||||
strcpy(dst.staticConfig.subnet, value.c_str());
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["staticConfig"]["dns"].isNull()) {
|
|
||||||
String value = src["staticConfig"]["dns"].as<String>();
|
|
||||||
|
|
||||||
if (value.length() < sizeof(dst.staticConfig.dns)) {
|
|
||||||
strcpy(dst.staticConfig.dns, value.c_str());
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// ap
|
|
||||||
if (!src["ap"]["ssid"].isNull()) {
|
|
||||||
String value = src["ap"]["ssid"].as<String>();
|
|
||||||
|
|
||||||
if (value.length() < sizeof(dst.ap.ssid)) {
|
|
||||||
strcpy(dst.ap.ssid, value.c_str());
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["ap"]["password"].isNull()) {
|
|
||||||
String value = src["ap"]["password"].as<String>();
|
|
||||||
|
|
||||||
if (value.length() < sizeof(dst.ap.password)) {
|
|
||||||
strcpy(dst.ap.password, value.c_str());
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["ap"]["channel"].isNull()) {
|
|
||||||
unsigned char value = src["ap"]["channel"].as<unsigned char>();
|
|
||||||
|
|
||||||
if (value >= 0 && value < 12) {
|
|
||||||
dst.ap.channel = value;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// sta
|
|
||||||
if (!src["sta"]["ssid"].isNull()) {
|
|
||||||
String value = src["sta"]["ssid"].as<String>();
|
|
||||||
|
|
||||||
if (value.length() < sizeof(dst.sta.ssid)) {
|
|
||||||
strcpy(dst.sta.ssid, value.c_str());
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["sta"]["password"].isNull()) {
|
|
||||||
String value = src["sta"]["password"].as<String>();
|
|
||||||
|
|
||||||
if (value.length() < sizeof(dst.sta.password)) {
|
|
||||||
strcpy(dst.sta.password, value.c_str());
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["sta"]["channel"].isNull()) {
|
|
||||||
unsigned char value = src["sta"]["channel"].as<unsigned char>();
|
|
||||||
|
|
||||||
if (value >= 0 && value < 12) {
|
|
||||||
dst.sta.channel = value;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return changed;
|
|
||||||
}
|
|
||||||
|
|
||||||
void settingsToJson(const Settings& src, JsonVariant dst, bool safe = false) {
|
|
||||||
if (!safe) {
|
|
||||||
dst["system"]["debug"] = src.system.debug;
|
|
||||||
dst["system"]["useSerial"] = src.system.useSerial;
|
|
||||||
dst["system"]["useTelnet"] = src.system.useTelnet;
|
|
||||||
|
|
||||||
dst["portal"]["useAuth"] = src.portal.useAuth;
|
|
||||||
dst["portal"]["login"] = src.portal.login;
|
|
||||||
dst["portal"]["password"] = src.portal.password;
|
|
||||||
|
|
||||||
dst["opentherm"]["inPin"] = src.opentherm.inPin;
|
|
||||||
dst["opentherm"]["outPin"] = src.opentherm.outPin;
|
|
||||||
dst["opentherm"]["memberIdCode"] = src.opentherm.memberIdCode;
|
|
||||||
dst["opentherm"]["dhwPresent"] = src.opentherm.dhwPresent;
|
|
||||||
dst["opentherm"]["summerWinterMode"] = src.opentherm.summerWinterMode;
|
|
||||||
dst["opentherm"]["heatingCh2Enabled"] = src.opentherm.heatingCh2Enabled;
|
|
||||||
dst["opentherm"]["heatingCh1ToCh2"] = src.opentherm.heatingCh1ToCh2;
|
|
||||||
dst["opentherm"]["dhwToCh2"] = src.opentherm.dhwToCh2;
|
|
||||||
dst["opentherm"]["dhwBlocking"] = src.opentherm.dhwBlocking;
|
|
||||||
dst["opentherm"]["modulationSyncWithHeating"] = src.opentherm.modulationSyncWithHeating;
|
|
||||||
|
|
||||||
dst["mqtt"]["server"] = src.mqtt.server;
|
|
||||||
dst["mqtt"]["port"] = src.mqtt.port;
|
|
||||||
dst["mqtt"]["user"] = src.mqtt.user;
|
|
||||||
dst["mqtt"]["password"] = src.mqtt.password;
|
|
||||||
dst["mqtt"]["prefix"] = src.mqtt.prefix;
|
|
||||||
dst["mqtt"]["interval"] = src.mqtt.interval;
|
|
||||||
}
|
|
||||||
|
|
||||||
dst["emergency"]["enable"] = src.emergency.enable;
|
|
||||||
dst["emergency"]["target"] = roundd(src.emergency.target, 2);
|
|
||||||
dst["emergency"]["useEquitherm"] = src.emergency.useEquitherm;
|
|
||||||
dst["emergency"]["usePid"] = src.emergency.usePid;
|
|
||||||
|
|
||||||
dst["heating"]["enable"] = src.heating.enable;
|
|
||||||
dst["heating"]["turbo"] = src.heating.turbo;
|
|
||||||
dst["heating"]["target"] = roundd(src.heating.target, 2);
|
|
||||||
dst["heating"]["hysteresis"] = roundd(src.heating.hysteresis, 2);
|
|
||||||
dst["heating"]["minTemp"] = src.heating.minTemp;
|
|
||||||
dst["heating"]["maxTemp"] = src.heating.maxTemp;
|
|
||||||
dst["heating"]["maxModulation"] = src.heating.maxModulation;
|
|
||||||
|
|
||||||
dst["dhw"]["enable"] = src.dhw.enable;
|
|
||||||
dst["dhw"]["target"] = src.dhw.target;
|
|
||||||
dst["dhw"]["minTemp"] = src.dhw.minTemp;
|
|
||||||
dst["dhw"]["maxTemp"] = src.dhw.maxTemp;
|
|
||||||
|
|
||||||
dst["pid"]["enable"] = src.pid.enable;
|
|
||||||
dst["pid"]["p_factor"] = roundd(src.pid.p_factor, 3);
|
|
||||||
dst["pid"]["i_factor"] = roundd(src.pid.i_factor, 3);
|
|
||||||
dst["pid"]["d_factor"] = roundd(src.pid.d_factor, 1);
|
|
||||||
dst["pid"]["dt"] = src.pid.dt;
|
|
||||||
dst["pid"]["minTemp"] = src.pid.minTemp;
|
|
||||||
dst["pid"]["maxTemp"] = src.pid.maxTemp;
|
|
||||||
|
|
||||||
dst["equitherm"]["enable"] = src.equitherm.enable;
|
|
||||||
dst["equitherm"]["n_factor"] = roundd(src.equitherm.n_factor, 3);
|
|
||||||
dst["equitherm"]["k_factor"] = roundd(src.equitherm.k_factor, 3);
|
|
||||||
dst["equitherm"]["t_factor"] = roundd(src.equitherm.t_factor, 3);
|
|
||||||
|
|
||||||
dst["sensors"]["outdoor"]["type"] = src.sensors.outdoor.type;
|
|
||||||
dst["sensors"]["outdoor"]["pin"] = src.sensors.outdoor.pin;
|
|
||||||
dst["sensors"]["outdoor"]["offset"] = roundd(src.sensors.outdoor.offset, 2);
|
|
||||||
|
|
||||||
dst["sensors"]["indoor"]["type"] = src.sensors.indoor.type;
|
|
||||||
dst["sensors"]["indoor"]["pin"] = src.sensors.indoor.pin;
|
|
||||||
|
|
||||||
char bleAddress[18];
|
|
||||||
sprintf(
|
|
||||||
bleAddress,
|
|
||||||
"%02x:%02x:%02x:%02x:%02x:%02x",
|
|
||||||
src.sensors.indoor.bleAddresss[0],
|
|
||||||
src.sensors.indoor.bleAddresss[1],
|
|
||||||
src.sensors.indoor.bleAddresss[2],
|
|
||||||
src.sensors.indoor.bleAddresss[3],
|
|
||||||
src.sensors.indoor.bleAddresss[4],
|
|
||||||
src.sensors.indoor.bleAddresss[5]
|
|
||||||
);
|
|
||||||
dst["sensors"]["indoor"]["bleAddresss"] = String(bleAddress);
|
|
||||||
dst["sensors"]["indoor"]["offset"] = roundd(src.sensors.indoor.offset, 2);
|
|
||||||
|
|
||||||
if (!safe) {
|
|
||||||
dst["externalPump"]["use"] = src.externalPump.use;
|
|
||||||
dst["externalPump"]["pin"] = src.externalPump.pin;
|
|
||||||
dst["externalPump"]["postCirculationTime"] = roundd(src.externalPump.postCirculationTime / 60, 0);
|
|
||||||
dst["externalPump"]["antiStuckInterval"] = roundd(src.externalPump.antiStuckInterval / 86400, 0);
|
|
||||||
dst["externalPump"]["antiStuckTime"] = roundd(src.externalPump.antiStuckTime / 60, 0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void safeSettingsToJson(const Settings& src, JsonVariant dst) {
|
|
||||||
settingsToJson(src, dst, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool jsonToSettings(const JsonVariantConst src, Settings& dst, bool safe = false) {
|
|
||||||
bool changed = false;
|
|
||||||
|
|
||||||
if (!safe) {
|
|
||||||
// system
|
|
||||||
if (src["system"]["debug"].is<bool>()) {
|
|
||||||
dst.system.debug = src["system"]["debug"].as<bool>();
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (src["system"]["useSerial"].is<bool>()) {
|
|
||||||
dst.system.useSerial = src["system"]["useSerial"].as<bool>();
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (src["system"]["useTelnet"].is<bool>()) {
|
|
||||||
dst.system.useTelnet = src["system"]["useTelnet"].as<bool>();
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// portal
|
|
||||||
if (src["portal"]["useAuth"].is<bool>()) {
|
|
||||||
dst.portal.useAuth = src["portal"]["useAuth"].as<bool>();
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["portal"]["login"].isNull()) {
|
|
||||||
String value = src["portal"]["login"].as<String>();
|
|
||||||
|
|
||||||
if (value.length() < sizeof(dst.portal.login)) {
|
|
||||||
strcpy(dst.portal.login, value.c_str());
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["portal"]["password"].isNull()) {
|
|
||||||
String value = src["portal"]["password"].as<String>();
|
|
||||||
|
|
||||||
if (value.length() < sizeof(dst.portal.password)) {
|
|
||||||
strcpy(dst.portal.password, value.c_str());
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// opentherm
|
|
||||||
if (!src["opentherm"]["inPin"].isNull()) {
|
|
||||||
unsigned char value = src["opentherm"]["inPin"].as<unsigned char>();
|
|
||||||
|
|
||||||
if (value >= 0 && value < 50) {
|
|
||||||
dst.opentherm.inPin = value;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["opentherm"]["outPin"].isNull()) {
|
|
||||||
unsigned char value = src["opentherm"]["outPin"].as<unsigned char>();
|
|
||||||
|
|
||||||
if (value >= 0 && value < 50) {
|
|
||||||
dst.opentherm.outPin = value;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["opentherm"]["memberIdCode"].isNull()) {
|
|
||||||
unsigned int value = src["opentherm"]["memberIdCode"].as<unsigned int>();
|
|
||||||
|
|
||||||
if (value >= 0 && value < 65536) {
|
|
||||||
dst.opentherm.memberIdCode = value;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (src["opentherm"]["dhwPresent"].is<bool>()) {
|
|
||||||
dst.opentherm.dhwPresent = src["opentherm"]["dhwPresent"].as<bool>();
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (src["opentherm"]["summerWinterMode"].is<bool>()) {
|
|
||||||
dst.opentherm.summerWinterMode = src["opentherm"]["summerWinterMode"].as<bool>();
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (src["opentherm"]["heatingCh2Enabled"].is<bool>()) {
|
|
||||||
dst.opentherm.heatingCh2Enabled = src["opentherm"]["heatingCh2Enabled"].as<bool>();
|
|
||||||
|
|
||||||
if (dst.opentherm.heatingCh2Enabled) {
|
|
||||||
dst.opentherm.heatingCh1ToCh2 = false;
|
|
||||||
dst.opentherm.dhwToCh2 = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (src["opentherm"]["heatingCh1ToCh2"].is<bool>()) {
|
|
||||||
dst.opentherm.heatingCh1ToCh2 = src["opentherm"]["heatingCh1ToCh2"].as<bool>();
|
|
||||||
|
|
||||||
if (dst.opentherm.heatingCh1ToCh2) {
|
|
||||||
dst.opentherm.heatingCh2Enabled = false;
|
|
||||||
dst.opentherm.dhwToCh2 = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (src["opentherm"]["dhwToCh2"].is<bool>()) {
|
|
||||||
dst.opentherm.dhwToCh2 = src["opentherm"]["dhwToCh2"].as<bool>();
|
|
||||||
|
|
||||||
if (dst.opentherm.dhwToCh2) {
|
|
||||||
dst.opentherm.heatingCh2Enabled = false;
|
|
||||||
dst.opentherm.heatingCh1ToCh2 = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (src["opentherm"]["dhwBlocking"].is<bool>()) {
|
|
||||||
dst.opentherm.dhwBlocking = src["opentherm"]["dhwBlocking"].as<bool>();
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (src["opentherm"]["modulationSyncWithHeating"].is<bool>()) {
|
|
||||||
dst.opentherm.modulationSyncWithHeating = src["opentherm"]["modulationSyncWithHeating"].as<bool>();
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// mqtt
|
|
||||||
if (!src["mqtt"]["server"].isNull()) {
|
|
||||||
String value = src["mqtt"]["server"].as<String>();
|
|
||||||
|
|
||||||
if (value.length() < sizeof(dst.mqtt.server)) {
|
|
||||||
strcpy(dst.mqtt.server, value.c_str());
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["mqtt"]["port"].isNull()) {
|
|
||||||
unsigned short value = src["mqtt"]["port"].as<unsigned short>();
|
|
||||||
|
|
||||||
if (value > 0 && value <= 65535) {
|
|
||||||
dst.mqtt.port = value;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["mqtt"]["user"].isNull()) {
|
|
||||||
String value = src["mqtt"]["user"].as<String>();
|
|
||||||
|
|
||||||
if (value.length() < sizeof(dst.mqtt.user)) {
|
|
||||||
strcpy(dst.mqtt.user, value.c_str());
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["mqtt"]["password"].isNull()) {
|
|
||||||
String value = src["mqtt"]["password"].as<String>();
|
|
||||||
|
|
||||||
if (value.length() < sizeof(dst.mqtt.password)) {
|
|
||||||
strcpy(dst.mqtt.password, value.c_str());
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["mqtt"]["prefix"].isNull()) {
|
|
||||||
String value = src["mqtt"]["prefix"].as<String>();
|
|
||||||
|
|
||||||
if (value.length() < sizeof(dst.mqtt.prefix)) {
|
|
||||||
strcpy(dst.mqtt.prefix, value.c_str());
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["mqtt"]["interval"].isNull()) {
|
|
||||||
unsigned short value = src["mqtt"]["interval"].as<unsigned short>();
|
|
||||||
|
|
||||||
if (value >= 3 && value <= 60) {
|
|
||||||
dst.mqtt.interval = value;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// emergency
|
|
||||||
if (src["emergency"]["enable"].is<bool>()) {
|
|
||||||
dst.emergency.enable = src["emergency"]["enable"].as<bool>();
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["emergency"]["target"].isNull()) {
|
|
||||||
double value = src["emergency"]["target"].as<double>();
|
|
||||||
|
|
||||||
if (value > 0 && value < 100) {
|
|
||||||
dst.emergency.target = roundd(value, 2);
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (src["emergency"]["useEquitherm"].is<bool>()) {
|
|
||||||
if (dst.sensors.outdoor.type != 1) {
|
|
||||||
dst.emergency.useEquitherm = src["emergency"]["useEquitherm"].as<bool>();
|
|
||||||
|
|
||||||
} else {
|
|
||||||
dst.emergency.useEquitherm = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (dst.emergency.useEquitherm && dst.emergency.usePid) {
|
|
||||||
dst.emergency.usePid = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (src["emergency"]["usePid"].is<bool>()) {
|
|
||||||
if (dst.sensors.indoor.type != 1) {
|
|
||||||
dst.emergency.usePid = src["emergency"]["usePid"].as<bool>();
|
|
||||||
|
|
||||||
} else {
|
|
||||||
dst.emergency.usePid = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (dst.emergency.usePid && dst.emergency.useEquitherm) {
|
|
||||||
dst.emergency.useEquitherm = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// heating
|
|
||||||
if (src["heating"]["enable"].is<bool>()) {
|
|
||||||
dst.heating.enable = src["heating"]["enable"].as<bool>();
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (src["heating"]["turbo"].is<bool>()) {
|
|
||||||
dst.heating.turbo = src["heating"]["turbo"].as<bool>();
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["heating"]["target"].isNull()) {
|
|
||||||
double value = src["heating"]["target"].as<double>();
|
|
||||||
|
|
||||||
if (value > 0 && value < 100) {
|
|
||||||
dst.heating.target = roundd(value, 2);
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["heating"]["hysteresis"].isNull()) {
|
|
||||||
double value = src["heating"]["hysteresis"].as<double>();
|
|
||||||
|
|
||||||
if (value >= 0 && value <= 5) {
|
|
||||||
dst.heating.hysteresis = roundd(value, 2);
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["heating"]["minTemp"].isNull()) {
|
|
||||||
unsigned char value = src["heating"]["minTemp"].as<unsigned char>();
|
|
||||||
|
|
||||||
if (value >= vars.parameters.heatingMinTemp && value <= vars.parameters.heatingMaxTemp) {
|
|
||||||
dst.heating.minTemp = value;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["heating"]["maxTemp"].isNull()) {
|
|
||||||
unsigned char value = src["heating"]["maxTemp"].as<unsigned char>();
|
|
||||||
|
|
||||||
if (value >= vars.parameters.heatingMinTemp && value <= vars.parameters.heatingMaxTemp) {
|
|
||||||
dst.heating.maxTemp = value;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["heating"]["maxModulation"].isNull()) {
|
|
||||||
unsigned char value = src["heating"]["maxModulation"].as<unsigned char>();
|
|
||||||
|
|
||||||
if (value > 0 && value <= 100) {
|
|
||||||
dst.heating.maxModulation = value;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// dhw
|
|
||||||
if (src["dhw"]["enable"].is<bool>()) {
|
|
||||||
dst.dhw.enable = src["dhw"]["enable"].as<bool>();
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["dhw"]["target"].isNull()) {
|
|
||||||
unsigned char value = src["dhw"]["target"].as<unsigned char>();
|
|
||||||
|
|
||||||
if (value >= 0 && value < 100) {
|
|
||||||
dst.dhw.target = value;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["dhw"]["minTemp"].isNull()) {
|
|
||||||
unsigned char value = src["dhw"]["minTemp"].as<unsigned char>();
|
|
||||||
|
|
||||||
if (value >= vars.parameters.dhwMinTemp && value <= vars.parameters.dhwMaxTemp) {
|
|
||||||
dst.dhw.minTemp = value;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["dhw"]["maxTemp"].isNull()) {
|
|
||||||
unsigned char value = src["dhw"]["maxTemp"].as<unsigned char>();
|
|
||||||
|
|
||||||
if (value >= vars.parameters.dhwMinTemp && value <= vars.parameters.dhwMaxTemp) {
|
|
||||||
dst.dhw.maxTemp = value;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// pid
|
|
||||||
if (src["pid"]["enable"].is<bool>()) {
|
|
||||||
dst.pid.enable = src["pid"]["enable"].as<bool>();
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["pid"]["p_factor"].isNull()) {
|
|
||||||
double value = src["pid"]["p_factor"].as<double>();
|
|
||||||
|
|
||||||
if (value > 0 && value <= 1000) {
|
|
||||||
dst.pid.p_factor = roundd(value, 3);
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["pid"]["i_factor"].isNull()) {
|
|
||||||
double value = src["pid"]["i_factor"].as<double>();
|
|
||||||
|
|
||||||
if (value >= 0 && value <= 100) {
|
|
||||||
dst.pid.i_factor = roundd(value, 3);
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["pid"]["d_factor"].isNull()) {
|
|
||||||
double value = src["pid"]["d_factor"].as<double>();
|
|
||||||
|
|
||||||
if (value >= 0 && value <= 100000) {
|
|
||||||
dst.pid.d_factor = roundd(value, 1);
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["pid"]["dt"].isNull()) {
|
|
||||||
unsigned short value = src["pid"]["dt"].as<unsigned short>();
|
|
||||||
|
|
||||||
if (value >= 30 && value <= 600) {
|
|
||||||
dst.pid.dt = value;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["pid"]["maxTemp"].isNull()) {
|
|
||||||
unsigned char value = src["pid"]["maxTemp"].as<unsigned char>();
|
|
||||||
|
|
||||||
if (value > 0 && value <= 100 && value > dst.pid.minTemp) {
|
|
||||||
dst.pid.maxTemp = value;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["pid"]["minTemp"].isNull()) {
|
|
||||||
unsigned char value = src["pid"]["minTemp"].as<unsigned char>();
|
|
||||||
|
|
||||||
if (value >= 0 && value < 100 && value < dst.pid.maxTemp) {
|
|
||||||
dst.pid.minTemp = value;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// equitherm
|
|
||||||
if (src["equitherm"]["enable"].is<bool>()) {
|
|
||||||
dst.equitherm.enable = src["equitherm"]["enable"].as<bool>();
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["equitherm"]["n_factor"].isNull()) {
|
|
||||||
double value = src["equitherm"]["n_factor"].as<double>();
|
|
||||||
|
|
||||||
if (value > 0 && value <= 10) {
|
|
||||||
dst.equitherm.n_factor = roundd(value, 3);
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["equitherm"]["k_factor"].isNull()) {
|
|
||||||
double value = src["equitherm"]["k_factor"].as<double>();
|
|
||||||
|
|
||||||
if (value >= 0 && value <= 10) {
|
|
||||||
dst.equitherm.k_factor = roundd(value, 3);
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["equitherm"]["t_factor"].isNull()) {
|
|
||||||
double value = src["equitherm"]["t_factor"].as<double>();
|
|
||||||
|
|
||||||
if (value >= 0 && value <= 10) {
|
|
||||||
dst.equitherm.t_factor = roundd(value, 3);
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// sensors
|
|
||||||
if (!src["sensors"]["outdoor"]["type"].isNull()) {
|
|
||||||
unsigned char value = src["sensors"]["outdoor"]["type"].as<unsigned char>();
|
|
||||||
|
|
||||||
if (value >= 0 && value <= 2) {
|
|
||||||
dst.sensors.outdoor.type = value;
|
|
||||||
|
|
||||||
if (dst.sensors.outdoor.type == 1) {
|
|
||||||
dst.emergency.useEquitherm = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["sensors"]["outdoor"]["pin"].isNull()) {
|
|
||||||
unsigned char value = src["sensors"]["outdoor"]["pin"].as<unsigned char>();
|
|
||||||
|
|
||||||
if (value >= 0 && value <= 50) {
|
|
||||||
dst.sensors.outdoor.pin = value;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["sensors"]["outdoor"]["offset"].isNull()) {
|
|
||||||
double value = src["sensors"]["outdoor"]["offset"].as<double>();
|
|
||||||
|
|
||||||
if (value >= -10 && value <= 10) {
|
|
||||||
dst.sensors.outdoor.offset = roundd(value, 2);
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["sensors"]["indoor"]["type"].isNull()) {
|
|
||||||
unsigned char value = src["sensors"]["indoor"]["type"].as<unsigned char>();
|
|
||||||
|
|
||||||
if (value >= 1 && value <= 3) {
|
|
||||||
dst.sensors.indoor.type = value;
|
|
||||||
|
|
||||||
if (dst.sensors.indoor.type == 1) {
|
|
||||||
dst.emergency.usePid = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["sensors"]["indoor"]["pin"].isNull()) {
|
|
||||||
unsigned char value = src["sensors"]["indoor"]["pin"].as<unsigned char>();
|
|
||||||
|
|
||||||
if (value >= 0 && value <= 50) {
|
|
||||||
dst.sensors.indoor.pin = value;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#if USE_BLE
|
|
||||||
if (!src["sensors"]["indoor"]["bleAddresss"].isNull()) {
|
|
||||||
String value = src["sensors"]["indoor"]["bleAddresss"].as<String>();
|
|
||||||
int tmp[6];
|
|
||||||
if(sscanf(value.c_str(), "%02x:%02x:%02x:%02x:%02x:%02x", &tmp[0], &tmp[1], &tmp[2], &tmp[3], &tmp[4], &tmp[5]) == 6) {
|
|
||||||
for(uint8_t i = 0; i < 6; i++) {
|
|
||||||
dst.sensors.indoor.bleAddresss[i] = (uint8_t) tmp[i];
|
|
||||||
}
|
|
||||||
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
if (!src["sensors"]["indoor"]["offset"].isNull()) {
|
|
||||||
double value = src["sensors"]["indoor"]["offset"].as<double>();
|
|
||||||
|
|
||||||
if (value >= -10 && value <= 10) {
|
|
||||||
dst.sensors.indoor.offset = roundd(value, 2);
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
if (!safe) {
|
|
||||||
// external pump
|
|
||||||
if (src["externalPump"]["use"].is<bool>()) {
|
|
||||||
dst.externalPump.use = src["externalPump"]["use"].as<bool>();
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["externalPump"]["pin"].isNull()) {
|
|
||||||
unsigned char value = src["externalPump"]["pin"].as<unsigned char>();
|
|
||||||
|
|
||||||
if (value >= 0 && value <= 50) {
|
|
||||||
dst.externalPump.pin = value;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["externalPump"]["postCirculationTime"].isNull()) {
|
|
||||||
unsigned short value = src["externalPump"]["postCirculationTime"].as<unsigned short>();
|
|
||||||
|
|
||||||
if (value >= 0 && value <= 120) {
|
|
||||||
dst.externalPump.postCirculationTime = value * 60;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["externalPump"]["antiStuckInterval"].isNull()) {
|
|
||||||
unsigned int value = src["externalPump"]["antiStuckInterval"].as<unsigned int>();
|
|
||||||
|
|
||||||
if (value >= 0 && value <= 366) {
|
|
||||||
dst.externalPump.antiStuckInterval = value * 86400;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["externalPump"]["antiStuckTime"].isNull()) {
|
|
||||||
unsigned short value = src["externalPump"]["antiStuckTime"].as<unsigned short>();
|
|
||||||
|
|
||||||
if (value >= 0 && value <= 20) {
|
|
||||||
dst.externalPump.antiStuckTime = value * 60;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return changed;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool safeJsonToSettings(const JsonVariantConst src, Settings& dst) {
|
|
||||||
return jsonToSettings(src, dst, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
void varsToJson(const Variables& src, JsonVariant dst) {
|
|
||||||
dst["tuning"]["enable"] = src.tuning.enable;
|
|
||||||
dst["tuning"]["regulator"] = src.tuning.regulator;
|
|
||||||
|
|
||||||
dst["states"]["otStatus"] = src.states.otStatus;
|
|
||||||
dst["states"]["emergency"] = src.states.emergency;
|
|
||||||
dst["states"]["heating"] = src.states.heating;
|
|
||||||
dst["states"]["dhw"] = src.states.dhw;
|
|
||||||
dst["states"]["flame"] = src.states.flame;
|
|
||||||
dst["states"]["fault"] = src.states.fault;
|
|
||||||
dst["states"]["diagnostic"] = src.states.diagnostic;
|
|
||||||
dst["states"]["externalPump"] = src.states.externalPump;
|
|
||||||
|
|
||||||
dst["sensors"]["modulation"] = roundd(src.sensors.modulation, 2);
|
|
||||||
dst["sensors"]["pressure"] = roundd(src.sensors.pressure, 2);
|
|
||||||
dst["sensors"]["dhwFlowRate"] = src.sensors.dhwFlowRate;
|
|
||||||
dst["sensors"]["faultCode"] = src.sensors.faultCode;
|
|
||||||
dst["sensors"]["rssi"] = src.sensors.rssi;
|
|
||||||
dst["sensors"]["uptime"] = millis() / 1000ul;
|
|
||||||
|
|
||||||
dst["temperatures"]["indoor"] = roundd(src.temperatures.indoor, 2);
|
|
||||||
dst["temperatures"]["outdoor"] = roundd(src.temperatures.outdoor, 2);
|
|
||||||
dst["temperatures"]["heating"] = roundd(src.temperatures.heating, 2);
|
|
||||||
dst["temperatures"]["dhw"] = roundd(src.temperatures.dhw, 2);
|
|
||||||
|
|
||||||
dst["parameters"]["heatingEnabled"] = src.parameters.heatingEnabled;
|
|
||||||
dst["parameters"]["heatingMinTemp"] = src.parameters.heatingMinTemp;
|
|
||||||
dst["parameters"]["heatingMaxTemp"] = src.parameters.heatingMaxTemp;
|
|
||||||
dst["parameters"]["heatingSetpoint"] = src.parameters.heatingSetpoint;
|
|
||||||
dst["parameters"]["dhwMinTemp"] = src.parameters.dhwMinTemp;
|
|
||||||
dst["parameters"]["dhwMaxTemp"] = src.parameters.dhwMaxTemp;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool jsonToVars(const JsonVariantConst src, Variables& dst) {
|
|
||||||
bool changed = false;
|
|
||||||
|
|
||||||
// tuning
|
|
||||||
if (src["tuning"]["enable"].is<bool>()) {
|
|
||||||
dst.tuning.enable = src["tuning"]["enable"].as<bool>();
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["tuning"]["regulator"].isNull()) {
|
|
||||||
unsigned char value = src["tuning"]["regulator"].as<unsigned char>();
|
|
||||||
|
|
||||||
if (value >= 0 && value <= 1) {
|
|
||||||
dst.tuning.regulator = value;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// temperatures
|
|
||||||
if (!src["temperatures"]["indoor"].isNull()) {
|
|
||||||
double value = src["temperatures"]["indoor"].as<double>();
|
|
||||||
|
|
||||||
if (settings.sensors.indoor.type == 1 && value > -100 && value < 100) {
|
|
||||||
dst.temperatures.indoor = roundd(value, 2);
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src["temperatures"]["outdoor"].isNull()) {
|
|
||||||
double value = src["temperatures"]["outdoor"].as<double>();
|
|
||||||
|
|
||||||
if (settings.sensors.outdoor.type == 1 && value > -100 && value < 100) {
|
|
||||||
dst.temperatures.outdoor = roundd(value, 2);
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// actions
|
|
||||||
if (src["actions"]["restart"].is<bool>() && src["actions"]["restart"].as<bool>()) {
|
|
||||||
dst.actions.restart = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (src["actions"]["resetFault"].is<bool>() && src["actions"]["resetFault"].as<bool>()) {
|
|
||||||
dst.actions.resetFault = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (src["actions"]["resetDiagnostic"].is<bool>() && src["actions"]["resetDiagnostic"].as<bool>()) {
|
|
||||||
dst.actions.resetDiagnostic = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return changed;
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
<?xml version="1.0" standalone="no"?>
|
||||||
|
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" >
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg">
|
||||||
|
<defs>
|
||||||
|
<font id="iconly" horiz-adv-x="1024">
|
||||||
|
<font-face font-family="iconly"
|
||||||
|
units-per-em="1024" ascent="896"
|
||||||
|
descent="128" />
|
||||||
|
<missing-glyph horiz-adv-x="0" />
|
||||||
|
<glyph glyph-name="plus"
|
||||||
|
unicode=""
|
||||||
|
horiz-adv-x="895.5537099041368" d="M831.585587768127 479.8473854289214H543.729038156083V767.7039350409655C543.729038156083 803.0263324829433 515.0833134620511 831.6720571769752 479.7609160200732 831.6720571769752H415.7927938840635C380.4703964420856 831.6720571769752 351.8246717480538 803.0263324829433 351.8246717480538 767.7039350409655V479.8473854289214H63.9681221360098C28.6457246940319 479.8473854289214 0 451.2016607348895 0 415.8792632929117V351.9111411569019C0 316.588743714924 28.6457246940319 287.9430190208922 63.9681221360098 287.9430190208922H351.8246717480538V0.0864694088482C351.8246717480538 -35.2359280331298 380.4703964420857 -63.8816527271616 415.7927938840635 -63.8816527271616H479.7609160200732C515.0833134620511 -63.8816527271616 543.729038156083 -35.2359280331298 543.729038156083 0.0864694088482V287.9430190208922H831.585587768127C866.9079852101049 287.9430190208922 895.5537099041368 316.588743714924 895.5537099041368 351.9111411569019V415.8792632929117C895.5537099041368 451.2016607348896 866.9079852101049 479.8473854289214 831.585587768127 479.8473854289214z" />
|
||||||
|
<glyph glyph-name="plus-1"
|
||||||
|
unicode="plus"
|
||||||
|
horiz-adv-x="895.5537099041368" d="M831.585587768127 479.8473854289214H543.729038156083V767.7039350409655C543.729038156083 803.0263324829433 515.0833134620511 831.6720571769752 479.7609160200732 831.6720571769752H415.7927938840635C380.4703964420856 831.6720571769752 351.8246717480538 803.0263324829433 351.8246717480538 767.7039350409655V479.8473854289214H63.9681221360098C28.6457246940319 479.8473854289214 0 451.2016607348895 0 415.8792632929117V351.9111411569019C0 316.588743714924 28.6457246940319 287.9430190208922 63.9681221360098 287.9430190208922H351.8246717480538V0.0864694088482C351.8246717480538 -35.2359280331298 380.4703964420857 -63.8816527271616 415.7927938840635 -63.8816527271616H479.7609160200732C515.0833134620511 -63.8816527271616 543.729038156083 -35.2359280331298 543.729038156083 0.0864694088482V287.9430190208922H831.585587768127C866.9079852101049 287.9430190208922 895.5537099041368 316.588743714924 895.5537099041368 351.9111411569019V415.8792632929117C895.5537099041368 451.2016607348896 866.9079852101049 479.8473854289214 831.585587768127 479.8473854289214z" />
|
||||||
|
<glyph glyph-name="minus"
|
||||||
|
unicode=""
|
||||||
|
horiz-adv-x="893.7641930109211" d="M829.9238935101409 480.448527979227H63.8402995007801C28.5884841201931 480.4465329698676 0 451.8580488496745 0 416.6062334690875V352.7659339683073C0 317.5141185877203 28.5884841201931 288.9256344675273 63.8402995007801 288.9256344675273H829.9238935101409C865.1757088907281 288.9256344675273 893.7641930109211 317.5141185877203 893.7641930109211 352.7659339683073V416.6062334690875C893.7641930109211 451.8580488496744 865.1757088907281 480.4465329698675 829.9238935101409 480.4465329698675z" />
|
||||||
|
<glyph glyph-name="minus-1"
|
||||||
|
unicode="minus"
|
||||||
|
horiz-adv-x="893.7641930109211" d="M829.9238935101409 480.448527979227H63.8402995007801C28.5884841201931 480.4465329698676 0 451.8580488496745 0 416.6062334690875V352.7659339683073C0 317.5141185877203 28.5884841201931 288.9256344675273 63.8402995007801 288.9256344675273H829.9238935101409C865.1757088907281 288.9256344675273 893.7641930109211 317.5141185877203 893.7641930109211 352.7659339683073V416.6062334690875C893.7641930109211 451.8580488496744 865.1757088907281 480.4465329698675 829.9238935101409 480.4465329698675z" />
|
||||||
|
<glyph glyph-name="unlocked"
|
||||||
|
unicode=""
|
||||||
|
horiz-adv-x="1024" d="M426.667 341.333C473.6 341.333 512 303.36 512 256S474.027 170.667 426.6670000000001 170.667S341.3330000000001 208.64 341.3330000000001 256S379.733 341.333 426.6670000000001 341.333M768 853.333C650.24 853.333 554.667 757.76 554.667 640V554.667H170.667C123.733 554.667 85.333 516.267 85.333 469.333V42.667C85.333 -4.2669999999999 123.733 -42.6669999999999 170.667 -42.6669999999999H682.667C729.6 -42.6669999999999 768 -4.2669999999999 768 42.6670000000001V469.333C768 516.267 729.6 554.667 682.667 554.667H640V640C640 710.827 697.173 768 768 768S896 710.827 896 640V554.667H981.333V640C981.333 757.76 885.76 853.333 768 853.333M682.667 469.333V42.6669999999999H170.667V469.333H682.667z" />
|
||||||
|
<glyph glyph-name="unlocked-1"
|
||||||
|
unicode="unlocked"
|
||||||
|
horiz-adv-x="1024" d="M426.667 341.333C473.6 341.333 512 303.36 512 256S474.027 170.667 426.6670000000001 170.667S341.3330000000001 208.64 341.3330000000001 256S379.733 341.333 426.6670000000001 341.333M768 853.333C650.24 853.333 554.667 757.76 554.667 640V554.667H170.667C123.733 554.667 85.333 516.267 85.333 469.333V42.667C85.333 -4.2669999999999 123.733 -42.6669999999999 170.667 -42.6669999999999H682.667C729.6 -42.6669999999999 768 -4.2669999999999 768 42.6670000000001V469.333C768 516.267 729.6 554.667 682.667 554.667H640V640C640 710.827 697.173 768 768 768S896 710.827 896 640V554.667H981.333V640C981.333 757.76 885.76 853.333 768 853.333M682.667 469.333V42.6669999999999H170.667V469.333H682.667z" />
|
||||||
|
<glyph glyph-name="locked"
|
||||||
|
unicode=""
|
||||||
|
horiz-adv-x="1024" d="M512 170.667C464.64 170.667 426.6670000000001 209.067 426.6670000000001 256C426.6670000000001 303.36 464.64 341.333 512 341.333A85.333 85.333 0 0 0 597.333 256A85.333 85.333 0 0 0 512 170.667M768 42.667V469.333H256V42.667H768M768 554.667A85.333 85.333 0 0 0 853.333 469.333V42.667A85.333 85.333 0 0 0 768 -42.667H256C208.64 -42.667 170.667 -4.2670000000001 170.667 42.6669999999999V469.333C170.667 516.693 208.64 554.667 256 554.667H298.6670000000001V640A213.333 213.333 0 0 0 512 853.333A213.333 213.333 0 0 0 725.333 640V554.667H768M512 768A128 128 0 0 1 384 640V554.667H640V640A128 128 0 0 1 512 768z" />
|
||||||
|
<glyph glyph-name="locked-1"
|
||||||
|
unicode="locked"
|
||||||
|
horiz-adv-x="1024" d="M512 170.667C464.64 170.667 426.6670000000001 209.067 426.6670000000001 256C426.6670000000001 303.36 464.64 341.333 512 341.333A85.333 85.333 0 0 0 597.333 256A85.333 85.333 0 0 0 512 170.667M768 42.667V469.333H256V42.667H768M768 554.667A85.333 85.333 0 0 0 853.333 469.333V42.667A85.333 85.333 0 0 0 768 -42.667H256C208.64 -42.667 170.667 -4.2670000000001 170.667 42.6669999999999V469.333C170.667 516.693 208.64 554.667 256 554.667H298.6670000000001V640A213.333 213.333 0 0 0 512 853.333A213.333 213.333 0 0 0 725.333 640V554.667H768M512 768A128 128 0 0 1 384 640V554.667H640V640A128 128 0 0 1 512 768z" />
|
||||||
|
<glyph glyph-name="wifi-strength-1"
|
||||||
|
unicode=""
|
||||||
|
horiz-adv-x="1022.9733303792667" d="M511.4866651896334 768.1283337025917C332.0397604864727 768.1283337025917 157.7087214326013 708.0286505428097 16.1967447318741 597.6324456402496C187.9713494571903 381.9559014844185 336.3024823621839 198.2472739029395 511.4866651896334 -20.4132754656288C685.3921313541088 196.1154134663874 862.7071756207173 416.9078232715078 1008.0553023103668 597.6324456402497C866.1177527202434 708.0286505428097 691.3591427821901 768.1283337025917 511.4866651896334 768.1283337025917M511.4866651896334 682.8808891701171C642.3423366997788 682.8808891701171 771.0661477733722 646.2236788332648 882.7410693389065 578.4516956956384L665.3592366333123 307.3637631451326C618.0467201032712 329.95509018927 564.7661931477559 341.8891130454328 511.4866651896333 341.8891130454328C458.2071372315108 341.8891130454328 404.9266102759954 329.9550901892699 357.6140937459543 307.7903350319215L139.3801162641751 578.8782675824273C251.9071826058945 646.6502507200537 380.6309936794878 682.8808891701171 511.4866651896334 682.8808891701171z" />
|
||||||
|
<glyph glyph-name="wifi-strength-1-1"
|
||||||
|
unicode="wifi_strength_1"
|
||||||
|
horiz-adv-x="1022.9733303792667" d="M511.4866651896334 768.1283337025917C332.0397604864727 768.1283337025917 157.7087214326013 708.0286505428097 16.1967447318741 597.6324456402496C187.9713494571903 381.9559014844185 336.3024823621839 198.2472739029395 511.4866651896334 -20.4132754656288C685.3921313541088 196.1154134663874 862.7071756207173 416.9078232715078 1008.0553023103668 597.6324456402497C866.1177527202434 708.0286505428097 691.3591427821901 768.1283337025917 511.4866651896334 768.1283337025917M511.4866651896334 682.8808891701171C642.3423366997788 682.8808891701171 771.0661477733722 646.2236788332648 882.7410693389065 578.4516956956384L665.3592366333123 307.3637631451326C618.0467201032712 329.95509018927 564.7661931477559 341.8891130454328 511.4866651896333 341.8891130454328C458.2071372315108 341.8891130454328 404.9266102759954 329.9550901892699 357.6140937459543 307.7903350319215L139.3801162641751 578.8782675824273C251.9071826058945 646.6502507200537 380.6309936794878 682.8808891701171 511.4866651896334 682.8808891701171z" />
|
||||||
|
<glyph glyph-name="wifi-strength-0"
|
||||||
|
unicode=""
|
||||||
|
horiz-adv-x="1022.9733303792667" d="M511.4866651896334 768.1283337025917C332.4663323732617 768.1283337025917 157.7087214326013 708.4552224295987 17.0498885054521 597.6324456402496C183.283054692083 393.0377795643962 349.5162208787138 184.1813906102245 511.4866651896334 -20.4132754656289C609.5212763518488 103.1956689560682 711.8186093897755 226.8046133777654 809.8542195493837 350.4145567968553V486.8106678482933L511.4866651896334 115.9828355858092L140.6588329271492 580.5835561321903C251.4806107191054 648.7811121592129 379.3522770165138 682.8808891701171 511.4866651896334 682.8808891701171S771.4927196601614 644.5193892808945 882.3144974521176 580.5835561321903L865.2646089466655 555.0092228727087H976.0873857360147C988.8745523657554 567.7963895024495 997.398997119785 584.8452790105086 1010.186163749526 597.6324456402496C865.2646089466655 708.4552224295987 690.5069980060051 768.1283337025917 511.4866651896334 768.1283337025917M895.1016640818584 469.7607793428413V214.0174467480247H980.349108614333V469.7607793428413M895.1016640818584 128.77000221555V43.5225576830754H980.349108614333V128.77000221555" />
|
||||||
|
<glyph glyph-name="wifi-strength-0-1"
|
||||||
|
unicode="wifi_strength_0"
|
||||||
|
horiz-adv-x="1022.9733303792667" d="M511.4866651896334 768.1283337025917C332.4663323732617 768.1283337025917 157.7087214326013 708.4552224295987 17.0498885054521 597.6324456402496C183.283054692083 393.0377795643962 349.5162208787138 184.1813906102245 511.4866651896334 -20.4132754656289C609.5212763518488 103.1956689560682 711.8186093897755 226.8046133777654 809.8542195493837 350.4145567968553V486.8106678482933L511.4866651896334 115.9828355858092L140.6588329271492 580.5835561321903C251.4806107191054 648.7811121592129 379.3522770165138 682.8808891701171 511.4866651896334 682.8808891701171S771.4927196601614 644.5193892808945 882.3144974521176 580.5835561321903L865.2646089466655 555.0092228727087H976.0873857360147C988.8745523657554 567.7963895024495 997.398997119785 584.8452790105086 1010.186163749526 597.6324456402496C865.2646089466655 708.4552224295987 690.5069980060051 768.1283337025917 511.4866651896334 768.1283337025917M895.1016640818584 469.7607793428413V214.0174467480247H980.349108614333V469.7607793428413M895.1016640818584 128.77000221555V43.5225576830754H980.349108614333V128.77000221555" />
|
||||||
|
<glyph glyph-name="wifi-strength-2"
|
||||||
|
unicode=""
|
||||||
|
horiz-adv-x="1022.9733303792667" d="M511.4866651896334 768.1283337025917C332.0397604864727 768.1283337025917 157.7087214326013 708.0286505428097 16.1967447318741 597.6324456402496C187.9713494571903 381.9559014844185 336.3024823621839 198.2472739029395 511.4866651896334 -20.4132754656288C685.3921313541088 196.1154134663874 862.7071756207173 416.9078232715078 1008.0553023103668 597.6324456402497C866.1177527202434 708.0286505428097 691.3591427821901 768.1283337025917 511.4866651896334 768.1283337025917M511.4866651896334 682.8808891701171C642.3423366997788 682.8808891701171 771.0661477733722 646.2236788332648 882.7410693389065 578.4516956956384L745.9183864006797 408.8089514068742C693.0644313319532 438.2194346552781 612.505281564586 469.7607793428413 511.4866651896334 469.7607793428413C410.0414769278917 469.7607793428413 329.9088990473136 437.7928627684892 277.0549439785871 408.8089514068743L139.3801162641751 578.8782675824273C251.9071826058945 646.6502507200537 380.6309936794878 682.8808891701171 511.4866651896334 682.8808891701171z" />
|
||||||
|
<glyph glyph-name="wifi-strength-2-1"
|
||||||
|
unicode="wifi_strength_2"
|
||||||
|
horiz-adv-x="1022.9733303792667" d="M511.4866651896334 768.1283337025917C332.0397604864727 768.1283337025917 157.7087214326013 708.0286505428097 16.1967447318741 597.6324456402496C187.9713494571903 381.9559014844185 336.3024823621839 198.2472739029395 511.4866651896334 -20.4132754656288C685.3921313541088 196.1154134663874 862.7071756207173 416.9078232715078 1008.0553023103668 597.6324456402497C866.1177527202434 708.0286505428097 691.3591427821901 768.1283337025917 511.4866651896334 768.1283337025917M511.4866651896334 682.8808891701171C642.3423366997788 682.8808891701171 771.0661477733722 646.2236788332648 882.7410693389065 578.4516956956384L745.9183864006797 408.8089514068742C693.0644313319532 438.2194346552781 612.505281564586 469.7607793428413 511.4866651896334 469.7607793428413C410.0414769278917 469.7607793428413 329.9088990473136 437.7928627684892 277.0549439785871 408.8089514068743L139.3801162641751 578.8782675824273C251.9071826058945 646.6502507200537 380.6309936794878 682.8808891701171 511.4866651896334 682.8808891701171z" />
|
||||||
|
<glyph glyph-name="error"
|
||||||
|
unicode=""
|
||||||
|
horiz-adv-x="1024" d="M512 810.667C747.605 810.667 938.667 619.605 938.667 384C938.667 148.395 747.6049999999999 -42.6669999999999 511.9999999999999 -42.6669999999999C276.395 -42.6669999999999 85.333 148.3950000000001 85.333 384.0000000000001C85.333 619.605 276.395 810.667 512 810.667zM512 725.333C323.7970000000001 725.333 170.667 572.203 170.667 384C170.667 195.797 323.797 42.6669999999999 512 42.6669999999999C700.203 42.6669999999999 853.3330000000001 195.7969999999999 853.3330000000001 384C853.3330000000001 572.203 700.2030000000001 725.3330000000001 512 725.3330000000001zM609.835 542.165L670.1650000000001 481.835L572.33 384L670.1650000000001 286.165L609.835 225.8349999999999L512 323.67L414.165 225.8349999999999L353.8350000000001 286.165L451.67 384L353.8350000000001 481.835L414.165 542.165L512 444.33L609.835 542.165z" />
|
||||||
|
<glyph glyph-name="error-1"
|
||||||
|
unicode="error"
|
||||||
|
horiz-adv-x="1024" d="M512 810.667C747.605 810.667 938.667 619.605 938.667 384C938.667 148.395 747.6049999999999 -42.6669999999999 511.9999999999999 -42.6669999999999C276.395 -42.6669999999999 85.333 148.3950000000001 85.333 384.0000000000001C85.333 619.605 276.395 810.667 512 810.667zM512 725.333C323.7970000000001 725.333 170.667 572.203 170.667 384C170.667 195.797 323.797 42.6669999999999 512 42.6669999999999C700.203 42.6669999999999 853.3330000000001 195.7969999999999 853.3330000000001 384C853.3330000000001 572.203 700.2030000000001 725.3330000000001 512 725.3330000000001zM609.835 542.165L670.1650000000001 481.835L572.33 384L670.1650000000001 286.165L609.835 225.8349999999999L512 323.67L414.165 225.8349999999999L353.8350000000001 286.165L451.67 384L353.8350000000001 481.835L414.165 542.165L512 444.33L609.835 542.165z" />
|
||||||
|
<glyph glyph-name="wifi-strength-3"
|
||||||
|
unicode=""
|
||||||
|
horiz-adv-x="1022.9733303792667" d="M511.4866651896334 768.1283337025917C332.0397604864727 768.1283337025917 157.7087214326013 708.0286505428097 16.1967447318741 597.6324456402496C187.9713494571903 381.9559014844185 336.3024823621839 198.2472739029395 511.4866651896334 -20.4132754656288C685.3921313541088 196.1154134663874 862.7071756207173 416.9078232715078 1008.0553023103668 597.6324456402497C866.1177527202434 708.0286505428097 691.3591427821901 768.1283337025917 511.4866651896334 768.1283337025917M511.4866651896334 682.8808891701171C642.3423366997788 682.8808891701171 771.0661477733722 646.2236788332648 882.7410693389065 578.4516956956384L800.0500591349871 474.8756459947375C735.688653096887 512.385001107775 634.2434648351453 555.0092228727087 511.4866651896334 555.0092228727087C383.614998892225 555.0092228727087 284.7272439564316 512.385001107775 222.0701274707015 476.5809345445006L139.3801162641751 578.8782675824273C251.9071826058945 646.6502507200537 380.6309936794878 682.8808891701171 511.4866651896334 682.8808891701171z" />
|
||||||
|
<glyph glyph-name="wifi-strength-3-1"
|
||||||
|
unicode="wifi_strength_3"
|
||||||
|
horiz-adv-x="1022.9733303792667" d="M511.4866651896334 768.1283337025917C332.0397604864727 768.1283337025917 157.7087214326013 708.0286505428097 16.1967447318741 597.6324456402496C187.9713494571903 381.9559014844185 336.3024823621839 198.2472739029395 511.4866651896334 -20.4132754656288C685.3921313541088 196.1154134663874 862.7071756207173 416.9078232715078 1008.0553023103668 597.6324456402497C866.1177527202434 708.0286505428097 691.3591427821901 768.1283337025917 511.4866651896334 768.1283337025917M511.4866651896334 682.8808891701171C642.3423366997788 682.8808891701171 771.0661477733722 646.2236788332648 882.7410693389065 578.4516956956384L800.0500591349871 474.8756459947375C735.688653096887 512.385001107775 634.2434648351453 555.0092228727087 511.4866651896334 555.0092228727087C383.614998892225 555.0092228727087 284.7272439564316 512.385001107775 222.0701274707015 476.5809345445006L139.3801162641751 578.8782675824273C251.9071826058945 646.6502507200537 380.6309936794878 682.8808891701171 511.4866651896334 682.8808891701171z" />
|
||||||
|
<glyph glyph-name="down"
|
||||||
|
unicode=""
|
||||||
|
horiz-adv-x="893.7641930109211" d="M824.1383663678829 451.520892267936L868.427574146549 407.2306869845902C887.180662124903 388.477599006236 887.180662124903 358.1514617340061 868.427574146549 339.5978746915919L480.79725561525 -48.2279547569284C462.0441676368958 -66.9810427352825 431.7200253740253 -66.9810427352825 413.1664383316111 -48.2279547569284L25.3366188643721 339.6018647103107C6.5835308860179 358.3549526886648 6.5835308860179 388.6790949515354 25.3366188643721 407.2326819939496L69.6258266430383 451.5218897726157C88.5784155573323 470.4744786869098 119.5010606280227 470.07547681503 138.0546476704369 450.723886028856L367.0817221294855 210.325258221231V783.690948112612C367.0817221294855 810.2245725926238 388.4283222750588 831.5711727381971 414.9619467550705 831.5711727381971H478.8022462558506C505.3358707358623 831.5711727381971 526.6824708814356 810.2245725926238 526.6824708814356 783.690948112612V210.325258221231L755.7095453404842 450.723886028856C774.2631323828984 470.2749777509699 805.1857774535888 470.6739796228497 824.1383663678829 451.5218897726157z" />
|
||||||
|
<glyph glyph-name="down-1"
|
||||||
|
unicode="down"
|
||||||
|
horiz-adv-x="893.7641930109211" d="M824.1383663678829 451.520892267936L868.427574146549 407.2306869845902C887.180662124903 388.477599006236 887.180662124903 358.1514617340061 868.427574146549 339.5978746915919L480.79725561525 -48.2279547569284C462.0441676368958 -66.9810427352825 431.7200253740253 -66.9810427352825 413.1664383316111 -48.2279547569284L25.3366188643721 339.6018647103107C6.5835308860179 358.3549526886648 6.5835308860179 388.6790949515354 25.3366188643721 407.2326819939496L69.6258266430383 451.5218897726157C88.5784155573323 470.4744786869098 119.5010606280227 470.07547681503 138.0546476704369 450.723886028856L367.0817221294855 210.325258221231V783.690948112612C367.0817221294855 810.2245725926238 388.4283222750588 831.5711727381971 414.9619467550705 831.5711727381971H478.8022462558506C505.3358707358623 831.5711727381971 526.6824708814356 810.2245725926238 526.6824708814356 783.690948112612V210.325258221231L755.7095453404842 450.723886028856C774.2631323828984 470.2749777509699 805.1857774535888 470.6739796228497 824.1383663678829 451.5218897726157z" />
|
||||||
|
<glyph glyph-name="wifi-strength-4"
|
||||||
|
unicode=""
|
||||||
|
horiz-adv-x="1022.9733303792667" d="M511.4866651896334 768.1283337025917C332.0397604864727 768.1283337025917 157.7087214326013 708.0286505428097 16.1967447318741 597.6324456402496C187.9713494571903 381.9559014844185 336.3024823621839 198.2472739029395 511.4866651896334 -20.4132754656288C685.3921313541088 196.1154134663874 862.7071756207173 416.9078232715078 1008.0553023103668 597.6324456402497C866.1177527202434 708.0286505428097 691.3591427821901 768.1283337025917 511.4866651896334 768.1283337025917z" />
|
||||||
|
<glyph glyph-name="wifi-strength-4-1"
|
||||||
|
unicode="wifi_strength_4"
|
||||||
|
horiz-adv-x="1022.9733303792667" d="M511.4866651896334 768.1283337025917C332.0397604864727 768.1283337025917 157.7087214326013 708.0286505428097 16.1967447318741 597.6324456402496C187.9713494571903 381.9559014844185 336.3024823621839 198.2472739029395 511.4866651896334 -20.4132754656288C685.3921313541088 196.1154134663874 862.7071756207173 416.9078232715078 1008.0553023103668 597.6324456402497C866.1177527202434 708.0286505428097 691.3591427821901 768.1283337025917 511.4866651896334 768.1283337025917z" />
|
||||||
|
<glyph glyph-name="success"
|
||||||
|
unicode=""
|
||||||
|
horiz-adv-x="1024" d="M512 810.667C276.36 810.667 85.333 619.64 85.333 384C85.333 148.36 276.3590000000001 -42.6669999999999 512 -42.6669999999999C747.64 -42.6669999999999 938.667 148.3590000000002 938.667 384.0000000000001C938.667 619.64 747.64 810.667 512 810.667zM512 42.667C323.79 42.667 170.667 195.789 170.667 384.0000000000001C170.667 572.21 323.789 725.3330000000001 512 725.3330000000001C700.21 725.3330000000001 853.3330000000001 572.211 853.3330000000001 384.0000000000001C853.3330000000001 195.7900000000001 700.211 42.667 512 42.667zM672.672 536.437L733.005 476.104L469.333 211.328L311.167 369.495L371.5 429.828L469.333 331.995L672.673 536.438z" />
|
||||||
|
<glyph glyph-name="success-1"
|
||||||
|
unicode="success"
|
||||||
|
horiz-adv-x="1024" d="M512 810.667C276.36 810.667 85.333 619.64 85.333 384C85.333 148.36 276.3590000000001 -42.6669999999999 512 -42.6669999999999C747.64 -42.6669999999999 938.667 148.3590000000002 938.667 384.0000000000001C938.667 619.64 747.64 810.667 512 810.667zM512 42.667C323.79 42.667 170.667 195.789 170.667 384.0000000000001C170.667 572.21 323.789 725.3330000000001 512 725.3330000000001C700.21 725.3330000000001 853.3330000000001 572.211 853.3330000000001 384.0000000000001C853.3330000000001 195.7900000000001 700.211 42.667 512 42.667zM672.672 536.437L733.005 476.104L469.333 211.328L311.167 369.495L371.5 429.828L469.333 331.995L672.673 536.438z" />
|
||||||
|
<glyph glyph-name="up"
|
||||||
|
unicode=""
|
||||||
|
horiz-adv-x="893.7641930109211" d="M69.6258266430383 317.8562626928574L25.3366188643721 362.1454704715236C6.5835308860179 380.8985584498777 6.5835308860179 411.2227007127483 25.3366188643721 429.7762877551625L412.9669373956711 817.6021172036826C431.7200253740253 836.3552051820368 462.0441676368958 836.3552051820368 480.59775467931 817.6021172036826L868.2280732106092 429.9717986723836C886.9811611889633 411.2187106940295 886.9811611889633 380.894568431159 868.2280732106092 362.3409813887447L823.938865431943 318.0517736100786C804.9862765176489 299.0991846957845 774.0636314469585 299.4981865676644 755.5100444045443 318.8497773538383L526.6824708814356 559.0528942442421V-14.3127956471388C526.6824708814356 -40.8464201271506 505.3358707358623 -62.1930202727239 478.8022462558506 -62.1930202727239H414.9619467550705C388.4283222750588 -62.1930202727239 367.0817221294855 -40.8464201271506 367.0817221294855 -14.3127956471388V559.0528942442422L138.0546476704369 318.6542664366173C119.5010606280227 299.1031747145034 88.5784155573324 298.7041728426234 69.6258266430383 317.8562626928575z" />
|
||||||
|
<glyph glyph-name="up-1"
|
||||||
|
unicode="up"
|
||||||
|
horiz-adv-x="893.7641930109211" d="M69.6258266430383 317.8562626928574L25.3366188643721 362.1454704715236C6.5835308860179 380.8985584498777 6.5835308860179 411.2227007127483 25.3366188643721 429.7762877551625L412.9669373956711 817.6021172036826C431.7200253740253 836.3552051820368 462.0441676368958 836.3552051820368 480.59775467931 817.6021172036826L868.2280732106092 429.9717986723836C886.9811611889633 411.2187106940295 886.9811611889633 380.894568431159 868.2280732106092 362.3409813887447L823.938865431943 318.0517736100786C804.9862765176489 299.0991846957845 774.0636314469585 299.4981865676644 755.5100444045443 318.8497773538383L526.6824708814356 559.0528942442421V-14.3127956471388C526.6824708814356 -40.8464201271506 505.3358707358623 -62.1930202727239 478.8022462558506 -62.1930202727239H414.9619467550705C388.4283222750588 -62.1930202727239 367.0817221294855 -40.8464201271506 367.0817221294855 -14.3127956471388V559.0528942442422L138.0546476704369 318.6542664366173C119.5010606280227 299.1031747145034 88.5784155573324 298.7041728426234 69.6258266430383 317.8562626928575z" />
|
||||||
|
<glyph glyph-name="alarm"
|
||||||
|
unicode=""
|
||||||
|
horiz-adv-x="1024" d="M512 810.667C747.22 810.667 938.667 619.22 938.667 384C938.667 148.78 747.2199999999999 -42.6669999999999 511.9999999999999 -42.6669999999999C276.78 -42.667 85.333 148.78 85.333 384C85.333 619.22 276.78 810.667 512 810.667zM512 725.333C323.082 725.333 170.667 572.918 170.667 384C170.667 195.082 323.082 42.6669999999999 512 42.6669999999999C700.918 42.6669999999999 853.3330000000001 195.0819999999999 853.3330000000001 384C853.3330000000001 572.918 700.9180000000001 725.3330000000001 512 725.3330000000001zM512 266.581C542.476 266.581 565.333 244.054 565.333 213.3340000000001S542.476 160.085 512 160.085C480.83 160.085 458.667 182.6130000000001 458.667 214.015C458.667 244.053 481.524 266.581 512 266.581zM554.667 640V341.3330000000001H469.333V640H554.667z" />
|
||||||
|
<glyph glyph-name="alarm-1"
|
||||||
|
unicode="alarm"
|
||||||
|
horiz-adv-x="1024" d="M512 810.667C747.22 810.667 938.667 619.22 938.667 384C938.667 148.78 747.2199999999999 -42.6669999999999 511.9999999999999 -42.6669999999999C276.78 -42.667 85.333 148.78 85.333 384C85.333 619.22 276.78 810.667 512 810.667zM512 725.333C323.082 725.333 170.667 572.918 170.667 384C170.667 195.082 323.082 42.6669999999999 512 42.6669999999999C700.918 42.6669999999999 853.3330000000001 195.0819999999999 853.3330000000001 384C853.3330000000001 572.918 700.9180000000001 725.3330000000001 512 725.3330000000001zM512 266.581C542.476 266.581 565.333 244.054 565.333 213.3340000000001S542.476 160.085 512 160.085C480.83 160.085 458.667 182.6130000000001 458.667 214.015C458.667 244.053 481.524 266.581 512 266.581zM554.667 640V341.3330000000001H469.333V640H554.667z" />
|
||||||
|
</font>
|
||||||
|
</defs>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 27 KiB |