Compare commits
303
Commits
repeater-v1.19.0
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8f0f6859d3 | ||
|
|
1bcb850c99 | ||
|
|
36c6632aaa | ||
|
|
a7a39126ac | ||
|
|
6d114cd410 | ||
|
|
4754276221 | ||
|
|
7e911aa17d | ||
|
|
8b8e618da7 | ||
|
|
e73ed273ed | ||
|
|
81df23943d | ||
|
|
9ab7631ebf | ||
|
|
ad63c6b90a | ||
|
|
ffe461891f | ||
|
|
c418c737cd | ||
|
|
5b86800ec0 | ||
|
|
012ec9df28 | ||
|
|
9802093d38 | ||
|
|
139e767eb8 | ||
|
|
aa7b181944 | ||
|
|
41c7697e6d | ||
|
|
544b0f4ce3 | ||
|
|
764e7ee59b | ||
|
|
c70204bf74 | ||
|
|
65d31f6082 | ||
|
|
a8226f12e3 | ||
|
|
012f2d25fe | ||
|
|
a66788cc3d | ||
|
|
82e8c42817 | ||
|
|
8df070aa16 | ||
|
|
b522229ca8 | ||
|
|
f34284866e | ||
|
|
0d1dd7a872 | ||
|
|
a3daa9fb30 | ||
|
|
ca5e99418b | ||
|
|
d5cbb5ef00 | ||
|
|
8eea3e536c | ||
|
|
1c5adf7edb | ||
|
|
eb1df43906 | ||
|
|
9fc9072c6e | ||
|
|
fc56f3d2d3 | ||
|
|
086175d80f | ||
|
|
f3eae0582c | ||
|
|
739fdcceca | ||
|
|
35c1a05378 | ||
|
|
49733f38cb | ||
|
|
5c586e6ce4 | ||
|
|
0b17cd799a | ||
|
|
421cbbd52a | ||
|
|
34ba29f778 | ||
|
|
b2de11ea8a | ||
|
|
2ff8d96422 | ||
|
|
1cf1bbf6e8 | ||
|
|
302eeeca9b | ||
|
|
d74a2124af | ||
|
|
b8c5f6372d | ||
|
|
a508f75f43 | ||
|
|
2722c75865 | ||
|
|
f189855457 | ||
|
|
76109b168f | ||
|
|
8ee7f6a283 | ||
|
|
41457ce868 | ||
|
|
40565ed088 | ||
|
|
9e49a31657 | ||
|
|
3204e3733e | ||
|
|
045d92b6f4 | ||
|
|
e1886b25ae | ||
|
|
e20eab44c6 | ||
|
|
0d16dd541c | ||
|
|
4dbffda57b | ||
|
|
24c4c0066a | ||
|
|
9011ac11f6 | ||
|
|
ea2d4a0bfa | ||
|
|
784ca48d99 | ||
|
|
5fa4e7473b | ||
|
|
7465cfdcab | ||
|
|
02beb0b1c2 | ||
|
|
56d1520723 | ||
|
|
2292db937a | ||
|
|
160d487e69 | ||
|
|
fab08842e3 | ||
|
|
c47cbda5ea | ||
|
|
76b7c5713b | ||
|
|
7cb9b4cffd | ||
|
|
353ec9a2ec | ||
|
|
321cbf52ba | ||
|
|
2fbd374a29 | ||
|
|
25dd6d07ac | ||
|
|
61a728a49c | ||
|
|
97201e8374 | ||
|
|
ce8f91075a | ||
|
|
b866b95ccb | ||
|
|
a39621f928 | ||
|
|
5fce11db3f | ||
|
|
c6d05a49ff | ||
|
|
f2b927d205 | ||
|
|
32ad8b7eda | ||
|
|
c6a2e7befe | ||
|
|
d2cf84917f | ||
|
|
31f30b1100 | ||
|
|
76ea6fa951 | ||
|
|
96757c4aab | ||
|
|
af4c140971 | ||
|
|
8215085037 | ||
|
|
7803bc757f | ||
|
|
b60dcf381c | ||
|
|
d993a96f38 | ||
|
|
f0c65615b4 | ||
|
|
7dbce13a2b | ||
|
|
c938da61f4 | ||
|
|
0fdfc83428 | ||
|
|
ffc19ec8ba | ||
|
|
54e21e3da1 | ||
|
|
ff3cc3d8ef | ||
|
|
48f7032043 | ||
|
|
f8ba4ed070 | ||
|
|
47deb89624 | ||
|
|
62a244bd09 | ||
|
|
4ee2692e6e | ||
|
|
c9167bf453 | ||
|
|
c7df82d9d1 | ||
|
|
f82b0862a4 | ||
|
|
cd2314b54c | ||
|
|
d8be61a0fe | ||
|
|
fe65850d89 | ||
|
|
776ca25969 | ||
|
|
e2bc4a94a3 | ||
|
|
032407adbf | ||
|
|
514ee38dd5 | ||
|
|
5ac3d61825 | ||
|
|
75a680566c | ||
|
|
af62deb370 | ||
|
|
7807be68d0 | ||
|
|
3c04ae77a4 | ||
|
|
be08b55af0 | ||
|
|
503e984534 | ||
|
|
c19b088bcc | ||
|
|
49b5cc0b09 | ||
|
|
e13d1983ce | ||
|
|
6c06bd1647 | ||
|
|
b564dfd198 | ||
|
|
a72b6a3b8f | ||
|
|
d4a7659ccc | ||
|
|
27e6a5d6fd | ||
|
|
af34cf95dc | ||
|
|
2ba62d779e | ||
|
|
a542baf435 | ||
|
|
9de0065b7a | ||
|
|
a351ce4132 | ||
|
|
2682ae607e | ||
|
|
95164f3a9b | ||
|
|
75bd4fa8fa | ||
|
|
5f8d3a4c9e | ||
|
|
464e5c8e81 | ||
|
|
29740fb9ea | ||
|
|
298168399c | ||
|
|
4724c2316e | ||
|
|
15ca1afa78 | ||
|
|
e29832d655 | ||
|
|
997b049dad | ||
|
|
bfc616a5c3 | ||
|
|
79251bc3b8 | ||
|
|
173a5cefbe | ||
|
|
b4a7ad10a1 | ||
|
|
f9d812b3a2 | ||
|
|
a9f5a01fc3 | ||
|
|
59b22d122d | ||
|
|
4e28744401 | ||
|
|
30e713162f | ||
|
|
6a5331cc8d | ||
|
|
b6c704888d | ||
|
|
d01900130c | ||
|
|
ac624c30a8 | ||
|
|
783dfe8435 | ||
|
|
aec86e9ce5 | ||
|
|
95ebbd90b0 | ||
|
|
866f84ec5d | ||
|
|
7a62656c98 | ||
|
|
9fc1dcd7d5 | ||
|
|
940c612b49 | ||
|
|
6efdca9c28 | ||
|
|
357abd2f3f | ||
|
|
1f71cf1525 | ||
|
|
b03a701312 | ||
|
|
b61de73ac7 | ||
|
|
40cb5577e5 | ||
|
|
064a6388e6 | ||
|
|
0d4413835e | ||
|
|
dd562ab916 | ||
|
|
8fe477055f | ||
|
|
b815759612 | ||
|
|
70049a3be6 | ||
|
|
327c284ebe | ||
|
|
0956dfaef5 | ||
|
|
87879a6990 | ||
|
|
affd2f7a73 | ||
|
|
e36ce96bd9 | ||
|
|
ec4e7ff45d | ||
|
|
904848636a | ||
|
|
5cdc711ced | ||
|
|
67ac07880c | ||
|
|
4a3c541dce | ||
|
|
c603729bda | ||
|
|
e2c2e37daa | ||
|
|
e93e16f135 | ||
|
|
474c4a7f2a | ||
|
|
381c2aa078 | ||
|
|
ba19ed4de6 | ||
|
|
f8aac5d9b2 | ||
|
|
68c5653d96 | ||
|
|
60e0dfe740 | ||
|
|
c2a7c91868 | ||
|
|
7b62eed1f6 | ||
|
|
7290c5730c | ||
|
|
f96d966e88 | ||
|
|
72139a64e2 | ||
|
|
e00a63c077 | ||
|
|
6576774c0c | ||
|
|
5567d8bc12 | ||
|
|
3be3d1aea6 | ||
|
|
ae64b2de18 | ||
|
|
d07f406696 | ||
|
|
9ce7297ae8 | ||
|
|
2a612c46fe | ||
|
|
30a41c9300 | ||
|
|
3cf0a37594 | ||
|
|
cbe38de8d3 | ||
|
|
d0f9676474 | ||
|
|
1cd9afb385 | ||
|
|
deecd93d80 | ||
|
|
39ca7e9323 | ||
|
|
69c47c8bcb | ||
|
|
77ca8c6c56 | ||
|
|
6290ba9498 | ||
|
|
9c2673fb46 | ||
|
|
b8d1c7c698 | ||
|
|
9e1c9b8fb6 | ||
|
|
267cda4a4b | ||
|
|
926d960977 | ||
|
|
893cf02ed4 | ||
|
|
11a9c7fdd5 | ||
|
|
b50617e015 | ||
|
|
55b8de8d31 | ||
|
|
d03c77cb0d | ||
|
|
ea1235d9da | ||
|
|
beda10436f | ||
|
|
15cbff5283 | ||
|
|
4c347aa78c | ||
|
|
2e864d5e30 | ||
|
|
8cd0d9d6f8 | ||
|
|
51cfc54372 | ||
|
|
4fc34e5f0c | ||
|
|
3f0c1606cd | ||
|
|
6c202f7a1c | ||
|
|
75cf704381 | ||
|
|
a1472757dc | ||
|
|
66e5553ec2 | ||
|
|
efc527a30a | ||
|
|
16e621961b | ||
|
|
260c99e269 | ||
|
|
17764bd65e | ||
|
|
17ff7cdded | ||
|
|
49e978dd8e | ||
|
|
99df210dda | ||
|
|
77335f2eda | ||
|
|
6e1649445a | ||
|
|
7302dea1cc | ||
|
|
4f1c9aa0e2 | ||
|
|
7e817af5a4 | ||
|
|
6d388010f7 | ||
|
|
2cfe012854 | ||
|
|
7d1ebc8185 | ||
|
|
59bd33b261 | ||
|
|
e32c1f1932 | ||
|
|
0ffa74946c | ||
|
|
7e103d4ebd | ||
|
|
2203c339dd | ||
|
|
33893aa257 | ||
|
|
118a7b62b0 | ||
|
|
79a41e28b5 | ||
|
|
3e52c7e85d | ||
|
|
a578f2243c | ||
|
|
1e43109b74 | ||
|
|
53f5e54429 | ||
|
|
423c85bc1a | ||
|
|
1dcf4b60fe | ||
|
|
1a1ff937b9 | ||
|
|
ecb81e990d | ||
|
|
6513be8d07 | ||
|
|
c03ece2288 | ||
|
|
ebcebf95ef | ||
|
|
af42f8b15b | ||
|
|
99b89722d5 | ||
|
|
c873b06630 | ||
|
|
54bd64b4c6 | ||
|
|
25a30705ea | ||
|
|
bbb33f2429 | ||
|
|
8c06882fdb | ||
|
|
02b29632cf | ||
|
|
b4d13c5e3a | ||
|
|
6e2dab7be2 | ||
|
|
19c40e8ee9 | ||
|
|
85f17c15e3 | ||
|
|
f7bdd54097 |
No files matched your search
@@ -11,10 +11,32 @@ runs:
|
||||
~/.platformio/.cache
|
||||
key: ${{ runner.os }}-pio
|
||||
|
||||
# CUSTOM (TeTeHacko): no actions/setup-python (upstream: '3.13'). Its
|
||||
# Python for Ubuntu 26.04, the runner image, is built for x86-64-v3 and
|
||||
# grg-runner (Xeon E5-2630L v2) has only v2: "CPU ISA level is lower than
|
||||
# required" on every run. The image's own python3 runs anywhere and the
|
||||
# build needs no particular 3.x, so the build runs in a venv of it.
|
||||
- name: Install Python
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: '3.13'
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
SUDO="$(command -v sudo || true)"
|
||||
venv="$RUNNER_TEMP/pyenv"
|
||||
if ! python3 -m venv "$venv"; then
|
||||
$SUDO apt-get update -qq
|
||||
$SUDO apt-get install -y -qq python3 python3-venv
|
||||
python3 -m venv --clear "$venv"
|
||||
fi
|
||||
# The image's python is often newer than the wheels on PyPI (detools
|
||||
# 0.53.0 has none for 3.14): pip then builds from source and needs the
|
||||
# headers, which the image does not ship.
|
||||
inc="$("$venv/bin/python" -c 'import sysconfig; print(sysconfig.get_paths()["include"])')"
|
||||
if [ ! -e "$inc/Python.h" ]; then
|
||||
$SUDO apt-get update -qq
|
||||
$SUDO apt-get install -y -qq python3-dev
|
||||
fi
|
||||
echo "$venv/bin" >>"$GITHUB_PATH"
|
||||
"$venv/bin/python" --version
|
||||
|
||||
- name: Install PlatformIO
|
||||
shell: bash
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env bash
|
||||
# The docs website of this fork (https://tth-pub.pages.rfa.cz/meshcore-tth/):
|
||||
# mkdocs (theme mkdocs-terminal) over docs/, in English: the English half of
|
||||
# the fork's README is the home page, the Czech half one page (cs.md); the
|
||||
# fork's own docs first, upstream's below.
|
||||
#
|
||||
# Usage: .github/docs-site.sh <out dir> (run from the repo root)
|
||||
# Needs mkdocs-terminal and markdown-callouts, e.g.
|
||||
# uvx --with mkdocs-terminal --with markdown-callouts mkdocs --version
|
||||
# The script stages a copy of docs/ (README split into index.md / cs.md,
|
||||
# links that leave docs/ pointed at the repo) and builds it with
|
||||
# mkdocs.tth.yml. Upstream's mkdocs.yml (Material) stays as it is (no
|
||||
# conflicts in upstream-sync merges).
|
||||
# Build only from the PUBLIC tree (tth-pub): the export leaves our operations
|
||||
# docs out, a build of the private repo would publish them.
|
||||
set -euo pipefail
|
||||
case "${1:-}" in -h | --help | "")
|
||||
sed -n '2,/^[^#]/{/^#/s/^# \{0,1\}//p}' "$0"
|
||||
[ -n "${1:-}" ] || exit 2
|
||||
exit 0
|
||||
;;
|
||||
esac
|
||||
out=$(realpath -m "$1")
|
||||
repo=https://git.rfa.cz/tth-pub/meshcore-tth
|
||||
src="$repo/src/branch/main"
|
||||
stage=$(mktemp -d)
|
||||
trap 'rm -rf "$stage"' EXIT
|
||||
|
||||
cp -r docs "$stage/docs"
|
||||
# upstream's own introduction gets a page of its own; ours is the home page
|
||||
mv "$stage/docs/index.md" "$stage/docs/meshcore.md"
|
||||
rm -f "$stage/docs/docs.md" # how to build upstream's site, not for readers
|
||||
|
||||
# README of the fork: "## O tomto forku" .. "## About this fork" = Czech,
|
||||
# from there to "## About MeshCore" = English. One heading level up, links
|
||||
# into docs/ made site-relative, any other repo path absolute.
|
||||
readme_part() {
|
||||
sed -n "/^## $1/,/^## $2/p" README.md | sed '$d' |
|
||||
sed -E 's/^#(#+) /\1 /' |
|
||||
sed -E 's#\]\((\./)?docs/([^)]+)\)#](\2)#g' |
|
||||
sed -E "s#\\]\\((\\./)?([a-zA-Z][^):]*)\\)#](${src//#/\\#}/\\2)#g"
|
||||
}
|
||||
readme_part 'About this fork' 'About MeshCore' >"$stage/docs/index.md"
|
||||
readme_part 'O tomto forku' 'About this fork' >"$stage/docs/cs.md"
|
||||
if ! grep -q . "$stage/docs/index.md" || ! grep -q . "$stage/docs/cs.md"; then
|
||||
echo "docs-site: README sections not found (headings changed?)" >&2
|
||||
exit 1
|
||||
fi
|
||||
# the two languages link to each other by anchor, and "above"/"below"
|
||||
# is a separate page here
|
||||
sed -i -E 's#Česká verze \[výše\]#[Česká verze]#' "$stage/docs/index.md"
|
||||
sed -i -E 's#English version \[below\]#[English version]#' "$stage/docs/cs.md"
|
||||
sed -i -E 's#\]\(\#about-this-fork[^)]*\)#](index.md)#g' "$stage/docs/cs.md"
|
||||
sed -i -E 's#\]\(\#o-tomto-forku[^)]*\)#](cs.md)#g' "$stage/docs/index.md"
|
||||
# GFM (Gitea) needs `\|` for a pipe in code inside a table cell; Python-
|
||||
# Markdown keeps the backslash and does not split cells on a pipe in code
|
||||
perl -0pi -e 's/(`[^`\n]*`)/ (my $c = $1) =~ s#\\\|#|#g; $c /ge' "$stage"/docs/*.md
|
||||
# our docs link back to ../README.md
|
||||
sed -i -E 's#\]\(\.\./README\.md#](index.md#g' "$stage"/docs/*.md
|
||||
|
||||
cp mkdocs.tth.yml "$stage/"
|
||||
cd "$stage"
|
||||
mkdocs build --strict -f mkdocs.tth.yml -d "$out"
|
||||
@@ -0,0 +1,28 @@
|
||||
# shellcheck shell=bash
|
||||
# Build flags of the public firmware, sourced by pub-release.yml -- and by the
|
||||
# private mast release, which builds the very same observer image, so what the
|
||||
# fork publishes is what runs on its own nodes. PlatformIO appends
|
||||
# PLATFORMIO_BUILD_FLAGS after each env's flags: last -D wins.
|
||||
#
|
||||
# 869.432/62.5/SF7/CR5; repeater + room server: zero-hop advert off, flood
|
||||
# advert 25 h, AIRTIME_FACTOR 9 (= `dutycycle` 10 %); repeater: regions cz,cs next to *.
|
||||
# Path hash 2 B is this fork's default anyway. TX power stays the board's.
|
||||
# FILTER_CHANNEL_PSKS = [channel_filter] in platformio.ini (#meshcore, Public,
|
||||
# #test -- public keys): compiles the repeater's `filter` (deny-forward by
|
||||
# sender name); inert until an operator adds a name.
|
||||
# WITH_RX_POWERSAVING compiles `set radio.rxps` (SX1262 RX duty cycle); off
|
||||
# until an operator sets it.
|
||||
PUB_FLAGS='-D WITH_RX_POWERSAVING
|
||||
-D LORA_FREQ=869.432 -D LORA_BW=62.5 -D LORA_SF=7 -D LORA_CR=5
|
||||
-D ADVERT_INTERVAL_DEFAULT=0 -D FLOOD_ADVERT_INTERVAL_DEFAULT=25
|
||||
-D AIRTIME_FACTOR_DEFAULT=9.0 -D DEFAULT_REGIONS=\"cz,cs\"
|
||||
-D FILTER_CHANNEL_PSKS=\"2fa78a5aef618e7c2a78f0ab5c8869b3,8b3387e9c5cdea6ac9e5edbaa115cd72,9cd8fcf22a47333b591d96a2b848b73f\"'
|
||||
# Observer variants of the nRF52 repeaters: BLE console (starts OFF,
|
||||
# RPT_BLE_DEFAULT_OFF -- placeholder PIN), `rxlog`/`nodes` and the `pktlog`
|
||||
# raw-frame ring that the repeater observer reads over BLE or USB.
|
||||
OBS_FLAGS='-D BLE_PIN_CODE=123456 -D RPT_BLE_DEFAULT_OFF=1
|
||||
-D MAX_HEARD_NODES=128 -D RXLOG_SIZE=512 -D PKTFEED_SIZE=64'
|
||||
# one line each, as the YAML folded scalars they replace were
|
||||
PUB_FLAGS=${PUB_FLAGS//$'\n'/ }
|
||||
OBS_FLAGS=${OBS_FLAGS//$'\n'/ }
|
||||
export PUB_FLAGS OBS_FLAGS
|
||||
Executable
+155
@@ -0,0 +1,155 @@
|
||||
#!/usr/bin/env bash
|
||||
# The changes part of a public release's notes (pub-release.yml): our commits
|
||||
# since BASE, one computed line for the build dependencies that moved, and
|
||||
# upstream's merged PRs. Prints Markdown to stdout.
|
||||
#
|
||||
# Usage: .github/release-notes.sh <base> <sha> <web url of this repo>
|
||||
# Preview: in a clone of tth-pub/meshcore-tth checked out at <sha> (the
|
||||
# library line compares platformio.lock in the working tree with <base>).
|
||||
#
|
||||
# What a commit puts into the notes (body lines, AGENTS.md "Commit = řádek
|
||||
# veřejného changelogu"; .tth/tools/git-hooks/commit-msg enforces them):
|
||||
# Changelog: <English line> replaces the subject; "Changelog: -" = left out
|
||||
# Changelog-cs: <Czech line> the notes show "<cs> · *<en>*"
|
||||
# Changelog-topic: <slug> commits with the same topic in one release are
|
||||
# ONE item: the newest one's text, all links --
|
||||
# a fix of a fix, a pin moved twice, a
|
||||
# superseded step no longer show up as two items
|
||||
# Commits that touch the firmware (paths in $fwre) come first, the rest is
|
||||
# folded. Build dependencies are not taken from commit messages but diffed:
|
||||
# the nRF52 platform and toolchain pins in platformio.ini and every library in
|
||||
# platformio.lock (tools/pio_lock.py moved), so the daily lock refresh and
|
||||
# Renovate commits carry "Changelog: -" and a release still says what moved.
|
||||
set -euo pipefail
|
||||
case "${1:-}" in -h | --help)
|
||||
sed -n '2,/^[^#]/{/^#/s/^# \{0,1\}//p}' "$0"
|
||||
exit 0
|
||||
;;
|
||||
esac
|
||||
[ $# -eq 3 ] || {
|
||||
echo "usage: $0 <base> <sha> <web url>" >&2
|
||||
exit 2
|
||||
}
|
||||
base=$1 sha=$2 web=$3
|
||||
gh=https://github.com/meshcore-dev/MeshCore
|
||||
max=60
|
||||
fwre='^(src|examples|variants|lib|boards|arch)/|^platformio\.(ini|lock)$'
|
||||
|
||||
trailer() { git log -1 --format=%b "$1" | sed -n "s/^$2: *//p" | head -1; }
|
||||
|
||||
# ours: commits on our main itself (first parent); a merge of one of our own
|
||||
# branches (feat/...) is unfolded into the branch's commits, an upstream merge
|
||||
# is left to the upstream list below
|
||||
ourc=()
|
||||
for c in $(git log --first-parent --format=%H "$base..$sha"); do
|
||||
if git rev-parse -q --verify "$c^2" >/dev/null; then
|
||||
git log -1 --format=%s "$c" | grep -q '^Merge upstream' && continue
|
||||
# ^base: a merge of main into a branch carries what is released already
|
||||
mapfile -t -O "${#ourc[@]}" ourc < <(git log --no-merges --format=%H "$c^1..$c^2" "^$base")
|
||||
else
|
||||
ourc+=("$c")
|
||||
fi
|
||||
done
|
||||
|
||||
# items, newest first; a topic seen before only adds its link
|
||||
declare -A text=() links=() isfw=()
|
||||
keys=()
|
||||
for c in "${ourc[@]}"; do
|
||||
en=$(trailer "$c" Changelog)
|
||||
[ "$en" = "-" ] && continue
|
||||
[ -n "$en" ] || en=$(git log -1 --format=%s "$c")
|
||||
cs=$(trailer "$c" Changelog-cs)
|
||||
key=$(trailer "$c" Changelog-topic)
|
||||
key=${key:-$c}
|
||||
link="[${c:0:8}]($web/commit/$c)"
|
||||
if [ -z "${text[$key]+x}" ]; then
|
||||
keys+=("$key")
|
||||
if [ -n "$cs" ]; then text[$key]="$cs · *$en*"; else text[$key]=$en; fi
|
||||
links[$key]=$link
|
||||
else
|
||||
links[$key]+=", $link"
|
||||
fi
|
||||
git diff-tree --no-commit-id --name-only -r "$c" | grep -qE "$fwre" && isfw[$key]=1
|
||||
done
|
||||
|
||||
# build dependencies that moved between base and sha
|
||||
deps=()
|
||||
pin() { git show "$1:platformio.ini" 2>/dev/null | grep -m1 -oE "$2@[0-9][^[:space:]]*" | cut -d@ -f2 || true; }
|
||||
for p in nordicnrf52 toolchain-gccarmnoneeabi; do
|
||||
o=$(pin "$base" "platformio/$p") n=$(pin "$sha" "platformio/$p")
|
||||
[ "$o" = "$n" ] || deps+=("$p ${o:-unpinned} → ${n:-unpinned}")
|
||||
done
|
||||
if git cat-file -e "$base:platformio.lock" 2>/dev/null && [ -f platformio.lock ]; then
|
||||
if [ "$(git rev-parse HEAD)" = "$(git rev-parse "$sha^{commit}")" ]; then
|
||||
while IFS= read -r l; do
|
||||
[ -n "$l" ] && deps+=("${l/ -> / → }")
|
||||
done < <(python3 tools/pio_lock.py moved --base "$base")
|
||||
else
|
||||
echo "release-notes: checkout is not $sha, libraries left out" >&2
|
||||
fi
|
||||
fi
|
||||
|
||||
fw="" other="" nother=0
|
||||
for k in "${keys[@]}"; do
|
||||
line="- ${text[$k]} (${links[$k]})"
|
||||
if [ -n "${isfw[$k]:-}" ]; then
|
||||
fw+="$line"$'\n'
|
||||
else
|
||||
other+="$line"$'\n'
|
||||
nother=$((nother + 1))
|
||||
fi
|
||||
done
|
||||
if [ "${#deps[@]}" -gt 0 ]; then
|
||||
d=$(printf '%s, ' "${deps[@]}")
|
||||
fw+="- Závislosti buildu · *build dependencies*: ${d%, }"$'\n'
|
||||
fi
|
||||
fw=${fw%$'\n'} other=${other%$'\n'}
|
||||
|
||||
# upstream: the first-parent line of each merged upstream branch, PR merges as
|
||||
# their title, direct commits as their subject. A direct upstream commit (no
|
||||
# PR) links to GitHub by its ORIGINAL id: the public export (filter-repo)
|
||||
# gives every upstream commit a new one, which GitHub does not know
|
||||
# (30. 11. 2026: "* sec patch" linked to a 404). Author email + author time
|
||||
# survive the rewrite.
|
||||
declare -A seen=() upid=()
|
||||
if git fetch -q --no-tags "$gh.git" '+refs/heads/main:refs/upstream/main' '+refs/heads/dev:refs/upstream/dev'; then
|
||||
while read -r h k; do upid[$k]=$h; done < <(git log --format='%H %ae/%at' refs/upstream/main refs/upstream/dev)
|
||||
fi
|
||||
ups=()
|
||||
for m in $(git log --first-parent --merges --grep='^Merge upstream' --format=%H "$base..$sha"); do
|
||||
for c in $(git log --first-parent --format=%H "$m^1..$m^2"); do
|
||||
s=$(git log -1 --format=%s "$c")
|
||||
if [[ $s =~ ^Merge\ pull\ request\ \#([0-9]+)\ from\ ([^/]+)/(.*)$ ]]; then
|
||||
pr=${BASH_REMATCH[1]}
|
||||
[ -z "${seen[$pr]:-}" ] || continue
|
||||
seen[$pr]=1
|
||||
t=$(git log -1 --format=%b "$c" | sed -n '/./{p;q}')
|
||||
ups+=("- ${t:-${BASH_REMATCH[3]}} ([#$pr]($gh/pull/$pr), ${BASH_REMATCH[2]})")
|
||||
elif [[ $s != Merge* ]]; then
|
||||
[ -z "${seen[$c]:-}" ] || continue
|
||||
seen[$c]=1
|
||||
u=${upid[$(git log -1 --format='%ae/%at' "$c")]:-}
|
||||
if [ -n "$u" ]; then
|
||||
ups+=("- $s ([${u:0:7}]($gh/commit/$u))")
|
||||
else
|
||||
ups+=("- $s ([${c:0:7}]($web/commit/$c))")
|
||||
fi
|
||||
fi
|
||||
done
|
||||
done
|
||||
n=${#ups[@]}
|
||||
|
||||
echo "### Změny firmwaru · firmware changes"
|
||||
echo "${fw:-- žádné · none}"
|
||||
echo
|
||||
if [ "$nother" -gt 0 ]; then
|
||||
echo "<details><summary>Dokumentace, nástroje, CI · docs, tools, CI ($nother)</summary>"
|
||||
echo
|
||||
echo "$other"
|
||||
echo
|
||||
echo "</details>"
|
||||
echo
|
||||
fi
|
||||
echo "### Z upstreamu MeshCore · from upstream ($n)"
|
||||
if [ "$n" -gt 0 ]; then printf '%s\n' "${ups[@]:0:$max}"; else echo "- žádné · none"; fi
|
||||
[ "$n" -le "$max" ] || echo "- … a dalších $((n - max)) · and $((n - max)) more"
|
||||
@@ -11,6 +11,9 @@ permissions:
|
||||
|
||||
jobs:
|
||||
github-pages:
|
||||
# CUSTOM (TeTeHacko): upstream's site only; this fork publishes its own
|
||||
# (tth-docs.yml), and here the job only filled an unread gh-pages branch
|
||||
if: github.repository == 'meshcore-dev/MeshCore'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
|
||||
@@ -0,0 +1,511 @@
|
||||
# Public firmware builds of this fork -- runs only in the published repo
|
||||
# (git.rfa.cz tth-pub/meshcore-tth), skipped anywhere else.
|
||||
#
|
||||
# Generic envs only: upstream's placeholder BLE PIN (123456) and admin
|
||||
# password ("password") -- change both on the node after flashing. Nothing
|
||||
# here carries a site's identity or real secrets.
|
||||
#
|
||||
# Defaults follow the Czech mesh (meshcore.cz wiki: nastaveni_site_meshcore_cz,
|
||||
# instalace_repeateru, regiony), PUB_FLAGS below. They apply to a node with
|
||||
# no saved settings (fresh, or after an erase); a reflash keeps what is set.
|
||||
#
|
||||
# Runs on a push to main that touches the firmware -- the export pushes there
|
||||
# after every upstream sync (private repo, tth-upstream-sync) -- and by hand.
|
||||
# Documentation, the enclosure and CI files alone build nothing (paths-ignore):
|
||||
# a release would only make every -ota node update itself to the same code.
|
||||
# tools/ is NOT ignored: build_version.py and ota_ramlib.py are build inputs.
|
||||
# Release tag v1.18.0+tth.<commit date>[.n] (the n-th release of that day),
|
||||
# titled "v1.18.0+tth · 12. 11. 2026"; assets carry the tag in their names, the
|
||||
# body the version the node reports (`ver`: v1.18.0-tth<sha>). Until 12. 11.
|
||||
# 2026 the tags were tth-<sha8>; pruning and the changelog know both;
|
||||
# the newest KEEP releases stay, older ones are deleted. The body is a
|
||||
# changelog since the previous release: our own firmware commits, our docs /
|
||||
# tools / CI commits folded, then the upstream PRs the upstream merges brought
|
||||
# in, generated by .github/release-notes.sh (preview it locally; its header
|
||||
# lists the commit trailers: Changelog, Changelog-cs, Changelog-topic) with
|
||||
# one computed line for the build dependencies that moved.
|
||||
# nRF52: .uf2 (drag onto the bootloader drive) and .zip (DFU over BLE or
|
||||
# serial); ESP32: -merged.bin (fresh install at 0x0) and .bin (update).
|
||||
#
|
||||
# EXPERIMENTAL -ota images (docs/ota-public-plan.md): every nRF52 env with a
|
||||
# text console (OTA_ENVS) is built once more with -D FW_OTA=1 (admin-pushed
|
||||
# update, FwUpdate), the observer ones as -observer-ota too. Each comes with a
|
||||
# full .mcfw package and a delta from the same image of every kept earlier
|
||||
# release (its zip's firmware.bin, checked against that release's SHA256SUMS);
|
||||
# over the mesh a node takes only deltas, and none older than itself.
|
||||
# Packages and SHA256SUMS are signed with OTA_SIGNING_KEY (meshcore-ota@tth-pub,
|
||||
# tools/ota_allowed_signers); manifest.json lists what is there.
|
||||
#
|
||||
# dry_run: the same build anywhere (the private repo too), no release -- the
|
||||
# result goes up as a workflow artifact. Delta bases always come from the
|
||||
# public repo's releases. A pull request that changes a dependency pin
|
||||
# (platformio.ini, platformio.lock -- Renovate's) runs as a dry run too, and is
|
||||
# what Renovate waits for before it merges.
|
||||
#
|
||||
# Libraries come from platformio.lock (tools/pio_lock.py): installed before
|
||||
# each env's first build, and the build fails when anything else resolved.
|
||||
# Platform and toolchain are pinned in platformio.ini. ~/.platformio keeps
|
||||
# every version it ever installed side by side (platforms/<name>@<version>,
|
||||
# packages likewise) and a build takes the pinned one, so the cache is one
|
||||
# growing store: the newest is restored, new versions are added and saved
|
||||
# under a new key only when a pin changed. Libraries are not cached: small,
|
||||
# and an old version in .pio/libdeps/<env> would fail the lock check.
|
||||
name: pub-release
|
||||
|
||||
"on":
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "platformio.ini"
|
||||
- "platformio.lock"
|
||||
- "variants/**/platformio.ini"
|
||||
- ".github/workflows/pub-release.yml"
|
||||
- ".github/fw-flags.sh"
|
||||
push:
|
||||
branches: [main]
|
||||
paths-ignore:
|
||||
- "**/*.md"
|
||||
- "docs/**"
|
||||
- "hardware/**"
|
||||
- ".github/**"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
ref:
|
||||
description: "commit to build: FULL sha, branch or tag (checkout takes no short sha)"
|
||||
required: false
|
||||
default: "main"
|
||||
replace:
|
||||
description: "replace an existing release of this commit"
|
||||
required: false
|
||||
default: "false"
|
||||
dry_run:
|
||||
description: "build and package only, no release (runs in the private repo too)"
|
||||
required: false
|
||||
default: "false"
|
||||
bases_repo:
|
||||
description: "dry run only: take delta bases from this repo's releases instead (testing the delta path)"
|
||||
required: false
|
||||
default: ""
|
||||
only:
|
||||
description: "dry run only: build just these artifacts (e.g. Xiao_nrf52_repeater-ota), space separated"
|
||||
required: false
|
||||
default: ""
|
||||
|
||||
# Releases queue one after another (tag numbering); a pull request's check
|
||||
# and a dry run each in their own group: Gitea keeps ONE pending run per
|
||||
# group, so a push to main (twice a day) would cancel a waiting PR check and
|
||||
# Renovate's automerge would never come.
|
||||
concurrency:
|
||||
group: >-
|
||||
pub-release-${{ github.event_name == 'pull_request' && github.ref
|
||||
|| (github.event.inputs.dry_run == 'true' && 'dry' || 'release') }}
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
GITEA: https://git.rfa.cz
|
||||
KEEP: 5
|
||||
# PUB_FLAGS / OBS_FLAGS: .github/fw-flags.sh (shared with the private mast
|
||||
# release, which builds the same observer image). RAM 37-39 %, flash 41-58 %.
|
||||
OBS_ENVS: >-
|
||||
Xiao_nrf52_repeater SenseCap_Solar_repeater RAK_4631_repeater t1000e_repeater Heltec_t114_repeater
|
||||
# nRF52 envs with a text console: also released as experimental -ota images
|
||||
OTA_ENVS: >-
|
||||
Xiao_nrf52_repeater Xiao_nrf52_room_server Xiao_nrf52_sensor SenseCap_Solar_repeater
|
||||
RAK_4631_repeater RAK_4631_room_server t1000e_repeater Heltec_t114_repeater
|
||||
PUB_REPO: tth-pub/meshcore-tth # where delta bases come from, dry run or not
|
||||
# grg-runner: 24 cores, up to 8 jobs of its own; 6 builds x 6 compilers
|
||||
PARALLEL: 6
|
||||
PIO_JOBS: 6
|
||||
ENVS: >-
|
||||
Xiao_nrf52_repeater Xiao_nrf52_companion_radio_ble Xiao_nrf52_room_server Xiao_nrf52_sensor
|
||||
SenseCap_Solar_repeater SenseCap_Solar_companion_radio_ble
|
||||
RAK_4631_repeater RAK_4631_companion_radio_ble RAK_4631_room_server
|
||||
t1000e_repeater t1000e_companion_radio_ble
|
||||
Heltec_t114_repeater Heltec_t114_companion_radio_ble
|
||||
Heltec_v3_repeater Heltec_v3_companion_radio_ble
|
||||
|
||||
jobs:
|
||||
release:
|
||||
if: >-
|
||||
github.repository == 'tth-pub/meshcore-tth' || github.event.inputs.dry_run == 'true'
|
||||
|| github.event_name == 'pull_request'
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
DRY: ${{ github.event.inputs.dry_run == 'true' || github.event_name == 'pull_request' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ github.event.inputs.ref || github.sha }}
|
||||
|
||||
- name: Commit and tag
|
||||
id: src
|
||||
env:
|
||||
TOKEN: ${{ secrets.GITEA_TOKEN || github.token }}
|
||||
REPLACE: ${{ github.event.inputs.replace }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git fetch -q --tags
|
||||
# the private repo carries no upstream release tags (the export brings
|
||||
# them along): a dry run there fetches them, or the version base is "nover"
|
||||
if [ "$DRY" = "true" ]; then
|
||||
git fetch -q --no-tags https://github.com/meshcore-dev/MeshCore.git 'refs/tags/*:refs/tags/*'
|
||||
fi
|
||||
sha=$(git rev-parse HEAD)
|
||||
# upstream base as tools/build_version.py finds it: "companion-v1.18.0" -> v1.18.0
|
||||
desc=$(git describe --tags --abbrev=0 --match '*v[0-9]*' --exclude '*+tth*' --exclude 'backup/*' HEAD)
|
||||
[[ $desc =~ v[0-9].* ]] && base=${BASH_REMATCH[0]} || base=$desc
|
||||
# the COMMIT's date (Prague), so a rebuild of the same commit keeps its tag
|
||||
day=$(TZ=Europe/Prague git show -s --format=%cd --date=format-local:%Y%m%d HEAD)
|
||||
human=$(TZ=Europe/Prague git show -s --format=%cd --date=format-local:'%-d. %-m. %Y' HEAD)
|
||||
api="$GITEA/api/v1/repos/$GITHUB_REPOSITORY"
|
||||
auth="header = \"Authorization: token $TOKEN\""
|
||||
enc() { jq -rn --arg s "$1" '$s|@uri'; }
|
||||
# v1.18.0+tth.20261112, a second release of the day .2, ...
|
||||
n=1
|
||||
while :; do
|
||||
tag="$base+tth.$day"
|
||||
[ "$n" -eq 1 ] || tag="$tag.$n"
|
||||
rel=$(curl -sS --config - "$api/releases/tags/$(enc "$tag")" <<<"$auth")
|
||||
id=$(jq -r '.id // empty' <<<"$rel")
|
||||
[ -n "$id" ] || break
|
||||
if [ "$(jq -r .target_commitish <<<"$rel")" = "$sha" ]; then
|
||||
if [ "$REPLACE" != "true" ]; then
|
||||
echo "::error::release $tag already exists (id $id); set replace=true to rebuild it"
|
||||
exit 1
|
||||
fi
|
||||
curl -sSf --config - -X DELETE "$api/releases/$id" <<<"$auth"
|
||||
curl -sSf --config - -X DELETE "$api/tags/$(enc "$tag")" <<<"$auth" || true
|
||||
echo "removed old $tag"
|
||||
break
|
||||
fi
|
||||
n=$((n + 1))
|
||||
done
|
||||
title="$base+tth · $human"
|
||||
[ "$n" -eq 1 ] || title="$title ($n)"
|
||||
echo "release $tag: $title (commit $sha)"
|
||||
{
|
||||
echo "sha=$sha"
|
||||
echo "tag=$tag"
|
||||
echo "title=$title"
|
||||
} >>"$GITHUB_OUTPUT"
|
||||
|
||||
# one store of every platform/toolchain version (see the header)
|
||||
- name: PlatformIO platforms and packages
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: |
|
||||
~/.platformio/platforms
|
||||
~/.platformio/packages
|
||||
key: pio-store-${{ hashFiles('platformio.ini', 'variants/**/platformio.ini') }}
|
||||
restore-keys: pio-store-
|
||||
|
||||
- name: Setup Build Environment
|
||||
uses: ./.github/actions/setup-build-environment
|
||||
|
||||
- name: Build and package
|
||||
id: build
|
||||
env:
|
||||
TAG: ${{ steps.src.outputs.tag }}
|
||||
OTA_SIGNING_KEY: ${{ secrets.OTA_SIGNING_KEY }}
|
||||
TOKEN: ${{ secrets.GITEA_TOKEN || github.token }}
|
||||
BASES_REPO: ${{ github.event.inputs.bases_repo }}
|
||||
ONLY: ${{ github.event.inputs.only }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
source .github/fw-flags.sh
|
||||
sha=$(git rev-parse --short=8 HEAD)
|
||||
dist="$GITHUB_WORKSPACE/dist"
|
||||
mkdir -p "$dist"
|
||||
version=""
|
||||
[ -n "$OTA_SIGNING_KEY" ] || { echo "::error::OTA_SIGNING_KEY secret missing"; exit 1; }
|
||||
okey="$RUNNER_TEMP/ota_signing_key"
|
||||
(umask 077 && printf '%s\n' "$OTA_SIGNING_KEY" >"$okey")
|
||||
trap 'rm -f "$okey"' EXIT
|
||||
pip install -q detools==0.53.0 cryptography
|
||||
echo '{}' >"$dist/manifest.json"
|
||||
# earlier public releases (newest first): delta bases for the -ota images
|
||||
[ "$DRY" = "true" ] && [ -n "$BASES_REPO" ] && PUB_REPO=$BASES_REPO
|
||||
[ "$DRY" = "true" ] || ONLY="" # a real release always builds everything
|
||||
api="$GITEA/api/v1/repos/$PUB_REPO"
|
||||
auth="header = \"Authorization: token $TOKEN\""
|
||||
bases="$RUNNER_TEMP/bases"
|
||||
mkdir -p "$bases"
|
||||
curl -sSf --config - "$api/releases?limit=50" <<<"$auth" |
|
||||
jq -c --arg t "$TAG" '[.[] | select(.tag_name | startswith("tth-") or test("[+]tth[.]")) | select(.tag_name != $t)]
|
||||
| sort_by(.created_at) | reverse | .[]' >"$bases/releases.jsonl" || : >"$bases/releases.jsonl"
|
||||
asset() { jq -r --arg n "$2" '.assets[] | select(.name == $n) | .browser_download_url' <<<"$1"; }
|
||||
# ota_package <env> <artifact>: full package + deltas from earlier releases
|
||||
ota_package() {
|
||||
local env=$1 art=$2 b=".pio/build/$1" tags img rel ptag url dir out
|
||||
tools/ota_check_ramfunc.sh "$env"
|
||||
tags=$(grep -aoE 'MCFW-TAGS target=[!-~]+ epoch=[0-9]+' "$b/firmware.elf" | head -1)
|
||||
img=$(sha256sum <"$b/firmware.bin" | cut -d' ' -f1)
|
||||
python3 tools/ota_pack.py pack "$env" --key "$okey" --out "$dist/$art-$TAG.mcfw"
|
||||
jq --arg a "$art" --arg z "$art-$TAG.zip" --arg f "$art-$TAG.mcfw" --arg i "$img" --arg t "${tags#MCFW-TAGS }" \
|
||||
'.envs[$a] = {zip: $z, ota: {image_sha256: $i, tags: $t, full: $f, deltas: {}}}' \
|
||||
"$dist/manifest.json" >"$dist/m.tmp" && mv "$dist/m.tmp" "$dist/manifest.json"
|
||||
while read -r rel; do
|
||||
ptag=$(jq -r .tag_name <<<"$rel")
|
||||
url=$(asset "$rel" "$art-$ptag.zip")
|
||||
[ -n "$url" ] || continue # that release had no such -ota image yet
|
||||
dir="$bases/$ptag"
|
||||
mkdir -p "$dir"
|
||||
[ -f "$dir/SHA256SUMS" ] || curl -sSfL --config - -o "$dir/SHA256SUMS" "$(asset "$rel" SHA256SUMS)" <<<"$auth"
|
||||
curl -sSfL --config - -o "$dir/$art-$ptag.zip" "$url" <<<"$auth"
|
||||
(cd "$dir" && grep " $art-$ptag.zip\$" SHA256SUMS | sha256sum -c --quiet -)
|
||||
unzip -p "$dir/$art-$ptag.zip" firmware.bin >"$dir/$art.bin"
|
||||
out="$art-$TAG.from-$ptag.mcfw"
|
||||
if python3 tools/ota_pack.py diff "$env" --base "$dir/$art.bin" --key "$okey" --out "$dist/$out"; then
|
||||
jq --arg a "$art" --arg p "$ptag" --arg f "$out" --arg s "$(sha256sum <"$dir/$art.bin" | cut -d' ' -f1)" \
|
||||
'.envs[$a].ota.deltas[$p] = {file: $f, base_sha256: $s}' \
|
||||
"$dist/manifest.json" >"$dist/m.tmp" && mv "$dist/m.tmp" "$dist/manifest.json"
|
||||
else
|
||||
echo "::warning::$art: no delta from $ptag, full package only"
|
||||
rm -f "$dist/$out"
|
||||
fi
|
||||
done <"$bases/releases.jsonl"
|
||||
}
|
||||
# The artifacts: <env>|<extra flags>|<name suffix>|<ota variant>.
|
||||
# PlatformIO appends PLATFORMIO_BUILD_FLAGS after each env's flags:
|
||||
# last -D wins.
|
||||
arts=()
|
||||
declare -A spec=()
|
||||
add() {
|
||||
if [ -n "$ONLY" ] && [[ " $ONLY " != *" $1$3 "* ]]; then return 0; fi
|
||||
arts+=("$1$3")
|
||||
spec[$1$3]="$1|$2|$3|${4:-}"
|
||||
}
|
||||
for env in $ENVS; do add "$env" "" ""; done
|
||||
for env in $OBS_ENVS; do add "$env" "$OBS_FLAGS" "-observer"; done
|
||||
for env in $OTA_ENVS; do add "$env" "-D FW_OTA=1" "-ota" ota; done
|
||||
for env in $OBS_ENVS; do add "$env" "$OBS_FLAGS -D FW_OTA=1" "-observer-ota" observer-ota; done
|
||||
# Builds run PARALLEL at a time: one by one they took 38 of the run's
|
||||
# 40 minutes on a 24-core runner that sat mostly idle.
|
||||
bdir="$RUNNER_TEMP/build" logs="$RUNNER_TEMP/logs"
|
||||
mkdir -p "$bdir" "$logs"
|
||||
# par <function> <name>...: `<function> <name>` PARALLEL at a time,
|
||||
# output to $logs/<name>.log, exit code to $logs/<name>.rc
|
||||
par() {
|
||||
local fn=$1 n running=0
|
||||
shift
|
||||
for n in "$@"; do
|
||||
if [ "$running" -ge "$PARALLEL" ]; then wait -n || :; running=$((running - 1)); fi
|
||||
(set +e; "$fn" "$n"; echo $? >"$logs/$n.rc") >"$logs/$n.log" 2>&1 &
|
||||
running=$((running + 1))
|
||||
done
|
||||
wait
|
||||
}
|
||||
# report <title> <name>...: each log as a group, in this order; fails
|
||||
# the step, with the tails of the failed ones, if any failed
|
||||
report() {
|
||||
local title=$1 n rc failed=()
|
||||
shift
|
||||
for n in "$@"; do
|
||||
rc=$(cat "$logs/$n.rc" 2>/dev/null || echo "?")
|
||||
echo "::group::$n (rc $rc)"
|
||||
cat "$logs/$n.log"
|
||||
echo "::endgroup::"
|
||||
[ "$rc" = 0 ] || failed+=("$n")
|
||||
done
|
||||
[ ${#failed[@]} -eq 0 ] && return 0
|
||||
for n in "${failed[@]}"; do echo "== $n"; tail -n 30 "$logs/$n.log"; done
|
||||
echo "::error::$title failed: ${failed[*]}"
|
||||
exit 1
|
||||
}
|
||||
# 1) install the platforms. Nothing is cached here (reproducible),
|
||||
# so each run downloads platforms, toolchains and libraries: 8 min
|
||||
# env by env up front. One env per distinct platform (+
|
||||
# platform_packages) installs those first, one at a time -- they
|
||||
# are shared in ~/.platformio, concurrent installs would race.
|
||||
envs=$(printf '%s\n' "${arts[@]}" | while read -r a; do echo "${spec[$a]%%|*}"; done | sort -u)
|
||||
mapfile -t first < <(pio project config --json-output | python3 -c '
|
||||
import json, sys
|
||||
want, seen = set(sys.argv[1].split()), set()
|
||||
for name, opts in json.load(sys.stdin):
|
||||
o = dict(opts)
|
||||
key = (o.get("platform"), str(o.get("platform_packages")))
|
||||
if name[4:] in want and name.startswith("env:") and key not in seen:
|
||||
seen.add(key)
|
||||
print(name[4:])' "$envs")
|
||||
# deps <env>: the locked libraries first, then whatever lib_deps still
|
||||
# miss (platform, toolchain, git/file pins), then the lock check --
|
||||
# once per env: the flock keeps its other flag sets waiting
|
||||
locks="$RUNNER_TEMP/locks"
|
||||
mkdir -p "$locks"
|
||||
deps() {
|
||||
flock "$locks/$1" sh -c "python3 tools/pio_lock.py install -e '$1' && pio pkg install -e '$1' -s &&
|
||||
python3 tools/pio_lock.py check -e '$1'"
|
||||
}
|
||||
install() { deps "${1#install-}"; }
|
||||
t0=$SECONDS
|
||||
for env in "${first[@]}"; do par install "install-$env"; done
|
||||
report "install" "${first[@]/#/install-}"
|
||||
echo "installed ${#first[@]} platforms in $((SECONDS - t0)) s"
|
||||
# 2) compile, each artifact into its own build dir (one env comes in
|
||||
# up to four flag sets). An env's libraries come with its first
|
||||
# build (deps), into its own .pio/libdeps/<env>, while other envs
|
||||
# compile; the check fails the build when anything is not exactly
|
||||
# platformio.lock.
|
||||
compile() {
|
||||
local env flags suffix variant
|
||||
IFS='|' read -r env flags suffix variant <<<"${spec[$1]}"
|
||||
deps "$env" || return 1
|
||||
export FW_OTA_VARIANT=$variant PLATFORMIO_BUILD_DIR="$bdir/$1" PLATFORMIO_BUILD_FLAGS="$PUB_FLAGS $flags"
|
||||
pio run -j "$PIO_JOBS" -e "$env" || return 1
|
||||
[ -f "$bdir/$1/$env/firmware.zip" ] || pio run -j "$PIO_JOBS" -t mergebin -e "$env" # ESP32
|
||||
}
|
||||
t1=$SECONDS
|
||||
par compile "${arts[@]}"
|
||||
echo "compiled ${#arts[@]} artifacts in $((SECONDS - t1)) s ($PARALLEL at a time)"
|
||||
report "build" "${arts[@]}"
|
||||
# 3) package in order: manifest.json, deltas and the version are
|
||||
# written one artifact at a time. The OTA tools read .pio/build/<env>,
|
||||
# so that points at the artifact being packaged.
|
||||
mkdir -p .pio/build
|
||||
for a in "${arts[@]}"; do
|
||||
IFS='|' read -r env flags suffix variant <<<"${spec[$a]}"
|
||||
b="$bdir/$a/$env"
|
||||
echo "::group::package $env$suffix"
|
||||
if [ -f "$b/firmware.zip" ]; then # nRF52
|
||||
python3 bin/uf2conv/uf2conv.py "$b/firmware.hex" -c -o "$b/firmware.uf2" -f 0xADA52840
|
||||
cp "$b/firmware.uf2" "$dist/$env$suffix-$TAG.uf2"
|
||||
cp "$b/firmware.zip" "$dist/$env$suffix-$TAG.zip"
|
||||
v=$(grep -m1 -aoE 'v[0-9]+\.[0-9]+\.[0-9]+-tth[0-9a-f]+\+?' "$b/firmware.elf" || true)
|
||||
case "$v" in *+) echo "::error::$env is dirty ($v)"; exit 1 ;; esac
|
||||
[ -n "$version" ] || version="$v"
|
||||
if [ -n "$variant" ]; then
|
||||
rm -rf ".pio/build/$env"
|
||||
ln -s "$b" ".pio/build/$env"
|
||||
unzip -p "$b/firmware.zip" firmware.bin >"$b/firmware.bin"
|
||||
ota_package "$env" "$env$suffix"
|
||||
fi
|
||||
else # ESP32
|
||||
cp "$b/firmware.bin" "$dist/$env$suffix-$TAG.bin"
|
||||
cp "$b/firmware-merged.bin" "$dist/$env$suffix-$TAG-merged.bin"
|
||||
fi
|
||||
echo "::endgroup::"
|
||||
done
|
||||
echo "installed, built and packaged in $((SECONDS - t0)) s"
|
||||
jq --arg c "$(git rev-parse HEAD)" --arg t "$TAG" '.commit = $c | .tag = $t' \
|
||||
"$dist/manifest.json" >"$dist/m.tmp" && mv "$dist/m.tmp" "$dist/manifest.json"
|
||||
cd "$dist"
|
||||
sha256sum -- * >SHA256SUMS
|
||||
ssh-keygen -q -Y sign -f "$okey" -n meshcore-ota SHA256SUMS
|
||||
ssh-keygen -Y verify -f "$GITHUB_WORKSPACE/tools/ota_allowed_signers" -I meshcore-ota@tth-pub \
|
||||
-n meshcore-ota -s SHA256SUMS.sig <SHA256SUMS
|
||||
cat SHA256SUMS
|
||||
echo "version=${version:-tth-$sha}" >>"$GITHUB_OUTPUT"
|
||||
|
||||
- name: Dry run artifact
|
||||
if: env.DRY == 'true'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: pub-release-dry-run
|
||||
path: dist/
|
||||
|
||||
- name: Release
|
||||
if: env.DRY != 'true'
|
||||
env:
|
||||
TOKEN: ${{ secrets.GITEA_TOKEN || github.token }}
|
||||
SHA: ${{ steps.src.outputs.sha }}
|
||||
TAG: ${{ steps.src.outputs.tag }}
|
||||
TITLE: ${{ steps.src.outputs.title }}
|
||||
VERSION: ${{ steps.build.outputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
api="$GITEA/api/v1/repos/$GITHUB_REPOSITORY"
|
||||
auth="header = \"Authorization: token $TOKEN\""
|
||||
readme="$GITEA/$GITHUB_REPOSITORY#o-tomto-forku-meshcore-tth"
|
||||
note=$(cat <<EOF
|
||||
- **BLE PIN \`123456\` a admin heslo \`password\` jsou zástupné.** Po nahrání je změň: \`password <nové>\` (nejvýš 15
|
||||
znaků), \`ble pin <6 číslic>\`.
|
||||
- **Výchozí nastavení pro český mesh** ([meshcore.cz](https://meshcore.cz/)): 869,432 MHz / 62,5 kHz / SF7 / CR5;
|
||||
repeater a room server: zero-hop advert vypnutý, flood advert á 25 h, duty cycle 10 % (\`get dutycycle\`); repeater:
|
||||
regiony \`cz\` a \`cs\`. **Platí jen pro nový nebo smazaný uzel** – nové nahrání ponechá uložené nastavení.
|
||||
- **\`*-observer\`**: repeater s BLE konzolí a buffery \`rxlog\` / \`pktlog\` pro repeater observer. BLE je po nahrání
|
||||
vypnuté: nejdřív \`ble pin\`, pak \`ble on\`.
|
||||
- **RX duty cycle** (\`set radio.rxps\`, jen SX1262) je zabudovaný a vypnutý.
|
||||
- **EXPERIMENTÁLNÍ \`*-ota\` / \`*-observer-ota\`**: totéž s aktualizací firmwaru od admina (\`fw ...\`, i přes
|
||||
mesh). Ke každému plný balíček \`.mcfw\` (USB/BLE) a delta \`.from-<vydání>.mcfw\` od předchozích vydání –
|
||||
přes mesh uzel přijme jen deltu a nikdy starší verzi. Balíčky i \`SHA256SUMS\` jsou podepsané klíčem
|
||||
\`meshcore-ota@tth-pub\` (\`tools/ota_allowed_signers\`).
|
||||
- Ověření: \`ver\` ukáže verzi z řádku *Verze v uzlu* výše. Co fork mění proti upstreamu: [README]($readme).
|
||||
|
||||
<details><summary>English</summary>
|
||||
|
||||
- **BLE PIN \`123456\` and admin password \`password\` are placeholders.** Change them after flashing: \`password
|
||||
<new>\` (15 characters at most), \`ble pin <6 digits>\`.
|
||||
- **Czech mesh defaults** ([meshcore.cz](https://meshcore.cz/)): 869.432 MHz / 62.5 kHz / SF7 / CR5; repeater and room
|
||||
server: zero-hop advert off, flood advert every 25 h, 10 % duty cycle (\`get dutycycle\`); repeater: regions \`cz\`
|
||||
and \`cs\`. **A fresh or erased node only** – a reflash keeps the saved settings.
|
||||
- **\`*-observer\`**: repeater with a BLE console and the \`rxlog\` / \`pktlog\` rings for the repeater observer. BLE
|
||||
is off after flashing: \`ble pin\` first, then \`ble on\`.
|
||||
- **RX duty cycle** (\`set radio.rxps\`, SX1262 only) is built in and off.
|
||||
- **EXPERIMENTAL \`*-ota\` / \`*-observer-ota\`**: the same with admin-pushed firmware update (\`fw ...\`, over the
|
||||
mesh too). Each with a full \`.mcfw\` package (USB/BLE) and a delta \`.from-<release>.mcfw\` from earlier
|
||||
releases -- over the mesh a node takes only a delta and never an older version. Packages and \`SHA256SUMS\`
|
||||
are signed by \`meshcore-ota@tth-pub\` (\`tools/ota_allowed_signers\`).
|
||||
- Check: \`ver\` shows the version from the *Verze v uzlu* (node version) line above. What the fork changes against
|
||||
upstream: [README]($readme).
|
||||
|
||||
</details>
|
||||
EOF
|
||||
)
|
||||
web="$GITEA/$GITHUB_REPOSITORY"
|
||||
# changelog against the newest older release that HEAD descends from
|
||||
prev="" base=""
|
||||
while read -r t c; do
|
||||
# the tag, not the release's target_commitish: Gitea keeps the
|
||||
# commitish from creation, and after a rewrite of the public
|
||||
# history (26. 11. 2026) it named commits no longer in it -- no
|
||||
# base was found and the notes listed the last 20 commits
|
||||
c=$(git rev-parse -q --verify "refs/tags/$t^{commit}" 2>/dev/null || echo "$c")
|
||||
if [ "$c" != "$SHA" ] && git merge-base --is-ancestor "$c" "$SHA" 2>/dev/null; then
|
||||
prev=$t base=$c
|
||||
break
|
||||
fi
|
||||
done < <(curl -sSf --config - "$api/releases?limit=50" <<<"$auth" |
|
||||
jq -r --arg t "$TAG" 'map(select(.tag_name | startswith("tth-") or test("[+]tth[.]")) | select(.tag_name != $t))
|
||||
| sort_by(.created_at) | reverse | .[] | "\(.tag_name) \(.target_commitish)"')
|
||||
# no older release: the last 20 commits of our own line
|
||||
[ -n "$base" ] || base=$(git rev-list --first-parent --max-count=21 "$SHA" | tail -1)
|
||||
# our commits, moved build dependencies, upstream PRs -- the
|
||||
# generator is a script so the notes can be previewed locally
|
||||
changes=$(bash .github/release-notes.sh "$base" "$SHA" "$web")
|
||||
body=$(
|
||||
echo "$TITLE"
|
||||
echo
|
||||
echo "Verze v uzlu · \`ver\`: $VERSION"
|
||||
echo
|
||||
if [ -n "$prev" ]; then
|
||||
echo "Od předchozího vydání · since [$prev]($web/releases/tag/$(jq -rn --arg s "$prev" '$s|@uri'))"
|
||||
echo
|
||||
fi
|
||||
echo "$changes"
|
||||
echo
|
||||
echo "### Po flashi · after flashing"
|
||||
echo
|
||||
echo "$note"
|
||||
echo
|
||||
echo "commit $SHA, run $GITHUB_RUN_NUMBER"
|
||||
)
|
||||
jq -n --arg t "$TAG" --arg c "$SHA" --arg n "$TITLE" --arg b "$body" \
|
||||
'{tag_name: $t, target_commitish: $c, name: $n, body: $b}' >"$RUNNER_TEMP/rel.json"
|
||||
id=$(curl -sSf --config - -X POST -H 'Content-Type: application/json' \
|
||||
--data-binary "@$RUNNER_TEMP/rel.json" "$api/releases" <<<"$auth" | jq -r .id)
|
||||
for f in dist/*; do
|
||||
curl -sSf --config - -X POST -F "attachment=@$f" \
|
||||
"$api/releases/$id/assets?name=$(jq -rn --arg s "${f##*/}" '$s|@uri')" <<<"$auth" >/dev/null
|
||||
echo "uploaded $(basename "$f")"
|
||||
done
|
||||
echo "released $TAG = $VERSION (id $id)"
|
||||
# keep the newest $KEEP, oldest go (with their tags)
|
||||
curl -sSf --config - "$api/releases?limit=50" <<<"$auth" |
|
||||
jq -r --argjson k "$KEEP" 'map(select(.tag_name | startswith("tth-") or test("[+]tth[.]")))
|
||||
| sort_by(.created_at) | reverse | .[$k:][] | "\(.id) \(.tag_name)"' |
|
||||
while read -r old_id old_tag; do
|
||||
curl -sSf --config - -X DELETE "$api/releases/$old_id" <<<"$auth"
|
||||
curl -sSf --config - -X DELETE "$api/tags/$(jq -rn --arg s "$old_tag" '$s|@uri')" <<<"$auth" || true
|
||||
echo "pruned $old_tag"
|
||||
done
|
||||
@@ -20,7 +20,12 @@ jobs:
|
||||
uses: ./.github/actions/setup-build-environment
|
||||
|
||||
- name: Run Unit Tests
|
||||
run: pio test -e native -e native_kiss_modem -vv
|
||||
# native_asan MUSI byt v seznamu. Bounds guardy v Packet::readFrom
|
||||
# zamerne nemeni navratovou hodnotu (odmitnou presne to, co upstream
|
||||
# odmitne az po precteni), takze pod `native` projdou i BEZ nich -- rika
|
||||
# to i hlavicka test_packet_readfrom.cpp. Bez tohohle envu slo ty ctyri
|
||||
# kontroly z Packet.cpp odstranit a CI zustalo zelene.
|
||||
run: pio test -e native -e native_asan -e native_kiss_modem -vv
|
||||
|
||||
- name: Upload Test Results
|
||||
# Upload test results even if the test step failed.
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
# Docs website of this fork: https://tth-pub.pages.rfa.cz/meshcore-tth/
|
||||
#
|
||||
# Runs only in the published repo (tth-pub/meshcore-tth), after a push to main
|
||||
# that touches the docs: .github/docs-site.sh builds the site (mkdocs, theme
|
||||
# mkdocs-terminal, mkdocs.tth.yml) from the public tree -- the export leaves
|
||||
# our operations docs out, so nothing private can end up on it -- and the
|
||||
# result is force-pushed as the only commit of the branch `pages`. A webhook
|
||||
# of the repo (push, branch filter `pages`) tells git-pages on pages.rfa.cz,
|
||||
# which clones the branch anonymously: no token outside this repo's own.
|
||||
# git-pages: roles/git_pages in the proxmox.rfa.cz repo.
|
||||
name: tth-docs
|
||||
|
||||
"on":
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "docs/**"
|
||||
- "README.md"
|
||||
- "mkdocs.tth.yml"
|
||||
- ".github/docs-site.sh"
|
||||
- ".github/workflows/tth-docs.yml"
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: tth-docs
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
env:
|
||||
MKDOCS_VERSION: "1.6.1"
|
||||
MKDOCS_TERMINAL_VERSION: "4.8.0"
|
||||
MARKDOWN_CALLOUTS_VERSION: "0.4.0"
|
||||
PYMDOWN_EXTENSIONS_VERSION: "13.1.2"
|
||||
|
||||
jobs:
|
||||
site:
|
||||
if: github.repository == 'tth-pub/meshcore-tth'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
# No actions/setup-python: its builds need x86-64-v3, the runner has v2
|
||||
# (see tth-tools-lint.yml). mkdocs goes into a venv of the image's python3.
|
||||
- name: Install mkdocs
|
||||
run: |
|
||||
set -euo pipefail
|
||||
SUDO="$(command -v sudo || true)"
|
||||
if ! python3 -m venv "$RUNNER_TEMP/docs"; then
|
||||
$SUDO apt-get update -qq
|
||||
$SUDO apt-get install -y -qq python3 python3-venv
|
||||
python3 -m venv --clear "$RUNNER_TEMP/docs"
|
||||
fi
|
||||
"$RUNNER_TEMP/docs/bin/pip" install --quiet \
|
||||
"mkdocs==$MKDOCS_VERSION" "mkdocs-terminal==$MKDOCS_TERMINAL_VERSION" \
|
||||
"markdown-callouts==$MARKDOWN_CALLOUTS_VERSION" \
|
||||
"pymdown-extensions==$PYMDOWN_EXTENSIONS_VERSION"
|
||||
echo "$RUNNER_TEMP/docs/bin" >>"$GITHUB_PATH"
|
||||
|
||||
- name: Build
|
||||
env:
|
||||
NO_MKDOCS_2_WARNING: "1"
|
||||
run: bash .github/docs-site.sh "$RUNNER_TEMP/site"
|
||||
|
||||
# A worktree shares the checkout's credentials (github.token); the
|
||||
# branch keeps one commit, the site of the newest main.
|
||||
- name: Publish to the pages branch
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git config --global user.name "tth-docs"
|
||||
git config --global user.email "tth-docs@localhost"
|
||||
wt="$RUNNER_TEMP/pages"
|
||||
git worktree add -q --detach "$wt"
|
||||
cd "$wt"
|
||||
git checkout -q --orphan pages-build
|
||||
git rm -rqf .
|
||||
cp -r "$RUNNER_TEMP/site/." .
|
||||
git add -A
|
||||
git commit -q -m "docs site from main ${GITHUB_SHA:0:8}"
|
||||
git push -q -f origin HEAD:refs/heads/pages
|
||||
echo "published ${GITHUB_SHA:0:8} to pages"
|
||||
+17
@@ -17,3 +17,20 @@ compile_commands.json
|
||||
.venv/
|
||||
venv/
|
||||
platformio.local.ini
|
||||
|
||||
# Python bytecode from tools/
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# Claude Code: lokální stav, nepatří do repa (settings.json a skills/ ANO)
|
||||
.claude/settings.local.json
|
||||
.claude/RESUME.md
|
||||
|
||||
# PID soubor lokálního helperu (běhový balast, ne konfigurace)
|
||||
ether.pid
|
||||
|
||||
# data z pochůzkových testů (.tth/tools/walk.sh fetch) — polohy, necommitovat
|
||||
walk-data/
|
||||
|
||||
# raw bench data (measurement nights, watch logs): local only, results go to docs/
|
||||
/logs/
|
||||
@@ -1,3 +1,704 @@
|
||||
## O tomto forku (meshcore-tth)
|
||||
|
||||
*English version [below](#about-this-fork-meshcore-tth) -- experimental
|
||||
firmware, not meant for regular users.*
|
||||
|
||||
> [!WARNING]
|
||||
> **Experimentální firmware – není určený pro běžné uživatele.** Tenhle fork
|
||||
> i všechny jeho releasy jsou osobní vývojová větev pro uzly jedné malé sítě:
|
||||
> rolling release nad upstreamovou větví `dev`, sestavovaný automaticky
|
||||
> zhruba dvakrát denně, bez stabilního kanálu, bez podpory a vyzkoušený jen
|
||||
> na našich deskách. Může obsahovat chyby, které uzel vyřadí z provozu,
|
||||
> a vrátit ho pak jde jen s USB nebo BLE v ruce. Pro běžný provoz nahrajte
|
||||
> oficiální MeshCore ([flasher.meshcore.io](https://flasher.meshcore.io)).
|
||||
|
||||
Fork projektu [meshcore-dev/MeshCore](https://github.com/meshcore-dev/MeshCore),
|
||||
na kterém běží repeatery, senzory a testovací desky malé české sítě na CZ
|
||||
meshi (869,432 MHz). Upstreamové větve `main` a `dev` se slučují automaticky
|
||||
dvakrát denně; všechno níže je navíc nad nimi. Náš kód je ve zdrojácích
|
||||
označený `CUSTOM (TeTeHacko)`. Nic z toho nemění protokol na rádiu.
|
||||
|
||||
Dokumentace forku i upstreamu jako web (anglicky, tahle část česky):
|
||||
<https://tth-pub.pages.rfa.cz/meshcore-tth/>
|
||||
|
||||
### Repeater: antispam (všechno vypínatelné, nic z toho není v upstreamu)
|
||||
|
||||
**Po nahrání je zapnutý jen FairnessLimiter**, s limity se zhruba
|
||||
dvojnásobnou rezervou nad 30 dní skutečného provozu CZ meshe: na kanál dávka
|
||||
100 zpráv a pak jedna za 30 s, na odesílatele 150 a jedna za 10 s, na
|
||||
původce advertu 30 a jeden za 10 min. Je to síť na utržené floody, ne kvóta;
|
||||
`fairness off` ho vypne natrvalo. Okno na adverty, filtry a dry-run jsou
|
||||
vypnuté, dokud je nezapnete.
|
||||
|
||||
* **FairnessLimiter** – token buckety na přeposílané floody podle 1bajtových
|
||||
identifikátorů, které jsou v paketu stejně v čitelné podobě (hash kanálu,
|
||||
hash odesílatele, původce advertu). Port návrhu Beanowa
|
||||
[#1502](https://github.com/meshcore-dev/MeshCore/pull/1502), limity
|
||||
přepočítané z 30 dní skutečného provozu CZ meshe.
|
||||
`fairness <on|off>`, `fairness cap`, `fairness refill`, `fairness grid`; přímo směrovaný provoz se neomezuje nikdy.
|
||||
* **Okno na adverty podle původce** – flood advert každého uzlu se přepošle
|
||||
nejvýš jednou za N hodin (`fairness advert <hours>`, `fairness advert clear`), převzato
|
||||
z AdvertLimiteru [DutchMeshCore](https://github.com/Dutch-MeshCore/MeshCore).
|
||||
Míří na uzly, které advertují každou minutu.
|
||||
* **Dry-run** – `fairness dryrun on` započítá každý verdikt, ale přepošle
|
||||
i tak; `fairness air` ukáže ušetřený (nebo ušetřitelný) airtime podle důvodu.
|
||||
* **Filtr kanálů** – na kanálech, jejichž klíč repeater zná (Public
|
||||
a `#hashtag` kanály), přestane přeposílat zprávy uvedených jmen odesílatelů
|
||||
(`filter add <name>`, `filter del <name>`, `filter list`). Jméno se dá podvrhnout: je to brzda na utrženého
|
||||
bota, ne bezpečnost.
|
||||
* **Blokace přeposílání podle hashe kanálu** – `filter hash add <hex> [secs]`:
|
||||
bez klíče, takže funguje i na soukromých kanálech; příjem se nemění, jen
|
||||
přeposílání. S `s` se kanál neodřízne, ale přiškrtí (jeden paket za `s`
|
||||
sekund).
|
||||
* **Limit stáří zprávy** – `filter age <minutes>` / `filter age off` (volitelné, 1–10080 min):
|
||||
nepřeposílá skupinové zprávy na dešifrovaných kanálech, jejichž čas od
|
||||
odesílatele je starší; bez nastavených hodin repeateru neplatí. Posuzuje
|
||||
hodiny odesílatele, takže zahodí i companiony bez synchronizace času –
|
||||
nastavuj ho na dny.
|
||||
* `filter dryrun on` započítá každý verdikt `filter`, ale přepošle i tak.
|
||||
|
||||
### Diagnostika a provoz
|
||||
|
||||
Všechny příkazy forku, kde je který build má a výchozí hodnoty:
|
||||
[docs/tth-commands.md](docs/tth-commands.md).
|
||||
|
||||
Repeater, room server i senzor (všechno s textovou konzolí) mají:
|
||||
|
||||
* **Watchdogy rádia.** Hardwarový watchdog chytí jen zamrzlou smyčku; dva naše
|
||||
uzly ale byly nalezeny hluché s běžící smyčkou a pomohl až restart.
|
||||
* `set radio.silence <min>` – **hluchý přijímač**: když se za `<min>` minut
|
||||
nepohne čítač přijatých rámců (počítá se i rámec s chybou CRC), uzel
|
||||
napřed znovu nahodí příjem, a když ani to nepomůže, restartuje se. Každý
|
||||
takový restart zdvojnásobí práh pro příští start (až 16×), první přijatý
|
||||
rámec ho vrátí, takže tiché místo neskončí ve smyčce restartů. Uloží se;
|
||||
**ve výchozím stavu vypnutý** (`0`) – práh volte s rezervou nad nejdelší
|
||||
běžné ticho na místě.
|
||||
* **Zaseknuté vysílání** (jen repeater): pakety čekají ve frontě a čítač
|
||||
odeslaných se nehýbe → znovu nahodí rádio, pak restart. Prázdná fronta se
|
||||
nepočítá. **Zapnutý, 15 min** (`RADIO_TXSTALL_MIN`); `set radio.txstall
|
||||
<min>|off` platí jen do restartu.
|
||||
* `get radio.reboots` – kolik restartů watchdogy udělaly (přežije i výpadek
|
||||
napájení); `get boot` – proč se deska naposledy resetovala a záznam
|
||||
o hardfaultu (vypíše se i při startu).
|
||||
* `dfu [uf2|serial|ota]` – spolehlivý reboot do bootloaderu (jen z lokální
|
||||
konzole); `i2c` – sken sběrnice.
|
||||
|
||||
Repeater navíc:
|
||||
|
||||
* `blink` (rozbliká LED, i přes mesh – najdete uzel na stožáru), `txpwr`
|
||||
(vysílací výkon do restartu, s verdiktem RadioLibu), čítače chyb vysílání
|
||||
ve stavové odpovědi.
|
||||
* Jen observer varianty (`*-observer`): textová konzole přes BLE vedle USB,
|
||||
`ble <on|off>` uložené přes reboot (`RPT_BLE_DEFAULT_OFF`: startuje vypnuté),
|
||||
vlastní BLE PIN (`ble pin`), uložený vysílací výkon spojení (`blepwr`),
|
||||
`bleconn`, neblokující BLE vysílání a parametry spojení, které vydrží i na
|
||||
slabém linku.
|
||||
* Taky jen observer varianty: pasivní analyzátor v konzoli – `nodes`
|
||||
(slyšené repeatery a roomy, klíč pro spojení více cest), `rxlog` (každý
|
||||
slyšený rámec: typ, cesta, SNR, RSSI), `pktlog` (surové rámce pro feed
|
||||
observeru), velké stránkované odpovědi.
|
||||
* Jen vlastní buildy, ne releasy:
|
||||
* kanálový bot (`BOT_CHANNEL_PSK`: `!link`, `!path`, `!snr`, `!heard`,
|
||||
`!noise`, `!ping`, `!help`, výběr přes `BOT_COMMANDS`, cooldown na
|
||||
odesílatele, ignore list) – odpovídá, aniž by přeposílal;
|
||||
* `RADIO_DIAG`: `radiostat` (stav přijímače SX1262 bez zásahu) a
|
||||
`radiokick <rx|clrirq|standby|agc>` (jeden krok obnovy, od nejjemnějšího –
|
||||
první, který pomůže, ukáže rozbitou vrstvu);
|
||||
* `PIN_DIAG`: `dio1` (stav přerušení v čipu proti úrovni na pinu – který
|
||||
konec mrtvé linky DIO1 je přerušený);
|
||||
* `LORA_POLL_IRQ`: provoz bez DIO1 pro desku s mrtvou linkou přerušení.
|
||||
|
||||
### Opravy jádra
|
||||
|
||||
* **Ochrana proti přehrání admin příkazů přežije reboot.** Upstream si
|
||||
poslední timestamp klienta drží jen v RAM, takže po každém restartu projde
|
||||
libovolný zachycený příkaz znovu – zachycený `reboot` uzel restartuje
|
||||
pořád dokola. Repeater, room server i sensor ho teď zapíšou do flash dřív,
|
||||
než příkaz provedou (`/s_acl_ts0|1`, střídavě s kontrolním součtem, takže
|
||||
ho nesmaže ani výpadek napájení při zápisu). Timestamp víc než den před
|
||||
hodinami uzlu (`ACL_TS_MAX_AHEAD`) se přijme, ale neuloží, aby companion
|
||||
s rozhozenými hodinami nezamkl admina. Ukládá se jen u adminů: host smí
|
||||
jen číst a s prázdným guest heslem se jím stane kdokoli, takže by každý
|
||||
jeho dotaz znamenal zápis do flash. Klientů se to nijak netýká.
|
||||
* **Hesla nejde hádat přes éter plnou rychlostí.** Upstream kontroluje každý
|
||||
login bez omezení a na špatné heslo ani neodpoví. Po 4 špatných heslech
|
||||
během 3 minut (`LOGIN_FAIL_MAX`, `LOGIN_FAIL_SECS`) se hesla do konce okna
|
||||
nekontrolují. Klient, který už je v ACL jako admin, projde vždy – login
|
||||
jeho jménem nikdo jiný poslat nedokáže, takže útok adminy nezamkne.
|
||||
* **Přehraný login bez hesla už nevyvolá flood odpověď.** Login klienta z ACL
|
||||
s prázdným heslem neměl ochranu proti přehrání; útočník tím nic nezískal,
|
||||
ale každá kopie donutila uzel poslat odpověď floodem přes celý mesh.
|
||||
* TRACE už nepřipisuje cestu za konec payloadu; parsování TRACE/PATH
|
||||
a `Packet::readFrom` hlídají meze.
|
||||
* `markSeen` je zase idempotentní (odesílací cesta ujídala okno deduplikace).
|
||||
* Záložní výpočet v `calcMaxPacketMillis` už nepodteče (uzel na tom ohluchl).
|
||||
* Šířka path hashe se bere z nastavení uzlu na všech cestách vysílání včetně
|
||||
`sendZeroHop`; výchozí jsou 2bajtové path hashe (`PATH_HASH_MODE_DEFAULT`).
|
||||
* Nepovedené vysílání se zařadí znovu s odstupem, místo aby se zahodilo.
|
||||
* **Čas nRF52 uzlu už neposkočí o 4,5 h dopředu.** Obsluha tiku FreeRTOS
|
||||
v Adafruit core přičetla 2^24 tiků naráz, když byl počet tiků byť o jeden
|
||||
před 24bitovým RTC: `millis()`, uptime, airtime a hodiny uzlu skočily
|
||||
o 16 384 s, někdy několikrát za pár minut, a uzel posílal adverty s časem
|
||||
až o 18 h napřed. Framework je proto náš fork
|
||||
[tth-pub/Adafruit_nRF52_Arduino](https://git.rfa.cz/tth-pub/Adafruit_nRF52_Arduino)
|
||||
(meshcore-dev + tahle oprava).
|
||||
* **Zaseknutá I2C sběrnice už uzel nezamrazí.** Když čidlo drží linku dole,
|
||||
`Wire` dřív čekal navždy. Teď vrátí chybu (probe po 100 ms, čtení do ~0,3 s;
|
||||
ne falešné „zařízení odpovědělo“) a sběrnici obnoví, takže čidla po uvolnění zase odpovídají bez
|
||||
restartu. Adafruit PR #873, který převzal i naši opravu; ověřeno na XIAO se
|
||||
SCL na GND.
|
||||
* RSSI každého paketu se zaznamená při příjmu; `ContactInfo` se před
|
||||
částečným vyplněním vynuluje.
|
||||
|
||||
### Napájení, hodiny, GPS
|
||||
|
||||
* GPS duty cycle (`gps duty`), i na T1000-E, kde nebyl: přijímač běží jen
|
||||
kolem synchronizace hodin (jednou denně, po neúspěšném okně znovu za 6 h).
|
||||
Dotaz na polohu přijímač probudí pro příští dotaz.
|
||||
* Uzel bez GPS startuje na čase sestavení firmwaru, ne v roce 2024; hodiny
|
||||
a záznam o hardfaultu přežijí teplý reset (`.noinit`); `clkreboot`.
|
||||
* Na solárních uzlech žádná blikající LED a pomalejší BLE advertising.
|
||||
* Stav baterie jako ikona na konci advertovaného jména: `set batt.icon on`,
|
||||
prahy `set batt.icon.lo <mV>` a `set batt.icon.hi <mV>` (výchozí vypnuté; dlouhé jméno ikonu
|
||||
nepojme a příkaz na to upozorní).
|
||||
* Volitelný RX duty cycle (`set radio.rxps <off|on|balanced|max>`, jemněji
|
||||
`set radio.rxps level <level>` 1–10; port PowerSaving z EasySkyMesh): SX1262 mezi krátkými okny
|
||||
poslechu spí. Ve veřejných buildech je zabudovaný a **vypnutý**; `max` na
|
||||
lavici ušetřil ~2,3 mA bez ztráty paketů ([docs/power.md](docs/power.md)),
|
||||
na ostrém meshi ale jeden náš stožár ztratil 16 % příjmu – zapínat s rozmyslem. Jen
|
||||
SX1262, ne LR1110 (T1000-E).
|
||||
* Podpěťová pojistka při startu (`PWRMGT_VOLTAGE_BOOTLOCK`) je na nRF52
|
||||
**vypnutá**, stejně jako v upstreamu od v1.18.0
|
||||
([#2377](https://github.com/meshcore-dev/MeshCore/pull/2377)): pevný práh
|
||||
3,3 V nepouštěl k životu uzly na LiFePO4 nebo LTO. Firmware tak naběhne na
|
||||
jakékoli chemii článku; před hlubokým vybitím má chránit BMS nebo ochranná
|
||||
destička článku. Konfigurovatelná pojistka podle chemie čeká na upstream
|
||||
([#2088](https://github.com/meshcore-dev/MeshCore/pull/2088)). Výjimkou je
|
||||
`SenseCap_Solar_repeater` (Li-ion, naše stožáry): pojistka je zapnutá
|
||||
a oba prahy jdou nastavit za běhu, i přes mesh jako admin –
|
||||
`set pwr.bootlock <mV>` nebo `off` (výchozí 3300, pod ním uzel nenaběhne a spí,
|
||||
dokud se článek nezotaví) a `set pwr.cutoff <mV>` nebo `off` (výchozí vypnuto,
|
||||
pod ním se běžící uzel vypne); `get pwr` ([docs/power.md](docs/power.md)).
|
||||
|
||||
### Senzory a companiony
|
||||
|
||||
* `simple_sensor`: telemetrie z externí stanice po UART
|
||||
(`BudkaLinkSensorManager`, jeden LPP kanál na veličinu), `sensor read`.
|
||||
* Senzory, které jinak měří nepřetržitě (INA219, INA226, INA260, INA3221,
|
||||
BMP280), mezi čteními telemetrie spí a měří jen na vyžádání; SHTC3 spí už
|
||||
od startu, ne až po prvním čtení. Na lavici bez PR stál INA226 0,34 mA
|
||||
a BMP280 0,42 mA navíc (nápad a první patch pro INA219: Alkel Brostl;
|
||||
upstream PR meshcore-dev/MeshCore#4017). Čipy INA se rozlišují podle ID, takže
|
||||
INA226 už se nedetekuje jako INA219. Odpor bočníku (INA219, INA226, INA3221; INA260 ho má uvnitř) se
|
||||
nastavuje za běhu a ukládá se: `sensor set ina.shunt <mOhm>`.
|
||||
* Nové čidlo **BMP388 / BMP390** (tlak, teplota, výška; adresa 0x77, se SDO na GND
|
||||
0x76; `ENV_INCLUDE_BMP3XX`, výchozí adresa `TELEM_BMP3XX_ADDRESS`). Měří jen na
|
||||
vyžádání a mezi čteními spí; první měření po startu, které je u tohoto čipu
|
||||
nesmyslné, se zahodí už při inicializaci.
|
||||
* Companion: `gps duty` přežije reboot, kopie data sestavení má hlídanou
|
||||
délku. Export privátního klíče, čtení BLE PINu a jeho změna (i přes CLI
|
||||
`set pin`) jdou jen přes spárované BLE, ne přes USB, UART ani WiFi/TCP,
|
||||
a odpověď s klíčem či PINem jde jen tam, odkud přišel dotaz. (Merge v1.17
|
||||
tu kontrolu potichu vyřadil; build bez BLE bere své jediné rozhraní dál
|
||||
jako důvěryhodné.) KISS modem: oprava o jedna vedle při zkracování jména.
|
||||
|
||||
### Veřejné buildy: výchozí nastavení pro český mesh
|
||||
|
||||
Releasy z tohoto repozitáře (`pub-release`) jsou přednastavené pro český
|
||||
mesh podle wiki [meshcore.cz](https://meshcore.cz/), takže čerstvě nahraný
|
||||
uzel nepotřebuje obvyklé kolečko nastavování:
|
||||
|
||||
* rádio 869,432 MHz / 62,5 kHz / SF7 / CR5 (všechny buildy);
|
||||
* repeater a room server: zero-hop advert vypnutý, flood advert každých 25 h,
|
||||
duty cycle 10 % (`get dutycycle` → `10.0%`; zastaralé `af` je 9);
|
||||
* repeater: regiony `cz` a `cs` vedle `*` – vlastní `cz-<kraj>` přidáš přes
|
||||
`region put cz-xxx cz` + `region save`;
|
||||
* 2bajtové path hashe (výchozí v tomto forku);
|
||||
* repeater: filtr kanálů (`filter add <jméno>`) je zabudovaný pro Public,
|
||||
`#meshcore` a `#test`, s prázdným seznamem – nedělá nic, dokud do něj
|
||||
nepřidáš jméno.
|
||||
|
||||
Platí jen pro uzel bez uloženého nastavení (nový nebo po `erase`): nové
|
||||
nahrání ponechá, co už uzel má, a regiony, které jsi smazal a uložil,
|
||||
zůstanou smazané. Jméno a admin heslo si nastav sám.
|
||||
|
||||
**BLE PIN companionu je veřejný `123456`** (desky s displejem si losují
|
||||
vlastní a ukážou ho). Kdo se s ním spáruje, má companion celý: zprávy,
|
||||
kontakty, export privátního klíče. Po prvním spárování ho proto změň
|
||||
v aplikaci. A s deskou v ruce nechrání nic ani PIN, ani heslo: flash není
|
||||
zamčená a bootloader přijme jakýkoli firmware. Ztracený nebo ukradený uzel
|
||||
ber jako vyzrazený – u repeateru změň admin heslo všude, kde bylo stejné,
|
||||
a vyhoď jeho klíč z ACL; u companionu ber kanály, které na něm byly, jako
|
||||
známé.
|
||||
|
||||
Varianty observer (`*_repeater-observer-*`) nRF52 repeaterů (XIAO, SenseCAP
|
||||
Solar, RAK4631, T1000-E, Heltec T114) přidávají buffery `nodes` / `rxlog` /
|
||||
`pktlog` a textovou konzoli přes BLE, aby šel repeater číst přes USB nebo BLE
|
||||
([meshcore-repeater-observer](https://git.rfa.cz/tth-pub/meshcore-repeater-observer)).
|
||||
BLE konzole je po nahrání **vypnutá** (`RPT_BLE_DEFAULT_OFF`). Nemá vlastní
|
||||
přihlášení, jen BLE PIN, a PIN v buildu je veřejný zástupný `123456`. Nejdřív
|
||||
si proto nastav vlastní – v USB konzoli, nebo jako admin přes mesh (vzdálené
|
||||
CLI v aplikaci): `ble pin <6 číslic>` (uloží se a přežije reboot i nové
|
||||
nahrání; zároveň smaže všechny bondy, takže spárovaná zařízení se párují
|
||||
znovu). Teprve pak `ble on` – dokud je PIN zástupný, tyhle buildy ho odmítnou.
|
||||
`ble` ukáže, jestli je PIN `own` nebo `build default`, samotný PIN nikdy.
|
||||
Releasy do `tth-654d53f3` `ble pin` nemají: BLE tam nech vypnuté a používej USB.
|
||||
|
||||
### Nahrání releasu
|
||||
|
||||
Každý release je automatický build nad upstreamovým `dev` (viz upozornění
|
||||
nahoře), ne stabilní verze. Nahrávejte ho jen na uzly, na které dosáhnete,
|
||||
a nový release vždy nejdřív na jeden z nich.
|
||||
|
||||
Soubory jsou v [Releases](https://git.rfa.cz/tth-pub/meshcore-tth/releases).
|
||||
Release se jmenuje podle upstreamové verze a data, např.
|
||||
`v1.18.0+tth.20261112` (druhý téhož dne `.2`), a v popisu má změny od
|
||||
předchozího releasu. Pro každou desku a roli je jedna sada
|
||||
(`<deska>_<role>-<release>`, např. `Xiao_nrf52_repeater-v1.18.0+tth.20261112.zip`):
|
||||
`.zip` a `.uf2` pro nRF52, `.bin` pro ESP32 (`-merged.bin` je celý obraz pro
|
||||
prázdnou desku, obyčejný `.bin` aktualizace). Kontrolní součty jsou
|
||||
v `SHA256SUMS`. Releasy do 12. 11. 2026 se jmenovaly `tth-<sha>`.
|
||||
|
||||
**nRF52 (XIAO, RAK4631, SenseCAP Solar, T1000-E, T114) přes
|
||||
[webový flasher MeshCore](https://flasher.meshcore.io)** – Chrome, Edge nebo
|
||||
Chromium na počítači (Web Serial; ne Firefox ani Safari):
|
||||
|
||||
1. Připoj desku přes USB.
|
||||
2. Klikni na **Custom Firmware** a vyber `.zip` pro svou desku.
|
||||
3. Klikni na **Enter DFU mode** a vyber sériový port desky. Deska se
|
||||
restartuje do bootloaderu a objeví se jako nový port.
|
||||
4. Klikni na **Flash!** a vyber ten nový port. Zhruba 30 s, pak se deska
|
||||
restartuje do nového firmwaru.
|
||||
5. **Console** ve flasheru (nebo jakýkoli sériový terminál, 115200) ověří
|
||||
výsledek: `ver` ukáže `v1.xx.x-tth<sha>`, stejně jako řádek „Verze v uzlu“
|
||||
v popisu releasu.
|
||||
|
||||
**Neklikej na Erase Flash**, pokud nechceš nový uzel: smaže identitu (klíč
|
||||
uzlu a všechno, co ho zná) i veškeré nastavení. Obyčejné nahrání je zachová.
|
||||
|
||||
Vyzkoušeno na XIAO (repeater-observer, 3. 11. 2026). ESP32 `.bin` přes stejné
|
||||
tlačítko Custom Firmware tu vyzkoušené není.
|
||||
|
||||
Bez webového flasheru: na většině desek otevře dvojí stisk resetu bootloader
|
||||
jako USB disk; zkopíruj na něj `.uf2`. Nebo
|
||||
`adafruit-nrfutil dfu serial -pkg <soubor>.zip -p <port> -b 115200` s deskou
|
||||
v bootloaderu.
|
||||
|
||||
Nový uzel po nahrání nastav v konzoli: `set name <jméno>`,
|
||||
`password <admin heslo>` (nejvýš 15 znaků), vlastní region přes
|
||||
`region put cz-<kraj> cz` + `region save`. Repeater přeposílá od prvního
|
||||
startu (výchozí v upstreamu) a tyhle buildy jsou na ostré CZ frekvenci: na
|
||||
stole bez antény dej `set repeat off`, dokud není na místě.
|
||||
|
||||
### Experimentální: aktualizace firmwaru od admina (`*-ota`)
|
||||
|
||||
Každý nRF52 build s textovou konzolí (repeater, observer, room server,
|
||||
senzor) je v releasu ještě jednou jako **experimentální** `*-ota` /
|
||||
`*-observer-ota`. Ten umí přijmout nový firmware od admina příkazy `fw …`:
|
||||
v USB nebo BLE konzoli, nebo **přes mesh jako vzdálené admin CLI**. Bez změny
|
||||
bootloaderu a bez druhé banky: uzel si balíček uloží do volné flash,
|
||||
zkontroluje ho celý (podpis, hashe, nanečisto provedená delta) a přepíše se
|
||||
až na `fw apply`, rutinou běžící z RAM. Když během přepisu vypadne napájení,
|
||||
zůstane v bootloaderu a vrátí se přes USB/BLE DFU.
|
||||
|
||||
* V releasu je ke každému `*-ota` obrazu plný balíček
|
||||
`<deska>_<role>-ota-<release>.mcfw` (jen přes USB/BLE) a delta
|
||||
`….from-<starší release>.mcfw` od každého drženého předchozího releasu,
|
||||
typicky jednotky kB.
|
||||
* **Přes mesh uzel přijme jen deltu, a nikdy ne starší verzi, než má** –
|
||||
vynucuje to uzel, ne nástroj. Plný obraz nebo návrat ke starší verzi jen
|
||||
lokálně (`fw apply downgrade`). `fw apply` čeká na baterii ≥ 3,8 V, pokud
|
||||
uzel neběží z USB.
|
||||
* Balíčky i `SHA256SUMS` jsou podepsané klíčem `meshcore-ota@tth-pub`
|
||||
a `*-ota` obraz jiný podpis nepřijme. Ověření stažených souborů:
|
||||
`ssh-keygen -Y verify -f tools/ota_allowed_signers -I meshcore-ota@tth-pub
|
||||
-n meshcore-ota -s SHA256SUMS.sig < SHA256SUMS`. Vlastní build s vlastním
|
||||
klíčem: `[ota] pubkey` v `platformio.local.ini`.
|
||||
* První `*-ota` obraz se nahraje obyčejně (viz výše), další už jako delta.
|
||||
Nástroje: `tools/ota_push.py` (USB), `tools/ota_mesh_push.py` (přes mesh
|
||||
skrz companion; potřebuje pythonovou knihovnu `meshcore`, admin heslo bere
|
||||
z `[secrets] admin_pw` v `platformio.local.ini`; s `--side` jde přenos po
|
||||
vedlejším kanálu mimo sdílený mesh), `tools/ota_pack.py info`. Přenos samotný
|
||||
je OTA engine kolekce
|
||||
[tth.meshcore](https://git.rfa.cz/tth-pub/meshcore-ansible) (modul
|
||||
`meshcore_fw_ota`), stejný kód pro nástroje i Ansible. Z telefonu: fork
|
||||
aplikace [meshcore-open](https://git.rfa.cz/tth-pub/meshcore-open), správa
|
||||
repeateru → Firmware update (OTA), deltu si najde v releasu sám.
|
||||
Postup a čísla: [docs/ota.md](docs/ota.md).
|
||||
* **Experimentální i v rámci tohoto forku**: obrazy přicházejí s každým
|
||||
releasem (viz upozornění nahoře) a nemají druhou banku ani automatický
|
||||
návrat. Vadný firmware, který nabootuje, běží, dokud nepošlete další;
|
||||
takový, který nenabootuje, chce USB/BLE DFU v ruce. Vyzkoušeno na lavici
|
||||
(XIAO, USB, mesh, vedlejší kanál) a od 13. 11. 2026 na dvou našich
|
||||
stožárech. Proti obrazu, který nabootuje s mrtvým rádiem, jsou watchdogy
|
||||
rádia (viz Diagnostika a provoz): pro uzly, kam posíláte OTA, zapněte
|
||||
`set radio.silence`. Stojí ~10 kB RAM navíc.
|
||||
|
||||
### Sestavení
|
||||
|
||||
* Razítko verze v každém nRF52 envu (`v1.18.0-tth<sha>`, `+` = neuklizený
|
||||
strom), základní verze z upstreamového tagu (`tools/build_version.py`).
|
||||
* `tools/`: nástroje na uzly – konzole (USB, BLE), flashování, testy na
|
||||
lavici, diagnostika ([tools/README.md](tools/README.md)). Desky podle jména
|
||||
bere z lokálního configu mimo repo (`tools/config.example.ini`).
|
||||
* `hardware/cavity-box`: parametrická krabička pro dutinový filtr na stožár.
|
||||
|
||||
---
|
||||
|
||||
## About this fork (meshcore-tth)
|
||||
|
||||
*Česká verze [výše](#o-tomto-forku-meshcore-tth).*
|
||||
|
||||
> [!WARNING]
|
||||
> **Experimental firmware -- not meant for regular users.** This fork and all
|
||||
> its releases are a personal development branch for the nodes of one small
|
||||
> network: a rolling release on upstream `dev`, built automatically about
|
||||
> twice a day, with no stable channel, no support, and tried only on our own
|
||||
> boards. It may carry bugs that take a node out of service, and getting one
|
||||
> back then needs USB or BLE in hand. For everyday use flash the official
|
||||
> MeshCore ([flasher.meshcore.io](https://flasher.meshcore.io)).
|
||||
|
||||
A fork of [meshcore-dev/MeshCore](https://github.com/meshcore-dev/MeshCore)
|
||||
that runs the repeaters, sensors and bench boards of a small Czech network on
|
||||
the CZ mesh (869.432 MHz). Upstream `main` and `dev` are merged automatically
|
||||
twice a day; everything below is on top of that. Our code is marked
|
||||
`CUSTOM (TeTeHacko)` in the source. Nothing here changes the wire protocol.
|
||||
|
||||
The fork's and upstream's docs as a website:
|
||||
<https://tth-pub.pages.rfa.cz/meshcore-tth/>
|
||||
|
||||
### Repeater: antispam (all of it off-switchable, none of it upstream)
|
||||
|
||||
**After flashing only the FairnessLimiter is on**, with limits about twice
|
||||
above 30 days of real CZ mesh traffic: per channel a burst of 100 messages,
|
||||
then one per 30 s; per sender 150 and one per 10 s; per advert origin 30 and
|
||||
one per 10 min. It is a net for runaway floods, not a quota; `fairness off`
|
||||
switches it off for good. The advert window, the filters and dry-run stay
|
||||
off until you turn them on.
|
||||
|
||||
* **FairnessLimiter** -- token buckets on forwarded floods, keyed on the 1-byte
|
||||
ids already in the clear (channel hash, sender hash, advert origin). Port of
|
||||
Beanow's proposal [#1502](https://github.com/meshcore-dev/MeshCore/pull/1502),
|
||||
limits re-sized from 30 days of real CZ traffic.
|
||||
`fairness <on|off>`, `fairness cap`, `fairness refill`, `fairness grid`; direct-routed traffic is never limited.
|
||||
* **Per-origin advert window** -- each node's flood advert forwarded at most
|
||||
once per N hours (`fairness advert <hours>`, `fairness advert clear`), ported from
|
||||
[DutchMeshCore](https://github.com/Dutch-MeshCore/MeshCore)'s AdvertLimiter.
|
||||
Aimed at nodes that re-advertise every minute.
|
||||
* **Dry-run** -- `fairness dryrun on` counts every verdict but forwards anyway;
|
||||
`fairness air` reports the airtime shed (or that would be) per reason.
|
||||
* **Channel filter** -- on channels whose key the repeater knows (Public and
|
||||
`#hashtag` channels), stop forwarding messages of listed sender names
|
||||
(`filter add <name>`, `filter del <name>`, `filter list`). Names are spoofable: it contains a runaway bot,
|
||||
it is not security.
|
||||
* **Channel-hash deny-forward** -- `filter hash add <hex> [secs]`: keyless,
|
||||
works on private channels too; reception is unaffected, only forwarding.
|
||||
With `secs` the channel is throttled (one packet per `secs`) instead of cut.
|
||||
* **Message age limit** -- `filter age <minutes>` / `filter age off` (opt-in, 1-10080 min): do not
|
||||
forward group texts on the decrypted channels whose sender timestamp is
|
||||
older; inactive while the repeater clock is unset. It judges the sender's
|
||||
clock, so companions without a time sync are dropped too -- keep it in days.
|
||||
* `filter dryrun on` counts every `filter` verdict but forwards anyway.
|
||||
|
||||
### Diagnostics and operations
|
||||
|
||||
Every command of the fork, which builds have it and the defaults:
|
||||
[docs/tth-commands.md](docs/tth-commands.md).
|
||||
|
||||
Repeater, room server and sensor (everything with a text console) have:
|
||||
|
||||
* **Radio watchdogs.** The hardware watchdog only catches a frozen loop; two
|
||||
of our nodes were found deaf with the loop running, and only a reboot
|
||||
helped.
|
||||
* `set radio.silence <min>` -- **deaf receiver**: when the received-frame
|
||||
counter does not move for `<min>` minutes (a frame with a CRC error
|
||||
counts), the node re-arms its receiver first and reboots if that does not
|
||||
help either. Each such reboot doubles the threshold for the next boot (up
|
||||
to 16x) and the first frame received resets it, so a quiet site does not
|
||||
end in a reboot loop. Saved; **off by default** (`0`) -- pick a threshold
|
||||
well above the longest normal quiet spell of the site.
|
||||
* **Stalled TX** (repeater only): packets wait in the queue and the sent
|
||||
counter does not move -> re-arm the radio, then reboot. An empty queue
|
||||
never counts. **On, 15 min** (`RADIO_TXSTALL_MIN`); `set radio.txstall
|
||||
<min>|off` holds until the next reboot.
|
||||
* `get radio.reboots` -- reboots done by the watchdogs (survives power
|
||||
loss); `get boot` -- why the board last reset, and the hardfault record
|
||||
(also printed at boot).
|
||||
* `dfu [uf2|serial|ota]` -- a deterministic reboot into the bootloader (local
|
||||
console only); `i2c` -- bus scan.
|
||||
|
||||
The repeater also has:
|
||||
|
||||
* `blink` (flashes the LED, also over the mesh -- finds a node on a mast),
|
||||
`txpwr` (TX power until reboot, with RadioLib's verdict), TX-failure
|
||||
counters in the status reply.
|
||||
* Observer variants only (`*-observer`): text console over BLE next to USB,
|
||||
`ble <on|off>` saved across reboots (`RPT_BLE_DEFAULT_OFF`: starts off), own
|
||||
BLE PIN (`ble pin`), persisted connection TX power (`blepwr`), `bleconn`, a
|
||||
non-blocking BLE TX pump and connection parameters that hold on a weak
|
||||
link.
|
||||
* Also observer variants only: a passive analyzer in the console --
|
||||
`nodes` (heard repeaters/rooms, multi-path join key), `rxlog` (every frame
|
||||
heard, type/path/SNR/RSSI), `pktlog` (raw frames for an observer feed), big
|
||||
paged replies.
|
||||
* Own builds only, not in the releases:
|
||||
* channel bot (`BOT_CHANNEL_PSK`: `!link`, `!path`, `!snr`, `!heard`,
|
||||
`!noise`, `!ping`, `!help`, narrowed by `BOT_COMMANDS`, per-sender
|
||||
cooldown, ignore list) -- answers without repeating;
|
||||
* `RADIO_DIAG`: `radiostat` (SX1262 receiver state, hands off) and
|
||||
`radiokick <rx|clrirq|standby|agc>` (one recovery step at a time, gentlest
|
||||
first -- the first that helps names the broken layer);
|
||||
* `PIN_DIAG`: `dio1` (the chip's IRQ status against the level on the pin --
|
||||
which end of a dead DIO1 line is broken);
|
||||
* `LORA_POLL_IRQ`: DIO1-less operation for a board with a dead IRQ line.
|
||||
|
||||
### Core fixes
|
||||
|
||||
* **Replay protection of admin commands survives a reboot.** Upstream keeps a
|
||||
client's last timestamp in RAM only, so after every restart any captured
|
||||
command is accepted again -- a captured `reboot` reboots the node forever.
|
||||
Repeater, room server and sensor now write it to flash before acting on the
|
||||
command (`/s_acl_ts0|1`, alternating with a checksum, so a power cut mid-write
|
||||
does not lose it). A timestamp more than a day ahead of the node's clock
|
||||
(`ACL_TS_MAX_AHEAD`) is accepted but not stored, so a companion with a runaway
|
||||
clock cannot lock its admin out. Only admins are stored: a guest can only
|
||||
read, and with the empty guest password anybody is one, so its every
|
||||
request would be a flash write. Nothing changes for clients.
|
||||
* **Passwords can no longer be guessed over the air at full speed.** Upstream
|
||||
checks every login without a limit and does not even answer a wrong one.
|
||||
After 4 wrong passwords within 3 minutes (`LOGIN_FAIL_MAX`,
|
||||
`LOGIN_FAIL_SECS`) no password is checked until the window ends. A client
|
||||
that is already an admin in the ACL always gets through -- nobody else can
|
||||
send a login in its name, so the attack cannot lock the admins out.
|
||||
* **A replayed blank-password login no longer floods a reply.** A login from a
|
||||
client in the ACL with an empty password had no replay check; replayed, it
|
||||
gained nothing, but every copy made the node flood its reply over the mesh.
|
||||
* TRACE no longer appends its path past the end of the payload; TRACE/PATH
|
||||
parsing and `Packet::readFrom` are bounds-checked.
|
||||
* `markSeen` is idempotent again (the send path was eating the dedup window).
|
||||
* `calcMaxPacketMillis` fallback no longer underflows (a node went deaf on it).
|
||||
* Path-hash width comes from the node's prefs on every TX path, including
|
||||
`sendZeroHop`; 2-byte path hashes are the default (`PATH_HASH_MODE_DEFAULT`).
|
||||
* Failed transmits are re-queued with backoff instead of dropped.
|
||||
* **An nRF52 node's time no longer jumps 4.5 h ahead.** The FreeRTOS tick
|
||||
handler of the Adafruit core added 2^24 ticks at once when the tick count
|
||||
was even one tick ahead of the 24-bit RTC: `millis()`, uptime, airtime and
|
||||
the node's clock jumped 16384 s, sometimes several times within minutes, and
|
||||
the node sent adverts dated up to 18 h ahead. The framework is therefore our
|
||||
fork [tth-pub/Adafruit_nRF52_Arduino](https://git.rfa.cz/tth-pub/Adafruit_nRF52_Arduino)
|
||||
(meshcore-dev + this fix).
|
||||
* **A stuck I2C bus no longer freezes the node.** With a sensor holding a line
|
||||
low, `Wire` used to wait forever. Now it returns an error (a probe after
|
||||
100 ms, a read within ~0.3 s; not a false "device ACKed") and resets the bus, so the sensors answer again once
|
||||
it is released, without a reboot. Adafruit PR #873, which took our fix in
|
||||
too; tested on a XIAO with SCL tied to GND.
|
||||
* Per-packet RSSI captured at RX; `ContactInfo` zeroed before a partial fill.
|
||||
|
||||
### Power, clock, GPS
|
||||
|
||||
* GPS duty cycle (`gps duty`), also on the T1000-E, which had none: the
|
||||
receiver runs only around a clock sync (once a day, after a window without
|
||||
a fix again in 6 h). A position request warms it for the next request.
|
||||
* A node without GPS starts at its build epoch, not in 2024; the clock and a
|
||||
hardfault record survive a warm reset (`.noinit`); `clkreboot`.
|
||||
* No blinking LED and slower BLE advertising on solar nodes.
|
||||
* Battery level as an icon at the end of the advertised name: `set batt.icon
|
||||
on`, thresholds `set batt.icon.lo <mV>` and `set batt.icon.hi <mV>` (off by default; a long name has
|
||||
no room for it and the command says so).
|
||||
* Optional RX duty cycle (`set radio.rxps <off|on|balanced|max>`, finer
|
||||
`set radio.rxps level <level>` 1-10; ported from EasySkyMesh PowerSaving): the SX1262 sleeps
|
||||
between short listening windows. Built into the public releases and
|
||||
**off**; `max` saved ~2.3 mA on the bench with no packet loss
|
||||
([docs/power.md](docs/power.md)), but on the live mesh one of our masts lost
|
||||
16 % of its reception -- switch it on with care. SX1262 only, not the LR1110
|
||||
(T1000-E).
|
||||
* The nRF52 boot undervoltage lock (`PWRMGT_VOLTAGE_BOOTLOCK`) is **off**,
|
||||
as in upstream since v1.18.0
|
||||
([#2377](https://github.com/meshcore-dev/MeshCore/pull/2377)): its fixed
|
||||
3.3 V threshold kept LiFePO4 and LTO nodes from booting. The firmware boots
|
||||
on any cell chemistry; deep-discharge protection is up to the BMS or the
|
||||
cell's protection board. A configurable, chemistry-aware lock is waiting
|
||||
for upstream ([#2088](https://github.com/meshcore-dev/MeshCore/pull/2088)). The exception
|
||||
is `SenseCap_Solar_repeater` (Li-ion, our masts): the lock is on and both
|
||||
thresholds are settable at runtime, also as an admin over the mesh --
|
||||
`set pwr.bootlock <mV>` or `off` (default 3300; below it the node does not start
|
||||
and sleeps until the cell recovers) and `set pwr.cutoff <mV>` or `off` (default
|
||||
off; below it a running node switches off); `get pwr`
|
||||
([docs/power.md](docs/power.md)).
|
||||
|
||||
### Sensors and companions
|
||||
|
||||
* `simple_sensor`: telemetry from an external station over UART
|
||||
(`BudkaLinkSensorManager`, one LPP channel per meter), `sensor read`.
|
||||
* Sensors that would otherwise convert continuously (INA219, INA226, INA260,
|
||||
INA3221, BMP280) sleep between telemetry reads and measure on demand; the
|
||||
SHTC3 sleeps from init, not only after its first read. On the bench the
|
||||
INA226 cost 0.34 mA and the BMP280 0.42 mA without this (idea and first
|
||||
INA219 patch: Alkel Brostl; upstream PR meshcore-dev/MeshCore#4017). INA chips are told apart by their ID,
|
||||
so an INA226 is no longer taken for an INA219. The shunt (INA219, INA226,
|
||||
INA3221; the INA260 has it inside) is set at runtime and saved:
|
||||
`sensor set ina.shunt <mOhm>`.
|
||||
* New sensor **BMP388 / BMP390** (pressure, temperature, altitude; address 0x77,
|
||||
0x76 with SDO to GND; `ENV_INCLUDE_BMP3XX`, default address
|
||||
`TELEM_BMP3XX_ADDRESS`). It measures on demand and sleeps between reads; the
|
||||
first conversion after boot, which this chip gets wrong, is spent during init.
|
||||
* Companion: `gps duty` persists, bounded build-date copy. Private key
|
||||
export, reading the BLE PIN and changing it (CLI `set pin` included) work
|
||||
only over paired BLE, never over USB, a UART or WiFi/TCP, and the reply that
|
||||
carries the key or PIN goes back only where the request came from. (The
|
||||
v1.17 merge had silently disabled that gate; a build without BLE still
|
||||
trusts its one transport.) KISS modem: off-by-one in the name clamp.
|
||||
|
||||
### Public builds: Czech mesh defaults
|
||||
|
||||
Releases built from this repository (`pub-release`) come preset for the
|
||||
Czech mesh, following the [meshcore.cz](https://meshcore.cz/) wiki, so a
|
||||
freshly flashed node does not need the usual round of settings:
|
||||
|
||||
* radio 869.432 MHz / 62.5 kHz / SF7 / CR5 (all builds);
|
||||
* repeater and room server: zero-hop advert off, flood advert every 25 h,
|
||||
10 % duty cycle (`get dutycycle` → `10.0%`; the deprecated `af` reads 9);
|
||||
* repeater: regions `cz` and `cs` next to `*` -- add your own `cz-<kraj>`
|
||||
with `region put cz-xxx cz` + `region save`;
|
||||
* 2-byte path hashes (this fork's default);
|
||||
* repeater: the channel filter (`filter add <name>`) is built in for Public,
|
||||
`#meshcore` and `#test`, with an empty list -- it does nothing until you
|
||||
add a name.
|
||||
|
||||
They apply only to a node with no saved settings (new, or after an erase):
|
||||
a reflash keeps whatever the node already has, and regions you removed and
|
||||
saved stay removed. Set a name and an admin password yourself.
|
||||
|
||||
**The companion's BLE PIN is the public `123456`** (boards with a display
|
||||
draw their own and show it). Whoever pairs with it owns the companion:
|
||||
messages, contacts, private key export. So change it in the app after the
|
||||
first pairing. And with the board in hand neither the PIN nor a password
|
||||
protects anything: the flash is not locked and the bootloader takes any
|
||||
firmware. Treat a lost or stolen node as compromised -- for a repeater,
|
||||
change the admin password wherever it was the same and drop its key from
|
||||
ACLs; for a companion, treat the channels it held as known.
|
||||
|
||||
Observer variants (`*_repeater-observer-*`) of the nRF52 repeaters (XIAO,
|
||||
SenseCAP Solar, RAK4631, T1000-E, Heltec T114) add the `nodes` / `rxlog` /
|
||||
`pktlog` rings and a text console over BLE, for reading the repeater over
|
||||
USB or BLE ([meshcore-repeater-observer](https://git.rfa.cz/tth-pub/meshcore-repeater-observer)).
|
||||
The BLE console is **off** after flashing (`RPT_BLE_DEFAULT_OFF`). It has no
|
||||
login of its own, only the BLE PIN, and the build's PIN is the public
|
||||
placeholder `123456`. So first set your own -- in the USB console, or as
|
||||
admin over the mesh (remote CLI in the app): `ble pin <6 digits>` (saved, survives a reboot and a reflash; it also drops
|
||||
every existing bond, so paired devices pair again). Only then `ble on` --
|
||||
these builds refuse it while the PIN is still the placeholder. `ble` shows
|
||||
whether the PIN is `own` or `build default`, never the PIN itself. Releases
|
||||
up to `tth-654d53f3` do not have `ble pin`: keep BLE off there and use USB.
|
||||
|
||||
### Flashing a release
|
||||
|
||||
Every release is an automatic build on upstream `dev` (see the warning
|
||||
above), not a stable version. Flash it only on nodes you can reach, and each
|
||||
new release on one of them first.
|
||||
|
||||
Files are in [Releases](https://git.rfa.cz/tth-pub/meshcore-tth/releases).
|
||||
A release is named after the upstream version and the date, e.g.
|
||||
`v1.18.0+tth.20261112` (a second one that day `.2`), and its notes list the
|
||||
changes since the previous release. One set per board and role
|
||||
(`<board>_<role>-<release>`, e.g. `Xiao_nrf52_repeater-v1.18.0+tth.20261112.zip`):
|
||||
`.zip` and `.uf2` for nRF52 boards, `.bin` for ESP32 (`-merged.bin` is the
|
||||
full image for a blank board, the plain `.bin` an update). `SHA256SUMS` lists
|
||||
the checksums. Releases up to 12. 11. 2026 were named `tth-<sha>`.
|
||||
|
||||
**nRF52 (XIAO, RAK4631, SenseCAP Solar, T1000-E, T114) with the
|
||||
[MeshCore web flasher](https://flasher.meshcore.io)** -- Chrome, Edge or
|
||||
Chromium on a computer (Web Serial; not Firefox or Safari):
|
||||
|
||||
1. Connect the board over USB.
|
||||
2. Click **Custom Firmware** and choose the `.zip` for your board.
|
||||
3. Click **Enter DFU mode** and pick the board's serial port. The board
|
||||
restarts into its bootloader and shows up as a new port.
|
||||
4. Click **Flash!** and pick that new port. About 30 s, then the board
|
||||
restarts into the new firmware.
|
||||
5. **Console** in the flasher (or any serial terminal, 115200) checks the
|
||||
result: `ver` shows `v1.xx.x-tth<sha>`, the same as the "Verze v uzlu"
|
||||
(node version) line in the release notes.
|
||||
|
||||
**Do not click Erase Flash** unless you want a new node: it wipes the
|
||||
identity (the node's key and everything that knows it) together with all
|
||||
settings. A plain flash keeps them.
|
||||
|
||||
Tried on a XIAO (repeater-observer, 3. 11. 2026). ESP32 `.bin` through the
|
||||
same Custom Firmware button is untested here.
|
||||
|
||||
Without the web flasher: on most boards a double-tap of reset opens the
|
||||
bootloader as a USB drive; copy the `.uf2` onto it. Or
|
||||
`adafruit-nrfutil dfu serial -pkg <file>.zip -p <port> -b 115200` with the
|
||||
board in the bootloader.
|
||||
|
||||
After flashing a new node, set it up in the console: `set name <name>`,
|
||||
`password <admin password>` (at most 15 characters), your own region with
|
||||
`region put cz-<kraj> cz` + `region save`. A repeater forwards from its
|
||||
first boot (upstream default) and these builds are on the live CZ frequency:
|
||||
on a desk without its antenna, `set repeat off` until it is in place.
|
||||
|
||||
### Experimental: firmware update pushed by the admin (`*-ota`)
|
||||
|
||||
Every nRF52 build with a text console (repeater, observer, room server,
|
||||
sensor) is in the release once more as an **experimental** `*-ota` /
|
||||
`*-observer-ota` image. It takes a new firmware from its admin with the
|
||||
`fw …` commands: on the USB or BLE console, or **over the mesh as remote admin
|
||||
CLI**. No bootloader change, no second bank: the node stores the package in
|
||||
free flash, checks all of it (signature, hashes, the delta applied dry) and
|
||||
rewrites itself only on `fw apply`, from a routine running in RAM. A power
|
||||
cut during the rewrite leaves it in the bootloader, back via USB/BLE DFU.
|
||||
|
||||
* Each `*-ota` image comes with a full package
|
||||
`<board>_<role>-ota-<release>.mcfw` (USB/BLE only) and a delta
|
||||
`….from-<earlier release>.mcfw` from every kept earlier release, typically
|
||||
a few kB.
|
||||
* **Over the mesh a node takes only a delta, and never an older version than
|
||||
it runs** -- enforced by the node, not by the tool. A full image or a step
|
||||
back only locally (`fw apply downgrade`). `fw apply` wants the battery at
|
||||
3.8 V or more unless the node runs on USB.
|
||||
* Packages and `SHA256SUMS` are signed by `meshcore-ota@tth-pub`, and an
|
||||
`*-ota` image accepts no other signature. Checking the downloads:
|
||||
`ssh-keygen -Y verify -f tools/ota_allowed_signers -I meshcore-ota@tth-pub
|
||||
-n meshcore-ota -s SHA256SUMS.sig < SHA256SUMS`. Your own build with your own
|
||||
key: `[ota] pubkey` in `platformio.local.ini`.
|
||||
* The first `*-ota` image is flashed the usual way (above), later ones go as
|
||||
deltas. Tools: `tools/ota_push.py` (USB), `tools/ota_mesh_push.py` (over the
|
||||
mesh through a companion; needs the `meshcore` Python library, takes the
|
||||
admin password from `[secrets] admin_pw` in `platformio.local.ini`; `--side`
|
||||
carries the transfer on a side channel, off the shared mesh),
|
||||
`tools/ota_pack.py info`. The transfer itself is the OTA engine of the
|
||||
[tth.meshcore](https://git.rfa.cz/tth-pub/meshcore-ansible) Ansible
|
||||
collection (module `meshcore_fw_ota`), one code for the tools and Ansible.
|
||||
From a phone: the [meshcore-open](https://git.rfa.cz/tth-pub/meshcore-open)
|
||||
fork, repeater management → Firmware update (OTA), which finds the delta in
|
||||
the release by itself. How it works and bench numbers:
|
||||
[docs/ota.md](docs/ota.md).
|
||||
* **Experimental even within this fork**: the images come with every
|
||||
release (see the warning above) and have no second bank and no automatic
|
||||
rollback. A bad firmware that boots keeps running until you push the next
|
||||
one; one that does not boot needs USB/BLE DFU in hand. Tried on the bench
|
||||
(XIAO, USB, mesh, side channel) and on two of our masts since 13. 11. 2026.
|
||||
The radio watchdogs (see Diagnostics and operations) catch an image that
|
||||
boots with a dead radio: switch `set radio.silence` on for nodes you push
|
||||
to. Costs ~10 kB of RAM.
|
||||
|
||||
### Build
|
||||
|
||||
* Version stamping in every nRF52 env (`v1.18.0-tth<sha>`, `+` = dirty tree),
|
||||
base version from the upstream tag (`tools/build_version.py`).
|
||||
* `tools/`: host tools for the nodes -- consoles (USB, BLE), flashing, bench
|
||||
tests, diagnostics ([tools/README.md](tools/README.md)). Board names come
|
||||
from a local config outside the repo (`tools/config.example.ini`).
|
||||
* `hardware/cavity-box`: parametric enclosure for a cavity filter on a mast.
|
||||
|
||||
---
|
||||
|
||||
*Níže je README upstreamového MeshCore. Jeho flasher, klienti a návody se
|
||||
týkají oficiálního firmwaru, ne releasů tohoto forku. / Below is upstream
|
||||
MeshCore's README: its flasher, clients and guides refer to the official
|
||||
firmware, not to this fork's releases.*
|
||||
|
||||
## About MeshCore
|
||||
|
||||
MeshCore is a lightweight, portable C++ library that enables multi-hop packet routing for embedded projects using LoRa and other packet radios. It is designed for developers who want to create resilient, decentralized communication networks that work without the internet.
|
||||
|
||||
@@ -14,7 +14,34 @@ MEMORY
|
||||
* - Concurrent connection peripheral + central + secure links
|
||||
* - Event Len, HVN queue, Write CMD queue
|
||||
*/
|
||||
RAM (rwx) : ORIGIN = 0x20006000, LENGTH = 0x20040000 - 0x20006000
|
||||
/* CUSTOM (TeTeHacko): reserve 16 B at the end of RAM for a hardfault record
|
||||
* (PC/LR survive soft reset, printed on next boot) — see HardFault_Handler
|
||||
* in the framework and the boot-time printout in main.cpp.
|
||||
*
|
||||
* MEASURED 7. 8. 2026, AND IT UNDERMINES THE PREMISE: keeping an address out of
|
||||
* the linker's region is NOT enough to survive a soft reset on this hardware.
|
||||
* A clock record was tried at 0x2003FFE0 (32 B reserved) and came back as
|
||||
* `00000000 10001000 00000000` after a `reboot` — not zeroed, OVERWRITTEN, and
|
||||
* 0x10001000 is the nRF52 UICR base, i.e. a UICR pointer left on somebody's
|
||||
* stack. The Adafruit bootloader runs before the app on every reset and links
|
||||
* against the full RAM, so its stack starts at 0x20040000 and grows down
|
||||
* through this area; it reached at least 24 B down.
|
||||
*
|
||||
* The hardfault record at 0x2003FFF0 is HIGHER, i.e. the first thing that stack
|
||||
* touches, so it is unlikely to be any safer. Nothing here has ever
|
||||
* demonstrated it surviving. Do not build anything new on this mechanism
|
||||
* without proving retention first, and treat a missing hardfault report as
|
||||
* "unknown" rather than "no fault happened".
|
||||
*
|
||||
* 18. 10. 2026: what DOES survive is the middle of RAM. The clock record now
|
||||
* lives in .noinit (src/helpers/NRF52Board.cpp), which the linker places right
|
||||
* after .bss -- measured on x1 (XIAO, companion): set +30 days, soft `reboot`,
|
||||
* the clock came back +30 days. The hardfault record moved there too
|
||||
* (g_hardfault_record, handler in NRF52Board.cpp) and was proven on x2: a
|
||||
* deliberate fault printed its PC on the next boot. These 16 B are no longer
|
||||
* used by anything; kept only so the RAM layout of existing envs is unchanged.
|
||||
*/
|
||||
RAM (rwx) : ORIGIN = 0x20006000, LENGTH = 0x2003FFF0 - 0x20006000
|
||||
}
|
||||
|
||||
SECTIONS
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
/* Docs site of the meshcore-tth fork (mkdocs.tth.yml, theme mkdocs-terminal,
|
||||
palette "dark"): only what the palette lacks. Green instead of its blue,
|
||||
and the GitHub callouts (> [!WARNING]) the theme does not style. */
|
||||
:root {
|
||||
--primary-color: #5fd38d;
|
||||
--progress-bar-fill: #5fd38d;
|
||||
/* plain black; the palette's 60em column was a thin noodle on a wide
|
||||
screen (user, 2. 12. 2026) */
|
||||
--background-color: #000;
|
||||
--invert-font-color: #000;
|
||||
--code-bg-color: #161616;
|
||||
--page-width: min(110em, 94vw);
|
||||
}
|
||||
|
||||
.admonition {
|
||||
border: 1px solid var(--secondary-color);
|
||||
padding: 0.2em 1em;
|
||||
margin: var(--global-line-height) 0;
|
||||
}
|
||||
.admonition-title {
|
||||
font-weight: bold;
|
||||
margin: 0.4em 0 0;
|
||||
}
|
||||
.admonition.warning, .admonition.caution, .admonition.danger {
|
||||
border-color: #e5a50a;
|
||||
}
|
||||
.admonition.warning > .admonition-title,
|
||||
.admonition.caution > .admonition-title,
|
||||
.admonition.danger > .admonition-title {
|
||||
color: #e5a50a;
|
||||
}
|
||||
.admonition.note > .admonition-title,
|
||||
.admonition.tip > .admonition-title,
|
||||
.admonition.important > .admonition-title {
|
||||
color: var(--primary-color);
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
# BLE/LoRa coexistence — bench reproduction attempt
|
||||
|
||||
Working notes for the DIRECT-forward loss seen on `mast-three` (SenseCap Solar,
|
||||
`SenseCap_Solar_repeater_ble`). Written down because the result is mostly
|
||||
**negative**, and a negative result is only worth anything if the method and its
|
||||
limits are recorded with it.
|
||||
|
||||
## The claim under test
|
||||
|
||||
Commit `f6e9aeca` widened the BLE connection interval from 15–30 ms to 60–80 ms
|
||||
after an A/B on the mast showed ~40 % of DIRECT-route forwards silently lost
|
||||
with an **idle** BLE connection at 15–30 ms. The stated mechanism is that the
|
||||
SoftDevice's per-connection-event preemption disturbs the SX126x TX path
|
||||
(`startTransmit` fail / send-complete timeout).
|
||||
|
||||
The fix is deployed. What was never established is whether a bench rig can
|
||||
**detect** the effect at all — a measurement that reads zero in both the
|
||||
treatment and the control has shown nothing.
|
||||
|
||||
## Rig
|
||||
|
||||
Isolated test mesh on **866.5 MHz** (BW 62.5, SF 8, CR 5). Isolation is by
|
||||
frequency, not by tx power: a hilltop repeater with `RX_BOOSTED_GAIN` hears a
|
||||
few mW just fine. The override is compile-time (`platformio.local.ini`) because
|
||||
`MyMesh.cpp` seeds `_prefs.freq` from `LORA_FREQ`, so the firmware cannot come
|
||||
up on the production frequency even after `erase`.
|
||||
|
||||
| node | board | role |
|
||||
|---|---|---|
|
||||
| `bench-board` | XIAO nRF52840 + Wio-SX1262 | forwarder under test |
|
||||
| `bench-board` | same | paired control / radiating witness |
|
||||
| `bench-board`, `bench-board` | same | probe sources |
|
||||
| `bench-rpt` | SenseCap Solar Node | forwarder, mast-identical hardware |
|
||||
| `tth-s2-rpt` | same | paired control |
|
||||
|
||||
Paired controls differ **only** in `ADVERT_NAME`, verified by diffing strings in
|
||||
the ELF. Any other difference invalidates them.
|
||||
|
||||
### Oracle
|
||||
|
||||
The measured quantity is the node's own `direct_rx − direct_tx` from
|
||||
`stats-packets`: how many DIRECT packets it accepted for forwarding versus how
|
||||
many it actually sent. This is self-normalising — it does not depend on channel
|
||||
conditions or on a receiver hearing anything. `tx_start_fail` and `tx_timeout`
|
||||
are the mechanism-level counters. A second repeater with `repeat off` acts as a
|
||||
radiating witness, so "counted a TX" can be distinguished from "actually
|
||||
radiated".
|
||||
|
||||
Route forcing: a contact is injected into the sender's companion with an
|
||||
explicit `out_path`, so the DM must traverse the node under test.
|
||||
**`out_path_len` is not a hop count** — it is a packed byte, top two bits =
|
||||
hash size − 1, low six = hop count (`Packet.h:85`). One hop with a 2-byte hash
|
||||
is `0x41`, not `1`. The receiver reads the size out of the packet
|
||||
(`Mesh.cpp:93`), so a forced path works regardless of the node's
|
||||
`path.hash.mode`.
|
||||
|
||||
## What was measured
|
||||
|
||||
All cells at a **verified** 22.50 ms connection interval — `bleconn` reports the
|
||||
parameters actually negotiated, because `bleOnSecured()` only requests them and
|
||||
the central may refuse. Without that read-back none of the null results below
|
||||
would mean anything.
|
||||
|
||||
| `blepwr` | ≈RSSI at central | link up | direct_rx | direct_tx | lost | tx_timeout |
|
||||
|---:|---:|---:|---:|---:|---:|---:|
|
||||
| BLE off | — | — | 8 | 8 | 0 | 0 |
|
||||
| 0 dBm | −67 | 100 % | 8 | 8 | 0 | 0 |
|
||||
| −8 | −75 | 100 % | 8 | 8 | 0 | 0 |
|
||||
| −12 | −79 | 100 % | 8 | 8 | 0 | 0 |
|
||||
| −16 | −83 | 87 % | 8 | 8 | 0 | 0 |
|
||||
| −20 | −87 | 27 % | 8 | 8 | 0 | 0 |
|
||||
|
||||
The −20 dBm row is a bonus condition: the link held only a quarter of the
|
||||
window, so the node spent the rest advertising and re-connecting — close to the
|
||||
reconnect churn the mast reports as HCI 0x3E.
|
||||
|
||||
**Ruled out as the missing factor: BLE link margin.** The whole −75..−90 window
|
||||
the mast sits in is covered, at the known-bad interval, with zero loss.
|
||||
|
||||
### Why idle + weak link does nothing
|
||||
|
||||
In idle the connection events carry empty PDUs, whose retransmission costs
|
||||
almost no radio time. The cost of a retransmission scales with payload size, and
|
||||
the mast has a bridge actively draining the console. Hence the `poll` mode in
|
||||
the harness.
|
||||
|
||||
Direction matters too, and it is the reason to weaken **our** side rather than
|
||||
the central's: a connection event ends as soon as either side misses a packet,
|
||||
so if the central misses our PDU we must re-send it at the next anchor — an
|
||||
extra slave TX. If we miss the central's PDU we never transmit in that event at
|
||||
all, and the SoftDevice uses *less* radio.
|
||||
|
||||
## On mast hardware, with the file log on
|
||||
|
||||
Two SenseCap Solar nodes (`bench-rpt` forwarder, `tth-s2-rpt` paired control) —
|
||||
the same board as the mast, so InternalFS logging, INA226/solar telemetry and
|
||||
the SenseCap SPI layout are all in play. Again at a verified 22.50 ms interval
|
||||
(`bleconn`).
|
||||
|
||||
| file log | BLE | direct_rx | direct_tx | lost | tx_timeout | witness |
|
||||
|---|---|---:|---:|---:|---:|---:|
|
||||
| off | off | 8 | 8 | 0 | 0 | +39 |
|
||||
| off | idle, 88 % of window | 8 | 8 | 0 | 0 | +37 |
|
||||
| **on** | off | 8 | 8 | 0 | 0 | +39 |
|
||||
| **on** | idle, 90 % of window | 8 | 8 | 0 | 0 | +40 |
|
||||
|
||||
The logging condition was real, not nominal: `log` afterwards held 69 entries
|
||||
with RX/TX lines timestamped inside the measurement window, i.e. an InternalFS
|
||||
write per packet — the mechanism behind the known deaf windows.
|
||||
|
||||
**Ten cells, 80 forced forwards, zero lost, `tx_timeout` and `tx_start_fail` at
|
||||
zero throughout.** Against the mast's reported ~40 % loss rate this is not a
|
||||
weak null: a single 8-probe cell would miss a true 40 % effect with probability
|
||||
0.6⁸ ≈ 1.7 %, and ten cells make it vanishing. Whatever the mast is doing, it is
|
||||
not reproduced by the connection interval, the BLE link margin, the board, or
|
||||
InternalFS logging — alone or together.
|
||||
|
||||
## Still open
|
||||
|
||||
**Loaded LoRa channel** is the one uncontrolled difference left. Ours is idle;
|
||||
the mast relays flood traffic, so its forwards contend for a busy channel and
|
||||
the TX window lands on a BLE connection event far more often. This cannot be
|
||||
tested legally here: 866.5 is capped at 1 % duty and the 10 % sub-band
|
||||
(869.4–869.65) is where production lives.
|
||||
|
||||
Practical consequence: **f6e9aeca can be neither confirmed nor refuted on the
|
||||
bench.** Deciding whether the 60–80 ms interval is still needed requires
|
||||
measuring on `mast-three` itself — the counters (`stats-packets`, and now
|
||||
`bleconn` to prove which interval is actually in force) are all reachable over
|
||||
its BLE console.
|
||||
|
||||
## Airtime is a hard limit, and the firmware will not enforce it
|
||||
|
||||
866.5 MHz sits in 865–868 (CZ VO-R/10): 25 mW ERP, **1 % duty cycle = 36 s of
|
||||
transmission per hour**. The firmware does not police this — `airtime_factor`
|
||||
defaults to 0 (= 100 %) and is clamped to 9, so the lowest duty MeshCore can
|
||||
enforce is 10 %. The first sweep consumed `tx_air_secs` 27 s in 18 minutes of
|
||||
uptime, a rate of ~2.5 %. Budget the probes: `stats-radio.tx_air_secs` is the
|
||||
ground truth, and the harness aborts before crossing a configured cap.
|
||||
|
||||
`stats-core.queue_len` and `errors` are a required control, not decoration: when
|
||||
the airtime budget runs out the Dispatcher **defers** a forward
|
||||
(`next_tx_time`, `Dispatcher.cpp:101`), which looks identical to loss in the
|
||||
counters. Both were zero throughout.
|
||||
|
||||
## Traps worth remembering
|
||||
|
||||
- **USB and BLE consoles share one `command[160]`.** Two concurrent consoles
|
||||
interleave into one line and crash the node. The harness keeps a strict
|
||||
sequence: counters over USB → close USB → BLE client → probes → stop BLE →
|
||||
counters over USB.
|
||||
- **`Bluefruit.setTxPower()` is advertising-only** (see the commit message for
|
||||
`blepwr`); the connection runs at the SoftDevice default 0 dBm.
|
||||
- **Weakening the link can lock you out of BLE.** Below about −16 dBm the
|
||||
node's replies stop arriving and the value is re-applied on every reconnect
|
||||
(and, since 6. 10. 2026, saved). The way back is `blepwr` over the mesh admin
|
||||
CLI.
|
||||
- **~~Runtime `set tx` does not change radiated LoRa power~~ — retracted.** The
|
||||
original reading (+2 dBm → RSSI −44.1, −9 dBm → −44.0) was made with an
|
||||
instrument that could not report failure: `RadioLibWrapper::setTxPower()`
|
||||
discarded RadioLib's status, so a refused request looked exactly like an
|
||||
accepted one. Re-measured 2026-08-04 on the repeater build with `txpwr`
|
||||
confirming each step, x1 transmitting and x4 as witness:
|
||||
|
||||
| `txpwr` | witness `last_rssi` |
|
||||
|---:|---:|
|
||||
| +22 | 0 dBm *(saturated)* |
|
||||
| +14 | −1 dBm *(saturated)* |
|
||||
| +6 | −7 dBm |
|
||||
| 0 | −18 dBm |
|
||||
| −9 | −28 dBm |
|
||||
|
||||
31 dB of command produced 28 dB of RSSI, and the witness `recv` counter rose
|
||||
by one at every step, so no point was missed. Radiated power does follow the
|
||||
setting. The top two points are saturated — the boards were ~10 cm apart — so
|
||||
the usable range of that particular rig starts around +6 dBm; characterising
|
||||
the top end needs attenuation or distance, not a bigger number.
|
||||
|
||||
The lesson is not about tx power. It is that a null result from an instrument
|
||||
which cannot distinguish "refused" from "no effect" is not a result at all.
|
||||
|
||||
## The two commands this bench added
|
||||
|
||||
Both live in `examples/simple_repeater/main.cpp` and are repeater-only.
|
||||
|
||||
### `bleconn` — what the link is actually doing
|
||||
|
||||
```
|
||||
bleconn
|
||||
-> BLE conn: interval 75.00 ms (req 60-80), latency 0, sup timeout 4000 ms [live]
|
||||
```
|
||||
|
||||
Reports the **negotiated** connection parameters, not the requested ones. The
|
||||
central is free to ignore a peripheral's request, so this is the only way to
|
||||
know whether a change like `f6e9aeca` (widening the requested interval to
|
||||
60–80 ms) is in force on a node you cannot see. The trailing `[live]` /
|
||||
`[last]` says whether a client is connected right now or these are the values
|
||||
from the last one; before any client has ever connected it answers
|
||||
`nothing seen yet`.
|
||||
|
||||
### `blepwr [dBm|default]` — connection TX power, saved
|
||||
|
||||
```
|
||||
blepwr # report: BLE conn tx: 0 dBm, adv tx: 8 dBm
|
||||
blepwr 8 # set, apply to live connections and save
|
||||
blepwr default # forget the saved value, back to RPT_BLE_CONN_TX_POWER
|
||||
```
|
||||
|
||||
The reply carries how many live connections accepted the value
|
||||
(`OK - BLE conn tx 8 dBm (1/1 conn), saved`) because the nRF52840 only takes
|
||||
−40, −20, −16, −12, −8, −4, 0 and 2..8 dBm; anything else is rejected and is
|
||||
*not* latched or saved, so a typo cannot arm itself for the next reconnect.
|
||||
The value lives in `/ble_pwr` in InternalFS, so it survives a reboot and also a
|
||||
reflash with a different build default: an explicit value is pinned even when
|
||||
it equals the default (no file = follow `RPT_BLE_CONN_TX_POWER`, which
|
||||
mast-three's env sets to 8).
|
||||
|
||||
Sets `BLE_GAP_TX_POWER_ROLE_CONN`, which is **independent of**
|
||||
`Bluefruit.setTxPower()` — that one only affects advertising, despite reading
|
||||
like a global. The connection otherwise runs at the SoftDevice default of
|
||||
0 dBm; the compile-time starting value is `RPT_BLE_CONN_TX_POWER`.
|
||||
|
||||
The value is re-applied on every 'secured' event and saved, so a setting weak
|
||||
enough to break the link persists across reconnects and reboots — at −40 dBm
|
||||
during this bench it locked the BLE console out. Fix it over the mesh admin
|
||||
CLI (`blepwr 0`), which does not depend on BLE. Until 6. 10. 2026 a weakening
|
||||
auto-reverted after 5 minutes and nothing was saved; that went away once the
|
||||
value started to be saved, because a revert that the next reboot undoes again
|
||||
only made the state harder to read.
|
||||
@@ -0,0 +1,64 @@
|
||||
# Budka link — a Chytra Budka as a sensor source
|
||||
|
||||
A Chytra Budka (ESP32-S3 bird box) sends its readings over a one-way UART line
|
||||
to a XIAO nRF52840 running `simple_sensor`; the sensor serves them as
|
||||
CayenneLPP telemetry to anyone on the mesh. The line format and the budka side
|
||||
are documented in the chytra-budka repo, `firmware/MESHCORE.md`.
|
||||
|
||||
## Build
|
||||
|
||||
`BudkaLinkSensorManager` (`src/helpers/sensors/`) replaces the variant's
|
||||
`EnvironmentSensorManager` when the env defines `BUDKA_LINK_RX_PIN`; every
|
||||
other env is unchanged.
|
||||
|
||||
```ini
|
||||
[env:Xiao_x1_budka] ; platformio.local.ini
|
||||
extends = env:Xiao_nrf52_sensor
|
||||
build_flags =
|
||||
${env:Xiao_nrf52_sensor.build_flags}
|
||||
${test_radio.build_flags} ; bench: test band only
|
||||
-D BUDKA_LINK_RX_PIN=0 ; D0 = the only pad LoRa + I²C leave free
|
||||
```
|
||||
|
||||
Optional: `BUDKA_LINK_TX_PIN` (default `LED_GREEN` — nothing is ever sent, the
|
||||
idle-high line keeps that LED dark), `BUDKA_LINK_BAUD` (115200),
|
||||
`BUDKA_LINK_METERS` (3), `BUDKA_LINK_STALE_MS` (120 s).
|
||||
|
||||
## Wiring
|
||||
|
||||
Budka `mc_tx` pad → XIAO **D0**, GND ↔ GND, each board on its own USB. A
|
||||
1 kΩ series resistor protects against back-powering when one side is off.
|
||||
|
||||
## Telemetry layout
|
||||
|
||||
| channel | content |
|
||||
|---|---|
|
||||
| 1 | the node itself |
|
||||
| next | budka: temperature, humidity, pressure, motion count (generic sensor) |
|
||||
| next + k | UC96 meter *k*: voltage, current, power (analog input), energy (kWh) |
|
||||
|
||||
A line with a bad checksum is dropped whole; a value not refreshed for 2 min is
|
||||
left out. Meter channels stay reserved while a meter is missing.
|
||||
|
||||
Read it with `.tth/tools/budka_telem.py <companion-port> <sensor-name>`. The sensor
|
||||
answers only clients in its ACL — a request from anyone else is dropped
|
||||
(`recv matches no peers` in a `MESH_DEBUG` build). Add the companion from the
|
||||
sensor's USB console with `setperm <companion-pubkey> 1`, or log in as admin.
|
||||
The port may be a pyserial URL (`socket://…` for an openHop companion), and the
|
||||
name may be the sensor's public key when the companion does not have it yet.
|
||||
|
||||
## Bench result (13. 10. 2026)
|
||||
|
||||
x1 (sensor, test band) fed by the bench budka; x4 as USB companion:
|
||||
|
||||
```
|
||||
ch2 temp_C 25.3 humidity_% 59.0 generic 29
|
||||
ch3 voltage_V 4.94 current_A 0.10 analog_in 0.49 energy_kWh 0.111
|
||||
ch4 voltage_V 4.94 current_A 0.18 analog_in 0.89 energy_kWh 0.311
|
||||
```
|
||||
|
||||
## Not done
|
||||
|
||||
Alerts (reed opened, budka WiFi down) and the return direction (mesh → budka).
|
||||
The sensor build has no `dfu` console command — reflash with
|
||||
`pio run -t upload`, one touch per power session.
|
||||
+221
-2
@@ -44,23 +44,43 @@ This document provides an overview of CLI commands that can be sent to MeshCore
|
||||
---
|
||||
|
||||
### Reset the clock and reboot
|
||||
*meshcore-tth addition.*
|
||||
|
||||
**Usage:**
|
||||
- `clkreboot`
|
||||
|
||||
**Note:** No reply is sent.
|
||||
|
||||
Resets the clock to the firmware's build epoch (or, on an unstamped build, the
|
||||
upstream 15 May 2024 literal) and reboots. This is the **only** way to move a
|
||||
clock backwards: `time` and `clock sync` both refuse to.
|
||||
|
||||
---
|
||||
|
||||
### Sync the clock with the remote device
|
||||
**Usage:**
|
||||
- `clock sync`
|
||||
|
||||
Takes the time from the *packet's* `sender_timestamp`, so it works **only over
|
||||
the remote admin CLI**, never from the USB or BLE console — those pass
|
||||
`sender_timestamp = 0` (they share one command buffer, see
|
||||
`examples/simple_repeater/main.cpp`), and `0 > curr` is never true, so a local
|
||||
`clock sync` always answers `ERR: clock cannot go backwards`. Use `time <epoch>`
|
||||
locally.
|
||||
|
||||
---
|
||||
|
||||
### Display current time in UTC
|
||||
**Usage:**
|
||||
- `clock`
|
||||
|
||||
**Reply:** `HH:MM - D/M/YYYY UTC (epoch <seconds>)`
|
||||
|
||||
The epoch is a meshcore-tth addition. The human part is minutes only, so a host
|
||||
comparing clocks cannot see a difference smaller than a minute and has to leave
|
||||
a deadband of over 59 s; the epoch makes the comparison exact. It is appended,
|
||||
so anything that only prints the reply is unaffected.
|
||||
|
||||
---
|
||||
|
||||
### Set the time to a specific timestamp
|
||||
@@ -70,6 +90,23 @@ This document provides an overview of CLI commands that can be sent to MeshCore
|
||||
**Parameters:**
|
||||
- `epoch_seconds`: Unix epoch time
|
||||
|
||||
Refuses to go backwards (`secs > curr`), answering
|
||||
`(ERR: clock cannot go backwards)`. That reply usually means the clock was
|
||||
already right, so treat it as success and judge by reading `clock` back.
|
||||
|
||||
**Where the clock comes from if nobody sets it.** Without GPS and without an
|
||||
I2C RTC the clock is volatile: it starts at the build epoch and only ticks from
|
||||
`millis()`. It is worth setting, because the RTC stamps every advert the node
|
||||
transmits and a receiver drops a stale timestamp as a replay. Automatic sources,
|
||||
in order of preference:
|
||||
|
||||
- **GPS** (`gps duty` is enough — see `docs/power.md`);
|
||||
- **an attached host** — `tools/ble_cli.py <MAC> "time {epoch}"`, the
|
||||
`meshcore-ble-bridge`/`meshcore-serial-bridge` scrape, or
|
||||
`tools/xiao_uf2_flash.sh`, which sets it right after every flash;
|
||||
- **the build epoch**, which is where a freshly flashed board starts, and
|
||||
which needs nothing at all.
|
||||
|
||||
---
|
||||
|
||||
### Send a flood advert
|
||||
@@ -253,7 +290,7 @@ Refer to the node's manual for the correct settings to use.
|
||||
- `set tx <dbm>`
|
||||
|
||||
**Parameters:**
|
||||
- `dbm`: Power level in dBm (1-22)
|
||||
- `dbm`: Power level in dBm (-9 to 22 on SX126x; meshcore-tth refuses values out of range or not taken by the radio)
|
||||
|
||||
**Set by build flag:** `LORA_TX_POWER`
|
||||
|
||||
@@ -361,6 +398,57 @@ Refer to the node's manual for the correct settings to use.
|
||||
|
||||
---
|
||||
|
||||
#### Show battery state as an icon on the advertised name
|
||||
|
||||
*meshcore-tth addition.* Appends a solar marker and a charge level to the name
|
||||
carried in adverts, so anyone who hears the node can see its state without
|
||||
logging in for telemetry. Off by default.
|
||||
|
||||
**Usage:**
|
||||
- `get batt.icon`
|
||||
- `set batt.icon <on|off>`
|
||||
|
||||
**Default:** `off`
|
||||
|
||||
**Glyphs:** `☀` permanently (solar node), then one of `▁▂▃▄▅▆▇█`
|
||||
for the charge level -- or `⚡` instead of the level while the node runs on
|
||||
external power (USB), where VBAT reads the charger rather than the cell.
|
||||
|
||||
**Note:** The indicator costs 6 bytes of the name (3 + 3), which with a
|
||||
position in the advert leaves 17. Unicode has only two battery emoji and no
|
||||
"half full" one, and at 4 bytes each they do not fit -- hence block elements,
|
||||
which are 3 bytes and come in eight steps. If the name is too long the whole
|
||||
indicator is dropped rather than truncated, and both `set` and `get` say so.
|
||||
|
||||
**Note:** Every level is the same byte width on purpose. A name that changed
|
||||
length with the charge would be re-truncated at some steps and not others, and
|
||||
every client that heard it would rewrite the contact.
|
||||
|
||||
**Note:** Switching is hysteretic (`BATT_ICON_HYST_MV`, default 50 mV) and
|
||||
asymmetric -- the level drops as soon as the voltage crosses a boundary but
|
||||
climbs only once clear of it. The measured daily swing of a solar node under
|
||||
weak sun is 38-46 mV and the drift 13 mV/day, so at eight levels the name
|
||||
changes roughly once a week.
|
||||
|
||||
---
|
||||
|
||||
#### Battery scale for the name icon
|
||||
*meshcore-tth addition.*
|
||||
|
||||
**Usage:**
|
||||
- `get batt.icon.lo` / `set batt.icon.lo <millivolts>`
|
||||
- `get batt.icon.hi` / `set batt.icon.hi <millivolts>`
|
||||
|
||||
**Set by build flag:** `BATT_ICON_LO_MV`, `BATT_ICON_HI_MV`
|
||||
|
||||
**Default:** `3300` and `4200` -- the same 1S Li-Ion scale the dashboards use,
|
||||
so the icon and the Grafana percentage tell one story.
|
||||
|
||||
**Parameters:**
|
||||
- `millivolts`: `2500`..`4500`, or `0` to use the build default
|
||||
|
||||
---
|
||||
|
||||
#### View or change this node's latitude
|
||||
**Usage:**
|
||||
- `get lat`
|
||||
@@ -514,6 +602,49 @@ Refer to the node's manual for the correct settings to use.
|
||||
|
||||
---
|
||||
|
||||
#### View or change the RX duty cycle (rxps)
|
||||
*meshcore-tth addition.*
|
||||
|
||||
**Usage:**
|
||||
- `get radio.rxps`
|
||||
- `set radio.rxps <off|on|balanced|max|overdrive|riskyWorkingMax>`
|
||||
- `set radio.rxps <max|overdrive|riskyWorkingMax> preamble <16|32>`
|
||||
- `set radio.rxps level <level> [preamble <16|32>]`
|
||||
- `set radio.rxps <level>`
|
||||
- `set radio.rxps <rx_us> <sleep_us>`
|
||||
|
||||
The SX1262 sleeps between short listening windows (`SetRxDutyCycle`) instead
|
||||
of listening all the time, and stays awake through a packet once it hears a
|
||||
preamble. Ported from EasySkyMesh PowerSaving v18 (IoTThinks). Repeater, room
|
||||
server and sensor; SX1262 only (an LR11x0 reports `supported=no`). Present
|
||||
only in builds with `-D WITH_RX_POWERSAVING` (the public releases have it) and
|
||||
off until you set it; the setting is saved.
|
||||
|
||||
**Parameters:**
|
||||
- `on` (= `conservative`, level 3), `balanced` (level 6), `max` (level 8): the
|
||||
higher the level, the longer the sleep. The named presets assume senders
|
||||
with a 16-symbol preamble (the MeshCore default), so they are safe on a
|
||||
mixed mesh.
|
||||
- `level`: the same scale by number, 1..10; without `preamble` it follows the SF.
|
||||
9 (`overdrive`) and 10 (`riskyWorkingMax`) are past the datasheet's timing
|
||||
condition -- 10 is known to lose packets.
|
||||
- `<rx_us> <sleep_us>`: raw window lengths.
|
||||
|
||||
`get radio.rxps` shows the requested and the effective state
|
||||
(`desired=on,effective=armed`), the window lengths and two error counters. If
|
||||
arming fails three times in a row, the radio falls back to continuous RX by
|
||||
itself (`effective=continuous`, `fail` counts up). The noise-floor calibration
|
||||
also runs in continuous RX.
|
||||
|
||||
**Default:** `off`
|
||||
|
||||
**Note:** Measured 12. 11. 2026 on a XIAO nRF52840 + Wio-SX1262 at 5 V
|
||||
(866.5 MHz / SF8 / BW62.5, A/B/A/B, 15 min cells): `max` saves **~2.3 mA**
|
||||
(cell repeatability 0.3 mA). A 3-board zero-hop test lost nothing on `max`
|
||||
(0/240 over two runs, the second on the public release). See `docs/power.md`.
|
||||
|
||||
---
|
||||
|
||||
### Routing
|
||||
|
||||
#### View or change this node's repeat flag
|
||||
@@ -690,6 +821,61 @@ Refer to the node's manual for the correct settings to use.
|
||||
|
||||
---
|
||||
|
||||
#### Radio silence watchdog (repeater, sensor, room server)
|
||||
*meshcore-tth addition.*
|
||||
|
||||
**Usage:**
|
||||
- `get radio.silence`
|
||||
- `set radio.silence <minutes>`
|
||||
- `get radio.reboots`
|
||||
|
||||
**Parameters:**
|
||||
- `minutes`: 1-1440, or `0`/`off` to disable.
|
||||
|
||||
**Description:** Recovers a receiver that has gone deaf while the node keeps running (the hardware watchdog only catches a frozen loop). After `minutes` without a single received frame — a receive error counts as heard, too — the receiver is re-armed (IRQs cleared, RX restarted). If nothing arrives within a further quarter of the threshold (at least 5 minutes), the node reboots.
|
||||
|
||||
To keep a quiet site out of a reboot loop, each such reboot doubles the threshold for the next boot (up to 16×); the first frame received afterwards resets it. `get radio.silence` shows the threshold, the current multiplier, how long the receiver has been quiet and the stage (0 healthy, 1 re-armed). `get radio.reboots` counts the reboots done by this watchdog; it survives power loss. Pick a threshold well above the longest quiet spell the site normally has.
|
||||
|
||||
**Default:** `0` (off)
|
||||
|
||||
---
|
||||
|
||||
#### TX stall watchdog (repeater)
|
||||
*meshcore-tth addition.*
|
||||
|
||||
**Usage:**
|
||||
- `get radio.txstall`
|
||||
- `set radio.txstall <minutes>`
|
||||
|
||||
**Parameters:**
|
||||
- `minutes`: 1-1440, or `0`/`off` to disable. Not saved: the build default (`RADIO_TXSTALL_MIN`) is back after a reboot.
|
||||
|
||||
**Description:** Recovers a node that still receives but no longer transmits. If packets wait in the outbound queue and the sent counter does not move for `minutes`, the radio is re-armed (IRQs cleared, back to standby); if still nothing goes out within a further quarter of the threshold (at least 5 minutes), the node reboots. An empty queue never counts, so a quiet site cannot trigger it. `get radio.txstall` shows the threshold, the queue (in total and due now), how long nothing has been sent and the stage (0 healthy, 1 re-armed). Its reboots are counted in `get radio.reboots` and are logged with the queue numbers.
|
||||
|
||||
**Default:** `15`
|
||||
|
||||
---
|
||||
|
||||
#### Reboot into the bootloader (repeater, sensor, room server; nRF52, local console only)
|
||||
*meshcore-tth addition.*
|
||||
|
||||
**Usage:**
|
||||
- `dfu [uf2|serial|ota]`
|
||||
|
||||
**Description:** Reboots straight into the Adafruit bootloader: `uf2` (default) brings up the UF2 drive, `serial` only the CDC port for `adafruit-nrfutil`, `ota` BLE DFU. Refused over the mesh, where it would leave the node waiting in the bootloader with no way back.
|
||||
|
||||
---
|
||||
|
||||
#### Why the board last reset (repeater, sensor, room server)
|
||||
*meshcore-tth addition.*
|
||||
|
||||
**Usage:**
|
||||
- `get boot`
|
||||
|
||||
**Description:** The reset reason latched at boot (`RESETREAS` on nRF52: `0x1` reset pin, `0x2` watchdog, `0x4` software reset, `0x8` lockup, `0` power-on) and, if the board crashed, the hardfault record (PC, LR, PSR). The same is printed once at boot, but on a build without a settle delay the console is not open yet at that moment.
|
||||
|
||||
---
|
||||
|
||||
#### Enable or disable Multi-Acks support
|
||||
**Usage:**
|
||||
- `get multi.acks`
|
||||
@@ -1068,10 +1254,23 @@ region save
|
||||
- `gps <state>`
|
||||
|
||||
**Parameters:**
|
||||
- `state`: `on`|`off`
|
||||
- `state`: `on`|`off`|`duty`
|
||||
|
||||
**Default:** `off`
|
||||
|
||||
**Note:** In duty-cycle mode `gps` answers `duty, {awake|asleep}, {fix|no fix}, {sat count} sats`.
|
||||
|
||||
*meshcore-tth addition:* `gps duty` powers the receiver only around a clock sync and cuts it in between.
|
||||
It is meant for a node that runs GPS purely to keep its (volatile) RTC set — a
|
||||
mast or solar repeater — where a receiver drawing tens of mA continuously
|
||||
dwarfs the rest of the power budget. Unlike `gps period`, every attempt is
|
||||
capped even before the first fix ever, so a node that never sees the sky does
|
||||
not keep the receiver powered. It sets `gps period` to 0. The position still
|
||||
comes from prefs (see `set advert.loc`), so duty mode does not affect what a repeater
|
||||
advertises. `gps on` / `gps off` leave duty mode. Build-time knobs:
|
||||
`GPS_DUTY_SYNC_INTERVAL_SECS` (86400), `GPS_DUTY_MAX_AWAKE_SECS` (300, the cap on
|
||||
one attempt) and `GPS_DUTY_RETRY_SECS` (21600, backoff after a window with no fix).
|
||||
|
||||
---
|
||||
|
||||
#### View or change the GPS acquisition period
|
||||
@@ -1211,6 +1410,26 @@ Covers serial NMEA receivers (`MicroNMEALocationProvider`).
|
||||
|
||||
---
|
||||
|
||||
#### Set the INA current sensor's shunt resistor
|
||||
*meshcore-tth addition.*
|
||||
|
||||
**Usage:**
|
||||
- `sensor get ina.shunt`
|
||||
- `sensor set ina.shunt <mOhm>`
|
||||
|
||||
**Parameters:**
|
||||
- `mOhm`: the shunt on the module, in milliohms (`10` for a shunt marked `R010`,
|
||||
`100` for `R100`); `0` = the build's value (100 mOhm unless the build sets
|
||||
`TELEM_INA219_SHUNT_VALUE` / `TELEM_INA226_SHUNT_VALUE` / `TELEM_INA3221_SHUNT_VALUE`)
|
||||
|
||||
**Note:** Listed only when an INA219, INA226 or INA3221 was detected at boot.
|
||||
Saved, applies at once and survives a reboot; it also works over the mesh as
|
||||
admin, and on a companion as the custom variable `ina.shunt`. With the wrong value
|
||||
the current is off by the ratio -- LaskaKit's INA226 modules carry 10 mOhm, the
|
||||
default assumes 100. Current is reported in steps of 1 mA (CayenneLPP).
|
||||
|
||||
---
|
||||
|
||||
### Bridge (When bridge support is compiled in)
|
||||
|
||||
#### View the compiled bridge type
|
||||
|
||||
@@ -123,7 +123,7 @@ Radio parameters are common to all roles and handled by `CommonRadioPrefs`.
|
||||
- `set tx <dbm>`
|
||||
|
||||
**Parameters:**
|
||||
- `dbm`: Power level in dBm (1-22)
|
||||
- `dbm`: Power level in dBm (-9 to 22 on SX126x; meshcore-tth refuses values out of range or not taken by the radio)
|
||||
|
||||
**Set by build flag:** `LORA_TX_POWER`
|
||||
|
||||
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
# Admin-pushed firmware update (experimental `-ota` images)
|
||||
|
||||
> [!WARNING]
|
||||
> Part of an experimental fork, not meant for regular users: its releases
|
||||
> are a rolling release on MeshCore `dev` (see the [README](../README.md)).
|
||||
|
||||
The `*-ota` and `*-observer-ota` images of this fork's releases can take a new
|
||||
firmware from their admin -- over the USB or BLE console, or **over the mesh,
|
||||
as remote admin CLI**. Nothing changes in the bootloader and there is no second
|
||||
bank: the node stores the package in free flash, checks all of it, and only on
|
||||
an explicit `fw apply` rewrites itself from a routine running in RAM.
|
||||
|
||||
The point is the **delta**: a package against the image the node runs is
|
||||
usually a few kB, so it goes through LoRa in minutes. A full image (~300 kB)
|
||||
goes only over USB or BLE.
|
||||
|
||||
**Rolling release on `dev`, for experienced users.** These `-ota` images track
|
||||
MeshCore `dev`, merged continuously, so a new release lands roughly twice a day
|
||||
and each delta stays small. There is no stable channel, no second bank, and no
|
||||
automatic rollback: a bad image that still boots keeps running until you push the
|
||||
next one, and one that will not boot needs USB/BLE DFU in hand. Run it only on
|
||||
nodes you can reach, and try every release on one within reach first.
|
||||
|
||||
## What a release carries
|
||||
|
||||
For every `<board>_<role>-ota` / `-observer-ota` image:
|
||||
|
||||
| file | what |
|
||||
|---|---|
|
||||
| `<image>-<release>.zip` / `.uf2` | the image, flashed the usual way (first time) |
|
||||
| `<image>-<release>.mcfw` | full package: USB/BLE console only |
|
||||
| `<image>-<release>.from-<earlier>.mcfw` | delta from an earlier release's same image |
|
||||
| `manifest.json` | image sha256, target, build epoch, packages, deltas by base |
|
||||
| `SHA256SUMS`, `SHA256SUMS.sig` | checksums, signed by `meshcore-ota@tth-pub` |
|
||||
|
||||
Check a download:
|
||||
|
||||
ssh-keygen -Y verify -f tools/ota_allowed_signers -I meshcore-ota@tth-pub \
|
||||
-n meshcore-ota -s SHA256SUMS.sig < SHA256SUMS
|
||||
sha256sum -c --ignore-missing SHA256SUMS
|
||||
|
||||
`tools/ota_pack.py fetch <image> --base <sha8>` does both and picks the delta
|
||||
for the node's image (`--full` for the full package, `--release <tag>` for
|
||||
another than the latest).
|
||||
|
||||
## On the node
|
||||
|
||||
```
|
||||
fw status state, battery, the running image's size and sha256 prefix
|
||||
fw ver target and build epoch a package for this image needs
|
||||
fw begin <bytes> [sid] start a transfer
|
||||
fw w <offset> <base64> one 96 B chunk (text)
|
||||
fw missing what is still missing
|
||||
fw verify queue the full check, poll fw status
|
||||
fw apply battery gate, then rewrite and reboot
|
||||
fw apply downgrade local console only: an older (or the same) image
|
||||
fw abort
|
||||
```
|
||||
|
||||
What the node checks before it touches its own image:
|
||||
|
||||
1. The **manifest**, as soon as it is in: an Ed25519 signature by the key the
|
||||
image was built with (`[ota] pubkey`), the target (board + variant: an
|
||||
`-observer-ota` node takes no `-ota` package), the size, for a delta the
|
||||
base (the sha256 of the image it runs), and the build epoch.
|
||||
2. Over the mesh: **only a delta, and only a newer build.** An older or equal
|
||||
one is refused right after the manifest; a full image is refused when the
|
||||
transfer begins. Locally a full image is fine, and an older one takes
|
||||
`fw apply downgrade`.
|
||||
3. `fw verify`: the payload hash, and a delta applied **dry** -- the same code
|
||||
the real run uses, with the flash untouched -- must produce the signed
|
||||
image hash.
|
||||
4. `fw apply`: battery at 3.8 V or more unless the node runs on USB. The
|
||||
bootloader settings get the new image's CRC **first**, so a power cut during
|
||||
the rewrite leaves the node in the bootloader (back with USB/BLE DFU), not
|
||||
in half an image.
|
||||
|
||||
## When an update goes wrong
|
||||
|
||||
No second bank, no automatic rollback. The checks above stop a *corrupt* package,
|
||||
but firmware that passes them and still boots into a broken state keeps running.
|
||||
Two watchdogs catch that. The deaf-receiver one is **off by default** -- turn it
|
||||
on for nodes you push to; the TX stall one is on in repeaters:
|
||||
|
||||
set radio.silence <min> re-arm the receiver, then reboot, if it hears nothing
|
||||
for <min> (persisted, off by default); catches an OTA
|
||||
that boots with a dead radio
|
||||
set radio.txstall <min> the same when the TX queue stalls (repeater only, on
|
||||
at 15 min by default, a change holds until reboot)
|
||||
get radio.reboots watchdog reboots so far (survives power loss)
|
||||
get boot why the board last reset, plus the hardfault record
|
||||
|
||||
Details: `docs/cli_commands.md`, "Radio silence watchdog" and "TX stall watchdog".
|
||||
|
||||
A node that will not boot at all has to be reflashed over USB/BLE DFU. After an
|
||||
`fw apply` over **BLE** the bond can drop (a supervision timeout while the node
|
||||
reboots) -- re-pair from the same host; it is not a brick.
|
||||
|
||||
## Tools
|
||||
|
||||
```bash
|
||||
# a delta for the node's image, from the latest release
|
||||
tools/ota_pack.py fetch Xiao_nrf52_repeater-ota --base <sha8 from fw status>
|
||||
|
||||
# over the mesh, through a companion (USB port or tcp://host:port), as admin
|
||||
tools/ota_mesh_push.py /dev/serial/by-id/<companion> <node pubkey prefix> pkg.mcfw --apply
|
||||
|
||||
# over the node's own USB console
|
||||
tools/ota_push.py /dev/serial/by-id/<node> pkg.mcfw --apply
|
||||
```
|
||||
|
||||
### From a phone
|
||||
|
||||
The [tth fork of meshcore-open](https://git.rfa.cz/tth-pub/meshcore-open)
|
||||
(Android, Obtainium) has it in the repeater management of an admin: Firmware
|
||||
update (OTA). With no file chosen it reads the node's target and image and
|
||||
takes the delta from the latest release (checked against `SHA256SUMS`); the
|
||||
side channel below is a switch there.
|
||||
|
||||
### Off the shared channel: `--side`
|
||||
|
||||
tools/ota_mesh_push.py <companion> <node> pkg.mcfw --apply \
|
||||
--side 869.525,62.5,7,5 --duty 10 --gap 1
|
||||
|
||||
Login, `fw status` and `get radio` still go over the mesh; then the node gets
|
||||
`tempradio <side>,3`, the companion retunes to the same preset, logs in again
|
||||
zero-hop, and the chunks go there. The window grows to `--window` (15 min) once
|
||||
the link is proven and is renewed while the transfer runs. The node comes back
|
||||
by itself when the window runs out, on `fw apply` (the reboot), or when the
|
||||
tool sends it back with `tempradio <its preset>,1`. Nothing new in the firmware:
|
||||
any node with `tempradio` takes it.
|
||||
|
||||
- The companion must be in **direct** range of the node, and it must be a
|
||||
companion **firmware** that retunes its own radio. An openHop virtual
|
||||
companion answers `set_radio` with OK and stays put; the tool checks that
|
||||
and stops, and the node returns within 3 minutes.
|
||||
- The companion's preset is put back at the end -- unless the tool is killed
|
||||
hard; then `set_radio` it back yourself.
|
||||
- The example preset sits inside 869.4-869.65 MHz (10 % duty) between the CZ
|
||||
mesh (869.432/62.5) and EU Narrow (869.618/62.5). The node keeps its TX
|
||||
power on the side channel: pick a band where that power is allowed.
|
||||
|
||||
The transfer in both tools is the OTA engine of the
|
||||
[tth.meshcore Ansible collection](https://git.rfa.cz/tth-pub/meshcore-ansible)
|
||||
(`plugins/module_utils/meshcore_ota_engine.py`) -- its `meshcore_fw_ota` module
|
||||
runs the same code, so a fix lands everywhere at once. The tools need only its
|
||||
files, not Ansible: an installed collection
|
||||
(`ansible-galaxy collection install git+https://git.rfa.cz/tth-pub/meshcore-ansible.git`),
|
||||
a checkout named by `MESHCORE_ANSIBLE`, or one next to this repository
|
||||
(`tools/ota_collection.py` prints which one it uses).
|
||||
|
||||
`ota_mesh_push.py` needs the `meshcore` Python library. It logs in as admin
|
||||
(password from `[secrets] admin_pw` of `platformio.local.ini`, or asked for),
|
||||
sends binary chunks with a pause between them, asks which are missing and
|
||||
resends only those, and keeps an airtime budget (`--duty`, default 1 % per
|
||||
hour: the 865-868 MHz band). A refused package costs the two manifest chunks,
|
||||
not the whole transfer. Check `get radio` on both ends first: this transmits.
|
||||
|
||||
## Your own builds
|
||||
|
||||
A build with `-D FW_OTA=1` trusts `[ota] pubkey` of `platformio.ini` -- the
|
||||
release key. To sign your own packages, set your key in the gitignored
|
||||
`platformio.local.ini`:
|
||||
|
||||
```ini
|
||||
[ota]
|
||||
pubkey = <tools/ota_pack.py pubkey --key your.key>
|
||||
```
|
||||
|
||||
and pack with `tools/ota_pack.py pack|diff <env> --key your.key`. Target and
|
||||
build epoch come from the ELF, never from the command line. Keep every image
|
||||
you flash: a delta needs the exact bytes the node runs as its base.
|
||||
|
||||
Cost: about 10 kB of RAM on a repeater, the applier code in RAM, a 32 kB
|
||||
buffer while a full package is verified or applied. Classic images (without
|
||||
`-ota`) have none of it.
|
||||
+398
@@ -0,0 +1,398 @@
|
||||
# Power saving on a solar repeater — what it costs, measured
|
||||
|
||||
Everything here was measured on the deployment hardware (SenseCAP Solar Node
|
||||
P1-Pro, nRF52840 + SX1262 + L76K) on 2026-08-05/06 with `tools/power_ab.py`, not
|
||||
taken from a datasheet. Numbers are input current on the 5 V USB side; the delta
|
||||
between two states is what the paired design measures, and that is what these
|
||||
figures are.
|
||||
|
||||
## The order that matters
|
||||
|
||||
| lever | measured | verdict |
|
||||
|---|---|---|
|
||||
| **GPS running continuously** | **46.0 mA** (spread 43.7-47.5) | `gps duty` recovers 42-45 of it |
|
||||
| BLE advertising + Bluefruit's blinking LED | see below | defaults changed, LED off, 1 s interval |
|
||||
| `powersaving on` (MCU light sleep) | **~1 mA** with USB, **2.7 mA** without (XIAO, 11/2026) | keep it on |
|
||||
| CC310 IRQ cleared before sleep (nRF52) | **2.6 mA** after every boot | fixed in firmware, see below |
|
||||
| RX duty cycle (`set radio.rxps`, from EasySkyMesh) | **~2.3 mA** at `max` (XIAO, 12. 11. 2026) | **no** on a live node: -16 % received and a TX stall on mast-three, see below |
|
||||
| `radio.rxgain off` | ~0.7 mA | **no** — 1-3 dB of sensitivity is what a mast node is for |
|
||||
| FEM LNA control | n/a | SenseCap has no FEM, only an RXEN switch |
|
||||
|
||||
A whole node in the shipping configuration, with the battery charged and GPS
|
||||
duty-cycled, sits at **~24 mA**. Continuous GPS alone would nearly triple that.
|
||||
|
||||
## GPS is the whole game
|
||||
|
||||
The receiver on this board draws 46 mA, and a mast repeater runs GPS for one
|
||||
reason only: the RTC is volatile, and a node whose clock is wrong has its
|
||||
replies dropped by clients. It does not need a continuous fix — it needs the
|
||||
clock set.
|
||||
|
||||
GPS is no longer the *only* way to get that (since 7. 8. 2026 a node starts at
|
||||
its build epoch and any attached host sets it — see `docs/cli_commands.md` under
|
||||
`time`). A reboot still throws the clock back to the build epoch: carrying it
|
||||
across one in retained RAM was tried and measured not to work, because the
|
||||
bootloader's stack owns the top of RAM. GPS is still
|
||||
what makes a mast node's clock **absolutely** right months after the flash, with
|
||||
nobody there to set it, so this reasoning stands for anything on a mast. What
|
||||
changed is that a node without GPS is no longer stuck in 2024.
|
||||
|
||||
`gps duty` (`gps_enabled == 2`, so no prefs-layout change) powers the receiver
|
||||
only around a sync, once a day (until 11/2026 every 30 minutes, the cadence
|
||||
`gps on` re-syncs at). The LF crystal is ±20 ppm plus ~40 ppm at −10 °C, so a
|
||||
day costs ~5 s of clock — far below what the mesh notices — and a reboot syncs
|
||||
at once anyway. Verified on hardware in both paths (with the old 30 min / 1 h
|
||||
timers):
|
||||
|
||||
- with sky (`mast-three`): `duty, asleep, fix, 7 sats` — got a fix, set the clock,
|
||||
cut power to the receiver;
|
||||
- without (indoors, `bench-rpt`): `awake` for exactly 300 s
|
||||
(`GPS_DUTY_MAX_AWAKE_SECS`), then `asleep` with an hourly retry, so a blocked
|
||||
sky cannot turn duty mode back into "always on".
|
||||
|
||||
Worst case (fix never obtained) still saves 42 mA; a normal 30 s fix saves 45.
|
||||
Going from 30 min to 24 h saves another 0.25–0.75 mA (hot vs. warm start, not
|
||||
measured per window), and the retry from 1 h to 6 h takes a node whose dome is
|
||||
under snow from 3.8 mA (300 s at 46 mA hourly) to 0.64 mA.
|
||||
Knobs: `GPS_DUTY_SYNC_INTERVAL_SECS` (86400), `GPS_DUTY_MAX_AWAKE_SECS` (300),
|
||||
`GPS_DUTY_RETRY_SECS` (21600).
|
||||
|
||||
Upstream later (v1.18 dev, 11/2026) added its own `gps period <s>`. It is not a
|
||||
replacement: a periodic acquisition has no timeout until the first fix ever, so
|
||||
the indoor case above would stay at 46 mA for good. `gps duty` sets the period
|
||||
to 0, and `gps on` / `gps off` leave duty mode.
|
||||
|
||||
**One visible side effect:** `querySensors()` only adds the GPS channel to
|
||||
telemetry while the receiver is powered, so a duty-cycled node reports position
|
||||
in telemetry only during its sync windows (well under 1 % of the time). What a repeater
|
||||
*advertises* is unaffected — that comes from prefs via `set advert.loc prefs` (formerly `gps advert prefs`) — and
|
||||
`node_lat/lon` keep the last fix. Confirmed in the field: `mast-three`'s scrape now
|
||||
carries `voltage/temperature/humidity` and no `gps` field.
|
||||
|
||||
## BLE: two defaults that were quietly expensive
|
||||
|
||||
- **The blinking LED.** Bluefruit drives `LED_BLUE` while advertising and holds
|
||||
it on while connected. On SenseCap Solar that pin is **12 — the same pin as
|
||||
`P_LORA_TX_LED`**, so a sealed mast node spent solar charge blinking an LED
|
||||
nobody can see, and the LoRa TX indicator lied as a bonus.
|
||||
`RPT_BLE_CONN_LED` now defaults to 0.
|
||||
- **The advertising rate.** Upstream leaves the slow interval at 244 units =
|
||||
152.5 ms, i.e. three channels ~6.5 times a second, forever.
|
||||
`RPT_BLE_ADV_SLOW` now defaults to 1600 = 1 s; the first
|
||||
`RPT_BLE_ADV_FAST_SECS` (30) after boot or disconnect stay fast so discovery
|
||||
is still immediate when someone is looking.
|
||||
|
||||
Bench boards keep both upstream behaviours (`-D RPT_BLE_CONN_LED=1`,
|
||||
`-D RPT_BLE_ADV_SLOW=244` in `xiao_analyzer`): on a desk the blinking LED is the
|
||||
"this thing is alive" indicator.
|
||||
|
||||
`ble off` remains the big BLE lever for a deployed node, but the deployment rule
|
||||
stands: ship with BLE **on**, verify the node on site, and only then turn it off
|
||||
over the mesh — otherwise a node that does not come up has no way in.
|
||||
|
||||
## RX duty cycle (rxps)
|
||||
|
||||
Ported from EasySkyMesh PowerSaving v18 behind `-D WITH_RX_POWERSAVING` (the
|
||||
public releases have it), SX1262 only, **off until set**. The radio listens in
|
||||
short windows and sleeps between them, staying awake through a packet once it
|
||||
hears a preamble; after three failed arms it falls back to continuous RX by
|
||||
itself. Commands: `docs/cli_commands.md`, `radio.rxps`.
|
||||
|
||||
Measured 12. 11. 2026 on a XIAO nRF52840 + Wio-SX1262 (not the SenseCAP of
|
||||
the rest of this page), bench preset 866.5 MHz / SF8 / BW62.5, fed at 5 V
|
||||
through an INA226 (10 mOhm) read every 5 s; the only other load was a UC96 on
|
||||
the XIAO's USB port. A/B/A/B, 15 min cells, the first 2 min of each dropped:
|
||||
|
||||
| cell | rxps | mean | median |
|
||||
|---|---|---|---|
|
||||
| 1 | off | 33.84 mA | 32.2 mA |
|
||||
| 2 | max | 31.31 mA | 30.5 mA |
|
||||
| 3 | off | 33.53 mA | 32.5 mA |
|
||||
| 4 | max | 31.36 mA | 30.3 mA |
|
||||
|
||||
`max` (level 8) against the mean of its neighbours: **-2.4 / -2.2 mA**, pooled
|
||||
-2.35 mA (medians -1.95 mA); off vs off differs by 0.3 mA, max vs max by
|
||||
0.05 mA. That is the radio's share, so it carries over to other SX1262 boards
|
||||
in absolute terms; the 33 mA base is this bench (meter, BLE advertising), not
|
||||
a node. Behind the XIAO's linear regulator the battery sees the same current:
|
||||
~7-8 mW at 3.3 V.
|
||||
|
||||
Reception: a 3-board zero-hop matrix (x1, x3, x4; rxps switched on x1 and x4,
|
||||
x3 the reference with rxps off; 20 rounds per phase, each link witnessed by
|
||||
another board), run twice -- on the development build, then repeated on the
|
||||
public release `v1.18.0+tth.20261112` (`ver` v1.18.0-tthd4afea1):
|
||||
|
||||
| phase | development build | public release | together |
|
||||
|---|---|---|---|
|
||||
| rxps off | 0/120 | 1/120 | 1/240 |
|
||||
| `on` (level 3) | 1/120 | 2/120 | 3/240 |
|
||||
| `max` (level 8) | 0/120 | 0/120 | **0/240** |
|
||||
|
||||
rxps stayed armed throughout, no error counts. Single losses happen with rxps
|
||||
off as well, and of the three at level 3 one was on x3, which had rxps off: the
|
||||
bench shows no degradation at any level. Not measured: mixed SF/preamble senders, a busy
|
||||
live mesh. On a mast, where 2 mA of ~24 is not the problem, leave it off.
|
||||
|
||||
**On the live mesh it failed (mast-three, 14. 11. 2026, `max`).** Against ob1 as
|
||||
the reference for the hour-to-hour traffic, the node received ~16 % fewer
|
||||
packets (2.08 vs 2.47 per ob1 packet) with ~30 % more `recv_errors`, and within
|
||||
two hours of switching it on it stopped transmitting altogether: `sent` frozen,
|
||||
queue full (32), no `tx_start_fail`/`tx_timeout`, RX still counting -- so no
|
||||
adverts and no replies to an admin login, for 6+ hours. `radiostat` showed
|
||||
`irq=0x0014` (preamble + header valid, no RX done). `set radio.rxps off` did
|
||||
NOT bring TX back; a reboot did. The mechanism is not proven, and the radio
|
||||
silence watchdog cannot see it (it watches RX only). Do not enable rxps on a
|
||||
node that has to answer.
|
||||
|
||||
## MCU sleep
|
||||
|
||||
`powersaving on` makes the nRF52 wait in WFE between events (it wakes on any
|
||||
interrupt, including LoRa DIO1). Upstream ships it **off**, and it was missing
|
||||
from our provisioning, so every node built from that file ran the core at 64 MHz
|
||||
around the clock. It is now in our provisioning file.
|
||||
|
||||
**But it buys about 1 mA, not the 3-4 that seemed obvious.** Measured with GPS
|
||||
held off so its sync windows could not pollute the cells: paired estimate
|
||||
-0.96 mA over three pairs, spread -1.97 to +0.07, against a measured
|
||||
cell-to-cell repeatability of 1.16 mA — i.e. the effect is the same size as this
|
||||
rig's noise and cannot be told from zero. That fits the mechanism: the loop
|
||||
still polls the SX1262 over SPI on every pass and the SoftDevice wakes the core
|
||||
for each advertising event, so there is not much idle left to sleep through.
|
||||
Keep it on (it is free and cannot hurt), but do not budget for it.
|
||||
|
||||
Blocking the loop task instead of waiting for an event (so that FreeRTOS can
|
||||
sleep tickless) changes nothing either: `delay(10)` against `sd_app_evt_wait()`,
|
||||
XIAO x4, A/B/A/B 30 min cells (14. 11. 2026): paired difference **0.04 mA**,
|
||||
cell repeatability 0.1-0.4 mA. The tick wakeups are not where the current goes.
|
||||
|
||||
One fork-specific fix goes with it: the sleep is also held off while the BLE
|
||||
console still has queued output (`bleTxPending()`), because on the observer node
|
||||
a half-drained `rxlog`/`pktlog` page would otherwise wait for the next
|
||||
connection event — the bridge drains those on a 2-minute duty cycle, so a slower
|
||||
drain directly costs collected frames.
|
||||
|
||||
### CPU time per received packet (`PWR_DUTY_INSTRUMENT`)
|
||||
|
||||
A bench build with `-D PWR_DUTY_INSTRUMENT` (nRF52 only, nothing changes
|
||||
without the flag) prints one line to the USB console every ~10 s:
|
||||
|
||||
```
|
||||
PWRDUTY awake_ms=… asleep_ms=… wakes=… duty_permille=… pkt_us=… pkt_n=…
|
||||
```
|
||||
|
||||
- `awake_ms`, `asleep_ms` and `duty_permille` are the time between a return
|
||||
from `NRF52Board::sleep()` and the next entry into it, against the WFE span
|
||||
inside it. This needs `powersaving on`: without it `sleep()` is never called.
|
||||
- `wakes` counts the passes through `sleep()`. BLE and USB events wake the
|
||||
core too, so the duty is not packet cost alone.
|
||||
- `pkt_us` and `pkt_n` are the CPU time spent in
|
||||
`Dispatcher::processRecvPacket()` (dedup, crypto, routing) and the number of
|
||||
packets. They do not depend on background wakes. This is the work a filter
|
||||
on the radio side could skip for a packet that is dropped anyway.
|
||||
|
||||
All counters are cumulative since boot, so take the difference between two
|
||||
lines.
|
||||
|
||||
Measured on the XIAO x4, 24. 11. 2026, live mesh, about 440 packets/h (all
|
||||
flood adverts): about **6.8 ms CPU per received packet**, mostly the Ed25519
|
||||
check of the advert signature. The duty went from 0.05 % at rest to 0.13 %.
|
||||
The awake time is a small part of a node's current; the radio's RX and the
|
||||
SoftDevice dominate.
|
||||
|
||||
## A mast that runs flat: bootlock and cutoff
|
||||
|
||||
A panel that gets no direct sun in winter (remote-mast faces east, 11/2026:
|
||||
-50 mV a day from mid-November with consumption unchanged) eventually drains
|
||||
the cell. Without protection the node runs until the brown-out, and every bit
|
||||
of light then restarts it on a cell that cannot hold it -- a boot loop at the
|
||||
edge, with the cell deep-discharged on the way.
|
||||
|
||||
`SenseCap_Solar_repeater` builds with `NRF52_POWER_MANAGEMENT` (upstream code,
|
||||
wired in `variants/sensecap_solar`) and `PWRMGT_RUNTIME` (ours), which gives
|
||||
two thresholds, both saved on the node and settable from the console or as an
|
||||
admin over the mesh:
|
||||
|
||||
| command | default | what |
|
||||
|---|---|---|
|
||||
| `set pwr.bootlock <mV>` | 3300 mV (`variant.h`) | 3000..4200 or `off`; at boot, below it the node goes to SYSTEMOFF and the LPCOMP wakes it when the battery recovers |
|
||||
| `set pwr.cutoff <mV>` | off | 3000..4200 or `off`; while running, three readings in a row (one a minute) below it switch the node off into the same SYSTEMOFF |
|
||||
| `get pwr` | | both, the battery now and at boot, USB, the reason of the last switch-off |
|
||||
|
||||
The cutoff must stay below the bootlock -- a node switched off at the cutoff
|
||||
starts again only past the bootlock, which is the hysteresis (e.g. cutoff
|
||||
3400, bootlock 3600). The node refuses a threshold above the battery voltage
|
||||
at that moment (it would lock itself out of a mast), USB power disarms the
|
||||
cutoff and skips the boot check, a reading under 1 V counts as an ADC glitch.
|
||||
The values live in `/pwr_guard`, not in the prefs; without the file the build
|
||||
defaults apply (`PWRMGT_BOOTLOCK_DEFAULT`, `PWRMGT_CUTOFF_DEFAULT`).
|
||||
|
||||
The wake level is not one of the thresholds: it is the LPCOMP comparing the
|
||||
battery divider with 3/8 VDD, ~3.4-3.7 V on the cell per `variant.h`, fixed in
|
||||
hardware steps. A bootlock above it means the node wakes, checks, and sleeps
|
||||
again until the cell is past the bootlock -- harmless, each wake is a few ms.
|
||||
The clock goes back to the build epoch after such a restart, as after any
|
||||
power loss (`gps duty` resyncs it, `time` sets it).
|
||||
|
||||
Why upstream has it off: a fixed 3.3 V lock kept LiFePO4 and LTO nodes from
|
||||
booting (#2377, v1.18.0); a chemistry-aware version is open as #2088 (FS read
|
||||
before the check, per-chemistry thresholds). Ours is narrower -- one board
|
||||
with a known Li-ion cell, two numbers, `off` for either -- and has to be
|
||||
reconciled with #2088 if that lands.
|
||||
|
||||
**Not yet verified on hardware**: the logic has host tests
|
||||
(`test/test_low_voltage_guard`), the thresholds and the wake level do not.
|
||||
Bench test with an adjustable supply on the battery terminals: boot at 3.2 V
|
||||
must stay dark; raising it to ~3.8 V must wake the node by itself (`get boot`
|
||||
then shows `RESETREAS=0x00020000`, bit 17, wake from LPCOMP); with a cutoff
|
||||
set, lowering the supply below it must switch the node off within ~3 minutes
|
||||
and `get pwr` after the wake must say `last off: Low Voltage`.
|
||||
|
||||
## nRF52 sleep & peripheral fixes
|
||||
|
||||
An audit of the nRF52840 firmware and the Adafruit core found several sources of
|
||||
idle draw that apply to all nRF52 boards, not only SenseCAP Solar. They were
|
||||
measured on 25./26. 11. 2026 on XIAO x4 (nRF52840 + Wio-SX1262, repeater build,
|
||||
bench preset). Setup: no USB host, fed at 5 V through an INA226 read every
|
||||
~1 s. Each cell was 10 min (20 min for rxps), 38 cells over two rounds. Every
|
||||
knob was switched at runtime between two baseline cells. The baseline
|
||||
repeatability was **0.05 mA**, so an effect counts only above 0.1 mA and with
|
||||
the same sign in both rounds. The 5 V pin is VBUS, so USBD and HFXO stay up;
|
||||
read the absolute numbers as this rig and the deltas as the result.
|
||||
|
||||
**The one that matters: `CRYPTOCELL_IRQn` sleep insomnia (+2.6 mA).**
|
||||
`USE_CC310_HW_CRYPTO=1` runs CC310 in polling mode with `CRYPTOCELL_IRQn`
|
||||
disabled in NVIC. A completed operation leaves the IRQ pending, and a pending
|
||||
IRQ ends `sd_app_evt_wait()`/`__WFE()` immediately. `NRF52Board::sleep()` now
|
||||
clears it before sleeping, as the Adafruit core's `wiring.c` does. Without the
|
||||
clear, a node comes out of every boot stuck at **14.1 mA instead of 11.5**:
|
||||
|
||||
| boot with | before first BLE connection | after it |
|
||||
|---|---|---|
|
||||
| both fixes | 11.51 / 11.51 mA | 11.48 / 11.49 mA |
|
||||
| no CC clear | **14.13 / 14.15 mA** | 11.38 / 11.52 mA |
|
||||
| no CC clear, no late DC/DC (= old main) | **14.04 / 14.14 mA** | 11.50 / 11.55 mA |
|
||||
| no late DC/DC | 11.43 / 11.53 mA | 11.51 / 11.53 mA |
|
||||
|
||||
Values are round 1 / round 2. In the stuck state the core wakes
|
||||
~15 000 times a second, against ~990 for the 1024 Hz tick, and it is awake
|
||||
for 80 % of the time. It is not an occasional spike either: 98–100 % of the
|
||||
samples sit above 13 mA. Received LoRa packets do not end it (5 per window). The
|
||||
first BLE connection does; the mechanism is not traced. A mast node that nobody
|
||||
connects to over BLE stays in it. Toggling the clear at runtime
|
||||
on an already clean node changes nothing (+0.01 / +0.02 mA), because the state
|
||||
is decided at boot.
|
||||
|
||||
**The same run again at 3.3 V without VBUS (27. 11. 2026).** Here x4 is fed on
|
||||
its 3V3 pin at 3.25 V, so `bench duty` reads `vbus 0 usbd 0` and HFXO is
|
||||
off. This is the closer match to a node on a cell. The setup was the same:
|
||||
38 cells, two rounds, all of them valid. Baseline repeatability (detrended SD of
|
||||
the base cells) was **0.009 / 0.015 mA**, so the threshold here is 0.03 mA.
|
||||
The baseline is **6.90 mA** (22 mW, against 57 mW on the 5 V pin).
|
||||
|
||||
| boot with | before first BLE connection | after it |
|
||||
|---|---|---|
|
||||
| both fixes | 6.91 / 6.92 mA | 6.89 / 6.88 mA |
|
||||
| no CC clear | **10.16 / 10.16 mA** | 6.91 / 6.89 mA |
|
||||
| no CC clear, no late DC/DC (= old main) | **10.18 / 10.18 mA** | 6.89 / 6.94 mA |
|
||||
| no late DC/DC | 6.90 / 6.91 mA | 6.93 / 6.92 mA |
|
||||
|
||||
The CC310 insomnia costs **+3.3 mA, almost half of the whole node**. Every
|
||||
sample of those windows sits above 8.5 mA. The core wakes 14 900 times a
|
||||
second, against 986, it is awake 79 % of the time, and `cc_pend` reads 1.
|
||||
|
||||
At this voltage **DC/DC is worth 0.6 mA**. `bench dcdc off` at runtime gives
|
||||
+0.63 / +0.60 mA, and `A_like` (DC/DC off, CC clear off, nfcal 2 s) gives
|
||||
+0.59 / +0.61 mA, the same thing. On the 5 V pin the same switch was below
|
||||
resolution. The late re-enable still changes nothing, because `DCDCEN` reads 1
|
||||
after every boot with or without it. So the regulator mode matters, and
|
||||
SoftDevice simply does not turn it off.
|
||||
|
||||
| knob (3.3 V) | round 1 | round 2 |
|
||||
|---|---|---|
|
||||
| `bench dcdc off` | +0.63 mA | +0.60 mA |
|
||||
| `bench cc off` (runtime) | +0.00 mA | −0.01 mA |
|
||||
| `bench nfcal 2000` | −0.04 mA (one pair) | |
|
||||
| `set radio.rxps max` | −2.30 mA | −2.30 mA |
|
||||
| `set radio.rxps balanced` | −1.98 mA | −1.82 mA |
|
||||
| `set radio.rxgain off` | −0.45 mA | −0.51 mA |
|
||||
| `powersaving off` | +2.37 mA (one pair) | |
|
||||
|
||||
The rxps, rxgain and powersaving deltas match the 5 V run to within 0.3 mA.
|
||||
In relative terms, rxps max now takes a third off the node. Reception from the
|
||||
x1 witness matched what it sent in every cell (base 82 received for 72 sent;
|
||||
x4 also hears other bench traffic). The witness again only detects a gross
|
||||
loss, not a sensitivity loss.
|
||||
|
||||
**Measured to make no difference, kept anyway** (each below 0.1 mA):
|
||||
- **DC/DC re-enabled after SoftDevice start** (`onBootComplete()`):
|
||||
+0.02 / −0.10 mA at runtime on the 5 V pin, and no difference as a boot flag
|
||||
at either voltage. The premise that S140 puts `NRF_POWER` back to LDO did not
|
||||
hold on this board. `DCDCEN` read 1 after every boot, with or without the
|
||||
late enable. The late enable is kept as a harmless safeguard. DC/DC itself
|
||||
does matter at 3.3 V (see above).
|
||||
- **Noise-floor calibration every 10 s instead of 2 s**
|
||||
(`NOISE_FLOOR_CALIB_INTERVAL`): +0.08 mA at 5 V and −0.04 mA at 3.3 V, one
|
||||
pair each. That is at the edge of resolution and of no practical weight.
|
||||
|
||||
**Not measured** (compile-time or other hardware):
|
||||
- **Avoid `NRF_SPIM3` (Nordic Errata 195)**: `[nrf52_base]` sets
|
||||
`-D SPI_32MHZ_INTERFACE=1`, which moves the SX1262 `SPI` bus from `NRF_SPIM3`
|
||||
to `NRF_SPIM2`. `SPIClass::endTransaction()` disables `SPIM3` without the
|
||||
errata workaround, which is worth ~1.2–2 mA idle per the errata. A clean
|
||||
baseline of 11.5 mA on this board leaves little room for that.
|
||||
- **GPS UART pins disconnected while the GPS is off**:
|
||||
`NmeaGpsDriver::stopHardware()` resets TX/RX via `nrf_gpio_cfg_default()`
|
||||
after `Uart::end()`, so the unpowered receiver is not back-powered.
|
||||
- **Unused I2C bus switched off**: `EnvironmentSensorManager::begin()` calls
|
||||
`Wire.end()` when the bus scan finds no device, and enables it again for the
|
||||
`i2c` CLI command.
|
||||
- **SenseCAP Solar battery divider (`VBAT_ENABLE`)**: held `HIGH` (off) at boot
|
||||
and set back to `HIGH` right after `getBattMilliVolts()`, instead of staying
|
||||
`LOW`. `initiateShutdown()` still drives it `LOW` when it arms the LPCOMP
|
||||
wake. It saves ~2.8 µA (4.2 V over 1.5 MOhm). With the old 10 ms settle the
|
||||
reading came out 110-150 mV high (mast-three and second-mast after the OTA of
|
||||
26.-27. 11. 2026, both at night, remote-mast without the change flat): the ADC
|
||||
node starts high with the divider off. The settle is 100 ms now; still to be
|
||||
checked against a meter, and whether the ADC pin sits near VDD + 0.3 V on a
|
||||
full cell.
|
||||
|
||||
**Runtime knobs from the same night**, for comparison (paired deltas):
|
||||
|
||||
| knob | round 1 | round 2 | reception (x1 witness) |
|
||||
|---|---|---|---|
|
||||
| `set radio.rxps max` | −2.47 mA | −2.33 mA | 20/21 |
|
||||
| `set radio.rxps balanced` | −1.98 mA | −1.88 mA | 20/21 |
|
||||
| `set radio.rxgain off` | −0.49 mA | −0.45 mA | 10/12 |
|
||||
| `powersaving off` | +2.66 mA | (one pair) | 5/6 |
|
||||
| baseline | | | 83/90 |
|
||||
|
||||
The x1 witness sends zero-hop adverts every ~130 s at 2 dBm. Reception counts
|
||||
are approximate at cell edges, and no knob showed a gross loss. The bench
|
||||
signal is strong, so this does not test sensitivity, and the rxps failure on
|
||||
the live mesh (see above) still stands. `powersaving` is worth 2.7 mA here
|
||||
without USB, much more than the ~1 mA measured with USB attached (USB keeps
|
||||
HFCLK running).
|
||||
|
||||
Tools: `tools/power_ab.py --ina <url>` (INA226 of a solar controller as the
|
||||
meter, raw samples saved), firmware bench knobs and the night driver are kept with
|
||||
the run log, outside the repository.
|
||||
|
||||
## Measuring this yourself — two traps
|
||||
|
||||
1. **A solar node measured on its USB side measures the CHARGER.** With a
|
||||
charging cell the meter reads 500-700 mA, pulsing, and the node's own tens of
|
||||
mA ride on top of a drifting number. Wait for the charge to finish (it fell
|
||||
0.71 → 0.53 → 0.22 → 0.05 A over about an hour here) or the numbers are
|
||||
fiction. There is **no INA226 on this board** to cross-check with — the `i2c`
|
||||
command reports nothing at all on the only bus the variant has — on three
|
||||
separate P1-Pro units (`bench-rpt`, `mast-rpt-two`, `tth-mast-repeater-one`),
|
||||
against a sensor table that expects `38 76 70 44 5C 42 40 41 5A 29 77`. So it
|
||||
is the board, not one dead part, and the cross-check for a power measurement
|
||||
has to be a second *board*.
|
||||
2. **With `gps duty` enabled you cannot measure anything under ~5 mA.** A sync
|
||||
window lands in a random cell and adds ~17 mA to a 10-minute average (seen:
|
||||
40.9 mA against 24.1-24.5 in its neighbours). Put `gps off` in every cell of
|
||||
such a run and restore `gps duty` afterwards.
|
||||
|
||||
See `tools/power_ab.py --help` for the alternating-cell design that makes
|
||||
these deltas trustworthy in the first place.
|
||||
@@ -0,0 +1,246 @@
|
||||
# Console commands of this fork (meshcore-tth)
|
||||
|
||||
> [!WARNING]
|
||||
> Part of an experimental fork, not meant for regular users: its releases are
|
||||
> a rolling release on MeshCore `dev` (see the [README](../README.md)).
|
||||
|
||||
Everything this fork adds to the text console of a node, on top of upstream's
|
||||
[cli_commands.md](cli_commands.md). Where a command is described there too
|
||||
(the watchdogs, `rxps`, `batt.icon`, `gps duty`, `dfu`, `get boot`), this page
|
||||
gives the short form and points to it.
|
||||
|
||||
**How commands are written** (as in cli_commands.md): `<value>` is required,
|
||||
`[value]` optional, `<on|off>` one of the listed words. One command per line;
|
||||
ranges, units and defaults are in the description.
|
||||
|
||||
**Where a command exists** depends on the role and on build flags:
|
||||
|
||||
| mark | builds |
|
||||
|---|---|
|
||||
| all | repeater, room server and sensor -- every build with a text console |
|
||||
| repeater | `simple_repeater` builds |
|
||||
| observer | the `*-observer` variants of the nRF52 repeaters in the releases (`MAX_HEARD_NODES`, `RXLOG_SIZE`, `PKTFEED_SIZE`, `BLE_PIN_CODE`) |
|
||||
| own build | only with the named flag -- not in the releases |
|
||||
|
||||
**Where it can be sent from:** the USB console, the BLE console (observer
|
||||
variants) and the mesh, as admin in the remote CLI of an app -- unless the
|
||||
entry says *local only*. Replies over the mesh are cut to one packet (~150 B).
|
||||
|
||||
## Antispam (repeater)
|
||||
|
||||
Forwarding only: what this node hears, logs and feeds to an observer is never
|
||||
affected. Everything is persisted in prefs, so a reboot keeps it.
|
||||
|
||||
### FairnessLimiter -- `fairness`
|
||||
|
||||
Token buckets on forwarded floods, keyed on the 1-byte ids already in the
|
||||
clear: channel hash, sender hash, advert origin. Buckets collide (the hash is
|
||||
masked), and every key is chosen by the sender: it contains runaway floods,
|
||||
it is not security. Direct-routed traffic is never limited.
|
||||
|
||||
| command | what |
|
||||
|---|---|
|
||||
| `fairness` | state, denials per category, caps and refill intervals |
|
||||
| `fairness <on\|off>` | the buckets on or off. Default: on (`FAIRNESS_ENABLED_DEFAULT`) |
|
||||
| `fairness cap <group> <sender> <advert>` | burst caps, 0..255 each; `0` = build default (100 / 150 / 30) |
|
||||
| `fairness refill <group> <sender> <advert>` | one token per interval, seconds, 0..65535 each; `0` = build default (30 / 10 / 600) |
|
||||
| `fairness grid` | the busiest denied buckets per category -- what is being shed |
|
||||
| `fairness air` | estimated airtime shed per reason |
|
||||
| `fairness advert` | the per-origin advert window: hours, held adverts, cache |
|
||||
| `fairness advert <hours>` | one flood advert per origin per `hours`, 0..720; `0` = off. Default: off |
|
||||
| `fairness advert clear` | forget the origins seen |
|
||||
| `fairness dryrun [on\|off]` | count every verdict but forward anyway; without an argument shows the state. Default: off |
|
||||
|
||||
The defaults keep about twice the headroom over 30 days of CZ mesh traffic
|
||||
(the zero-loss frontier was 60 s / cap 60 per channel, 10 s / 60 per sender,
|
||||
600 s / 12 per advert origin).
|
||||
|
||||
### Channel filter -- `filter`
|
||||
|
||||
On channels whose key the node knows (`FILTER_CHANNEL_PSKS`; the releases
|
||||
know Public, `#meshcore` and `#test`) the node decrypts each group text and
|
||||
refuses to forward listed senders. The sender name is plain text in the
|
||||
message: anyone can rename around it.
|
||||
|
||||
| command | what |
|
||||
|---|---|
|
||||
| `filter [list]` | channels known, drops, the deny list |
|
||||
| `filter add <name>` | deny a sender name: exact, case-insensitive; spaces allowed, commas not |
|
||||
| `filter del <name>` | remove a name from the deny list |
|
||||
| `filter clear` | empty the deny list |
|
||||
|
||||
### Channel-hash deny-forward -- `filter hash` (every repeater)
|
||||
|
||||
Keyless: the first byte of a group packet is the channel hash, in the clear,
|
||||
so this works on private channels too. One byte is coarse -- every other
|
||||
channel whose key hashes to the same byte is hit as well; check what else
|
||||
lives on it before adding one.
|
||||
|
||||
| command | what |
|
||||
|---|---|
|
||||
| `filter hash [list]` | drops, passes by a throttle, the list (`43` blocked, `43/60` throttled) |
|
||||
| `filter hash add <hex> [secs]` | block the byte, or with `secs` (1..65535) let one packet through per `secs`; re-adding changes the interval |
|
||||
| `filter hash del <hex>` | remove one byte |
|
||||
| `filter hash clear` | empty the list |
|
||||
|
||||
A throttle's window lives in RAM: the first match after a boot passes.
|
||||
|
||||
### Message age -- `filter age` (repeater with channel keys)
|
||||
|
||||
| command | what |
|
||||
|---|---|
|
||||
| `filter age` | the limit and how many were dropped |
|
||||
| `filter age <minutes>` | do not forward a group text on a decrypted channel whose sender timestamp is older than `minutes` (1..10080) by this node's clock |
|
||||
| `filter age off` | no age limit. Default: off |
|
||||
|
||||
It judges the sender's clock, so a companion that never got a time sync (it
|
||||
stamps 2024) is dropped too -- keep it in days. Inactive while the node's own
|
||||
clock reads before 2026; a clock running ahead makes everything look old.
|
||||
|
||||
### Dry run -- `filter dryrun`
|
||||
|
||||
| command | what |
|
||||
|---|---|
|
||||
| `filter dryrun [on\|off]` | count every `filter` verdict (sender, hash, age) but forward anyway -- try a rule on a live node before it bites; without an argument shows the state. Default: off |
|
||||
|
||||
## Radio watchdogs and board upkeep (all)
|
||||
|
||||
Details: [cli_commands.md](cli_commands.md), "Radio silence watchdog", "TX
|
||||
stall watchdog", "Reboot into the bootloader" and "Why the board last reset".
|
||||
|
||||
| command | what |
|
||||
|---|---|
|
||||
| `get radio.silence` | threshold, current multiplier, quiet time, stage |
|
||||
| `set radio.silence <minutes>` | deaf receiver: re-arm RX, then reboot after `minutes` (1..1440) without a received frame (CRC errors count as heard); each such reboot doubles the threshold for the next boot (up to 16x), the first frame clears it. `0` or `off` = off. Saved. Default: off |
|
||||
| `get radio.txstall` | threshold, queue, time without TX, stage |
|
||||
| `set radio.txstall <minutes>` | repeater only: packets queued and nothing sent for `minutes` (1..1440) -> re-arm, then reboot. An empty queue never counts. `0` or `off` = off. Not saved: a reboot returns to the build value. Default: 15 (`RADIO_TXSTALL_MIN`) |
|
||||
| `get radio.reboots` | reboots done by the watchdogs, survives power loss |
|
||||
| `get boot` | reset reason and the hardfault record (also printed at boot) |
|
||||
| `dfu [uf2\|serial\|ota]` | *local only*, nRF52: reboot into the bootloader -- UF2 drive (default), CDC port for `adafruit-nrfutil`, or BLE DFU |
|
||||
| `fw <subcommand>` | `-ota` images only: admin-pushed firmware update, see [ota.md](ota.md) |
|
||||
|
||||
## Number arguments of `set` (all, and the companion's serial CLI)
|
||||
|
||||
Upstream parses the value of a `set` with `atoi()`/`atof()`: text became 0,
|
||||
`300` became 44 in a one-byte setting, and the result was saved with `OK`. This
|
||||
fork refuses a value that is not a number or lies outside the range and keeps
|
||||
the old one (`Error, must be ...`). It applies to `set tx` (-9 up to the
|
||||
board's `MAX_LORA_TX_POWER`, else 30, and saved only if the radio takes it:
|
||||
SX1262 -9..22), `set radio` and `tempradio` (each field; the timeout 1-10080
|
||||
min), `set freq`, `set lat`/`set lon`, `set flood.max`, `set
|
||||
flood.max.unscoped`, `set flood.max.advert` (0-64), `set int.thresh` (0-255),
|
||||
`set multi.acks` (0-1), `set path.hash.mode` (0-2), `set agc.reset.interval`
|
||||
(0-1020), `set rxdelay`, `set txdelay`, `set direct.txdelay`, `set
|
||||
adc.multiplier`, and on the companion `set pin`, `set adc.multiplier`, `set
|
||||
tz.offset`. No exponent (`1e3`), no `nan`/`inf`.
|
||||
|
||||
## Diagnostics
|
||||
|
||||
| command | where | what |
|
||||
|---|---|---|
|
||||
| `blink [count]` | repeater | flash a spare LED (not the BLE or TX one) `count` times (1..999, default 6); finds a board on a bench or a node on a mast |
|
||||
| `blink <on\|off>` | repeater | blink until `blink off` (gives up after 10 min) |
|
||||
| `txpwr` | repeater | the last requested LoRa output power and RadioLib's status |
|
||||
| `txpwr <dBm>` | repeater | LoRa output power until reboot, -9..30 (SX1262 takes -9..22), with RadioLib's status |
|
||||
| `i2c` | all | scan the I2C bus |
|
||||
| `get chip` | nRF52 (repeater, room server, sensor) | the silicon (`nRF52840 AAD0`; variant `xxF0` and later = rev3) and `UICR.APPROTECT`: `open` means SWD can read the whole flash, keys included |
|
||||
| `dio1` | own build: `PIN_DIAG` | has the SX1262 raise TX_DONE and compares its IRQ register with the level on the DIO1 pin -- which end of a dead IRQ line is broken |
|
||||
| `radiostat` | own build: `RADIO_DIAG` | receiver state, interrupt and RX counters, without touching the radio |
|
||||
| `radiokick <rx\|clrirq\|standby\|agc>` | own build: `RADIO_DIAG` | one recovery step, gentlest first: re-arm RX, clear latched IRQs, standby + RX, AGC reset; the first that brings `recv` back names the broken layer |
|
||||
|
||||
A board with a dead DIO1 line still runs with `LORA_POLL_IRQ` (own build):
|
||||
the IRQ status is polled over SPI.
|
||||
|
||||
## BLE console (observer)
|
||||
|
||||
The text console over BLE (Nordic UART), next to USB. No login of its own:
|
||||
the BLE PIN is the only lock, and the release PIN is the public placeholder
|
||||
`123456`. These commands also work as admin over the mesh.
|
||||
|
||||
| command | what |
|
||||
|---|---|
|
||||
| `ble` | on or off, PIN `own` or `build default`, connected or not -- never the PIN itself |
|
||||
| `ble <on\|off>` | the BLE console on or off, saved. Default: off (`RPT_BLE_DEFAULT_OFF`); `ble on` is refused while the PIN is the placeholder |
|
||||
| `ble pin` | whether the PIN is your own or the build default |
|
||||
| `ble pin <pin>` | set your own PIN, 6 digits (saved, survives a reflash; drops every bond, so paired devices pair again) |
|
||||
| `blepwr` | TX power of the connection and of advertising |
|
||||
| `blepwr <dBm>` | TX power of the connection: -40, -20, -16, -12, -8, -4, 0, 2..8; applied to live connections and saved |
|
||||
| `blepwr default` | back to the build value (0 dBm) |
|
||||
| `bleconn` | what the central actually agreed to: interval (and what was requested), latency, supervision timeout |
|
||||
|
||||
A connected central stops the node advertising: if the BLE console cannot be
|
||||
found, look for who is connected (`ble` shows it).
|
||||
|
||||
## Passive analyzer (observer)
|
||||
|
||||
| command | what |
|
||||
|---|---|
|
||||
| `nodes [offset]` | heard repeaters and room servers with a key to join several paths, paged from `offset` |
|
||||
| `rxlog [cursor]` | every frame heard: type, path, SNR, RSSI; `cursor` from the previous page (`0` = all) |
|
||||
| `pktlog [cursor]` | raw frames heard, for an observer feed ([meshcore-repeater-observer](https://git.rfa.cz/tth-pub/meshcore-repeater-observer)) |
|
||||
|
||||
A page is as big as the caller's reply buffer: ~1000 B on the local console,
|
||||
one packet over the mesh.
|
||||
|
||||
## Channel bot (own build: `BOT_CHANNEL_PSK`)
|
||||
|
||||
A repeater that answers on one channel without forwarding anything:
|
||||
`!link`, `!path`, `!snr`, `!heard`, `!noise`, `!ping`, `!help` (narrowed by
|
||||
`BOT_COMMANDS`), with a per-sender cooldown and an ignore list. `bot` on the
|
||||
console shows its state.
|
||||
|
||||
## Power and clock
|
||||
|
||||
| command | where | what |
|
||||
|---|---|---|
|
||||
| `get radio.rxps` | all, SX1262 only (`WITH_RX_POWERSAVING`, in the releases) | requested and effective RX duty cycle, window lengths, error counters |
|
||||
| `set radio.rxps <off\|on\|balanced\|max>` | same | RX duty cycle: the radio sleeps between short listening windows. Presets: `on` = level 3, `balanced` = 6, `max` = 8. Saved. Default: off |
|
||||
| `set radio.rxps level <level> [preamble <16\|32>]` | same | the same by number, 1..10 (9 and 10 are past the datasheet's timing condition, 10 is known to lose packets) |
|
||||
| `set radio.rxps <rx_us> <sleep_us>` | same | raw window lengths |
|
||||
| `get batt.icon` | all | whether the icon is on, and whether the name leaves room for it |
|
||||
| `set batt.icon <on\|off>` | all | battery level as an icon at the end of the advertised name; with a name too long for it the icon is left out, and the reply says so. Default: off |
|
||||
| `set batt.icon.lo <mV>` | all | the empty end of the icon's scale, 2500..4500; `0` = build default (3300) |
|
||||
| `set batt.icon.hi <mV>` | all | the full end, 2500..4500; `0` = build default (4200) |
|
||||
| `gps duty` | GPS boards | the receiver runs only around a clock sync; `gps on` / `gps off` leave it. See cli_commands.md |
|
||||
| `get pwr` | SenseCAP Solar repeater (`PWRMGT_RUNTIME`) | both thresholds, the battery now and at boot, why the node last switched off |
|
||||
| `set pwr.bootlock <mV>` | same | do not start below this voltage, 3000..4200 or `off`; saved on the node, see [power.md](power.md) |
|
||||
| `set pwr.cutoff <mV>` | same | switch a running node off below this voltage, 3000..4200 or `off`. Must stay under the bootlock; neither may be above the battery right now |
|
||||
| `clkreboot` | all | reset the clock to the build epoch and reboot -- the only way to move a clock backwards (`time` and `clock sync` refuse to) |
|
||||
|
||||
RX duty cycle: `max` saved ~2.3 mA on the bench, but a mast on the live mesh
|
||||
lost 16 % of its reception -- see cli_commands.md and [power.md](power.md).
|
||||
|
||||
## Sensors
|
||||
|
||||
| command | what |
|
||||
|---|---|
|
||||
| `sensor read` | the live telemetry decoded into one line (`sensor list` shows only settings) |
|
||||
| `sensor get ina.shunt` | the shunt the current is computed with |
|
||||
| `sensor set ina.shunt <mOhm>` | shunt resistance of an INA219, INA226 or INA3221 module (`10` for `R010`), saved; `0` = build default (100). The INA260 has its shunt inside and no setting |
|
||||
|
||||
## Build flags
|
||||
|
||||
The ones that change what a node does; set in `platformio.ini` /
|
||||
`platformio.local.ini` (`-D NAME=value`, the last `-D` wins).
|
||||
|
||||
| flag | default | what |
|
||||
|---|---|---|
|
||||
| `FAIRNESS_ENABLED_DEFAULT` | `1` | FairnessLimiter on for a node without prefs |
|
||||
| `RADIO_SILENCE_MIN_DEFAULT` | `0` | deaf-receiver watchdog for a node without prefs |
|
||||
| `RADIO_TXSTALL_MIN` | `15` | TX stall watchdog at boot (repeater), `0` = off |
|
||||
| `FILTER_CHANNEL_PSKS` | releases: Public, `#meshcore`, `#test` | channel keys the filter can decrypt |
|
||||
| `MAX_HEARD_NODES`, `RXLOG_SIZE`, `PKTFEED_SIZE` | `0` (observer variants: 128 / 512 / 64) | the analyzer rings |
|
||||
| `BLE_PIN_CODE`, `RPT_BLE_DEFAULT_OFF` | observer variants | BLE console, starting off |
|
||||
| `BOT_CHANNEL_PSK`, `BOT_COMMANDS` | unset | channel bot |
|
||||
| `RADIO_DIAG`, `PIN_DIAG`, `LORA_POLL_IRQ` | unset | radio diagnostics, DIO1-less operation |
|
||||
| `FW_OTA` | `-ota` images | admin-pushed firmware update |
|
||||
| `PATH_HASH_MODE_DEFAULT` | `1` (2 B per hop) | path hash width for a node without prefs |
|
||||
| `ACL_TS_MAX_AHEAD` | `86400` (s) | a client timestamp further ahead of the node's clock is not stored as the replay floor |
|
||||
| `LOCKED_NODE` | unset | a node that keeps its secrets from whoever holds it: `get prv.key`, `get guest.password` and `get bridge.secret` answer `Error: locked build` to everyone (USB and BLE console, an admin over the mesh); a companion serves only paired BLE (USB, UART and WiFi get the device info and nothing else) and its rescue CLI refuses `set pin`. Only half of it: whoever can rewrite the flash (SWD with `APPROTECT` open, an unsigned DFU) still gets the keys -- the other half is a locked bootloader (SWD closed, signed images only), which these builds do not have |
|
||||
| `LOGIN_FAIL_MAX`, `LOGIN_FAIL_SECS` | `4`, `180` (s) | after that many wrong passwords in the window no password is checked until it ends (an admin already in the ACL always gets in) |
|
||||
| `NRF52_POWER_MANAGEMENT`, `PWRMGT_RUNTIME` | upstream: off; on in `SenseCap_Solar_repeater` (the masts) | boot protection, and with `PWRMGT_RUNTIME` the runtime `pwr.bootlock` / `pwr.cutoff` above |
|
||||
| `PWRMGT_BOOTLOCK_DEFAULT`, `PWRMGT_CUTOFF_DEFAULT` | `PWRMGT_VOLTAGE_BOOTLOCK` (SenseCAP 3300), `0` (mV) | thresholds for a node without `/pwr_guard` |
|
||||
| `PWR_DUTY_INSTRUMENT` | unset | bench only, nRF52: every ~10 s a `PWRDUTY` line on the USB console with the time the MCU was awake and asleep, its wakes, and the CPU time spent on received packets. See [power.md](power.md#cpu-time-per-received-packet-pwr_duty_instrument) |
|
||||
|
||||
Prefs saved on the node override the build defaults: a reflash keeps what a
|
||||
node already has; only a new node or one after `erase` takes them.
|
||||
@@ -265,6 +265,12 @@ File file = openRead(_getContactsChannelsFS(), "/contacts3");
|
||||
uint8_t pub_key[32];
|
||||
uint8_t unused;
|
||||
|
||||
// The on-disk record has no shared_secret/shared_secret_valid, so those
|
||||
// two members are never written by the reads below. Left indeterminate,
|
||||
// a non-zero shared_secret_valid makes getSharedSecret() return an
|
||||
// uninitialised secret for a contact loaded at boot.
|
||||
memset(&c, 0, sizeof(c));
|
||||
|
||||
bool success = (file.read(pub_key, 32) == 32);
|
||||
success = success && (file.read((uint8_t *)&c.name, 32) == 32);
|
||||
success = success && (file.read(&c.type, 1) == 1);
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include <WiFi.h>
|
||||
#endif
|
||||
#include <Mesh.h>
|
||||
#include <helpers/CliArgs.h>
|
||||
|
||||
#define CMD_APP_START 1
|
||||
#define CMD_SEND_TXT_MSG 2
|
||||
@@ -651,6 +652,12 @@ uint8_t MyMesh::onContactRequest(const ContactInfo &contact, uint32_t sender_tim
|
||||
permissions &= perm_mask;
|
||||
|
||||
if (permissions & TELEM_PERM_BASE) { // only respond if base permission bit is set
|
||||
if (permissions & TELEM_PERM_LOCATION) {
|
||||
// Nudge a duty-cycled GPS awake. This reply still carries the position
|
||||
// we already have -- the fix is ~65 s away and the reply goes out now --
|
||||
// but the next request lands after the window and gets a fresh one.
|
||||
sensors.requestLocationRefresh();
|
||||
}
|
||||
telemetry.reset();
|
||||
telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f);
|
||||
// query other sensors -- target specific
|
||||
@@ -910,6 +917,15 @@ MyMesh::MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMe
|
||||
_prefs.bw = LORA_BW;
|
||||
_prefs.cr = LORA_CR;
|
||||
_prefs.tx_power_dbm = LORA_TX_POWER;
|
||||
// CUSTOM (TeTeHacko): 2-byte path hashes by default, same as the repeater --
|
||||
// upstream left this unset, so a fresh node came up at mode 0 = 1 byte per
|
||||
// hop, which nobody on the CZ mesh runs any more. See the longer note in
|
||||
// simple_repeater/MyMesh.cpp: this is the PATH hash (bytes each hop appends
|
||||
// while flooding, size carried in the packet), NOT PATH_HASH_SIZE.
|
||||
#ifndef PATH_HASH_MODE_DEFAULT
|
||||
#define PATH_HASH_MODE_DEFAULT 1 // 1 = 2 bytes per hop
|
||||
#endif
|
||||
_prefs.path_hash_mode = PATH_HASH_MODE_DEFAULT;
|
||||
_prefs.gps_enabled = 0; // GPS disabled by default
|
||||
_prefs.gps_interval = 0; // No automatic GPS updates by default
|
||||
_prefs.radio_fem_rxgain = 1;
|
||||
@@ -978,7 +994,7 @@ void MyMesh::begin() {
|
||||
_prefs.sf = constrain(_prefs.sf, 5, 12);
|
||||
_prefs.cr = constrain(_prefs.cr, 5, 8);
|
||||
_prefs.tx_power_dbm = constrain(_prefs.tx_power_dbm, -9, MAX_LORA_TX_POWER);
|
||||
_prefs.gps_enabled = constrain(_prefs.gps_enabled, 0, 1); // Ensure boolean 0 or 1
|
||||
_prefs.gps_enabled = constrain(_prefs.gps_enabled, 0, 2); // 0 off, 1 on, 2 duty cycle
|
||||
_prefs.gps_interval = constrain(_prefs.gps_interval, 0, 86400); // Max 24 hours
|
||||
_prefs.adc_multiplier = constrain(_prefs.adc_multiplier, 0.0f, 10.0f);
|
||||
if (!board.setAdcMultiplier(_prefs.adc_multiplier)) _prefs.adc_multiplier = 0.0f;
|
||||
@@ -1042,6 +1058,16 @@ void MyMesh::startInterface(BaseSerialInterface &serial) {
|
||||
}
|
||||
|
||||
void MyMesh::handleCmdFrame(size_t len) {
|
||||
#ifdef LOCKED_NODE
|
||||
// CUSTOM (TeTeHacko): a locked companion serves only paired BLE. USB, a UART
|
||||
// and WiFi/TCP get the device info (so an app sees what it talks to) and
|
||||
// nothing else: no contacts, channels, messages or settings for whoever holds
|
||||
// the board or sits on the LAN. docs/locked-bootloader.md, point 4.
|
||||
if (!_serial->isConnectionSecure() && cmd_frame[0] != CMD_DEVICE_QUERY) {
|
||||
writeDisabledFrame();
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
if (cmd_frame[0] == CMD_DEVICE_QUERY && len >= 2) { // sent when app establishes connection
|
||||
app_target_ver = cmd_frame[1]; // which version of protocol does app understand
|
||||
|
||||
@@ -1050,10 +1076,19 @@ void MyMesh::handleCmdFrame(size_t len) {
|
||||
out_frame[i++] = FIRMWARE_VER_CODE;
|
||||
out_frame[i++] = MAX_CONTACTS / 2; // v3+
|
||||
out_frame[i++] = MAX_GROUP_CHANNELS; // v3+
|
||||
memcpy(&out_frame[i], &_prefs.ble_pin, 4);
|
||||
// Never reveal the BLE pairing PIN over an unauthenticated transport (USB):
|
||||
// it would let a momentary physical connection learn the PIN and then pair
|
||||
// over BLE remotely. Only report it to an already-paired BLE peer.
|
||||
uint32_t reported_ble_pin = _serial->isConnectionSecure() ? _prefs.ble_pin : 0;
|
||||
memcpy(&out_frame[i], &reported_ble_pin, 4);
|
||||
i += 4;
|
||||
memset(&out_frame[i], 0, 12);
|
||||
strcpy((char *)&out_frame[i], FIRMWARE_BUILD_DATE);
|
||||
// 12-byte field = 11 chars + NUL. strcpy() here was unbounded: the default
|
||||
// FIRMWARE_BUILD_DATE literal ("6 Jun 2026") fits, but a stamped one from
|
||||
// tools/build_version.py does not, and the overrun ran into the
|
||||
// manufacturer-name field below -- invisibly, because strzcpy() overwrote it
|
||||
// on the next line. strzcpy() truncates and NUL-pads instead (so the memset
|
||||
// is redundant), same as every other string in this frame.
|
||||
StrHelper::strzcpy((char *)&out_frame[i], FIRMWARE_BUILD_DATE, 12);
|
||||
i += 12;
|
||||
StrHelper::strzcpy((char *)&out_frame[i], board.getManufacturerName(), 40);
|
||||
i += 40;
|
||||
@@ -1061,7 +1096,7 @@ void MyMesh::handleCmdFrame(size_t len) {
|
||||
i += 20;
|
||||
out_frame[i++] = _prefs.isRepeatEn() ? 1 : 0; // v9+
|
||||
out_frame[i++] = _prefs.path_hash_mode; // v10+
|
||||
_serial->writeFrame(out_frame, i);
|
||||
_serial->writeReplyFrame(out_frame, i); // carries the PIN: never to the other transports
|
||||
} else if (cmd_frame[0] == CMD_APP_START &&
|
||||
len >= 8) { // sent when app establishes connection, respond with node ID
|
||||
// cmd_frame[1..7] reserved future
|
||||
@@ -1327,6 +1362,13 @@ void MyMesh::handleCmdFrame(size_t len) {
|
||||
writeOKFrame();
|
||||
} else {
|
||||
ContactInfo contact;
|
||||
// The frame's lat/lon/lastmod are optional, and clients omit them when the
|
||||
// contact has no location -- so anything updateContactFromFrame() does not
|
||||
// write stays as whatever was on the stack. That leaks garbage into
|
||||
// gps_lat/gps_lon and, worse, into shared_secret_valid: a non-zero byte
|
||||
// there makes getSharedSecret() hand out an uninitialised secret.
|
||||
// populateContactFromAdvert() zeroes for the same reason.
|
||||
memset(&contact, 0, sizeof(contact));
|
||||
updateContactFromFrame(contact, last_mod, cmd_frame, len);
|
||||
contact.lastmod = last_mod;
|
||||
contact.sync_since = 0;
|
||||
@@ -1518,10 +1560,15 @@ void MyMesh::handleCmdFrame(size_t len) {
|
||||
_serial->writeFrame(reply, i);
|
||||
} else if (cmd_frame[0] == CMD_EXPORT_PRIVATE_KEY) {
|
||||
#if ENABLE_PRIVATE_KEY_EXPORT
|
||||
uint8_t reply[65];
|
||||
reply[0] = RESP_CODE_PRIVATE_KEY;
|
||||
self_id.writeTo(&reply[1], 64);
|
||||
_serial->writeFrame(reply, 65);
|
||||
if (!_serial->isConnectionSecure()) {
|
||||
// never export the identity over an unauthenticated transport (USB)
|
||||
writeDisabledFrame();
|
||||
} else {
|
||||
uint8_t reply[65];
|
||||
reply[0] = RESP_CODE_PRIVATE_KEY;
|
||||
self_id.writeTo(&reply[1], 64);
|
||||
_serial->writeReplyFrame(reply, 65); // only back to the paired BLE peer, not out on USB too
|
||||
}
|
||||
#else
|
||||
writeDisabledFrame();
|
||||
#endif
|
||||
@@ -1829,17 +1876,22 @@ void MyMesh::handleCmdFrame(size_t len) {
|
||||
}
|
||||
} else if (cmd_frame[0] == CMD_SET_DEVICE_PIN && len >= 5) {
|
||||
|
||||
// get pin from command frame
|
||||
uint32_t pin;
|
||||
memcpy(&pin, &cmd_frame[1], 4);
|
||||
|
||||
// ensure pin is zero, or a valid 6 digit pin
|
||||
if (pin == 0 || (pin >= 100000 && pin <= 999999)) {
|
||||
_prefs.ble_pin = pin;
|
||||
savePrefs();
|
||||
writeOKFrame();
|
||||
} else {
|
||||
if (!_serial->isConnectionSecure()) {
|
||||
// don't let an unauthenticated transport (USB) change the BLE pairing PIN
|
||||
writeErrFrame(ERR_CODE_ILLEGAL_ARG);
|
||||
} else {
|
||||
// get pin from command frame
|
||||
uint32_t pin;
|
||||
memcpy(&pin, &cmd_frame[1], 4);
|
||||
|
||||
// ensure pin is zero, or a valid 6 digit pin
|
||||
if (pin == 0 || (pin >= 100000 && pin <= 999999)) {
|
||||
_prefs.ble_pin = pin;
|
||||
savePrefs();
|
||||
writeOKFrame();
|
||||
} else {
|
||||
writeErrFrame(ERR_CODE_ILLEGAL_ARG);
|
||||
}
|
||||
}
|
||||
} else if (cmd_frame[0] == CMD_GET_CUSTOM_VARS) {
|
||||
out_frame[0] = RESP_CODE_CUSTOM_VARS;
|
||||
@@ -1866,7 +1918,7 @@ void MyMesh::handleCmdFrame(size_t len) {
|
||||
#if ENV_INCLUDE_GPS == 1
|
||||
// Update node preferences for GPS settings
|
||||
if (strcmp(sp, "gps") == 0) {
|
||||
_prefs.gps_enabled = (np[0] == '1') ? 1 : 0;
|
||||
_prefs.gps_enabled = (np[0] == '2') ? 2 : ((np[0] == '1') ? 1 : 0);
|
||||
savePrefs();
|
||||
} else if (strcmp(sp, "gps_interval") == 0) {
|
||||
uint32_t interval_seconds = atoi(np);
|
||||
@@ -1874,6 +1926,10 @@ void MyMesh::handleCmdFrame(size_t len) {
|
||||
savePrefs();
|
||||
}
|
||||
#endif
|
||||
if (strcmp(sp, "ina.shunt") == 0) { // CUSTOM (TeTeHacko): survives a reboot
|
||||
_prefs.ina_shunt_mohm = atof(np);
|
||||
savePrefs();
|
||||
}
|
||||
writeOKFrame();
|
||||
} else {
|
||||
writeErrFrame(ERR_CODE_ILLEGAL_ARG);
|
||||
@@ -2067,15 +2123,10 @@ void MyMesh::enterCLIRescue() {
|
||||
Serial.println("========= CLI Rescue =========");
|
||||
}
|
||||
|
||||
bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* reply) {
|
||||
while (*command == ' ') command++; // skip leading spaces
|
||||
extern "C" void retainedClockInvalidate() __attribute__((weak)); // NRF52Board.cpp
|
||||
|
||||
if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI)
|
||||
memcpy(reply, command, 3); // reflect the prefix back
|
||||
reply += 3;
|
||||
*reply = 0;
|
||||
command += 3;
|
||||
}
|
||||
bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* reply) {
|
||||
cli_args::stripPrefix(command, reply);
|
||||
|
||||
if (_prefs.getRadioPrefs()->handleCommand(command, sender_timestamp, reply)) { // is radio CLI command?
|
||||
if (_prefs.getRadioPrefs()->isDirty()) { savePrefs(); }
|
||||
@@ -2098,6 +2149,19 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char*
|
||||
return true;
|
||||
}
|
||||
|
||||
// CUSTOM (TeTeHacko): the only way to move an over-set clock BACKWARDS.
|
||||
// CMD_SET_DEVICE_TIME refuses to, and since the clock survives a warm reset on
|
||||
// nRF52 (ArduinoHelpers.h) a plain `reboot` no longer drops it to the build
|
||||
// epoch either -- without this a companion that is ahead stays ahead until its
|
||||
// power is pulled. Same as the repeater's `clkreboot` (CommonCLI.cpp). Then set
|
||||
// the right time again (the app, or `time` from a host); forward is allowed.
|
||||
if (strcmp(command, "clkreboot") == 0) {
|
||||
if (retainedClockInvalidate) retainedClockInvalidate();
|
||||
getRTCClock()->setCurrentTime(FIRMWARE_BUILD_EPOCH);
|
||||
board.reboot(); // doesn't return
|
||||
return true;
|
||||
}
|
||||
|
||||
if (strcmp(command, "poweroff") == 0 || strcmp(command, "shutdown") == 0) {
|
||||
board.powerOff(); // doesn't return
|
||||
return true;
|
||||
@@ -2136,7 +2200,23 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char*
|
||||
#endif
|
||||
|
||||
if (memcmp(command, "set pin ", 8) == 0) {
|
||||
_prefs.ble_pin = atoi(&command[8]);
|
||||
const char* err = nullptr;
|
||||
#ifdef LOCKED_NODE
|
||||
const bool locked = true;
|
||||
#else
|
||||
const bool locked = false;
|
||||
#endif
|
||||
if (!cli_args::canSetPin(sender_timestamp, _cli_rescue, locked,
|
||||
_serial && _serial->isConnectionSecure(), &err)) {
|
||||
strcpy(reply, err);
|
||||
return true;
|
||||
}
|
||||
long pin; // atoi(): "abc" was PIN 0, i.e. a random one
|
||||
if (!cli_args::parseInt(&command[8], 0, 999999, &pin)) {
|
||||
strcpy(reply, "Error, PIN must be 0-999999");
|
||||
return true;
|
||||
}
|
||||
_prefs.ble_pin = pin;
|
||||
savePrefs();
|
||||
sprintf(reply, "> pin is now %06d", _prefs.ble_pin);
|
||||
return true;
|
||||
@@ -2229,8 +2309,8 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char*
|
||||
}
|
||||
|
||||
if (memcmp(command, "set adc.multiplier ", 19) == 0) { // same as CommonCLI
|
||||
float mult = atof(&command[19]);
|
||||
if (mult < 0.0f || mult > 10.0f) {
|
||||
float mult = 0;
|
||||
if (!cli_args::parseFloat(&command[19], 0.0f, 10.0f, &mult)) {
|
||||
strcpy(reply, "Error, must be from 0 to 10");
|
||||
} else if (board.setAdcMultiplier(mult)) {
|
||||
_prefs.adc_multiplier = mult;
|
||||
@@ -2261,8 +2341,8 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char*
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "set tz.offset ", 14) == 0) {
|
||||
float tz = atof(&command[14]);
|
||||
if (tz < -12 || tz > 14) {
|
||||
float tz = 0;
|
||||
if (!cli_args::parseFloat(&command[14], -12.0f, 14.0f, &tz)) {
|
||||
strcpy(reply, "Error, must be from -12 to +14");
|
||||
} else {
|
||||
_prefs.tz_offset = tz;
|
||||
|
||||
@@ -122,6 +122,11 @@ protected:
|
||||
bool filterRecvFloodPacket(mesh::Packet* packet) override;
|
||||
bool allowPacketForward(const mesh::Packet* packet) override;
|
||||
|
||||
// Šířku path hashe volí ODESÍLATEL, takže musí přijít z prefs tohohle uzlu.
|
||||
// Díky tomuhle overridu ji dostanou i volání send*(), která ji nepředávají
|
||||
// explicitně (ACKy, PATH-return, zerohop odpovědi sousedovi).
|
||||
uint8_t getSelfPathHashSize() const override { return _prefs.path_hash_mode + 1; }
|
||||
|
||||
void sendFloodScoped(const TransportKey& scope, mesh::Packet* pkt, uint32_t delay_millis);
|
||||
void sendFloodScoped(const ContactInfo& recipient, mesh::Packet* pkt, uint32_t delay_millis=0) override;
|
||||
void sendFloodScoped(const mesh::GroupChannel& channel, mesh::Packet* pkt, uint32_t delay_millis=0) override;
|
||||
@@ -185,6 +190,9 @@ public:
|
||||
sensors.setSettingValue("gps_interval", interval);
|
||||
}
|
||||
_prefs.getGpsPrefs()->apply(sensors);
|
||||
// 2 = duty cycle (see EnvironmentSensorManager::gpsDutyLoop); apply() only
|
||||
// knows on/off, so switch the sensor manager into duty after it
|
||||
if (_prefs.gps_enabled == 2) sensors.setSettingValue("gps", "2");
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
@@ -320,6 +320,7 @@ void setup() {
|
||||
#if ENV_INCLUDE_GPS == 1
|
||||
the_mesh.applyGpsPrefs();
|
||||
#endif
|
||||
sensors.applyInaShunt(the_mesh.getNodePrefs()->ina_shunt_mohm); // CUSTOM (TeTeHacko)
|
||||
|
||||
#ifdef DISPLAY_CLASS
|
||||
ui_task.begin(disp, &sensors, the_mesh.getNodePrefs(), &interface_manager, &the_mesh, the_mesh.getBLEPin(), FIRMWARE_VERSION, FIRMWARE_BUILD_DATE);
|
||||
|
||||
@@ -760,8 +760,26 @@ void KissModem::handleReboot() {
|
||||
}
|
||||
|
||||
void KissModem::handleGetDeviceName() {
|
||||
const char* name = _board.getManufacturerName();
|
||||
writeHardwareFrame(HW_RESP(HW_CMD_GET_DEVICE_NAME), (const uint8_t*)name, strlen(name));
|
||||
// CUSTOM (TeTeHacko): k výrobci se připojuje STAMPOVANÁ verze firmwaru.
|
||||
//
|
||||
// Bez ní je deska s tímhle buildem z hlediska verzí neidentifikovatelná:
|
||||
// GetVersion (0x11) vrací verzi KISS PROTOKOLU (konstanta KISS_FIRMWARE_VERSION),
|
||||
// textovou konzoli ani companion protokol tenhle build nemá, a protože se
|
||||
// FIRMWARE_VERSION nikde jinde nepoužívá, linker ten řetězec z obrazu vyhodí --
|
||||
// takže ho nenajde ani `tools/xiao_uf2_flash.sh`, který kvůli tomu flash rovnou
|
||||
// odmítne ("obraz nema verzi od tools/build_version.py").
|
||||
//
|
||||
// 1. 9. 2026 to stálo hodinu: KISS modem skončil omylem na x2, deska pak
|
||||
// neodpovídala konzoli ani companionu a vypadala jako zaseklá, a nešlo z ní
|
||||
// zjistit, co na ní vlastně je. `tools/board_probe.py` se ptá právě sem.
|
||||
char buf[96];
|
||||
int n = snprintf(buf, sizeof(buf), "%s %s", _board.getManufacturerName(), FIRMWARE_VERSION);
|
||||
if (n < 0) n = 0;
|
||||
// snprintf vraci delku BEZ koncove nuly, takze n == sizeof(buf) znamena
|
||||
// "presne se to nevleslo". `n > sizeof(buf)` to propustilo a clampovalo na
|
||||
// sizeof(buf), cimz na drat sla i ta koncova nula na buf[95].
|
||||
if (n >= (int)sizeof(buf)) n = (int)sizeof(buf) - 1;
|
||||
writeHardwareFrame(HW_RESP(HW_CMD_GET_DEVICE_NAME), (const uint8_t*)buf, n);
|
||||
}
|
||||
|
||||
void KissModem::handleSetSignalReport(const uint8_t* data, uint16_t len) {
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
#pragma once
|
||||
|
||||
// CUSTOM (TeTeHacko): pure string helpers for the channel modules
|
||||
// (ChannelCommon.h, ChannelFilter.h, ChannelBot.h). No MyMesh, no Arduino --
|
||||
// deliberately, so test/test_chan_list can compile them on the native env.
|
||||
|
||||
#include <ctype.h>
|
||||
#include <string.h>
|
||||
|
||||
// Longest node name an entry may hold. MeshCore node names are 32 bytes
|
||||
// (NodePrefs.node_name), the margin is for UTF-8 names people paste with
|
||||
// trailing decoration.
|
||||
#define CHAN_NAME_MAX 40
|
||||
|
||||
#define CHAN_LIST_OK 0
|
||||
#define CHAN_LIST_BAD_NAME -1 // empty, too long, or contains the ',' separator
|
||||
#define CHAN_LIST_DUP -2
|
||||
#define CHAN_LIST_FULL -3
|
||||
|
||||
static int chan_hex_nibble(char c) {
|
||||
if (c >= '0' && c <= '9') return c - '0';
|
||||
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
|
||||
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Exact, case-insensitive membership in a comma-separated list. Deliberately
|
||||
// NOT a substring search: an ignore/deny list matching on substrings would be
|
||||
// a trap (a node called "TTH" silencing "tracker"). Entries are trimmed of
|
||||
// surrounding spaces; case folding is ASCII-only, so UTF-8 names match
|
||||
// byte-exactly (good enough -- nobody case-shifts emoji).
|
||||
static bool chan_list_has(const char* list, const char* word) {
|
||||
const char* seg = list;
|
||||
while (*seg) {
|
||||
const char* comma = strchr(seg, ',');
|
||||
int len = comma ? (int)(comma - seg) : (int)strlen(seg);
|
||||
while (len > 0 && *seg == ' ') { seg++; len--; }
|
||||
while (len > 0 && seg[len - 1] == ' ') len--;
|
||||
if (len > 0 && (int)strlen(word) == len) {
|
||||
int i = 0;
|
||||
while (i < len && tolower((unsigned char)word[i]) == tolower((unsigned char)seg[i])) i++;
|
||||
if (i == len) return true;
|
||||
}
|
||||
if (!comma) break;
|
||||
seg = comma + 1;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Append name[0..name_len) to the comma-separated `list` (buffer of `cap`
|
||||
// bytes, NUL-terminated). Leading/trailing spaces are trimmed off the name
|
||||
// first (RF-padded commands happen).
|
||||
static int chan_list_add(char* list, int cap, const char* name, int name_len) {
|
||||
while (name_len > 0 && *name == ' ') { name++; name_len--; }
|
||||
while (name_len > 0 && name[name_len - 1] == ' ') name_len--;
|
||||
if (name_len <= 0 || name_len >= CHAN_NAME_MAX) return CHAN_LIST_BAD_NAME;
|
||||
if (memchr(name, ',', name_len) != NULL) return CHAN_LIST_BAD_NAME; // ',' is the separator
|
||||
|
||||
char tmp[CHAN_NAME_MAX];
|
||||
memcpy(tmp, name, name_len);
|
||||
tmp[name_len] = 0;
|
||||
if (chan_list_has(list, tmp)) return CHAN_LIST_DUP;
|
||||
|
||||
int cur = strlen(list);
|
||||
if (cur + (cur > 0 ? 1 : 0) + name_len + 1 > cap) return CHAN_LIST_FULL;
|
||||
if (cur > 0) list[cur++] = ',';
|
||||
memcpy(&list[cur], tmp, name_len + 1);
|
||||
return CHAN_LIST_OK;
|
||||
}
|
||||
|
||||
// Remove the (case-insensitively) matching entry. Returns false when absent.
|
||||
static bool chan_list_del(char* list, const char* name) {
|
||||
while (*name == ' ') name++;
|
||||
int name_len = strlen(name);
|
||||
while (name_len > 0 && name[name_len - 1] == ' ') name_len--; // trim trailing too (RF pads)
|
||||
char out[512]; // callers' lists are far smaller (filter_deny is 128 B)
|
||||
int out_len = 0;
|
||||
bool removed = false;
|
||||
const char* seg = list;
|
||||
int list_len = strlen(list);
|
||||
if (list_len >= (int)sizeof(out)) return false; // defensive, never expected
|
||||
|
||||
while (*seg) {
|
||||
const char* comma = strchr(seg, ',');
|
||||
int len = comma ? (int)(comma - seg) : (int)strlen(seg);
|
||||
const char* e = seg;
|
||||
int elen = len;
|
||||
while (elen > 0 && *e == ' ') { e++; elen--; }
|
||||
while (elen > 0 && e[elen - 1] == ' ') elen--;
|
||||
bool match = false;
|
||||
if (name_len == elen) {
|
||||
int i = 0;
|
||||
while (i < elen && tolower((unsigned char)name[i]) == tolower((unsigned char)e[i])) i++;
|
||||
match = (i == elen);
|
||||
}
|
||||
if (match) {
|
||||
removed = true;
|
||||
} else if (len > 0) {
|
||||
if (out_len > 0) out[out_len++] = ',';
|
||||
memcpy(&out[out_len], seg, len);
|
||||
out_len += len;
|
||||
}
|
||||
if (!comma) break;
|
||||
seg = comma + 1;
|
||||
}
|
||||
if (removed) {
|
||||
out[out_len] = 0;
|
||||
memcpy(list, out, out_len + 1);
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
#pragma once
|
||||
|
||||
// CUSTOM (TeTeHacko): channel bot -- not part of upstream simple_repeater.
|
||||
// Included at the bottom of MyMesh.cpp, after ChannelCommon.h (which owns the
|
||||
// channel registry, the PSK parsing, searchChannelsByHash() and the
|
||||
// onGroupDataRecv() dispatcher that calls botOnChannelText() here), so these
|
||||
// are plain MyMesh methods with full access to the analyzer state.
|
||||
//
|
||||
// WHY THIS LIVES IN THE REPEATER/ANALYZER BUILD
|
||||
//
|
||||
// The obvious place for a bot is companion_radio (it already has channels and
|
||||
// contacts), but a companion build has no text CLI and no analyzer rings, so the
|
||||
// observer node would stop feeding CoreScope. The reverse -- teaching this build
|
||||
// to read one channel -- turned out to be small, because everything needed is
|
||||
// already virtual in mesh::Mesh:
|
||||
//
|
||||
// * Mesh::onRecvPacket() calls searchChannelsByHash() + onGroupDataRecv() and
|
||||
// THEN routeRecvPacket(), so decrypting a channel is independent of
|
||||
// forwarding it. Both defaults are no-ops (Mesh.cpp:37, Mesh.h:160), which
|
||||
// is the only reason a repeater is normally deaf to channel traffic.
|
||||
// * allowPacketForward() is consulted only for RECEIVED packets, so a node
|
||||
// with `repeat off` can still originate its own reply. That matters here:
|
||||
// x3 sits a few metres from mast-three and must never be a second repeater,
|
||||
// but it does have to be able to answer.
|
||||
// * createGroupDatagram() is in mesh::Mesh, not BaseChatMesh, and
|
||||
// sendFloodScoped() is a plain alias for sendFlood(), so no part of the
|
||||
// chat/contact machinery is needed to send.
|
||||
//
|
||||
// Written against the mesh::Mesh API only (no BaseChatMesh, no ClientACL, no
|
||||
// DataStore) so it can be dropped into simple_room_server unchanged -- that
|
||||
// example derives from the same base.
|
||||
|
||||
#ifdef BOT_CHANNEL_PSK
|
||||
|
||||
// Comma-separated, case-insensitive substrings; "*" answers anything, "" never.
|
||||
#ifndef BOT_TRIGGER
|
||||
#define BOT_TRIGGER "ping,test"
|
||||
#endif
|
||||
// Senders whose messages are skipped outright, comma-separated node names.
|
||||
// This is what keeps two bots on one channel from feeding each other: with
|
||||
// tracker (Solo firmware) periodically putting "Ping" on #tth-test, an
|
||||
// unfiltered trigger list made this node answer every one of them and burn the
|
||||
// cooldown, so a human asking a question got silence.
|
||||
#ifndef BOT_IGNORE_SENDERS
|
||||
#define BOT_IGNORE_SENDERS ""
|
||||
#endif
|
||||
// Whitelist of `!commands` this node answers, comma-separated, "" = all.
|
||||
// The point is complementarity: two bots answering !path means two packets and
|
||||
// one duplicate. Give each node the commands only it can answer well.
|
||||
#ifndef BOT_COMMANDS
|
||||
#define BOT_COMMANDS ""
|
||||
#endif
|
||||
// Throttle, PER SENDER. Measured reason it is not global: with one global
|
||||
// window, two people asking within it meant the second got silence -- observed
|
||||
// twice, and it reads as "the bot is broken" rather than "wait 10 s".
|
||||
#ifndef BOT_REPLY_COOLDOWN_MS
|
||||
#define BOT_REPLY_COOLDOWN_MS 10000
|
||||
#endif
|
||||
// Floor between ANY two replies, whoever asked. This is what still bounds the
|
||||
// node's airtime on a shared community mesh once the main window went
|
||||
// per-sender: N senders can no longer produce N simultaneous replies.
|
||||
#ifndef BOT_MIN_GAP_MS
|
||||
#define BOT_MIN_GAP_MS 2500
|
||||
#endif
|
||||
// Cap on the whole bot over a longer window: at most BOT_BURST_MAX replies per
|
||||
// BOT_BURST_WINDOW_MS (0 = off). The per-sender window is keyed by NAME, which
|
||||
// is plain text in a channel message, so ten names walk around it; the floor
|
||||
// alone still lets through 24 replies/min (~18 % of channel airtime). Normal
|
||||
// use is ~15 replies a DAY, so 10 per 5 min cuts nothing legitimate.
|
||||
// BOT_BURST_MAX itself defaults in MyMesh.h (it sizes an array there).
|
||||
#ifndef BOT_BURST_WINDOW_MS
|
||||
#define BOT_BURST_WINDOW_MS 300000
|
||||
#endif
|
||||
// Senders tracked for the per-sender window. Wraps LRU; overflowing just means
|
||||
// the oldest sender's window is forgotten early, i.e. one extra reply.
|
||||
#ifndef BOT_PEER_SLOTS
|
||||
#define BOT_PEER_SLOTS 8
|
||||
#endif
|
||||
|
||||
#define BOT_REPLY_LEN 120 // well under the 184 B packet payload
|
||||
#define BOT_PATH_STR_LEN 64 // "3f:a1:c8..." -- caps how many hops we print
|
||||
// One !command's answer. Sized for the WORST CASE of !link, which is the longest:
|
||||
// botFormatPath() caps the path string at 62 chars (21 hops x 1 B, or 9 x 3 B, or
|
||||
// 12 x 2 B -- all land just under BOT_PATH_STR_LEN), and the numbers in front of it
|
||||
// add 36 ("SNR -20.5 dB, RSSI -128 dBm, 63 hop "). 98 + NUL.
|
||||
//
|
||||
// It was 72, sized against the longest COMMAND rather than the longest PATH, and
|
||||
// that held only because !link had never been asked from further than 2 hops away.
|
||||
// Measured 7. 8. 2026: an 11-hop request wanted 88 chars, so the reply truncated at
|
||||
// 71 -- and with the old field order the part that got cut was exactly the SNR/RSSI
|
||||
// the command exists to report ("... 209f:34fa:ed9c, SNR 4.0 ").
|
||||
#define BOT_FRAG_LEN 100
|
||||
|
||||
// Registers the bot channel in the shared registry (ChannelCommon.h does the
|
||||
// hex parse and hash derivation) and resets bot state. Called by channelsInit().
|
||||
void MyMesh::botInit() {
|
||||
bot_next_reply_at = 0;
|
||||
bot_replies_sent = 0;
|
||||
bot_ignored = 0;
|
||||
bot_throttled = 0;
|
||||
memset(bot_peers, 0, sizeof(bot_peers));
|
||||
memset(bot_burst_until, 0, sizeof(bot_burst_until));
|
||||
bot_burst_head = 0;
|
||||
bot_last_reply_secs = 0;
|
||||
|
||||
const char* psk = BOT_CHANNEL_PSK;
|
||||
bot_channel_idx = (int8_t)channelAddFromPsk(psk, strlen(psk), CHAN_FLAG_BOT);
|
||||
}
|
||||
|
||||
// Colon-separated per-hop hashes, the same self-describing convention the
|
||||
// analyzer's pktlog uses (analyzer_path_hex): the hash width is uniform per
|
||||
// packet but invisible in the hex, so ':' marks where one hop ends. Width comes
|
||||
// from the packet, NOT a constant -- one node on this mesh runs 3-byte hashes
|
||||
// deliberately. `out` must hold BOT_PATH_STR_LEN bytes.
|
||||
void MyMesh::botFormatPath(char* out, const mesh::Packet* pkt) const {
|
||||
static const char hexd[] = "0123456789abcdef";
|
||||
uint8_t cnt = pkt->getPathHashCount();
|
||||
uint8_t sz = pkt->getPathHashSize();
|
||||
if (cnt == 0 || sz == 0) { strcpy(out, "direct"); return; }
|
||||
|
||||
uint8_t max_hops = (BOT_PATH_STR_LEN - 1) / (sz * 2 + 1);
|
||||
char* p = out;
|
||||
uint8_t off = 0;
|
||||
for (uint8_t h = 0; h < cnt && h < max_hops && off + sz <= MAX_PATH_SIZE; h++) {
|
||||
if (h) *p++ = ':';
|
||||
for (uint8_t b = 0; b < sz; b++, off++) {
|
||||
*p++ = hexd[pkt->path[off] >> 4];
|
||||
*p++ = hexd[pkt->path[off] & 0x0F];
|
||||
}
|
||||
}
|
||||
*p = 0;
|
||||
}
|
||||
|
||||
// NOTE: exact-membership matching lives in chan_list_has() (ChannelCommon.h);
|
||||
// it is distinct from botTriggerMatches(), which is a SUBSTRING search -- an
|
||||
// ignore list or a command whitelist matching on substrings would be a trap
|
||||
// ("path" enabling "!pathx", a node called "TTH" silencing "tracker").
|
||||
|
||||
// One `!command` -> one text fragment. Returns chars written, 0 for unknown.
|
||||
// The interesting ones are the analyzer's: a companion bot cannot answer these
|
||||
// at all, because it has no rxlog and no heard registry.
|
||||
int MyMesh::botCommandReply(char* out, int max_len, const char* cmd, const mesh::Packet* pkt) {
|
||||
// An empty BOT_COMMANDS means "all"; otherwise only what is listed.
|
||||
if (BOT_COMMANDS[0] != 0 && !chan_list_has(BOT_COMMANDS, cmd)) return 0;
|
||||
|
||||
if (strcmp(cmd, "noise") == 0) {
|
||||
// Noise floor is the analyzer's own measurement -- a companion bot has no
|
||||
// way to answer this, which makes it worth owning on a shared channel.
|
||||
return snprintf(out, max_len, "noise floor %d dBm",
|
||||
(int)(int16_t)_radio->getNoiseFloor());
|
||||
}
|
||||
if (strcmp(cmd, "ping") == 0) {
|
||||
return snprintf(out, max_len, "pong");
|
||||
}
|
||||
if (strcmp(cmd, "path") == 0) {
|
||||
char path[BOT_PATH_STR_LEN];
|
||||
botFormatPath(path, pkt);
|
||||
return snprintf(out, max_len, "path %s (%d hop)", path, (int)pkt->getPathHashCount());
|
||||
}
|
||||
if (strcmp(cmd, "link") == 0) {
|
||||
// "Jaky mam link domu?" v jednom prikazu. Zamerne slouceny path+snr: tohle
|
||||
// se pta clovek v aute, ktery nema chut psat dva prikazy -- a jde o cestu
|
||||
// JEHO paketu k NAM, cili presne ten smer, ktery si na svem uzlu overit
|
||||
// neumi (tam vidi jen to, co prijima).
|
||||
// The path goes LAST on purpose. It is the only unbounded part of this reply
|
||||
// (0 to 62 chars, and the sender picks the hash width), so it is also the only
|
||||
// part that can push the answer over BOT_FRAG_LEN. Putting it after the numbers
|
||||
// means a truncation eats hops off the tail instead of eating the SNR/RSSI --
|
||||
// and a partial path is still useful, a missing link budget is not.
|
||||
char path[BOT_PATH_STR_LEN];
|
||||
botFormatPath(path, pkt);
|
||||
return snprintf(out, max_len, "SNR %.1f dB, RSSI %d dBm, %d hop %s",
|
||||
pkt->getSNR(), pkt->getRSSI(), (int)pkt->getPathHashCount(), path);
|
||||
}
|
||||
if (strcmp(cmd, "snr") == 0) {
|
||||
// Straight off the frame that carried the request -- the same numbers
|
||||
// captureRx() files into the rxlog ring.
|
||||
return snprintf(out, max_len, "SNR %.1f dB / RSSI %d dBm", pkt->getSNR(), pkt->getRSSI());
|
||||
}
|
||||
#if MAX_HEARD_NODES
|
||||
if (strcmp(cmd, "heard") == 0) {
|
||||
int n = 0;
|
||||
for (int i = 0; i < MAX_HEARD_NODES; i++) {
|
||||
if (heard_nodes[i].heard_timestamp > 0) n++;
|
||||
}
|
||||
return snprintf(out, max_len, "heard %d nodes", n);
|
||||
}
|
||||
#endif
|
||||
if (strcmp(cmd, "help") == 0) {
|
||||
return snprintf(out, max_len, "!ping !path !snr"
|
||||
#if MAX_HEARD_NODES
|
||||
" !heard"
|
||||
#endif
|
||||
);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Scan the message for `!word` tokens and join their answers with " | ", so
|
||||
// "!path !snr" costs one packet instead of two. Returns total chars, 0 if the
|
||||
// message held no recognised command.
|
||||
int MyMesh::botScanCommands(char* out, int max_len, const char* text, const mesh::Packet* pkt) {
|
||||
int written = 0;
|
||||
int found = 0;
|
||||
out[0] = 0;
|
||||
|
||||
for (const char* p = text; *p; ) {
|
||||
if (*p != '!') { p++; continue; }
|
||||
p++;
|
||||
char word[12];
|
||||
int wl = 0;
|
||||
while (*p && wl < (int)sizeof(word) - 1 && isalpha((unsigned char)*p)) {
|
||||
word[wl++] = tolower((unsigned char)*p);
|
||||
p++;
|
||||
}
|
||||
word[wl] = 0;
|
||||
if (wl == 0) continue;
|
||||
|
||||
char frag[BOT_FRAG_LEN];
|
||||
if (botCommandReply(frag, sizeof(frag), word, pkt) <= 0) continue;
|
||||
|
||||
int room = max_len - written;
|
||||
if (room <= 1) break;
|
||||
int adv = snprintf(out + written, room, "%s%s", found ? " | " : "", frag);
|
||||
if (adv < 0) break;
|
||||
if (adv >= room) { written = max_len - 1; found++; break; } // truncated, stop
|
||||
written += adv;
|
||||
found++;
|
||||
}
|
||||
return found ? written : 0;
|
||||
}
|
||||
|
||||
// Comma-separated list, case-insensitive substring match. "*" answers anything.
|
||||
bool MyMesh::botTriggerMatches(const char* text) const {
|
||||
const char* seg = BOT_TRIGGER;
|
||||
if (*seg == 0) return false;
|
||||
if (seg[0] == '*' && seg[1] == 0) return true;
|
||||
|
||||
while (*seg) {
|
||||
const char* comma = strchr(seg, ',');
|
||||
int len = comma ? (int)(comma - seg) : (int)strlen(seg);
|
||||
while (len > 0 && *seg == ' ') { seg++; len--; }
|
||||
while (len > 0 && seg[len - 1] == ' ') len--;
|
||||
|
||||
if (len > 0) {
|
||||
for (const char* t = text; *t; t++) {
|
||||
int i = 0;
|
||||
while (i < len && t[i] && tolower((unsigned char)t[i]) == tolower((unsigned char)seg[i])) i++;
|
||||
if (i == len) return true;
|
||||
}
|
||||
}
|
||||
if (!comma) break;
|
||||
seg = comma + 1;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void MyMesh::botSendReply(const mesh::Packet* pkt, const char* text) {
|
||||
// Payload layout copied from BaseChatMesh::sendGroupMessage(): 4 B timestamp
|
||||
// (which is also what keeps the packet hash unique), 1 B text type, then
|
||||
// "<name>: <msg>" -- the prefix is how every client shows the sender, since a
|
||||
// channel packet carries no identity.
|
||||
uint8_t temp[5 + BOT_REPLY_LEN];
|
||||
uint32_t timestamp = getRTCClock()->getCurrentTimeUnique();
|
||||
memcpy(temp, ×tamp, 4);
|
||||
temp[4] = TXT_TYPE_PLAIN;
|
||||
|
||||
int n = snprintf((char*)&temp[5], BOT_REPLY_LEN, "%s: %s", _prefs.node_name, text);
|
||||
if (n < 0) return;
|
||||
if (n > BOT_REPLY_LEN - 1) n = BOT_REPLY_LEN - 1; // snprintf reports untruncated length
|
||||
|
||||
auto reply = createGroupDatagram(PAYLOAD_TYPE_GRP_TXT, known_channels[bot_channel_idx], temp, 5 + n);
|
||||
if (reply == NULL) {
|
||||
MESH_DEBUG_PRINTLN("botSendReply: packet pool empty");
|
||||
return;
|
||||
}
|
||||
// Mirror the request's path-hash width and transport scope, exactly like every
|
||||
// other reply this firmware sends (see the sendFloodReply call sites).
|
||||
sendFloodReply(reply, SERVER_RESPONSE_DELAY, pkt->getPathHashSize());
|
||||
bot_replies_sent++;
|
||||
bot_last_reply_secs = getRTCClock()->getCurrentTime();
|
||||
}
|
||||
|
||||
// Per-sender cooldown over a tiny LRU. Returns true and CLAIMS the window when
|
||||
// this sender may be answered now.
|
||||
bool MyMesh::botPeerAllowed(const char* name) {
|
||||
uint32_t h = 2166136261u; // FNV-1a over the lowercased name
|
||||
for (const char* p = name; *p; p++) h = (h ^ (uint8_t)tolower((unsigned char)*p)) * 16777619u;
|
||||
if (h == 0) h = 1; // 0 marks a free slot
|
||||
|
||||
int free_slot = -1, oldest = 0;
|
||||
for (int i = 0; i < BOT_PEER_SLOTS; i++) {
|
||||
if (bot_peers[i].name_hash == h) {
|
||||
if (!millisHasNowPassed(bot_peers[i].next_at)) return false; // still cooling
|
||||
bot_peers[i].next_at = futureMillis(BOT_REPLY_COOLDOWN_MS);
|
||||
return true;
|
||||
}
|
||||
if (bot_peers[i].name_hash == 0 && free_slot < 0) free_slot = i;
|
||||
// signed compare = wraparound-safe "which window expires soonest"
|
||||
if ((long)(bot_peers[i].next_at - bot_peers[oldest].next_at) < 0) oldest = i;
|
||||
}
|
||||
int slot = (free_slot >= 0) ? free_slot : oldest;
|
||||
bot_peers[slot].name_hash = h;
|
||||
bot_peers[slot].next_at = futureMillis(BOT_REPLY_COOLDOWN_MS);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Called from onChannelText() (ChannelCommon.h) for messages on the bot
|
||||
// channel only -- the "<sender>: <msg>" split already happened there, and a
|
||||
// sender on the ChannelFilter deny list never reaches this point.
|
||||
void MyMesh::botOnChannelText(mesh::Packet* packet, const char* sender, const char* msg) {
|
||||
// Bail out if the sender is us: our own reply comes back through the mesh and
|
||||
// would otherwise ping-pong forever. The cooldown alone would not stop that,
|
||||
// it would only slow it down.
|
||||
if (sender[0] != 0) {
|
||||
if (strcmp(sender, _prefs.node_name) == 0) return;
|
||||
// Peer bots: skip before any trigger or command matching. Measured need --
|
||||
// tracker puts "Ping" on this channel by itself, and answering those ate the
|
||||
// cooldown, so a human question landed in a closed window.
|
||||
if (BOT_IGNORE_SENDERS[0] != 0 && chan_list_has(BOT_IGNORE_SENDERS, sender)) {
|
||||
bot_ignored++;
|
||||
MESH_DEBUG_PRINTLN("bot: ignoruji odesilatele z BOT_IGNORE_SENDERS");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
char reply[BOT_REPLY_LEN];
|
||||
if (botScanCommands(reply, sizeof(reply), msg, packet) <= 0) {
|
||||
if (!botTriggerMatches(msg)) return;
|
||||
char path[BOT_PATH_STR_LEN];
|
||||
botFormatPath(path, packet);
|
||||
snprintf(reply, sizeof(reply), "pong (%s)", path);
|
||||
}
|
||||
|
||||
// Global floor first: it is the airtime guarantee and must hold regardless of
|
||||
// how many distinct senders are asking.
|
||||
if (bot_next_reply_at != 0 && !millisHasNowPassed(bot_next_reply_at)) {
|
||||
MESH_DEBUG_PRINTLN("bot: reply suppressed, global gap");
|
||||
bot_throttled++;
|
||||
return;
|
||||
}
|
||||
// Then the cap over the longer window: the slot at head holds the oldest of
|
||||
// the last BOT_BURST_MAX replies, and while its window runs we are at the cap.
|
||||
// Checked before botPeerAllowed(), which claims the sender's window.
|
||||
if (BOT_BURST_MAX > 0 && bot_burst_until[bot_burst_head] != 0
|
||||
&& !millisHasNowPassed(bot_burst_until[bot_burst_head])) {
|
||||
MESH_DEBUG_PRINTLN("bot: reply suppressed, burst cap");
|
||||
bot_throttled++;
|
||||
return;
|
||||
}
|
||||
// Then this sender's own window. Name-based, so spoofable -- fine, this is a
|
||||
// politeness throttle and channel messages carry no identity anyway.
|
||||
if (!botPeerAllowed(sender)) {
|
||||
MESH_DEBUG_PRINTLN("bot: reply suppressed, sender cooldown");
|
||||
bot_throttled++;
|
||||
return;
|
||||
}
|
||||
bot_next_reply_at = futureMillis(BOT_MIN_GAP_MS);
|
||||
if (bot_next_reply_at == 0) bot_next_reply_at = 1; // 0 means "not armed"
|
||||
if (BOT_BURST_MAX > 0) {
|
||||
unsigned long until = futureMillis(BOT_BURST_WINDOW_MS);
|
||||
bot_burst_until[bot_burst_head] = until ? until : 1; // 0 means "free slot"
|
||||
bot_burst_head = (bot_burst_head + 1) % (BOT_BURST_MAX > 0 ? BOT_BURST_MAX : 1);
|
||||
}
|
||||
|
||||
botSendReply(packet, reply);
|
||||
}
|
||||
|
||||
// `bot` -- read-only diagnostics. Trigger and reply text stay build-time, so
|
||||
// there is nothing here to set: this is for answering "is it actually armed,
|
||||
// and has it ever spoken?" without a client on the channel.
|
||||
bool MyMesh::botHandleCommand(const char* command, char* reply) {
|
||||
if (memcmp(command, "bot", 3) != 0 || (command[3] != 0 && command[3] != ' ')) return false;
|
||||
|
||||
if (bot_channel_idx < 0) {
|
||||
strcpy(reply, "bot: DISABLED (bad BOT_CHANNEL_PSK)");
|
||||
return true;
|
||||
}
|
||||
// Short keys and snprintf: a remote CLI reply has 161 B (MyMesh.cpp temp[166]
|
||||
// minus header), and the old long form already overran it with a real cmds list.
|
||||
snprintf(reply, 161, "bot: ch %02X trig '%s' cmds '%s' ign '%s' cd %dms/odes + %dms, max %d/%ds, odp %u thr %u ign %u last %u",
|
||||
(uint32_t)known_channels[bot_channel_idx].hash[0], BOT_TRIGGER,
|
||||
BOT_COMMANDS[0] ? BOT_COMMANDS : "(vse)",
|
||||
BOT_IGNORE_SENDERS[0] ? BOT_IGNORE_SENDERS : "(nikdo)",
|
||||
(int)BOT_REPLY_COOLDOWN_MS, (int)BOT_MIN_GAP_MS,
|
||||
(int)BOT_BURST_MAX, (int)(BOT_BURST_WINDOW_MS / 1000),
|
||||
(uint32_t)bot_replies_sent, (uint32_t)bot_throttled,
|
||||
(uint32_t)bot_ignored, (uint32_t)bot_last_reply_secs);
|
||||
return true;
|
||||
}
|
||||
|
||||
#endif // BOT_CHANNEL_PSK
|
||||
@@ -0,0 +1,189 @@
|
||||
#pragma once
|
||||
|
||||
// CUSTOM (TeTeHacko): shared channel plumbing for ChannelBot.h and
|
||||
// ChannelFilter.h -- not part of upstream simple_repeater. Included at the
|
||||
// bottom of MyMesh.cpp (before the other two), so these are plain MyMesh
|
||||
// methods with full access to state.
|
||||
//
|
||||
// A repeater is normally deaf to channel traffic only because the two virtuals
|
||||
// below are no-ops in mesh::Mesh (Mesh.h:160, Mesh.cpp:37). Overriding them
|
||||
// decrypts matching GRP_TXT packets on the side; forwarding is untouched --
|
||||
// Mesh::onRecvPacket() calls routeRecvPacket() either way (Mesh.cpp:237-259).
|
||||
// The ONE deliberate exception is the ChannelFilter veto in onChannelText(),
|
||||
// which uses packet->markDoNotRetransmit() -- the exact mechanism the ANON
|
||||
// branch uses at Mesh.cpp:229 -- to stop THIS node re-airing a matched packet.
|
||||
//
|
||||
// Registry slots are MAX_KNOWN_CHANNELS(4) because searchChannelsByHash()
|
||||
// callers cap matches at 4 (Mesh.cpp:247). A channel named by both the bot and
|
||||
// the filter shares one slot (flags are OR-ed).
|
||||
|
||||
#if defined(BOT_CHANNEL_PSK) || defined(FILTER_CHANNEL_PSKS)
|
||||
|
||||
#include "ChanListUtil.h"
|
||||
|
||||
// Inbound text, after decrypt: 4 B timestamp + 1 B type + "sender: msg".
|
||||
#define CHAN_TEXT_LEN 160
|
||||
|
||||
// The PSK is given as HEX, which is exactly the form `meshcore-cli get_channel
|
||||
// <n>` prints -- no base64 round trip by hand, and no base64.hpp dependency in
|
||||
// this build (only companion_radio pulls that in). 32 hex chars = 128-bit key
|
||||
// (what the phone app generates), 64 = 256-bit. Shorter keys are zero-padded in
|
||||
// the 32-byte secret, same as BaseChatMesh::addChannel().
|
||||
// Returns the registry index, or -1 (bad hex/length, or registry full).
|
||||
int MyMesh::channelAddFromPsk(const char* psk_hex, int psk_len, uint8_t flag) {
|
||||
if (psk_len != 32 && psk_len != 64) {
|
||||
MESH_DEBUG_PRINTLN("channelAddFromPsk: PSK must be 32 or 64 hex chars, got %d", psk_len);
|
||||
return -1;
|
||||
}
|
||||
int key_len = psk_len / 2;
|
||||
uint8_t secret[PUB_KEY_SIZE];
|
||||
memset(secret, 0, sizeof(secret));
|
||||
for (int i = 0; i < key_len; i++) {
|
||||
int hi = chan_hex_nibble(psk_hex[i * 2]);
|
||||
int lo = chan_hex_nibble(psk_hex[i * 2 + 1]);
|
||||
if (hi < 0 || lo < 0) {
|
||||
MESH_DEBUG_PRINTLN("channelAddFromPsk: PSK is not hex");
|
||||
return -1;
|
||||
}
|
||||
secret[i] = (uint8_t)((hi << 4) | lo);
|
||||
}
|
||||
|
||||
// one slot per channel: a PSK named twice (bot + filter) just ORs its flags
|
||||
for (int i = 0; i < num_known_channels; i++) {
|
||||
if (memcmp(known_channels[i].secret, secret, sizeof(secret)) == 0) {
|
||||
known_channel_flags[i] |= flag;
|
||||
return i;
|
||||
}
|
||||
}
|
||||
if (num_known_channels >= MAX_KNOWN_CHANNELS) {
|
||||
MESH_DEBUG_PRINTLN("channelAddFromPsk: registry full (%d)", MAX_KNOWN_CHANNELS);
|
||||
return -1;
|
||||
}
|
||||
int idx = num_known_channels++;
|
||||
memcpy(known_channels[idx].secret, secret, sizeof(secret));
|
||||
// Same derivation as BaseChatMesh::addChannel() (hash over the REAL key
|
||||
// length, not the padded 32), so the hash matches what every other node
|
||||
// computes. Cross-checked live: the 128-bit #tth-test key hashes to 0x75.
|
||||
mesh::Utils::sha256(known_channels[idx].hash, sizeof(known_channels[idx].hash),
|
||||
known_channels[idx].secret, key_len);
|
||||
known_channel_flags[idx] = flag;
|
||||
return idx;
|
||||
}
|
||||
|
||||
void MyMesh::channelsInit() {
|
||||
num_known_channels = 0;
|
||||
memset(known_channels, 0, sizeof(known_channels));
|
||||
memset(known_channel_flags, 0, sizeof(known_channel_flags));
|
||||
#ifdef FILTER_CHANNEL_PSKS
|
||||
filter_dropped = 0;
|
||||
filter_age_dropped = 0;
|
||||
{
|
||||
// comma-separated hex PSKs
|
||||
const char* seg = FILTER_CHANNEL_PSKS;
|
||||
while (*seg) {
|
||||
const char* comma = strchr(seg, ',');
|
||||
int len = comma ? (int)(comma - seg) : (int)strlen(seg);
|
||||
channelAddFromPsk(seg, len, CHAN_FLAG_FILTER);
|
||||
if (!comma) break;
|
||||
seg = comma + 1;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#ifdef BOT_CHANNEL_PSK
|
||||
botInit();
|
||||
#endif
|
||||
}
|
||||
|
||||
// Mirrors BaseChatMesh::searchChannelsByHash() over the registry. Matching on
|
||||
// hash[0] alone is upstream's design: PATH_HASH_SIZE is 1, so collisions are
|
||||
// expected and resolved by MACThenDecrypt() failing in the caller.
|
||||
int MyMesh::searchChannelsByHash(const uint8_t* hash, mesh::GroupChannel channels[], int max_matches) {
|
||||
int n = 0;
|
||||
for (int i = 0; i < num_known_channels && n < max_matches; i++) {
|
||||
if (known_channels[i].hash[0] == hash[0]) {
|
||||
channels[n++] = known_channels[i];
|
||||
}
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
void MyMesh::onGroupDataRecv(mesh::Packet* packet, uint8_t type, const mesh::GroupChannel& channel,
|
||||
uint8_t* data, size_t len) {
|
||||
if (type != PAYLOAD_TYPE_GRP_TXT) return; // GRP_DATA (telemetry etc.) is not ours
|
||||
if (len < 5) return;
|
||||
|
||||
// which registry entry decrypted this? (the caller passes a COPY, not our slot)
|
||||
int chan_idx = -1;
|
||||
for (int i = 0; i < num_known_channels; i++) {
|
||||
if (memcmp(known_channels[i].secret, channel.secret, sizeof(channel.secret)) == 0) {
|
||||
chan_idx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (chan_idx < 0) return;
|
||||
|
||||
#ifdef FILTER_CHANNEL_PSKS
|
||||
// `filter age` (ChannelFilter.h): any group text, not only plain ones -- the
|
||||
// timestamp leads every GRP_TXT. Same veto as the deny list below.
|
||||
if (known_channel_flags[chan_idx] & CHAN_FLAG_FILTER) {
|
||||
uint32_t sender_ts;
|
||||
memcpy(&sender_ts, data, 4);
|
||||
if (msgAgeCheck(sender_ts, getRTCClock()->getCurrentTime(), _prefs.filter_age_min) == MSG_AGE_OLD) {
|
||||
filter_age_dropped++;
|
||||
if (!_prefs.filter_dry_run) {
|
||||
packet->markDoNotRetransmit();
|
||||
MESH_DEBUG_PRINTLN("filter: drop fwd, zprava starsi nez %u min", _prefs.filter_age_min);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
if ((data[4] >> 2) != 0) return; // only plain text, per BaseChatMesh.cpp:374
|
||||
|
||||
// Work on a bounded copy. Upstream NUL-terminates the caller's buffer in place
|
||||
// (data[len] = 0), which is fine there but relies on headroom this function
|
||||
// cannot verify -- and every other parse in this fork is bounds-checked.
|
||||
char text[CHAN_TEXT_LEN];
|
||||
size_t body = len - 5;
|
||||
if (body >= sizeof(text)) body = sizeof(text) - 1;
|
||||
memcpy(text, &data[5], body);
|
||||
text[body] = 0;
|
||||
|
||||
// "<sender>: <msg>". A channel packet carries no identity; this prefix is the
|
||||
// only sender there is (and therefore spoofable -- see ChannelFilter.h).
|
||||
const char* sender = "";
|
||||
const char* msg = text;
|
||||
char* sep = strstr(text, ": ");
|
||||
if (sep) {
|
||||
*sep = 0;
|
||||
sender = text;
|
||||
msg = sep + 2;
|
||||
}
|
||||
onChannelText(packet, chan_idx, sender, msg);
|
||||
}
|
||||
|
||||
void MyMesh::onChannelText(mesh::Packet* packet, int chan_idx, const char* sender, const char* msg) {
|
||||
#ifdef FILTER_CHANNEL_PSKS
|
||||
if ((known_channel_flags[chan_idx] & CHAN_FLAG_FILTER)
|
||||
&& sender[0] != 0 && filterDenied(sender)) {
|
||||
// Veto the forward of THIS packet -- routeRecvPacket() checks the mark
|
||||
// (Mesh.cpp:357). Local processing already happened (rxlog/pktfeed capture
|
||||
// on receive), so the observer evidence trail is intact; the node just
|
||||
// refuses to re-air it. And the bot must not answer a denied sender either.
|
||||
filter_dropped++;
|
||||
if (!_prefs.filter_dry_run) { // dry-run: counted, but forwarded
|
||||
packet->markDoNotRetransmit();
|
||||
MESH_DEBUG_PRINTLN("filter: drop fwd, sender na deny listu");
|
||||
}
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
#ifdef BOT_CHANNEL_PSK
|
||||
if (chan_idx == bot_channel_idx) {
|
||||
botOnChannelText(packet, sender, msg);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#endif // BOT_CHANNEL_PSK || FILTER_CHANNEL_PSKS
|
||||
@@ -0,0 +1,290 @@
|
||||
#pragma once
|
||||
|
||||
// CUSTOM (TeTeHacko): channel-message deny list -- not part of upstream
|
||||
// simple_repeater. Included at the bottom of MyMesh.cpp, after ChannelCommon.h.
|
||||
//
|
||||
// WHAT THIS IS (and is not)
|
||||
//
|
||||
// A repeater that knows a channel's PSK (FILTER_CHANNEL_PSKS, see
|
||||
// ChannelCommon.h) decrypts each GRP_TXT on it and refuses to FORWARD messages
|
||||
// whose "<sender>: " prefix is on a runtime deny list. Born 5. 9. 2026, when a
|
||||
// runaway AI bot looped an 11-part Gemini quota dump onto #meshcore for hours
|
||||
// and every repeater dutifully re-aired it.
|
||||
//
|
||||
// * The sender name is just text inside the encrypted payload -- GRP_TXT
|
||||
// carries NO identity (only adverts do). Anyone can rename around this.
|
||||
// It is containment of a runaway/rude node, not security. (For the
|
||||
// content-neutral automatic layer, see FairnessLimiter.h.)
|
||||
// * Only forwarding by THIS node is affected. Reception, rxlog/pktfeed
|
||||
// capture (CoreScope feed) and the rest of the mesh are untouched.
|
||||
// * DIRECT-routed packets are not seen here (their forward is decided before
|
||||
// any decrypt, Mesh.cpp:94) -- channel messages flood, so in practice this
|
||||
// covers them.
|
||||
// * Upstream would not take this (privacy/no-censorship principles, see
|
||||
// issue #169 discussion) -- fork-only, do not upstream.
|
||||
//
|
||||
// The deny list lives in _prefs.filter_deny (comma-separated exact names,
|
||||
// case-insensitive) so the stock savePrefs()/loadPrefs() machinery persists
|
||||
// it, and it is editable at runtime over RF admin: an incident response is
|
||||
// `filter add <name>`, not a mast reflash.
|
||||
|
||||
#ifdef FILTER_CHANNEL_PSKS
|
||||
|
||||
bool MyMesh::filterDenied(const char* sender) const {
|
||||
if (_prefs.filter_deny[0] == 0) return false;
|
||||
return chan_list_has(_prefs.filter_deny, sender);
|
||||
}
|
||||
|
||||
// `filter` / `filter list` -- show state; `filter add|del <name>` -- edit;
|
||||
// `filter clear` -- empty the list. Names may contain spaces (everything after
|
||||
// the subcommand is the name); commas are the storage separator so they are
|
||||
// rejected. Matching is exact and case-insensitive (chan_list_has).
|
||||
bool MyMesh::filterHandleCommand(const char* command, char* reply, int reply_max) {
|
||||
if (memcmp(command, "filter", 6) != 0 || (command[6] != 0 && command[6] != ' ')) return false;
|
||||
|
||||
if (memcmp(&command[6], " add ", 5) == 0) {
|
||||
const char* name = &command[11];
|
||||
int rc = chan_list_add(_prefs.filter_deny, sizeof(_prefs.filter_deny), name, strlen(name));
|
||||
if (rc == CHAN_LIST_OK) {
|
||||
savePrefs();
|
||||
snprintf(reply, reply_max, "OK - deny: %s", _prefs.filter_deny);
|
||||
} else if (rc == CHAN_LIST_DUP) {
|
||||
strcpy(reply, "Err - already listed");
|
||||
} else if (rc == CHAN_LIST_FULL) {
|
||||
strcpy(reply, "Err - list full");
|
||||
} else {
|
||||
strcpy(reply, "Err - bad name (empty, too long, or contains ',')");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (memcmp(&command[6], " del ", 5) == 0) {
|
||||
if (chan_list_del(_prefs.filter_deny, &command[11])) {
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Err - not listed");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (strcmp(&command[6], " clear") == 0) {
|
||||
_prefs.filter_deny[0] = 0;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK - deny list cleared");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (command[6] == 0 || strcmp(&command[6], " list") == 0) {
|
||||
snprintf(reply, reply_max, "filter: %d chan, dropped %u, deny: %s",
|
||||
(int)num_known_channels, filter_dropped,
|
||||
_prefs.filter_deny[0] ? _prefs.filter_deny : "(nikdo)");
|
||||
return true;
|
||||
}
|
||||
|
||||
strcpy(reply, "Err - filter [add|del <name>|list|clear|hash|age|dryrun]");
|
||||
return true;
|
||||
}
|
||||
|
||||
#endif // FILTER_CHANNEL_PSKS
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Keyless deny-forward by CHANNEL HASH -- independent of FILTER_CHANNEL_PSKS.
|
||||
//
|
||||
// The deny list above needs the PSK, so it can never touch a private channel.
|
||||
// This one needs nothing: payload[0] of GRP_TXT/GRP_DATA is the channel hash,
|
||||
// in the clear, and a repeater can refuse to re-air every packet carrying it.
|
||||
// Born 14. 10. 2026 for 0x43 (one private chat+bot = 43 % of the airtime on
|
||||
// the CZ mesh, reflooded all the way to remote-mast); FairnessLimiter only
|
||||
// throttled it blindly, and its group bucket (hash & 0x1F) collides with
|
||||
// 0x23/0x63/... anyway.
|
||||
//
|
||||
// * Content-neutral and coarse: the hash is 1 byte, so a deny entry also
|
||||
// hits every OTHER channel whose key happens to hash to the same byte.
|
||||
// Check the analyzer for what else lives on a byte before denying it.
|
||||
// * Only forwarding by THIS node: reception and rxlog/pktfeed capture
|
||||
// (CoreScope feed) happen before routeRecvPacket(), so the evidence trail
|
||||
// stays intact.
|
||||
// * Runtime-editable over RF admin and persisted in prefs (f_dhash/f_dhash_n),
|
||||
// so an incident response is `filter hash add 43`, not a mast reflash.
|
||||
//
|
||||
// THROTTLE (tth #3, 2. 11. 2026): an entry may carry an interval --
|
||||
// `filter hash add 43 60` lets one packet of that byte through per 60 s and
|
||||
// drops the rest, so a chatty channel is tamed instead of cut off. The window
|
||||
// state is RAM only (first match after boot passes) and only a pass moves it;
|
||||
// see HashThrottle in src/helpers/ChannelGate.h. Interval 0 = block, as before.
|
||||
//
|
||||
// `filter dryrun on` counts every verdict of `filter` (hash, age, sender deny)
|
||||
// but forwards anyway -- the way to try a new rule on a live mast.
|
||||
|
||||
bool MyMesh::filterHashDenied(const mesh::Packet* packet) {
|
||||
uint8_t n = _prefs.deny_hash_n;
|
||||
if (n == 0) return false;
|
||||
uint8_t type = packet->getPayloadType();
|
||||
if (type != PAYLOAD_TYPE_GRP_TXT && type != PAYLOAD_TYPE_GRP_DATA) return false;
|
||||
if (packet->payload_len < 1) return false;
|
||||
if (n > sizeof(_prefs.deny_hash)) n = sizeof(_prefs.deny_hash);
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (_prefs.deny_hash[i] != packet->payload[0]) continue;
|
||||
uint16_t secs = _prefs.deny_hash_secs[i];
|
||||
if (secs != 0 && hash_throttle.pass(i, secs, millis())) {
|
||||
filter_hash_passed++;
|
||||
return false;
|
||||
}
|
||||
filter_hash_dropped++;
|
||||
return !_prefs.filter_dry_run;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// `filter hash` -- show list + counters (passed = let through by a throttle);
|
||||
// `filter hash add <hex> [secs]` -- block (no secs / 0) or throttle to one
|
||||
// packet per secs; re-adding a listed byte changes its interval;
|
||||
// `filter hash del <hex>`; `filter hash clear`.
|
||||
// Listing: `43` = blocked, `43/60` = throttled to one per 60 s. The Ansible
|
||||
// module (tth.meshcore.meshcore_filter_hash) parses this line -- keep the
|
||||
// "filter hash: dropped N, passed M, deny:" shape stable.
|
||||
bool MyMesh::filterHashHandleCommand(const char* command, char* reply, int reply_max) {
|
||||
if (memcmp(command, "filter hash", 11) != 0 || (command[11] != 0 && command[11] != ' ')) return false;
|
||||
|
||||
const char* arg = (command[11] == ' ') ? &command[12] : "";
|
||||
uint8_t n = _prefs.deny_hash_n;
|
||||
if (n > sizeof(_prefs.deny_hash)) n = sizeof(_prefs.deny_hash);
|
||||
|
||||
if (strcmp(arg, "clear") == 0) {
|
||||
_prefs.deny_hash_n = 0;
|
||||
memset(_prefs.deny_hash, 0, sizeof(_prefs.deny_hash));
|
||||
memset(_prefs.deny_hash_secs, 0, sizeof(_prefs.deny_hash_secs));
|
||||
hash_throttle.reset();
|
||||
savePrefs();
|
||||
strcpy(reply, "OK - hash deny list cleared");
|
||||
return true;
|
||||
}
|
||||
|
||||
bool is_add = strncmp(arg, "add ", 4) == 0;
|
||||
bool is_del = strncmp(arg, "del ", 4) == 0;
|
||||
if (is_add || is_del) {
|
||||
const char* hex = arg + 4;
|
||||
if (hex[0] == '0' && (hex[1] == 'x' || hex[1] == 'X')) hex += 2;
|
||||
char* end;
|
||||
long v = strtol(hex, &end, 16);
|
||||
if (end == hex || (*end != 0 && *end != ' ') || end - hex > 2 || v < 0 || v > 0xFF) {
|
||||
strcpy(reply, "Err - 1 byte hex, e.g. 43");
|
||||
return true;
|
||||
}
|
||||
long secs = 0;
|
||||
if (*end == ' ') {
|
||||
if (is_del) { strcpy(reply, "Err - filter hash del <hex>"); return true; }
|
||||
const char* s = end + 1;
|
||||
secs = strtol(s, &end, 10);
|
||||
if (end == s || *end != 0 || secs < 0 || secs > 65535) {
|
||||
strcpy(reply, "Err - secs 0..65535 (0 = block)");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
int at = -1;
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (_prefs.deny_hash[i] == (uint8_t)v) { at = i; break; }
|
||||
}
|
||||
if (is_add) {
|
||||
if (at >= 0) {
|
||||
if (_prefs.deny_hash_secs[at] == (uint16_t)secs) { strcpy(reply, "Err - already listed"); return true; }
|
||||
_prefs.deny_hash_secs[at] = (uint16_t)secs; // change of interval
|
||||
hash_throttle.reset(at);
|
||||
} else {
|
||||
if (n >= sizeof(_prefs.deny_hash)) { strcpy(reply, "Err - list full"); return true; }
|
||||
_prefs.deny_hash[n] = (uint8_t)v;
|
||||
_prefs.deny_hash_secs[n] = (uint16_t)secs;
|
||||
hash_throttle.reset(n);
|
||||
n++;
|
||||
}
|
||||
} else {
|
||||
if (at < 0) { strcpy(reply, "Err - not listed"); return true; }
|
||||
for (int i = at; i + 1 < n; i++) {
|
||||
_prefs.deny_hash[i] = _prefs.deny_hash[i + 1];
|
||||
_prefs.deny_hash_secs[i] = _prefs.deny_hash_secs[i + 1];
|
||||
}
|
||||
hash_throttle.remove(at);
|
||||
--n;
|
||||
_prefs.deny_hash[n] = 0;
|
||||
_prefs.deny_hash_secs[n] = 0;
|
||||
}
|
||||
_prefs.deny_hash_n = n;
|
||||
savePrefs();
|
||||
// fall through to the listing as the reply
|
||||
} else if (arg[0] != 0 && strcmp(arg, "list") != 0) {
|
||||
strcpy(reply, "Err - filter hash [add <hex> [secs]|del <hex>|list|clear]");
|
||||
return true;
|
||||
}
|
||||
|
||||
int len = snprintf(reply, reply_max, "filter hash: dropped %u, passed %u, deny:",
|
||||
filter_hash_dropped, filter_hash_passed);
|
||||
if (n == 0 && len < reply_max) len += snprintf(&reply[len], reply_max - len, " (nic)");
|
||||
for (int i = 0; i < n && len < reply_max; i++) {
|
||||
if (_prefs.deny_hash_secs[i]) {
|
||||
len += snprintf(&reply[len], reply_max - len, " %02X/%u", _prefs.deny_hash[i], _prefs.deny_hash_secs[i]);
|
||||
} else {
|
||||
len += snprintf(&reply[len], reply_max - len, " %02X", _prefs.deny_hash[i]);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// `filter dryrun [on|off]` -- verdicts of `filter` (hash, age, sender deny)
|
||||
// are counted but the packet is forwarded anyway. Persisted (f_dry).
|
||||
// `filter age [<min>|off]` -- refuse to forward a group text the node can
|
||||
// DECRYPT (channels of FILTER_CHANNEL_PSKS) whose sender timestamp is older
|
||||
// than <min> minutes by THIS node's clock (1..10080). Off by default.
|
||||
// * It judges the sender's clock: a companion that never got a time sync
|
||||
// stamps 2024 and is dropped. On the CZ mesh 2. 11. 2026 every one of the
|
||||
// 5/2026 messages older than 10 min was such a clock, none a reflood --
|
||||
// hence opt-in, and days rather than minutes.
|
||||
// * Inactive while our own clock reads before 2026 (RTC-less boot). A clock
|
||||
// running AHEAD is not detected and makes everything look old -- check the
|
||||
// drift (tools/fw_status.py) before turning it on.
|
||||
bool MyMesh::filterMiscHandleCommand(const char* command, char* reply, int reply_max) {
|
||||
if (strcmp(command, "filter dryrun") == 0 || strcmp(command, "filter dryrun on") == 0
|
||||
|| strcmp(command, "filter dryrun off") == 0) {
|
||||
if (command[13] == ' ') {
|
||||
_prefs.filter_dry_run = (command[15] == 'n') ? 1 : 0;
|
||||
savePrefs();
|
||||
snprintf(reply, reply_max, "OK - filter dry-run %s", _prefs.filter_dry_run ? "on" : "off");
|
||||
} else {
|
||||
snprintf(reply, reply_max, "filter dry-run %s", _prefs.filter_dry_run ? "on" : "off");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (memcmp(command, "filter age", 10) != 0 || (command[10] != 0 && command[10] != ' ')) return false;
|
||||
#ifndef FILTER_CHANNEL_PSKS
|
||||
strcpy(reply, "Err - no channel keys in this build (FILTER_CHANNEL_PSKS)");
|
||||
return true;
|
||||
#else
|
||||
const char* arg = (command[10] == ' ') ? &command[11] : "";
|
||||
bool changed = false;
|
||||
if (strcmp(arg, "off") == 0) {
|
||||
_prefs.filter_age_min = 0;
|
||||
changed = true;
|
||||
} else if (arg[0] != 0) {
|
||||
char* end;
|
||||
long v = strtol(arg, &end, 10);
|
||||
if (end == arg || *end != 0 || v < 0 || v > MSG_AGE_MAX_MINUTES) {
|
||||
snprintf(reply, reply_max, "Err - filter age <1..%d min>|off", MSG_AGE_MAX_MINUTES);
|
||||
return true;
|
||||
}
|
||||
_prefs.filter_age_min = (uint16_t)v;
|
||||
changed = true;
|
||||
}
|
||||
if (changed) savePrefs();
|
||||
|
||||
if (_prefs.filter_age_min == 0) {
|
||||
snprintf(reply, reply_max, "%sfilter age off, dropped %u", changed ? "OK - " : "", filter_age_dropped);
|
||||
} else {
|
||||
uint32_t now = getRTCClock()->getCurrentTime();
|
||||
snprintf(reply, reply_max, "%sfilter age %um%s%s, dropped %u", changed ? "OK - " : "",
|
||||
_prefs.filter_age_min, _prefs.filter_dry_run ? " DRY-RUN" : "",
|
||||
now < MSG_AGE_CLOCK_VALID_FROM ? " (clock not set, inactive)" : "", filter_age_dropped);
|
||||
}
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "MyMesh.h"
|
||||
#include <algorithm>
|
||||
#include <helpers/CliArgs.h>
|
||||
#include <helpers/sensors/LPPDataHelpers.h>
|
||||
#include <helpers/UTF8Helpers.h>
|
||||
|
||||
@@ -100,6 +101,266 @@ void MyMesh::putNeighbour(const mesh::Identity &id, uint32_t timestamp, float sn
|
||||
#endif
|
||||
}
|
||||
|
||||
#if MAX_HEARD_NODES || RXLOG_SIZE
|
||||
// Cheap deterministic frame id: FNV-1a over (type || payload). Same value for
|
||||
// every copy of one advert/packet regardless of the path it took (path is not
|
||||
// hashed), so it GROUPS the copies that arrived via different paths -> the bridge
|
||||
// joins nodes<->rxlog on it to reconstruct multi-path. NOT the SHA packet-hash
|
||||
// (the mesh already computes that once per frame in hasSeen(); a second SHA on
|
||||
// the radio hot path would be wasted work).
|
||||
static uint32_t analyzer_frame_id(const mesh::Packet* pkt) {
|
||||
uint32_t h = 2166136261u;
|
||||
uint8_t t = pkt->getPayloadType();
|
||||
h = (h ^ t) * 16777619u;
|
||||
for (uint16_t k = 0; k < pkt->payload_len; k++) h = (h ^ pkt->payload[k]) * 16777619u;
|
||||
return h;
|
||||
}
|
||||
|
||||
// Render a stored path as COLON-separated per-hop hashes. The path-hash width is
|
||||
// uniform per packet (1/2/3 B, top 2 bits of path_len) but not otherwise visible
|
||||
// in the hex, so delimit the hops: each token between ':' is one hop-hash and its
|
||||
// byte width is (token length / 2). 1-byte -> "36:2F:EC", 2-byte -> "362F:ECBD".
|
||||
// out must hold ANALYZER_PATH_LEN*3+1 bytes.
|
||||
static void analyzer_path_hex(char* out, const uint8_t* path, uint8_t path_len) {
|
||||
static const char hexd[] = "0123456789ABCDEF";
|
||||
uint8_t cnt = path_len & 63;
|
||||
uint8_t sz = (path_len >> 6) + 1;
|
||||
char* p = out;
|
||||
uint8_t off = 0;
|
||||
for (uint8_t h = 0; h < cnt && off + sz <= ANALYZER_PATH_LEN; h++) {
|
||||
if (h) *p++ = ':';
|
||||
for (uint8_t b = 0; b < sz; b++, off++) {
|
||||
*p++ = hexd[path[off] >> 4];
|
||||
*p++ = hexd[path[off] & 0x0F];
|
||||
}
|
||||
}
|
||||
*p = 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
#if MAX_HEARD_NODES
|
||||
// CUSTOM (TeTeHacko): record/update one heard node in the analyzer registry.
|
||||
void MyMesh::putHeardNode(const mesh::Identity& id, uint32_t advert_timestamp, uint8_t type,
|
||||
int32_t lat, int32_t lon, const char* name,
|
||||
int8_t snr, int8_t rssi, const mesh::Packet* pkt) {
|
||||
uint32_t now = getRTCClock()->getCurrentTime();
|
||||
bool is_direct = (pkt->getPathHashCount() == 0); // 0-hop = heard directly
|
||||
|
||||
uint32_t oldest = 0xFFFFFFFF;
|
||||
HeardNode* slot = &heard_nodes[0];
|
||||
bool existing = false;
|
||||
for (int i = 0; i < MAX_HEARD_NODES; i++) {
|
||||
HeardNode* n = &heard_nodes[i];
|
||||
if (n->heard_timestamp > 0 && memcmp(n->pub_prefix, id.pub_key, HEARD_NODE_PREFIX) == 0) {
|
||||
slot = n; existing = true; break; // update existing entry
|
||||
}
|
||||
if (n->heard_timestamp < oldest) { oldest = n->heard_timestamp; slot = n; } // else evict LRU
|
||||
}
|
||||
if (!existing) *slot = HeardNode(); // reused/evicted slot -> clear stale fields (direct_heard!)
|
||||
|
||||
// latest identity / position / name always win
|
||||
memcpy(slot->pub_prefix, id.pub_key, HEARD_NODE_PREFIX);
|
||||
slot->advert_timestamp = advert_timestamp;
|
||||
slot->heard_timestamp = now;
|
||||
slot->type = type;
|
||||
slot->lat = lat;
|
||||
slot->lon = lon;
|
||||
StrHelper::strncpy(slot->name, name ? name : "", sizeof(slot->name));
|
||||
slot->pkt_hash = analyzer_frame_id(pkt); // join key -> rxlog copies (= every path this advert took)
|
||||
|
||||
// Representative path + link quality. A DIRECT (0-hop) advert is the key edge
|
||||
// (us <-> node). Because all copies of one advert share a hash, dedup means
|
||||
// onAdvertRecv only fires for whichever copy arrives first -- often a stronger
|
||||
// relayed one -- so a plain last-write keeps overwriting a direct link with a
|
||||
// relayed path. Prefer the direct observation for HEARD_DIRECT_TTL_SECS. (Full
|
||||
// multi-path is reconstructed on the bridge via the pkt_hash join to rxlog.)
|
||||
bool direct_recent = slot->direct_heard != 0 && (now - slot->direct_heard) < HEARD_DIRECT_TTL_SECS;
|
||||
if (is_direct) {
|
||||
slot->direct_heard = now;
|
||||
slot->snr = snr; slot->rssi = rssi;
|
||||
slot->path_len = 0; // empty path = direct
|
||||
memset(slot->path, 0, sizeof(slot->path));
|
||||
} else if (!direct_recent) {
|
||||
slot->snr = snr; slot->rssi = rssi;
|
||||
slot->path_len = (uint8_t) pkt->path_len;
|
||||
uint8_t pb = pkt->getPathByteLen();
|
||||
if (pb > ANALYZER_PATH_LEN) pb = ANALYZER_PATH_LEN;
|
||||
memset(slot->path, 0, sizeof(slot->path));
|
||||
if (pb) memcpy(slot->path, pkt->path, pb);
|
||||
}
|
||||
// else: relayed advert but heard direct recently -> keep the direct path/SNR
|
||||
}
|
||||
|
||||
// `nodes [offset]` -> paged dump of the heard-node registry (newest first).
|
||||
// One text line per node: N,<prefix-hex>,<type>,<lat*1e6>,<lon*1e6>,<snr*4>,<rssi>,<secs_ago>,<pkthash-hex>,<path-hex>,<name>
|
||||
// <pkthash> = join key: group `rxlog` records by it to get EVERY path this
|
||||
// node's advert arrived by (multi-path). <path> is a single representative
|
||||
// (direct/0-hop preferred). Trailer line: E,<next_offset>,<total>
|
||||
void MyMesh::formatNodesReply(char* reply, int max_len, uint16_t offset) {
|
||||
char* dp = reply;
|
||||
int total = 0;
|
||||
static HeardNode* sorted[MAX_HEARD_NODES]; // BSS, ne stack (128 ptrů; volá se jen z loop tasku)
|
||||
for (int i = 0; i < MAX_HEARD_NODES; i++) {
|
||||
if (heard_nodes[i].heard_timestamp > 0) sorted[total++] = &heard_nodes[i];
|
||||
}
|
||||
std::sort(sorted, sorted + total, [](const HeardNode* a, const HeardNode* b) {
|
||||
return a->heard_timestamp > b->heard_timestamp; // newest first
|
||||
});
|
||||
|
||||
uint32_t now = getRTCClock()->getCurrentTime();
|
||||
int i = offset;
|
||||
char line[160];
|
||||
for (; i < total; i++) {
|
||||
HeardNode* n = sorted[i];
|
||||
char prefix[HEARD_NODE_PREFIX * 2 + 1];
|
||||
mesh::Utils::toHex(prefix, n->pub_prefix, HEARD_NODE_PREFIX);
|
||||
char pathhex[ANALYZER_PATH_LEN * 3 + 1];
|
||||
analyzer_path_hex(pathhex, n->path, n->path_len); // colon-separated hops (width self-describing)
|
||||
snprintf(line, sizeof(line), "N,%s,%u,%ld,%ld,%d,%d,%lu,%08lX,%s,%s\n",
|
||||
prefix, (unsigned)n->type, (long)n->lat, (long)n->lon,
|
||||
(int)n->snr, (int)n->rssi, (unsigned long)(now - n->heard_timestamp),
|
||||
(unsigned long)n->pkt_hash, pathhex, n->name);
|
||||
if (!cli_args::appendLine(dp, reply, max_len, 24, line)) break; // room for trailer; never overflow reply
|
||||
}
|
||||
dp += sprintf(dp, "E,%d,%d", i, total);
|
||||
*dp = 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
#if RXLOG_SIZE
|
||||
// CUSTOM (TeTeHacko): append one heard frame to the analyzer firehose ring.
|
||||
void MyMesh::captureRx(const mesh::Packet* pkt) {
|
||||
RxLogRec* r = &rxlog_ring[rxlog_head];
|
||||
rxlog_head = (rxlog_head + 1) % RXLOG_SIZE;
|
||||
r->seq = rxlog_next_seq++;
|
||||
if (rxlog_next_seq == 0) rxlog_next_seq = 1; // wrap guard (seq 0 reserved for empty)
|
||||
r->when = getRTCClock()->getCurrentTime();
|
||||
r->pkt_hash = analyzer_frame_id(pkt); // same key across all copies -> groups the paths a frame took
|
||||
r->snr = pkt->_snr;
|
||||
r->rssi = (int8_t) pkt->getRSSI();
|
||||
r->header = pkt->header;
|
||||
r->path_len = (uint8_t) pkt->path_len;
|
||||
uint8_t pb = pkt->getPathByteLen();
|
||||
if (pb > ANALYZER_PATH_LEN) pb = ANALYZER_PATH_LEN;
|
||||
memset(r->path, 0, sizeof(r->path));
|
||||
if (pb) memcpy(r->path, pkt->path, pb);
|
||||
}
|
||||
|
||||
// `rxlog [cursor]` -> paged dump of frames with seq > cursor (oldest first).
|
||||
// One text line per record: R,<seq>,<when>,<pkthash-hex>,<hdr-hex>,<snr*4>,<rssi>,<path-hex>
|
||||
// Trailer line: E,<last_returned_seq>,<oldest_seq_in_ring>,<newest_seq>
|
||||
void MyMesh::formatRxLogReply(char* reply, int max_len, uint32_t cursor) {
|
||||
char* dp = reply;
|
||||
static RxLogRec* recs[RXLOG_SIZE]; // BSS, ne stack (512 ptrů = 2 KB; volá se jen z loop tasku)
|
||||
int n = 0;
|
||||
uint32_t oldest = 0, newest = 0;
|
||||
for (int i = 0; i < RXLOG_SIZE; i++) {
|
||||
RxLogRec* r = &rxlog_ring[i];
|
||||
if (r->seq == 0) continue;
|
||||
if (oldest == 0 || r->seq < oldest) oldest = r->seq;
|
||||
if (r->seq > newest) newest = r->seq;
|
||||
if (r->seq > cursor) recs[n++] = r;
|
||||
}
|
||||
std::sort(recs, recs + n, [](const RxLogRec* a, const RxLogRec* b) {
|
||||
return a->seq < b->seq; // oldest unread first
|
||||
});
|
||||
|
||||
uint32_t last = cursor;
|
||||
char line[128];
|
||||
for (int i = 0; i < n; i++) {
|
||||
RxLogRec* r = recs[i];
|
||||
char pathhex[ANALYZER_PATH_LEN * 3 + 1];
|
||||
analyzer_path_hex(pathhex, r->path, r->path_len); // colon-separated hops (width self-describing)
|
||||
snprintf(line, sizeof(line), "R,%lu,%lu,%08lX,%02X,%d,%d,%s\n",
|
||||
(unsigned long)r->seq, (unsigned long)r->when,
|
||||
(unsigned long)r->pkt_hash, (unsigned)r->header,
|
||||
(int)r->snr, (int)r->rssi, pathhex);
|
||||
if (!cli_args::appendLine(dp, reply, max_len, 40, line)) break; // room for trailer; never overflow reply
|
||||
last = r->seq;
|
||||
}
|
||||
dp += sprintf(dp, "E,%lu,%lu,%lu", (unsigned long)last, (unsigned long)oldest, (unsigned long)newest);
|
||||
*dp = 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
#if PKTFEED_SIZE
|
||||
// CUSTOM (TeTeHacko): observer feed -- rxlog's sibling ring that keeps the FULL
|
||||
// raw frame so the bridge can publish meshcoretomqtt-compatible packets (the
|
||||
// SHA256 packet hash and type/route/payload decode all happen bridge-side).
|
||||
void MyMesh::stagePktFeed(const uint8_t raw[], int len) {
|
||||
if (len <= 0 || len > MAX_TRANS_UNIT) {
|
||||
pktfeed_stage_len = 0;
|
||||
return;
|
||||
}
|
||||
memcpy(pktfeed_stage, raw, len);
|
||||
pktfeed_stage_len = (uint8_t) len;
|
||||
}
|
||||
|
||||
void MyMesh::commitPktFeed(const mesh::Packet* pkt) {
|
||||
// stage/commit must be the same frame: both run in order inside one
|
||||
// Dispatcher::checkRecv pass, but a parse-failed frame leaves a stale stage
|
||||
// behind -- the length check discards such a mismatched pairing
|
||||
if (pktfeed_stage_len == 0 || pktfeed_stage_len != pkt->getRawLength()) {
|
||||
pktfeed_stage_len = 0;
|
||||
return;
|
||||
}
|
||||
PktFeedRec* r = &pktfeed_ring[pktfeed_head];
|
||||
pktfeed_head = (pktfeed_head + 1) % PKTFEED_SIZE;
|
||||
r->seq = pktfeed_next_seq++;
|
||||
if (pktfeed_next_seq == 0) pktfeed_next_seq = 1; // wrap guard (seq 0 reserved for empty)
|
||||
r->when = getRTCClock()->getCurrentTime();
|
||||
r->snr = pkt->_snr;
|
||||
r->rssi = (int8_t) pkt->getRSSI();
|
||||
r->len = pktfeed_stage_len;
|
||||
memcpy(r->raw, pktfeed_stage, pktfeed_stage_len);
|
||||
pktfeed_stage_len = 0;
|
||||
}
|
||||
|
||||
// `pktlog [cursor]` -> paged dump of raw frames with seq > cursor (oldest first).
|
||||
// One text line per record: P,<seq>,<when>,<snr*4>,<rssi>,<raw-hex>
|
||||
// Trailer line: E,<last_returned_seq>,<oldest_seq_in_ring>,<newest_seq>
|
||||
void MyMesh::formatPktFeedReply(char* reply, int max_len, uint32_t cursor) {
|
||||
char* dp = reply;
|
||||
PktFeedRec* recs[PKTFEED_SIZE]; // small ring -> stack is fine (32 ptrs)
|
||||
int n = 0;
|
||||
uint32_t oldest = 0, newest = 0;
|
||||
for (int i = 0; i < PKTFEED_SIZE; i++) {
|
||||
PktFeedRec* r = &pktfeed_ring[i];
|
||||
if (r->seq == 0) continue;
|
||||
if (oldest == 0 || r->seq < oldest) oldest = r->seq;
|
||||
if (r->seq > newest) newest = r->seq;
|
||||
if (r->seq > cursor) recs[n++] = r;
|
||||
}
|
||||
std::sort(recs, recs + n, [](const PktFeedRec* a, const PktFeedRec* b) {
|
||||
return a->seq < b->seq; // oldest unread first
|
||||
});
|
||||
|
||||
uint32_t last = cursor;
|
||||
static char line[40 + MAX_TRANS_UNIT * 2]; // BSS, ne stack (~550 B; volá se jen z loop tasku)
|
||||
for (int i = 0; i < n; i++) {
|
||||
PktFeedRec* r = recs[i];
|
||||
int ll = snprintf(line, sizeof(line), "P,%lu,%lu,%d,%d,",
|
||||
(unsigned long)r->seq, (unsigned long)r->when,
|
||||
(int)r->snr, (int)r->rssi);
|
||||
for (int b = 0; b < r->len; b++) {
|
||||
ll += sprintf(line + ll, "%02X", r->raw[b]);
|
||||
}
|
||||
line[ll++] = '\n';
|
||||
line[ll] = 0;
|
||||
// Unlike rxlog there is NO "always emit >=1" here: a full-size record line
|
||||
// (~550 B) exceeds the mesh admin CLI's 150 B budget and would overflow its
|
||||
// reply buffer. There the reply degrades to a bare trailer (paging stalls);
|
||||
// the intended consumer is the local console's ~1000 B pages, which always
|
||||
// fit at least one record.
|
||||
if ((dp - reply) + ll + 40 > max_len) break; // room for trailer
|
||||
memcpy(dp, line, ll); dp += ll;
|
||||
last = r->seq;
|
||||
}
|
||||
dp += sprintf(dp, "E,%lu,%lu,%lu", (unsigned long)last, (unsigned long)oldest, (unsigned long)newest);
|
||||
*dp = 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
uint8_t MyMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data, bool is_flood) {
|
||||
ClientInfo* client = NULL;
|
||||
if (data[0] == 0) { // blank password, just check if sender is in ACL
|
||||
@@ -108,10 +369,19 @@ uint8_t MyMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* secr
|
||||
#if MESH_DEBUG
|
||||
MESH_DEBUG_PRINTLN("Login, sender not in ACL");
|
||||
#endif
|
||||
} else {
|
||||
// CUSTOM (TeTeHacko): a blank login has a replay floor too -- replayed, it
|
||||
// gained nothing, but each copy made us flood a reply over the mesh.
|
||||
if (sender_timestamp <= client->last_timestamp) return 0;
|
||||
acl.persistTimestamp(client, sender_timestamp, getRTCClock()->getCurrentTime());
|
||||
client->last_timestamp = sender_timestamp;
|
||||
}
|
||||
}
|
||||
if (client == NULL) {
|
||||
uint8_t perms;
|
||||
// CUSTOM (TeTeHacko): capped wrong passwords (LoginGuard.h); a known admin is never locked out
|
||||
ClientInfo* known = acl.getClient(sender.pub_key, PUB_KEY_SIZE);
|
||||
if (login_guard.locked(millis()) && !(known && known->isAdmin())) return 0;
|
||||
if (strcmp((char *)data, _prefs.password) == 0) { // check for valid admin password
|
||||
perms = PERM_ACL_ADMIN;
|
||||
} else if (_prefs.ro_password[0] && strcmp((char *)data, _prefs.ro_password) == 0) { // check read-only password
|
||||
@@ -122,6 +392,7 @@ uint8_t MyMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* secr
|
||||
#if MESH_DEBUG
|
||||
MESH_DEBUG_PRINTLN("Invalid password: %s", data);
|
||||
#endif
|
||||
login_guard.failed(millis()); // CUSTOM (TeTeHacko)
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -132,7 +403,6 @@ uint8_t MyMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* secr
|
||||
MESH_DEBUG_PRINTLN("Possible login replay attack!");
|
||||
return 0; // FATAL: client table is full -OR- replay attack
|
||||
}
|
||||
|
||||
MESH_DEBUG_PRINTLN("Login success!");
|
||||
client->last_timestamp = sender_timestamp;
|
||||
if (!shared_pw || client->permissions == 0 || client->shared_login) { // shared passwords don't change saved entries
|
||||
@@ -140,6 +410,7 @@ uint8_t MyMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* secr
|
||||
client->permissions |= perms;
|
||||
client->shared_login = shared_pw;
|
||||
}
|
||||
acl.persistTimestamp(client, sender_timestamp, getRTCClock()->getCurrentTime()); // CUSTOM (TeTeHacko): admin only, so after the role
|
||||
memcpy(client->shared_secret, secret, PUB_KEY_SIZE);
|
||||
|
||||
if (!shared_pw) { // keep number of FS writes to a minimum
|
||||
@@ -294,6 +565,17 @@ int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t
|
||||
// memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
|
||||
memcpy(reply_data, &sender_timestamp, 4); // reflect sender_timestamp back in response packet (kind of like a 'tag')
|
||||
|
||||
// CUSTOM (TeTeHacko): firmware chunks for FwUpdate (REQ_TYPE_FW_OTA = 0xF0, admin
|
||||
// only, helpers/FwUpdate.h). 0 = no reply: chunks are fire and forget.
|
||||
if (payload_len >= 1 && payload[0] == 0xF0) {
|
||||
extern int maintHandleRequest(bool admin, const uint8_t* req, int len, uint8_t* reply, int reply_max);
|
||||
// 150: tag + reply pads to 160 B, and the companion's push frame (6 + padded
|
||||
// length - 4) must stay within MAX_FRAME_SIZE 176 -- a 163 B reply padded to
|
||||
// 176 made a 178 B frame that the companion silently dropped
|
||||
int n = maintHandleRequest(sender->isAdmin(), payload, (int)payload_len, &reply_data[4], 150);
|
||||
return n > 0 ? 4 + n : 0;
|
||||
}
|
||||
|
||||
if (payload[0] == REQ_TYPE_GET_STATUS) { // guests can also access this now
|
||||
RepeaterStats stats;
|
||||
stats.batt_milli_volts = board.getBattMilliVolts();
|
||||
@@ -314,6 +596,8 @@ int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t
|
||||
stats.n_flood_dups = std::min<uint32_t>(((SimpleMeshTables *)getTables())->getNumFloodDups(), 0xFFFF);
|
||||
stats.total_rx_air_time_secs = getReceiveAirTime() / 1000;
|
||||
stats.n_recv_errors = radio_driver.getPacketsRecvErrors();
|
||||
stats.n_tx_start_fail = getNumTxStartFail(); // CUSTOM (TeTeHacko)
|
||||
stats.n_tx_timeout = getNumTxTimeout(); // CUSTOM (TeTeHacko)
|
||||
memcpy(&reply_data[4], &stats, sizeof(stats));
|
||||
|
||||
return 4 + sizeof(stats); // reply_len
|
||||
@@ -583,6 +867,144 @@ bool MyMesh::allowPacketForward(const mesh::Packet *packet) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// CUSTOM (TeTeHacko): keyless channel-hash deny list / throttle (`filter hash`).
|
||||
// LAST of the checks here, so a throttle pass is only spent on a packet that
|
||||
// would otherwise go out; and before takeForwardingRateLimit() in
|
||||
// routeRecvPacket(), so a vetoed packet does not eat FairnessLimiter tokens.
|
||||
if (filterHashDenied(packet)) {
|
||||
MESH_DEBUG_PRINTLN("allowPacketForward: channel hash %02X on deny list", packet->payload[0]);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// CUSTOM (TeTeHacko): `fairness` -- denied-forward stats + current caps;
|
||||
// `fairness on|off` -- runtime kill switch (persisted).
|
||||
// `fairness grid` -- busiest deny buckets per category (what we shed).
|
||||
// `fairness cap <group> <sender> <advert>` -- burst caps, 0 = default.
|
||||
// `fairness refill <group_s> <sender_s> <advert_s>` -- refill interval secs, 0 = default.
|
||||
// `fairness advert [<hours>|clear]` -- per-origin advert window (0 = off).
|
||||
// `fairness dryrun [on|off]` -- count verdicts, forward anyway.
|
||||
// `fairness air` -- estimated airtime shed per reason.
|
||||
// All tuning is persisted, so a mast reboot keeps it.
|
||||
bool MyMesh::fairnessHandleCommand(const char *command, char *reply, int reply_max) {
|
||||
if (memcmp(command, "fairness", 8) != 0 || (command[8] != 0 && command[8] != ' ')) return false;
|
||||
|
||||
const char *arg = (command[8] == ' ') ? &command[9] : "";
|
||||
|
||||
if (strcmp(arg, "on") == 0 || strcmp(arg, "off") == 0) {
|
||||
_prefs.fairness_enabled = (arg[1] == 'n') ? 1 : 0;
|
||||
fairness_limiter.setBucketsEnabled(_prefs.fairness_enabled);
|
||||
savePrefs();
|
||||
snprintf(reply, reply_max, "OK - fairness %s", _prefs.fairness_enabled ? "on" : "off");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (strcmp(arg, "dryrun") == 0 || strcmp(arg, "dryrun on") == 0 || strcmp(arg, "dryrun off") == 0) {
|
||||
if (arg[6] == ' ') {
|
||||
_prefs.fair_dry_run = (arg[8] == 'n') ? 1 : 0;
|
||||
fairness_limiter.setDryRun(_prefs.fair_dry_run);
|
||||
savePrefs();
|
||||
}
|
||||
snprintf(reply, reply_max, "%sfairness dry-run %s", arg[6] == ' ' ? "OK - " : "",
|
||||
fairness_limiter.dryRun() ? "on" : "off");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (strcmp(arg, "advert") == 0 || strncmp(arg, "advert ", 7) == 0) {
|
||||
AdvertWindow& w = fairness_limiter.advertWindow();
|
||||
if (strcmp(arg, "advert clear") == 0) {
|
||||
w.clear();
|
||||
} else if (arg[6] == ' ') {
|
||||
char* end = NULL;
|
||||
long h = strtol(arg + 7, &end, 10);
|
||||
if (end == arg + 7 || *end != 0 || h < 0 || h > ADVERT_WINDOW_MAX_HOURS) {
|
||||
snprintf(reply, reply_max, "Err - fairness advert <0-%d hours>|clear", ADVERT_WINDOW_MAX_HOURS);
|
||||
return true;
|
||||
}
|
||||
_prefs.fair_advert_hours = (uint16_t)h;
|
||||
w.setHours(_prefs.fair_advert_hours);
|
||||
savePrefs();
|
||||
}
|
||||
snprintf(reply, reply_max, "advert window %uh%s, held %u (%us air), cache %d/%d, evicted %u",
|
||||
(uint32_t)w.hours(), fairness_limiter.dryRun() ? " DRY-RUN" : "", fairness_limiter.deniedWindow(),
|
||||
fairness_limiter.shedAirtimeMs(FAIR_SHED_WINDOW) / 1000, w.count(), w.capacity(), w.evicted());
|
||||
return true;
|
||||
}
|
||||
|
||||
if (strcmp(arg, "air") == 0) {
|
||||
snprintf(reply, reply_max, "shed air%s: group %us sender %us advert %us window %us",
|
||||
fairness_limiter.dryRun() ? " (dry-run, would be)" : "",
|
||||
fairness_limiter.shedAirtimeMs(FAIR_SHED_GROUP) / 1000,
|
||||
fairness_limiter.shedAirtimeMs(FAIR_SHED_SENDER) / 1000,
|
||||
fairness_limiter.shedAirtimeMs(FAIR_SHED_ADVERT) / 1000,
|
||||
fairness_limiter.shedAirtimeMs(FAIR_SHED_WINDOW) / 1000);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (strcmp(arg, "grid") == 0) {
|
||||
char grid[180];
|
||||
fairness_limiter.formatGrid(grid, sizeof(grid));
|
||||
snprintf(reply, reply_max, "%s", grid);
|
||||
return true;
|
||||
}
|
||||
|
||||
// strncmp, not memcmp: for the bare `fairness` command arg is the 1-byte ""
|
||||
// literal, and memcmp(arg, "cap ", 4) would over-read it (UB, trips ASAN).
|
||||
if (strncmp(arg, "cap ", 4) == 0) {
|
||||
int g = 0, s = 0, a = 0;
|
||||
if (sscanf(arg + 4, "%d %d %d", &g, &s, &a) != 3 || g < 0 || s < 0 || a < 0 || g > 255 || s > 255 || a > 255) {
|
||||
strcpy(reply, "Err - fairness cap <group> <sender> <advert> (0=default)");
|
||||
return true;
|
||||
}
|
||||
_prefs.fair_group_cap = (uint8_t)g;
|
||||
_prefs.fair_sender_cap = (uint8_t)s;
|
||||
_prefs.fair_advert_cap = (uint8_t)a;
|
||||
fairness_limiter.setGroupCap(_prefs.fair_group_cap);
|
||||
fairness_limiter.setSenderNormalCap(_prefs.fair_sender_cap);
|
||||
fairness_limiter.setSenderLowCap(_prefs.fair_advert_cap);
|
||||
savePrefs();
|
||||
snprintf(reply, reply_max, "OK - cap group %u sender %u advert %u",
|
||||
(uint32_t)fairness_limiter.groupCap(), (uint32_t)fairness_limiter.senderNormalCap(),
|
||||
(uint32_t)fairness_limiter.senderLowCap());
|
||||
return true;
|
||||
}
|
||||
|
||||
if (strncmp(arg, "refill ", 7) == 0) {
|
||||
int g = 0, s = 0, a = 0;
|
||||
if (sscanf(arg + 7, "%d %d %d", &g, &s, &a) != 3 || g < 0 || s < 0 || a < 0 || g > 65535 || s > 65535 || a > 65535) {
|
||||
strcpy(reply, "Err - fairness refill <group_s> <sender_s> <advert_s> (0=default)");
|
||||
return true;
|
||||
}
|
||||
_prefs.fair_group_refill_s = (uint16_t)g;
|
||||
_prefs.fair_sender_refill_s = (uint16_t)s;
|
||||
_prefs.fair_advert_refill_s = (uint16_t)a;
|
||||
// reschedule so the new interval takes effect from now
|
||||
next_fair_group_refill = futureMillis(fairGroupRefillMs());
|
||||
next_fair_sender_normal_refill = futureMillis(fairSenderRefillMs());
|
||||
next_fair_sender_low_refill = futureMillis(fairAdvertRefillMs());
|
||||
savePrefs();
|
||||
snprintf(reply, reply_max, "OK - refill group %us sender %us advert %us",
|
||||
(uint32_t)(fairGroupRefillMs() / 1000), (uint32_t)(fairSenderRefillMs() / 1000),
|
||||
(uint32_t)(fairAdvertRefillMs() / 1000));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (arg[0] != 0) {
|
||||
strcpy(reply, "Err - fairness [on|off|grid|cap|refill|advert|dryrun|air]");
|
||||
return true;
|
||||
}
|
||||
|
||||
// bare `fairness` -- stats + current caps/refills
|
||||
snprintf(reply, reply_max,
|
||||
"fairness: %s%s, denied group %u/sender %u/advert %u/window %u; cap %u/%u/%u; refill %u/%u/%us",
|
||||
_prefs.fairness_enabled ? "on" : "OFF", fairness_limiter.dryRun() ? " DRY-RUN" : "",
|
||||
fairness_limiter.deniedGroup(), fairness_limiter.deniedSenderNormal(),
|
||||
fairness_limiter.deniedSenderLow(), fairness_limiter.deniedWindow(),
|
||||
(uint32_t)fairness_limiter.groupCap(), (uint32_t)fairness_limiter.senderNormalCap(),
|
||||
(uint32_t)fairness_limiter.senderLowCap(),
|
||||
(uint32_t)(fairGroupRefillMs() / 1000), (uint32_t)(fairSenderRefillMs() / 1000),
|
||||
(uint32_t)(fairAdvertRefillMs() / 1000));
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -596,6 +1018,10 @@ const char *MyMesh::getLogDateTime() {
|
||||
}
|
||||
|
||||
void MyMesh::logRxRaw(float snr, float rssi, const uint8_t raw[], int len) {
|
||||
#if PKTFEED_SIZE
|
||||
// observer feed: raw bytes only exist here (pre-parse); committed in logRx
|
||||
stagePktFeed(raw, len);
|
||||
#endif
|
||||
#if MESH_PACKET_LOGGING
|
||||
Serial.print(getLogDateTime());
|
||||
Serial.print(" RAW: ");
|
||||
@@ -605,6 +1031,16 @@ void MyMesh::logRxRaw(float snr, float rssi, const uint8_t raw[], int len) {
|
||||
}
|
||||
|
||||
void MyMesh::logRx(mesh::Packet *pkt, int len, float score) {
|
||||
#if RXLOG_SIZE
|
||||
// analyzer firehose: every parsed frame we hear. Called synchronously from
|
||||
// Dispatcher::checkRecv (before any score-delay queueing), so getRSSI()/SNR
|
||||
// on the packet still belong to THIS frame.
|
||||
captureRx(pkt);
|
||||
#endif
|
||||
#if PKTFEED_SIZE
|
||||
// observer feed: pair the staged raw bytes (from logRxRaw) with this frame
|
||||
commitPktFeed(pkt);
|
||||
#endif
|
||||
#ifdef WITH_BRIDGE
|
||||
if (_prefs.bridge_pkt_src == 1) {
|
||||
bridge.sendPacket(pkt);
|
||||
@@ -779,13 +1215,32 @@ void MyMesh::onAdvertRecv(mesh::Packet *packet, const mesh::Identity &id, uint32
|
||||
const uint8_t *app_data, size_t app_data_len) {
|
||||
mesh::Mesh::onAdvertRecv(packet, id, timestamp, app_data, app_data_len); // chain to super impl
|
||||
|
||||
AdvertDataParser parser(app_data, app_data_len);
|
||||
|
||||
// if this a zero hop advert (and not via 'Share'), add it to neighbours
|
||||
if (packet->getPathHashCount() == 0 && !isShare(packet)) {
|
||||
AdvertDataParser parser(app_data, app_data_len);
|
||||
if (parser.isValid() && parser.getType() == ADV_TYPE_REPEATER) { // just keep neigbouring Repeaters
|
||||
putNeighbour(id, timestamp, packet->getSNR());
|
||||
}
|
||||
}
|
||||
|
||||
#if MAX_HEARD_NODES
|
||||
// analyzer: record infrastructure nodes only -- REPEATERS and ROOM SERVERS,
|
||||
// any hop count. Chat clients (and sensors) are deliberately NOT recorded:
|
||||
// they are personal/mobile devices, so mapping them is a privacy concern and
|
||||
// just churns the registry. The signature is already verified upstream
|
||||
// (mesh::Mesh::onAdvertRecv only reaches here for valid adverts), so the
|
||||
// identities/positions kept here are trustworthy.
|
||||
uint8_t adv_type = parser.getType();
|
||||
if (parser.isValid() && !isShare(packet)
|
||||
&& (adv_type == ADV_TYPE_REPEATER || adv_type == ADV_TYPE_ROOM)) {
|
||||
putHeardNode(id, timestamp, adv_type,
|
||||
parser.hasLatLon() ? parser.getIntLat() : 0,
|
||||
parser.hasLatLon() ? parser.getIntLon() : 0,
|
||||
parser.hasName() ? parser.getName() : "",
|
||||
packet->_snr, (int8_t)packet->getRSSI(), packet);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx, const uint8_t *secret,
|
||||
@@ -802,6 +1257,7 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx,
|
||||
memcpy(×tamp, data, 4);
|
||||
|
||||
if (timestamp > client->last_req_timestamp) { // prevent replay attacks
|
||||
acl.persistTimestamp(client, timestamp, getRTCClock()->getCurrentTime()); // CUSTOM (TeTeHacko): before acting
|
||||
int reply_len = handleRequest(client, timestamp, &data[4], len - 4);
|
||||
if (reply_len == 0) return; // invalid command
|
||||
|
||||
@@ -841,6 +1297,7 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx,
|
||||
MESH_DEBUG_PRINTLN("onPeerDataRecv: text is our own CLI reply");
|
||||
} else if (sender_timestamp >= client->last_timestamp) { // prevent replay attacks
|
||||
bool is_retry = (sender_timestamp == client->last_timestamp);
|
||||
acl.persistTimestamp(client, sender_timestamp, getRTCClock()->getCurrentTime()); // CUSTOM (TeTeHacko): before acting
|
||||
client->last_timestamp = sender_timestamp;
|
||||
client->last_activity = getRTCClock()->getCurrentTime();
|
||||
|
||||
@@ -947,7 +1404,7 @@ void MyMesh::onControlDataRecv(mesh::Packet* packet) {
|
||||
memcpy(&data[6], self_id.pub_key, PUB_KEY_SIZE);
|
||||
auto resp = createControlData(data, prefix_only ? 6 + 8 : 6 + PUB_KEY_SIZE);
|
||||
if (resp) {
|
||||
sendZeroHop(resp, getRetransmitDelay(resp)*4); // apply random delay (widened x4), as multiple nodes can respond to this
|
||||
sendZeroHop(resp, getRetransmitDelay(resp)*4, _prefs.path_hash_mode + 1); // apply random delay (widened x4), as multiple nodes can respond to this
|
||||
}
|
||||
}
|
||||
} else if (type == CTL_TYPE_NODE_DISCOVER_RESP && packet->payload_len >= 6) {
|
||||
@@ -990,7 +1447,7 @@ void MyMesh::sendNodeDiscoverReq() {
|
||||
|
||||
auto pkt = createControlData(data, sizeof(data));
|
||||
if (pkt) {
|
||||
sendZeroHop(pkt);
|
||||
sendZeroHop(pkt, (uint32_t)0, _prefs.path_hash_mode + 1); // přetypování nutné: holá 0 je i null pointer pro transport_codes přetížení
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1012,6 +1469,7 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc
|
||||
last_millis = 0;
|
||||
uptime_millis = 0;
|
||||
next_local_advert = next_flood_advert = 0;
|
||||
next_fair_sender_normal_refill = next_fair_sender_low_refill = next_fair_group_refill = 0;
|
||||
dirty_contacts_expiry = 0;
|
||||
last_read_time = 0;
|
||||
set_radio_at = revert_radio_at = 0;
|
||||
@@ -1022,9 +1480,29 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc
|
||||
#if MAX_NEIGHBOURS
|
||||
memset(neighbours, 0, sizeof(neighbours));
|
||||
#endif
|
||||
#if MAX_HEARD_NODES
|
||||
memset(heard_nodes, 0, sizeof(heard_nodes));
|
||||
#endif
|
||||
#if RXLOG_SIZE
|
||||
memset(rxlog_ring, 0, sizeof(rxlog_ring));
|
||||
rxlog_head = 0;
|
||||
rxlog_next_seq = 1; // seq 0 is reserved for "empty slot" / initial cursor
|
||||
#endif
|
||||
#if PKTFEED_SIZE
|
||||
memset(pktfeed_ring, 0, sizeof(pktfeed_ring));
|
||||
pktfeed_head = 0;
|
||||
pktfeed_next_seq = 1; // seq 0 is reserved for "empty slot" / initial cursor
|
||||
pktfeed_stage_len = 0;
|
||||
#endif
|
||||
#if defined(BOT_CHANNEL_PSK) || defined(FILTER_CHANNEL_PSKS)
|
||||
channelsInit(); // registers the bot channel and/or the filter channels
|
||||
#endif
|
||||
|
||||
// defaults
|
||||
_prefs.airtime_factor = 1.0;
|
||||
#ifdef AIRTIME_FACTOR_DEFAULT // CUSTOM (TeTeHacko): e.g. 9 = 10 % duty cycle (meshcore.cz)
|
||||
_prefs.airtime_factor = AIRTIME_FACTOR_DEFAULT;
|
||||
#endif
|
||||
_prefs.rx_delay_base = 0.0f; // turn off by default, was 10.0;
|
||||
_prefs.tx_delay_factor = 0.5f; // was 0.25f
|
||||
_prefs.direct_tx_delay_factor = 0.3f; // was 0.2
|
||||
@@ -1037,11 +1515,58 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc
|
||||
_prefs.bw = LORA_BW;
|
||||
_prefs.cr = LORA_CR;
|
||||
_prefs.tx_power_dbm = LORA_TX_POWER;
|
||||
_prefs.advert_interval = 1; // default to 2 minutes for NEW installs
|
||||
_prefs.flood_advert_interval = 47; // 47 hours
|
||||
// CUSTOM (TeTeHacko): 2-byte path hashes by default. Upstream leaves this
|
||||
// field unset, so a fresh node came up at mode 0 = 1 byte per hop -- which
|
||||
// nobody on the CZ mesh runs any more, and every new install then needed a
|
||||
// manual `set path.hash.mode 1`.
|
||||
//
|
||||
// NOTE this is the PATH hash, not PATH_HASH_SIZE. It is used as
|
||||
// sendFlood(..., path_hash_mode + 1), i.e. bytes each hop appends to the path
|
||||
// while flooding, and the size travels in the packet: Packet.h:85 packs it
|
||||
// into the top 2 bits of path_len and Mesh.cpp:93 matches with
|
||||
// getPathHashSize(), so mixed-mode nodes still route for each other.
|
||||
// PATH_HASH_SIZE (1) is a different field -- the destination and channel hash
|
||||
// in Mesh.cpp:458/548 -- and changing THAT would break the wire format
|
||||
// against every other node in the mesh.
|
||||
#ifndef PATH_HASH_MODE_DEFAULT
|
||||
#define PATH_HASH_MODE_DEFAULT 1 // 1 = 2 bytes per hop
|
||||
#endif
|
||||
_prefs.path_hash_mode = PATH_HASH_MODE_DEFAULT;
|
||||
// CUSTOM (TeTeHacko): overridable so a node can be built to SHIP SILENT.
|
||||
// ENABLE_ADVERT_ON_BOOT only suppresses the advert at boot, not the periodic
|
||||
// timer -- with the upstream defaults an `erase`d node starts advertising
|
||||
// within 2 minutes. For a repeater that is going somewhere unreachable that
|
||||
// is the wrong way round: it must stay quiet until somebody deliberately
|
||||
// turns it on, and a reboot on the mast must not undo that.
|
||||
// Set both to 0 in the deployment envs; 0 = off (CommonCLI.cpp:615-630).
|
||||
#ifndef ADVERT_INTERVAL_DEFAULT
|
||||
#define ADVERT_INTERVAL_DEFAULT 1 // *2 = 2 minutes, upstream default
|
||||
#endif
|
||||
#ifndef FLOOD_ADVERT_INTERVAL_DEFAULT
|
||||
#define FLOOD_ADVERT_INTERVAL_DEFAULT 47 // hours
|
||||
#endif
|
||||
#ifndef DISABLE_FWD_DEFAULT
|
||||
#define DISABLE_FWD_DEFAULT 0 // 0 = repeat on
|
||||
#endif
|
||||
_prefs.advert_interval = ADVERT_INTERVAL_DEFAULT;
|
||||
_prefs.flood_advert_interval = FLOOD_ADVERT_INTERVAL_DEFAULT;
|
||||
_prefs.disable_fwd = DISABLE_FWD_DEFAULT;
|
||||
_prefs.flood_max = 64;
|
||||
_prefs.flood_max_unscoped = 64;
|
||||
_prefs.flood_max_advert = 8;
|
||||
// CUSTOM (TeTeHacko): FairnessLimiter on by default; `fairness off` is the
|
||||
// runtime kill switch (persisted, so it survives a reboot on the mast).
|
||||
#ifndef FAIRNESS_ENABLED_DEFAULT
|
||||
#define FAIRNESS_ENABLED_DEFAULT 1
|
||||
#endif
|
||||
_prefs.fairness_enabled = FAIRNESS_ENABLED_DEFAULT;
|
||||
// CUSTOM (TeTeHacko): radio silence watchdog, minutes; 0 = off (see main.cpp).
|
||||
#ifndef RADIO_SILENCE_MIN_DEFAULT
|
||||
#define RADIO_SILENCE_MIN_DEFAULT 0
|
||||
#endif
|
||||
_prefs.radio_silence_min = RADIO_SILENCE_MIN_DEFAULT;
|
||||
filter_hash_dropped = 0;
|
||||
filter_hash_passed = 0;
|
||||
_prefs.interference_threshold = 0; // disabled
|
||||
_prefs.cad_enabled = 0; // hardware CAD before TX (off by default; 'set cad on')
|
||||
_prefs.loop_detect = LOOP_DETECT_MINIMAL;
|
||||
@@ -1084,8 +1609,37 @@ void MyMesh::begin(FILESYSTEM *fs) {
|
||||
// load persisted prefs
|
||||
_cli.loadPrefs(_fs);
|
||||
acl.load(_fs, self_id);
|
||||
|
||||
// Apply any persisted runtime cap tuning (0 = build default). Do this before
|
||||
// the first refill so the initial token respects a raised cap.
|
||||
fairness_limiter.setGroupCap(_prefs.fair_group_cap);
|
||||
fairness_limiter.setSenderNormalCap(_prefs.fair_sender_cap);
|
||||
fairness_limiter.setSenderLowCap(_prefs.fair_advert_cap);
|
||||
fairness_limiter.setBucketsEnabled(_prefs.fairness_enabled);
|
||||
fairness_limiter.setDryRun(_prefs.fair_dry_run);
|
||||
fairness_limiter.advertWindow().setHours(_prefs.fair_advert_hours);
|
||||
|
||||
// Fairness buckets start with just ONE token (not the full cap): a repeater
|
||||
// stuck in a crash loop must not hand out a fresh burst on every boot.
|
||||
fairness_limiter.refillSenderNormal();
|
||||
fairness_limiter.refillSenderLow();
|
||||
fairness_limiter.refillGroup();
|
||||
next_fair_sender_normal_refill = futureMillis(fairSenderRefillMs());
|
||||
next_fair_sender_low_refill = futureMillis(fairAdvertRefillMs());
|
||||
next_fair_group_refill = futureMillis(fairGroupRefillMs());
|
||||
// TODO: key_store.begin();
|
||||
#ifdef DEFAULT_REGIONS
|
||||
// CUSTOM (TeTeHacko): a node that never saved regions gets DEFAULT_REGIONS
|
||||
// (e.g. "cz,cs", meshcore.cz/regiony) -- as if `region put` each + `region
|
||||
// save`. Once /regions2 exists the operator's list wins, removals included.
|
||||
bool regions_saved = _fs->exists("/regions2");
|
||||
#endif
|
||||
region_map.load(_fs);
|
||||
#ifdef DEFAULT_REGIONS
|
||||
if (!regions_saved && region_map.putDefaults(DEFAULT_REGIONS) > 0) {
|
||||
region_map.save(_fs);
|
||||
}
|
||||
#endif
|
||||
|
||||
// establish default-scope
|
||||
{
|
||||
@@ -1115,6 +1669,9 @@ void MyMesh::begin(FILESYSTEM *fs) {
|
||||
|
||||
radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
|
||||
radio_driver.setTxPower(_prefs.tx_power_dbm);
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
_prefs.getRadioPrefs()->applyRxPowerSaving(_prefs.sf, _prefs.bw); // CUSTOM (TeTeHacko)
|
||||
#endif
|
||||
|
||||
radio_driver.setRxBoostedGainMode(_prefs.rx_boosted_gain);
|
||||
MESH_DEBUG_PRINTLN("RX Boosted Gain Mode: %s",
|
||||
@@ -1130,6 +1687,7 @@ void MyMesh::begin(FILESYSTEM *fs) {
|
||||
#if ENV_INCLUDE_GPS == 1
|
||||
applyGpsPrefs();
|
||||
#endif
|
||||
sensors.applyInaShunt(_prefs.ina_shunt_mohm); // CUSTOM (TeTeHacko)
|
||||
}
|
||||
|
||||
void MyMesh::sendFloodScoped(const TransportKey& scope, mesh::Packet* pkt, uint32_t delay_millis, uint8_t path_hash_size) {
|
||||
@@ -1172,7 +1730,7 @@ void MyMesh::sendSelfAdvertisement(int delay_millis, bool flood) {
|
||||
if (flood) {
|
||||
sendFloodScoped(default_scope, pkt, delay_millis, _prefs.path_hash_mode + 1);
|
||||
} else {
|
||||
sendZeroHop(pkt, delay_millis);
|
||||
sendZeroHop(pkt, delay_millis, _prefs.path_hash_mode + 1);
|
||||
}
|
||||
} else {
|
||||
MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
|
||||
@@ -1309,7 +1867,8 @@ void MyMesh::formatRadioStatsReply(char *reply) {
|
||||
|
||||
void MyMesh::formatPacketStatsReply(char *reply) {
|
||||
StatsFormatHelper::formatPacketStats(reply, radio_driver, getNumSentFlood(), getNumSentDirect(),
|
||||
getNumRecvFlood(), getNumRecvDirect());
|
||||
getNumRecvFlood(), getNumRecvDirect(),
|
||||
getNumTxStartFail(), getNumTxTimeout());
|
||||
}
|
||||
|
||||
void MyMesh::saveIdentity(const mesh::LocalIdentity &new_id) {
|
||||
@@ -1331,7 +1890,7 @@ void MyMesh::clearStats() {
|
||||
((SimpleMeshTables *)getTables())->resetStats();
|
||||
}
|
||||
|
||||
void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply) {
|
||||
void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply, int reply_max) {
|
||||
if (region_load_active) {
|
||||
if (StrHelper::isBlank(command)) { // empty/blank line, signal to terminate 'load' operation
|
||||
region_map = temp_map; // copy over the temp instance as new current map
|
||||
@@ -1367,12 +1926,17 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply
|
||||
}
|
||||
|
||||
while (*command == ' ') command++; // skip leading spaces
|
||||
|
||||
if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI)
|
||||
memcpy(reply, command, 3); // reflect the prefix back
|
||||
reply += 3;
|
||||
command += 3;
|
||||
#ifdef BENCH_FAULT_CMD
|
||||
// Bench builds only (PLATFORMIO_BUILD_FLAGS=-D BENCH_FAULT_CMD): crash on
|
||||
// purpose, to prove the hardfault record survives the reset and gets printed.
|
||||
if (strcmp(command, "hardfault") == 0) {
|
||||
__builtin_trap(); // UDF -> UsageFault, escalates to HardFault
|
||||
}
|
||||
#endif
|
||||
|
||||
const char* cmd = command;
|
||||
cli_args::stripPrefix(cmd, reply, &reply_max);
|
||||
command = const_cast<char*>(cmd);
|
||||
|
||||
// handle ACL related commands
|
||||
if (memcmp(command, "setperm ", 8) == 0) { // format: setperm {pubkey-hex} {permissions-int8}
|
||||
@@ -1417,7 +1981,75 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply
|
||||
sendNodeDiscoverReq();
|
||||
strcpy(reply, "OK - Discover sent");
|
||||
}
|
||||
#if MAX_HEARD_NODES
|
||||
} else if (memcmp(command, "nodes", 5) == 0 && (command[5] == 0 || command[5] == ' ')) {
|
||||
// analyzer: paged dump of heard repeaters/room servers (for a map/bridge).
|
||||
// Page size = caller's reply capacity: local console passes ~1000 (fewer BLE
|
||||
// round trips), the mesh admin CLI keeps the default 150 (one LoRa packet).
|
||||
uint16_t offset = (command[5] == ' ') ? (uint16_t) atoi(&command[6]) : 0;
|
||||
formatNodesReply(reply, reply_max, offset);
|
||||
#endif
|
||||
#if RXLOG_SIZE
|
||||
} else if (memcmp(command, "rxlog", 5) == 0 && (command[5] == 0 || command[5] == ' ')) {
|
||||
// analyzer: paged firehose of every frame heard, since <cursor> (0 = all)
|
||||
uint32_t cursor = (command[5] == ' ') ? (uint32_t) strtoul(&command[6], NULL, 10) : 0;
|
||||
formatRxLogReply(reply, reply_max, cursor);
|
||||
#endif
|
||||
#if PKTFEED_SIZE
|
||||
} else if (memcmp(command, "pktlog", 6) == 0 && (command[6] == 0 || command[6] == ' ')) {
|
||||
// observer feed: paged raw frames heard, since <cursor> (0 = all)
|
||||
uint32_t cursor = (command[6] == ' ') ? (uint32_t) strtoul(&command[7], NULL, 10) : 0;
|
||||
formatPktFeedReply(reply, reply_max, cursor);
|
||||
#endif
|
||||
} else{
|
||||
#ifdef BOT_CHANNEL_PSK
|
||||
// CUSTOM (TeTeHacko): `bot` — read-only channel bot diagnostics. See ChannelBot.h.
|
||||
if (botHandleCommand(command, reply)) return;
|
||||
#endif
|
||||
// CUSTOM (TeTeHacko): `filter hash [add|del <hex>|clear]` — keyless channel-hash
|
||||
// deny list. Before filterHandleCommand(), which would claim any `filter ...`.
|
||||
if (filterHashHandleCommand(command, reply, reply_max)) return;
|
||||
// CUSTOM (TeTeHacko): `filter dryrun [on|off]`, `filter age [<min>|off]`. Also
|
||||
// before filterHandleCommand(), which would take `dryrun`/`age` for names.
|
||||
if (filterMiscHandleCommand(command, reply, reply_max)) return;
|
||||
#ifdef FILTER_CHANNEL_PSKS
|
||||
// CUSTOM (TeTeHacko): `filter add|del|list|clear` — runtime deny list for
|
||||
// channel messages this repeater refuses to forward. See ChannelFilter.h.
|
||||
if (filterHandleCommand(command, reply, reply_max)) return;
|
||||
#endif
|
||||
// CUSTOM (TeTeHacko): `fairness [on|off|grid|cap ...|refill ...]` — rate limiter.
|
||||
if (fairnessHandleCommand(command, reply, reply_max)) return;
|
||||
// CUSTOM (TeTeHacko): `blink [n]` — flash the LED to identify this board.
|
||||
// Outside the BLE guard on purpose: a USB-only build needs it just as much,
|
||||
// since a board with no data cable and no BLE cannot be identified at all.
|
||||
extern bool identHandleCommand(const char* command, char* reply);
|
||||
if (identHandleCommand(command, reply)) return;
|
||||
// CUSTOM (TeTeHacko): `dfu [uf2|serial|ota]` (local only), `get/set
|
||||
// radio.silence`, `get radio.reboots`, `get boot` -- helpers/NodeMaintenance.
|
||||
// Ahead of CommonCLI's get/set.
|
||||
extern bool maintHandleCommand(uint32_t sender_timestamp, const char* command, char* reply);
|
||||
if (maintHandleCommand(sender_timestamp, command, reply)) return;
|
||||
// CUSTOM (TeTeHacko): `txpwr [dBm]` — set output power and report RadioLib's
|
||||
// verdict, which `set tx` swallows. See main.cpp.
|
||||
extern bool txPwrHandleCommand(const char* command, char* reply);
|
||||
if (txPwrHandleCommand(command, reply)) return;
|
||||
#ifdef RADIO_DIAG
|
||||
// CUSTOM (TeTeHacko): `radiostat` / `radiokick` -- see main.cpp.
|
||||
extern bool radioDiagHandleCommand(const char* command, char* reply);
|
||||
if (radioDiagHandleCommand(command, reply)) return;
|
||||
#endif
|
||||
#ifdef PIN_DIAG
|
||||
// CUSTOM (TeTeHacko): `dio1` — is the DIO1 IRQ line alive, and if not, which
|
||||
// END of it is broken? Salvage diagnostics, see main.cpp.
|
||||
extern bool pinDiagHandleCommand(const char* command, char* reply);
|
||||
if (pinDiagHandleCommand(command, reply)) return;
|
||||
#endif
|
||||
#if defined(BLE_PIN_CODE) && defined(NRF52_PLATFORM)
|
||||
// CUSTOM (TeTeHacko): `ble on|off|ble` — implemented in main.cpp (BLE console).
|
||||
// Available from serial, the BLE console and remotely via MC (admin remote CLI).
|
||||
extern bool bleConsoleHandleCommand(const char* command, char* reply);
|
||||
if (bleConsoleHandleCommand(command, reply)) return;
|
||||
#endif
|
||||
_cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
|
||||
}
|
||||
}
|
||||
@@ -1429,6 +2061,19 @@ void MyMesh::loop() {
|
||||
|
||||
mesh::Mesh::loop();
|
||||
|
||||
// Fairness limiter refilling. The `else if` chain keeps the three timers from
|
||||
// aligning on one loop pass; each adds ONE token per bucket per interval.
|
||||
if (next_fair_sender_normal_refill && millisHasNowPassed(next_fair_sender_normal_refill)) {
|
||||
fairness_limiter.refillSenderNormal();
|
||||
next_fair_sender_normal_refill = futureMillis(fairSenderRefillMs());
|
||||
} else if (next_fair_sender_low_refill && millisHasNowPassed(next_fair_sender_low_refill)) {
|
||||
fairness_limiter.refillSenderLow();
|
||||
next_fair_sender_low_refill = futureMillis(fairAdvertRefillMs());
|
||||
} else if (next_fair_group_refill && millisHasNowPassed(next_fair_group_refill)) {
|
||||
fairness_limiter.refillGroup();
|
||||
next_fair_group_refill = futureMillis(fairGroupRefillMs());
|
||||
}
|
||||
|
||||
if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
|
||||
mesh::Packet *pkt = createSelfAdvert();
|
||||
uint32_t delay_millis = 0;
|
||||
@@ -1437,8 +2082,11 @@ void MyMesh::loop() {
|
||||
updateFloodAdvertTimer(); // schedule next flood advert
|
||||
updateAdvertTimer(); // also schedule local advert (so they don't overlap)
|
||||
} else if (next_local_advert && millisHasNowPassed(next_local_advert)) {
|
||||
// Šířku předat i tady: tenhle periodický advert NEJDE přes
|
||||
// sendSelfAdvertisement(), takže by ji jinak minul — a je to přesně on, kdo
|
||||
// se každé `advert.interval` minuty hlásil na jeden bajt.
|
||||
mesh::Packet *pkt = createSelfAdvert();
|
||||
if (pkt) sendZeroHop(pkt);
|
||||
if (pkt) sendZeroHop(pkt, (uint32_t)0, _prefs.path_hash_mode + 1); // (uint32_t) viz výš
|
||||
|
||||
updateAdvertTimer(); // schedule next local advert
|
||||
}
|
||||
@@ -1446,12 +2094,18 @@ void MyMesh::loop() {
|
||||
if (set_radio_at && millisHasNowPassed(set_radio_at)) { // apply pending (temporary) radio params
|
||||
set_radio_at = 0; // clear timer
|
||||
radio_driver.setParams(pending_freq, pending_bw, pending_sf, pending_cr);
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
_prefs.getRadioPrefs()->applyRxPowerSaving(pending_sf, pending_bw); // timing is in symbols
|
||||
#endif
|
||||
MESH_DEBUG_PRINTLN("Temp radio params");
|
||||
}
|
||||
|
||||
if (revert_radio_at && millisHasNowPassed(revert_radio_at)) { // revert radio params to orig
|
||||
revert_radio_at = 0; // clear timer
|
||||
radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
_prefs.getRadioPrefs()->applyRxPowerSaving(_prefs.sf, _prefs.bw);
|
||||
#endif
|
||||
MESH_DEBUG_PRINTLN("Radio params restored");
|
||||
}
|
||||
|
||||
@@ -1510,10 +2164,22 @@ void MyMesh::loop() {
|
||||
last_millis = now;
|
||||
}
|
||||
|
||||
// CUSTOM (TeTeHacko): channel module method bodies. Included here, at the very
|
||||
// bottom, so they see the complete MyMesh definition (same convention the Solo
|
||||
// firmware uses for its own bot). Order matters: ChannelCommon.h defines the
|
||||
// helpers (chan_list_has, channelAddFromPsk) the other two use.
|
||||
#include "ChannelCommon.h"
|
||||
#include "ChannelFilter.h"
|
||||
#include "ChannelBot.h"
|
||||
|
||||
// To check if there is pending work
|
||||
bool MyMesh::hasPendingWork() const {
|
||||
#if defined(WITH_BRIDGE)
|
||||
if (bridge.isRunning()) return true; // bridge needs WiFi radio, can't sleep
|
||||
#endif
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
// no MCU sleep while the noise-floor window samples RSSI
|
||||
if (radio_driver.isRxPowerSavingCalibrationActive()) return true;
|
||||
#endif
|
||||
return _mgr->getOutboundTotal() > 0;
|
||||
}
|
||||
@@ -27,6 +27,7 @@
|
||||
#include <helpers/AdvertDataHelpers.h>
|
||||
#include <helpers/ArduinoHelpers.h>
|
||||
#include <helpers/ClientACL.h>
|
||||
#include <helpers/LoginGuard.h> // CUSTOM (TeTeHacko)
|
||||
#include <helpers/ReplyEchoGuard.h>
|
||||
#include <helpers/CommonCLI.h>
|
||||
#include <helpers/IdentityStore.h>
|
||||
@@ -34,6 +35,8 @@
|
||||
#include <helpers/StaticPoolPacketManager.h>
|
||||
#include <helpers/StatsFormatHelper.h>
|
||||
#include <helpers/TxtDataHelpers.h>
|
||||
#include <helpers/FairnessLimiter.h>
|
||||
#include <helpers/ChannelGate.h>
|
||||
#include <helpers/RegionMap.h>
|
||||
#include <helpers/RoutingPolicy.h>
|
||||
#include "RateLimiter.h"
|
||||
@@ -58,8 +61,31 @@ struct RepeaterStats {
|
||||
uint16_t n_direct_dups, n_flood_dups;
|
||||
uint32_t total_rx_air_time_secs;
|
||||
uint32_t n_recv_errors;
|
||||
// CUSTOM (TeTeHacko): appended at the END on purpose. Clients parse this
|
||||
// struct by fixed offsets, so fields added here are simply invisible to older
|
||||
// ones instead of shifting everything after them -- the same way upstream
|
||||
// grew its companion stats frame (docs/stats_binary_frames.md documents a
|
||||
// 26-byte "legacy" and a 30-byte frame that appends recv_errors).
|
||||
//
|
||||
// These two come from the Dispatcher requeue counters. Without them a
|
||||
// repeater that keeps failing to get its transmits out looks perfectly
|
||||
// healthy in every other field: sent/airtime just stop growing, and there is
|
||||
// nothing in the status that says why.
|
||||
uint32_t n_tx_start_fail, n_tx_timeout;
|
||||
};
|
||||
|
||||
// This struct goes on the air byte-for-byte, so its size is part of the
|
||||
// protocol: 56 bytes up to n_recv_errors (what upstream clients expect and
|
||||
// gate on -- meshcore-py's parse_status() reads recv_errors only
|
||||
// `if len(data) >= offset + 56`), plus the 8 appended here. Reordering a field
|
||||
// or letting the compiler insert padding would silently shift every offset
|
||||
// after it, so pin the number instead of trusting review.
|
||||
static_assert(sizeof(RepeaterStats) == 64,
|
||||
"RepeaterStats is a wire format: append only, keep it padding-free");
|
||||
|
||||
// MAX_CLIENTS zrusen tady mergem origin/dev (e0031870, "centralise max clients"):
|
||||
// od te doby ho definuje src/helpers/ClientACL.h, ktery se sem stejne dostane.
|
||||
|
||||
struct NeighbourInfo {
|
||||
mesh::Identity id;
|
||||
uint32_t advert_timestamp;
|
||||
@@ -67,6 +93,92 @@ struct NeighbourInfo {
|
||||
int8_t snr; // multiplied by 4, user should divide to get float value
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CUSTOM (TeTeHacko): passive "mesh analyzer" data. Two independent, RAM-only
|
||||
// tables (both compiled out unless the build sets a non-zero size), fed from
|
||||
// the normal RX path and pulled out over the text console (serial / BLE) for a
|
||||
// map/bridge to consume:
|
||||
// * heard_nodes[] -- one row per DISTINCT REPEATER / ROOM SERVER whose
|
||||
// (verified) advert we heard (chat clients are intentionally skipped for
|
||||
// privacy): pubkey prefix, name, type, position, last SNR/RSSI and the path
|
||||
// the advert arrived by. -> map dots + topology edges + link quality.
|
||||
// Exposed by the `nodes [offset]` CLI command.
|
||||
// * rxlog_ring[] -- a circular firehose of EVERY parsed frame we hear:
|
||||
// capture seq, time, packet hash, header (route|type), SNR/RSSI and the hop
|
||||
// path. -> live traffic / analyzer view.
|
||||
// Exposed by the `rxlog [cursor]` CLI command.
|
||||
// * pktfeed_ring[] -- like rxlog but with the FULL RAW FRAME BYTES, for the
|
||||
// community observer feed (meshcoretomqtt-compatible: the bridge derives
|
||||
// type/route/payload and the SHA256 packet hash from the raw bytes).
|
||||
// Smaller ring -- raw frames are fat (~268 B/record).
|
||||
// Exposed by the `pktlog [cursor]` CLI command.
|
||||
// Enable per-variant, e.g.: -D MAX_HEARD_NODES=48 -D RXLOG_SIZE=96 -D PKTFEED_SIZE=32
|
||||
// ---------------------------------------------------------------------------
|
||||
#ifndef MAX_HEARD_NODES
|
||||
#define MAX_HEARD_NODES 0
|
||||
#endif
|
||||
#ifndef RXLOG_SIZE
|
||||
#define RXLOG_SIZE 0
|
||||
#endif
|
||||
#ifndef PKTFEED_SIZE
|
||||
#define PKTFEED_SIZE 0
|
||||
#endif
|
||||
#ifndef HEARD_NODE_NAME_LEN
|
||||
#define HEARD_NODE_NAME_LEN 24
|
||||
#endif
|
||||
#ifndef HEARD_NODE_PREFIX
|
||||
#define HEARD_NODE_PREFIX 6 // bytes of pub_key kept (resolve path hashes + registry cross-ref)
|
||||
#endif
|
||||
#ifndef ANALYZER_PATH_LEN
|
||||
#define ANALYZER_PATH_LEN 16 // max hop-hash bytes kept per record
|
||||
#endif
|
||||
#ifndef HEARD_DIRECT_TTL_SECS
|
||||
#define HEARD_DIRECT_TTL_SECS 3600 // keep showing a node as direct (0-hop) this long after last hearing it direct
|
||||
#endif
|
||||
|
||||
#if MAX_HEARD_NODES
|
||||
struct HeardNode {
|
||||
uint8_t pub_prefix[HEARD_NODE_PREFIX];
|
||||
char name[HEARD_NODE_NAME_LEN];
|
||||
int32_t lat, lon; // degrees x 1e6, 0 = unknown
|
||||
uint32_t heard_timestamp; // epoch when last heard (0 = empty slot)
|
||||
uint32_t advert_timestamp; // advert's own timestamp (newest wins)
|
||||
uint32_t pkt_hash; // FNV of the latest advert (type||payload) -- JOIN KEY:
|
||||
// group rxlog records by this to get every path the
|
||||
// advert arrived by (rxlog logs all copies pre-dedup)
|
||||
uint32_t direct_heard; // epoch we last heard this node 0-hop (0 = never)
|
||||
int8_t snr; // x4
|
||||
int8_t rssi; // dBm
|
||||
uint8_t type; // ADV_TYPE_*
|
||||
uint8_t path_len; // bit-packed (hash size|count); representative/best path
|
||||
uint8_t path[ANALYZER_PATH_LEN];
|
||||
};
|
||||
#endif
|
||||
|
||||
#if RXLOG_SIZE
|
||||
struct RxLogRec {
|
||||
uint32_t seq; // monotonic capture sequence (0 = empty slot; also the paging cursor)
|
||||
uint32_t when; // epoch
|
||||
uint32_t pkt_hash; // FNV-1a of (type||payload) -- cheap dedup / cross-observer id (NOT the SHA packet-hash)
|
||||
int8_t snr; // x4
|
||||
int8_t rssi; // dBm
|
||||
uint8_t header; // raw header byte (route|type|ver)
|
||||
uint8_t path_len; // bit-packed (hash size|count)
|
||||
uint8_t path[ANALYZER_PATH_LEN];
|
||||
};
|
||||
#endif
|
||||
|
||||
#if PKTFEED_SIZE
|
||||
struct PktFeedRec {
|
||||
uint32_t seq; // monotonic capture sequence (0 = empty slot; also the paging cursor)
|
||||
uint32_t when; // epoch
|
||||
int8_t snr; // x4
|
||||
int8_t rssi; // dBm
|
||||
uint8_t len; // raw frame length in bytes
|
||||
uint8_t raw[MAX_TRANS_UNIT]; // full wire frame (header|[transport]|path_len|path|payload)
|
||||
};
|
||||
#endif
|
||||
|
||||
#ifndef FIRMWARE_BUILD_DATE
|
||||
#define FIRMWARE_BUILD_DATE "3 Dec 2026"
|
||||
#endif
|
||||
@@ -85,6 +197,7 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks {
|
||||
bool _logging;
|
||||
NodePrefs _prefs;
|
||||
ClientACL acl;
|
||||
LoginGuard login_guard; // CUSTOM (TeTeHacko)
|
||||
ReplyEchoGuard _reply_echo;
|
||||
CommonCLI _cli;
|
||||
uint8_t reply_data[MAX_PACKET_PAYLOAD];
|
||||
@@ -97,12 +210,72 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks {
|
||||
TransportKey default_scope;
|
||||
uint32_t last_read_time;
|
||||
RateLimiter discover_limiter, anon_limiter;
|
||||
// CUSTOM (TeTeHacko): token-bucket limiter over FORWARDED traffic (port of
|
||||
// upstream proposal #1502). Kill switch: _prefs.fairness_enabled.
|
||||
FairnessLimiter fairness_limiter;
|
||||
uint32_t filter_hash_dropped; // forwards vetoed by the channel-hash deny list
|
||||
uint32_t filter_hash_passed; // throttled entries: forwards let through within budget
|
||||
HashThrottle hash_throttle; // per-entry windows of `filter hash add <hex> <secs>`
|
||||
unsigned long next_fair_sender_normal_refill, next_fair_sender_low_refill, next_fair_group_refill;
|
||||
uint32_t pending_discover_tag;
|
||||
unsigned long pending_discover_until;
|
||||
bool region_load_active;
|
||||
unsigned long dirty_contacts_expiry;
|
||||
#if MAX_NEIGHBOURS
|
||||
NeighbourInfo neighbours[MAX_NEIGHBOURS];
|
||||
#endif
|
||||
#if MAX_HEARD_NODES
|
||||
HeardNode heard_nodes[MAX_HEARD_NODES];
|
||||
#endif
|
||||
#if RXLOG_SIZE
|
||||
RxLogRec rxlog_ring[RXLOG_SIZE];
|
||||
uint16_t rxlog_head; // next slot to write
|
||||
uint32_t rxlog_next_seq; // next capture sequence to assign (starts at 1)
|
||||
#endif
|
||||
#if PKTFEED_SIZE
|
||||
PktFeedRec pktfeed_ring[PKTFEED_SIZE];
|
||||
uint16_t pktfeed_head; // next slot to write
|
||||
uint32_t pktfeed_next_seq; // next capture sequence to assign (starts at 1)
|
||||
// raw bytes staged in logRxRaw (pre-parse, the only place they exist) and
|
||||
// committed to the ring in logRx (fires only for frames that parsed OK, so
|
||||
// radio garbage never enters the feed)
|
||||
uint8_t pktfeed_stage[MAX_TRANS_UNIT];
|
||||
uint8_t pktfeed_stage_len; // 0 = nothing staged
|
||||
#endif
|
||||
#if defined(BOT_CHANNEL_PSK) || defined(FILTER_CHANNEL_PSKS)
|
||||
// CUSTOM (TeTeHacko): registry of channels this node can DECRYPT (the bot
|
||||
// channel and/or the filter channels). Shared by ChannelBot.h and
|
||||
// ChannelFilter.h; fed to searchChannelsByHash(), whose API caps matches at 4.
|
||||
#define MAX_KNOWN_CHANNELS 4
|
||||
#define CHAN_FLAG_BOT 0x01 // ChannelBot answers on this channel
|
||||
#define CHAN_FLAG_FILTER 0x02 // deny list applies to this channel
|
||||
mesh::GroupChannel known_channels[MAX_KNOWN_CHANNELS];
|
||||
uint8_t known_channel_flags[MAX_KNOWN_CHANNELS];
|
||||
uint8_t num_known_channels;
|
||||
#endif
|
||||
#ifdef FILTER_CHANNEL_PSKS
|
||||
uint32_t filter_dropped; // forwards vetoed by the deny list
|
||||
uint32_t filter_age_dropped; // forwards vetoed by `filter age`
|
||||
#endif
|
||||
#ifdef BOT_CHANNEL_PSK
|
||||
// Default zde, ne az v ChannelBot.h -- ten se includuje na konci MyMesh.cpp,
|
||||
// tedy dlouho po teto deklaraci pole.
|
||||
#ifndef BOT_PEER_SLOTS
|
||||
#define BOT_PEER_SLOTS 8
|
||||
#endif
|
||||
#ifndef BOT_BURST_MAX
|
||||
#define BOT_BURST_MAX 10
|
||||
#endif
|
||||
int8_t bot_channel_idx; // index into known_channels, -1 = PSK malformed, bot silently off
|
||||
unsigned long bot_next_reply_at; // cooldown gate, 0 = not armed
|
||||
uint32_t bot_replies_sent;
|
||||
uint32_t bot_ignored; // zprav zahozenych podle BOT_IGNORE_SENDERS
|
||||
uint32_t bot_throttled; // odpovedi potlacenych cooldownem
|
||||
struct BotPeer { uint32_t name_hash; unsigned long next_at; };
|
||||
BotPeer bot_peers[BOT_PEER_SLOTS]; // per-odesilatel okno, LRU
|
||||
uint32_t bot_last_reply_secs; // RTC time of the last reply, 0 = never
|
||||
unsigned long bot_burst_until[BOT_BURST_MAX > 0 ? BOT_BURST_MAX : 1]; // konce oken poslednich odpovedi, kruh
|
||||
uint8_t bot_burst_head; // nejstarsi z poslednich BOT_BURST_MAX odpovedi
|
||||
#endif
|
||||
CayenneLPP telemetry;
|
||||
unsigned long set_radio_at, revert_radio_at;
|
||||
@@ -118,6 +291,64 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks {
|
||||
#endif
|
||||
|
||||
void putNeighbour(const mesh::Identity& id, uint32_t timestamp, float snr);
|
||||
#if MAX_HEARD_NODES
|
||||
void putHeardNode(const mesh::Identity& id, uint32_t advert_timestamp, uint8_t type,
|
||||
int32_t lat, int32_t lon, const char* name,
|
||||
int8_t snr, int8_t rssi, const mesh::Packet* pkt);
|
||||
void formatNodesReply(char* reply, int max_len, uint16_t offset);
|
||||
#endif
|
||||
#if RXLOG_SIZE
|
||||
void captureRx(const mesh::Packet* pkt);
|
||||
void formatRxLogReply(char* reply, int max_len, uint32_t cursor);
|
||||
#endif
|
||||
#if PKTFEED_SIZE
|
||||
void stagePktFeed(const uint8_t raw[], int len);
|
||||
void commitPktFeed(const mesh::Packet* pkt);
|
||||
void formatPktFeedReply(char* reply, int max_len, uint32_t cursor);
|
||||
#endif
|
||||
#if defined(BOT_CHANNEL_PSK) || defined(FILTER_CHANNEL_PSKS)
|
||||
// CUSTOM (TeTeHacko): shared channel plumbing. Definitions in ChannelCommon.h,
|
||||
// included at the bottom of MyMesh.cpp.
|
||||
void channelsInit();
|
||||
int channelAddFromPsk(const char* psk_hex, int psk_len, uint8_t flag);
|
||||
void onChannelText(mesh::Packet* packet, int chan_idx, const char* sender, const char* msg);
|
||||
#endif
|
||||
#ifdef FILTER_CHANNEL_PSKS
|
||||
// CUSTOM (TeTeHacko): deny-list forwarding filter. Definitions in ChannelFilter.h.
|
||||
bool filterDenied(const char* sender) const;
|
||||
bool filterHandleCommand(const char* command, char* reply, int reply_max);
|
||||
#endif
|
||||
#ifdef BOT_CHANNEL_PSK
|
||||
// CUSTOM (TeTeHacko): channel bot. Definitions in ChannelBot.h, included at
|
||||
// the bottom of MyMesh.cpp. See that file for why this lives in the analyzer
|
||||
// build rather than in companion_radio.
|
||||
void botInit();
|
||||
void botOnChannelText(mesh::Packet* packet, const char* sender, const char* msg);
|
||||
bool botTriggerMatches(const char* text) const;
|
||||
void botFormatPath(char* out, const mesh::Packet* pkt) const;
|
||||
int botCommandReply(char* out, int max_len, const char* cmd, const mesh::Packet* pkt);
|
||||
int botScanCommands(char* out, int max_len, const char* text, const mesh::Packet* pkt);
|
||||
void botSendReply(const mesh::Packet* pkt, const char* text);
|
||||
bool botPeerAllowed(const char* name);
|
||||
bool botHandleCommand(const char* command, char* reply);
|
||||
#endif
|
||||
// CUSTOM (TeTeHacko): `fairness [on|off|grid|cap ...|refill ...]` CLI. Defined in MyMesh.cpp.
|
||||
bool fairnessHandleCommand(const char* command, char* reply, int reply_max);
|
||||
// CUSTOM (TeTeHacko): keyless deny-forward by channel hash. Definitions in ChannelFilter.h.
|
||||
bool filterHashDenied(const mesh::Packet* packet);
|
||||
bool filterHashHandleCommand(const char* command, char* reply, int reply_max);
|
||||
// `filter dryrun [on|off]` and `filter age [<min>|off]`. Definitions in ChannelFilter.h.
|
||||
bool filterMiscHandleCommand(const char* command, char* reply, int reply_max);
|
||||
// Refill interval in ms: persisted pref (seconds) if set, else the build default.
|
||||
uint32_t fairGroupRefillMs() const {
|
||||
return _prefs.fair_group_refill_s ? (uint32_t)_prefs.fair_group_refill_s * 1000 : FAIRNESS_GROUP_REFILL_MS;
|
||||
}
|
||||
uint32_t fairSenderRefillMs() const {
|
||||
return _prefs.fair_sender_refill_s ? (uint32_t)_prefs.fair_sender_refill_s * 1000 : FAIRNESS_SENDER_NORMAL_REFILL_MS;
|
||||
}
|
||||
uint32_t fairAdvertRefillMs() const {
|
||||
return _prefs.fair_advert_refill_s ? (uint32_t)_prefs.fair_advert_refill_s * 1000 : FAIRNESS_SENDER_LOW_REFILL_MS;
|
||||
}
|
||||
uint8_t handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data, bool is_flood);
|
||||
uint8_t handleAnonRegionsReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data);
|
||||
uint8_t handleAnonOwnerReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data);
|
||||
@@ -136,6 +367,33 @@ protected:
|
||||
}
|
||||
|
||||
bool allowPacketForward(const mesh::Packet* packet) override;
|
||||
|
||||
// Šířku path hashe volí ODESÍLATEL, takže musí přijít z prefs tohohle uzlu.
|
||||
// Díky tomuhle overridu ji dostanou i volání send*(), která ji nepředávají
|
||||
// explicitně (ACKy, PATH-return, zerohop odpovědi sousedovi).
|
||||
uint8_t getSelfPathHashSize() const override { return _prefs.path_hash_mode + 1; }
|
||||
#if defined(BOT_CHANNEL_PSK) || defined(FILTER_CHANNEL_PSKS)
|
||||
// CUSTOM (TeTeHacko): both are no-op virtuals in mesh::Mesh, which is the only
|
||||
// reason a repeater is normally deaf to channel traffic. Overriding them does
|
||||
// NOT affect forwarding by itself -- Mesh::onRecvPacket() calls routeRecvPacket()
|
||||
// either way (Mesh.cpp:237-259). The ChannelFilter DOES veto forwarding of
|
||||
// matched packets, via packet->markDoNotRetransmit() (same mechanism the ANON
|
||||
// branch uses at Mesh.cpp:229).
|
||||
int searchChannelsByHash(const uint8_t* hash, mesh::GroupChannel channels[], int max_matches) override;
|
||||
void onGroupDataRecv(mesh::Packet* packet, uint8_t type, const mesh::GroupChannel& channel,
|
||||
uint8_t* data, size_t len) override;
|
||||
#endif
|
||||
// CUSTOM (TeTeHacko): FairnessLimiter veto. mesh::Mesh consults this as the
|
||||
// LAST condition of every forward decision, so a token is only taken for a
|
||||
// packet that would otherwise transmit. Buckets have a runtime kill switch
|
||||
// (`fairness on|off`), the advert window its own (`fairness advert 0`).
|
||||
// What gets shed is also summed as airtime -- in dry-run, what WOULD be.
|
||||
bool takeForwardingRateLimit(const mesh::Packet* packet) override {
|
||||
bool ok = fairness_limiter.allowPacket(packet, _ms->getMillis());
|
||||
FairShed why = fairness_limiter.lastShed();
|
||||
if (why != FAIR_SHED_NONE) fairness_limiter.addShedAirtime(why, _radio->getEstAirtimeFor(packet->getRawLength()));
|
||||
return ok;
|
||||
}
|
||||
const char* getLogDateTime() override;
|
||||
void logRxRaw(float snr, float rssi, const uint8_t raw[], int len) override;
|
||||
|
||||
@@ -170,6 +428,9 @@ protected:
|
||||
sensors.setSettingValue("gps_interval", interval);
|
||||
}
|
||||
_prefs.getGpsPrefs()->apply(sensors);
|
||||
// 2 = duty cycle -- apply() only knows on/off, and a duty-cycled node must
|
||||
// not come back from a reboot with GPS powered forever
|
||||
if (_prefs.gps_enabled == 2) sensors.setSettingValue("gps", "2");
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -236,7 +497,11 @@ public:
|
||||
void saveIdentity(const mesh::LocalIdentity& new_id) override;
|
||||
void clearStats() override;
|
||||
|
||||
void handleCommand(uint32_t sender_timestamp, char* command, char* reply);
|
||||
// reply_max = usable reply capacity. Default 150 keeps the mesh admin CLI reply
|
||||
// inside one LoRa packet; the local console (USB/BLE, big buffer) passes more so
|
||||
// the paged analyzer replies (nodes/rxlog) can use big pages. Explicit parameter
|
||||
// on purpose — a forged sender_timestamp must never be able to grow the reply.
|
||||
void handleCommand(uint32_t sender_timestamp, char* command, char* reply, int reply_max = 150);
|
||||
void loop();
|
||||
|
||||
#if defined(WITH_BRIDGE)
|
||||
@@ -261,6 +526,9 @@ public:
|
||||
|
||||
// To check if there is pending work
|
||||
bool hasPendingWork() const;
|
||||
// CUSTOM (TeTeHacko): for the TX stall watchdog (helpers/NodeMaintenance.h).
|
||||
int txQueued() const { return _mgr->getOutboundTotal(); }
|
||||
int txDue() const { return _mgr->getOutboundCount(_ms->getMillis()); }
|
||||
|
||||
bool setRxBoostedGain(bool enable) override;
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -156,6 +156,17 @@ int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t
|
||||
// memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
|
||||
memcpy(reply_data, &sender_timestamp, 4); // reflect sender_timestamp back in response packet (kind of like a 'tag')
|
||||
|
||||
// CUSTOM (TeTeHacko): firmware chunks for FwUpdate (REQ_TYPE_FW_OTA = 0xF0, admin
|
||||
// only, helpers/FwUpdate.h). 0 = no reply: chunks are fire and forget.
|
||||
if (payload_len >= 1 && payload[0] == 0xF0) {
|
||||
extern int maintHandleRequest(bool admin, const uint8_t* req, int len, uint8_t* reply, int reply_max);
|
||||
// 150: tag + reply pads to 160 B, and the companion's push frame (6 + padded
|
||||
// length - 4) must stay within MAX_FRAME_SIZE 176 -- a 163 B reply padded to
|
||||
// 176 made a 178 B frame that the companion silently dropped
|
||||
int n = maintHandleRequest(sender->isAdmin(), payload, (int)payload_len, &reply_data[4], 150);
|
||||
return n > 0 ? 4 + n : 0;
|
||||
}
|
||||
|
||||
if (payload[0] == REQ_TYPE_GET_STATUS) {
|
||||
ServerStats stats;
|
||||
stats.batt_milli_volts = board.getBattMilliVolts();
|
||||
@@ -340,10 +351,19 @@ void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const m
|
||||
#if MESH_DEBUG
|
||||
MESH_DEBUG_PRINTLN("Login, sender not in ACL");
|
||||
#endif
|
||||
} else {
|
||||
// CUSTOM (TeTeHacko): a blank login has a replay floor too -- replayed, it
|
||||
// gained nothing, but each copy made us flood a reply over the mesh.
|
||||
if (sender_timestamp <= client->last_timestamp) return;
|
||||
acl.persistTimestamp(client, sender_timestamp, getRTCClock()->getCurrentTime());
|
||||
client->last_timestamp = sender_timestamp;
|
||||
}
|
||||
}
|
||||
if (client == NULL) {
|
||||
uint8_t perm;
|
||||
// CUSTOM (TeTeHacko): capped wrong passwords (LoginGuard.h); a known admin is never locked out
|
||||
ClientInfo* known = acl.getClient(sender.pub_key, PUB_KEY_SIZE);
|
||||
if (login_guard.locked(millis()) && !(known && known->isAdmin())) return;
|
||||
if (strcmp((char *)&data[8], _prefs.password) == 0) { // check for valid admin password
|
||||
perm = PERM_ACL_ADMIN;
|
||||
} else {
|
||||
@@ -353,6 +373,7 @@ void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const m
|
||||
perm = PERM_ACL_GUEST;
|
||||
} else {
|
||||
MESH_DEBUG_PRINTLN("Incorrect room password");
|
||||
login_guard.failed(millis()); // CUSTOM (TeTeHacko)
|
||||
return; // no response. Client will timeout
|
||||
}
|
||||
}
|
||||
@@ -364,7 +385,6 @@ void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const m
|
||||
MESH_DEBUG_PRINTLN("possible replay attack!");
|
||||
return;
|
||||
}
|
||||
|
||||
MESH_DEBUG_PRINTLN("Login success!");
|
||||
client->last_timestamp = sender_timestamp;
|
||||
client->extra.room.sync_since = sender_sync_since;
|
||||
@@ -373,6 +393,7 @@ void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const m
|
||||
|
||||
client->permissions &= ~0x03;
|
||||
client->permissions |= perm;
|
||||
acl.persistTimestamp(client, sender_timestamp, getRTCClock()->getCurrentTime()); // CUSTOM (TeTeHacko): admin only, so after the role
|
||||
memcpy(client->shared_secret, secret, PUB_KEY_SIZE);
|
||||
|
||||
dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY);
|
||||
@@ -456,6 +477,7 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx,
|
||||
MESH_DEBUG_PRINTLN("onPeerDataRecv: text is our own CLI reply");
|
||||
} else if (sender_timestamp >= client->last_timestamp) { // prevent replay attacks, but send Acks for retries
|
||||
bool is_retry = (sender_timestamp == client->last_timestamp);
|
||||
acl.persistTimestamp(client, sender_timestamp, getRTCClock()->getCurrentTime()); // CUSTOM (TeTeHacko): before acting
|
||||
client->last_timestamp = sender_timestamp;
|
||||
|
||||
uint32_t now = getRTCClock()->getCurrentTimeUnique();
|
||||
@@ -552,6 +574,7 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx,
|
||||
if (sender_timestamp < client->last_req_timestamp) { // prevent replay attacks
|
||||
MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
|
||||
} else {
|
||||
acl.persistTimestamp(client, sender_timestamp, getRTCClock()->getCurrentTime()); // CUSTOM (TeTeHacko): before acting
|
||||
client->last_req_timestamp = sender_timestamp;
|
||||
|
||||
uint32_t now = getRTCClock()->getCurrentTime();
|
||||
@@ -656,6 +679,9 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc
|
||||
|
||||
// defaults
|
||||
_prefs.airtime_factor = 1.0;
|
||||
#ifdef AIRTIME_FACTOR_DEFAULT // CUSTOM (TeTeHacko): e.g. 9 = 10 % duty cycle (meshcore.cz)
|
||||
_prefs.airtime_factor = AIRTIME_FACTOR_DEFAULT;
|
||||
#endif
|
||||
_prefs.rx_delay_base = 0.0f; // off by default, was 10.0
|
||||
_prefs.tx_delay_factor = 0.5f; // was 0.25f;
|
||||
_prefs.direct_tx_delay_factor = 0.2f; // was zero
|
||||
@@ -671,6 +697,12 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc
|
||||
_prefs.disable_fwd = 1;
|
||||
_prefs.advert_interval = 1; // default to 2 minutes for NEW installs
|
||||
_prefs.flood_advert_interval = 47; // 47 hours
|
||||
#ifdef ADVERT_INTERVAL_DEFAULT // CUSTOM (TeTeHacko): same knobs as simple_repeater
|
||||
_prefs.advert_interval = ADVERT_INTERVAL_DEFAULT;
|
||||
#endif
|
||||
#ifdef FLOOD_ADVERT_INTERVAL_DEFAULT
|
||||
_prefs.flood_advert_interval = FLOOD_ADVERT_INTERVAL_DEFAULT;
|
||||
#endif
|
||||
_prefs.flood_max = 64;
|
||||
_prefs.flood_max_unscoped = 64;
|
||||
_prefs.flood_max_advert = 8;
|
||||
@@ -735,6 +767,9 @@ void MyMesh::begin(FILESYSTEM *fs) {
|
||||
|
||||
radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
|
||||
radio_driver.setTxPower(_prefs.tx_power_dbm);
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
_prefs.getRadioPrefs()->applyRxPowerSaving(_prefs.sf, _prefs.bw); // CUSTOM (TeTeHacko)
|
||||
#endif
|
||||
radio_driver.setRxBoostedGainMode(_prefs.rx_boosted_gain);
|
||||
|
||||
board.attachDynamicPrefs(_prefs.getCustom());
|
||||
@@ -747,6 +782,7 @@ void MyMesh::begin(FILESYSTEM *fs) {
|
||||
#if ENV_INCLUDE_GPS == 1
|
||||
applyGpsPrefs();
|
||||
#endif
|
||||
sensors.applyInaShunt(_prefs.ina_shunt_mohm); // CUSTOM (TeTeHacko)
|
||||
}
|
||||
|
||||
void MyMesh::sendFloodScoped(const TransportKey& scope, mesh::Packet* pkt, uint32_t delay_millis, uint8_t path_hash_size) {
|
||||
@@ -951,6 +987,10 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply
|
||||
command += 3;
|
||||
}
|
||||
|
||||
// CUSTOM (TeTeHacko): dfu (local only), radio silence watchdog, `get boot`.
|
||||
extern bool maintHandleCommand(uint32_t sender_timestamp, const char* command, char* reply);
|
||||
if (maintHandleCommand(sender_timestamp, command, reply)) return;
|
||||
|
||||
// handle ACL related commands
|
||||
if (memcmp(command, "setperm ", 8) == 0) { // format: setperm {pubkey-hex} {permissions-int8}
|
||||
char* hex = &command[8];
|
||||
@@ -1068,12 +1108,18 @@ void MyMesh::loop() {
|
||||
if (set_radio_at && millisHasNowPassed(set_radio_at)) { // apply pending (temporary) radio params
|
||||
set_radio_at = 0; // clear timer
|
||||
radio_driver.setParams(pending_freq, pending_bw, pending_sf, pending_cr);
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
_prefs.getRadioPrefs()->applyRxPowerSaving(pending_sf, pending_bw);
|
||||
#endif
|
||||
MESH_DEBUG_PRINTLN("Temp radio params");
|
||||
}
|
||||
|
||||
if (revert_radio_at && millisHasNowPassed(revert_radio_at)) { // revert radio params to orig
|
||||
revert_radio_at = 0; // clear timer
|
||||
radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
_prefs.getRadioPrefs()->applyRxPowerSaving(_prefs.sf, _prefs.bw);
|
||||
#endif
|
||||
MESH_DEBUG_PRINTLN("Radio params restored");
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
#include <helpers/CommonCLI.h>
|
||||
#include <helpers/StatsFormatHelper.h>
|
||||
#include <helpers/ClientACL.h>
|
||||
#include <helpers/LoginGuard.h> // CUSTOM (TeTeHacko)
|
||||
#include <helpers/ReplyEchoGuard.h>
|
||||
#include <helpers/RegionMap.h>
|
||||
#include <helpers/RoutingPolicy.h>
|
||||
@@ -99,6 +100,7 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks {
|
||||
TransportKeyStore key_store;
|
||||
RegionMap region_map, temp_map;
|
||||
ClientACL acl;
|
||||
LoginGuard login_guard; // CUSTOM (TeTeHacko)
|
||||
ReplyEchoGuard _reply_echo;
|
||||
CommonCLI _cli;
|
||||
unsigned long dirty_contacts_expiry;
|
||||
@@ -159,6 +161,11 @@ protected:
|
||||
mesh::DispatcherAction onRecvPacket(mesh::Packet* pkt) override;
|
||||
|
||||
bool allowPacketForward(const mesh::Packet* packet) override;
|
||||
|
||||
// Šířku path hashe volí ODESÍLATEL, takže musí přijít z prefs tohohle uzlu.
|
||||
// Díky tomuhle overridu ji dostanou i volání send*(), která ji nepředávají
|
||||
// explicitně (ACKy, PATH-return, zerohop odpovědi sousedovi).
|
||||
uint8_t getSelfPathHashSize() const override { return _prefs.path_hash_mode + 1; }
|
||||
void onAnonDataRecv(mesh::Packet* packet, const uint8_t* secret, const mesh::Identity& sender, uint8_t* data, size_t len) override;
|
||||
int searchPeersByHash(const uint8_t* hash) override ;
|
||||
void getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) override;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#include <Mesh.h>
|
||||
|
||||
#include "MyMesh.h"
|
||||
#include <helpers/NodeMaintenance.h>
|
||||
|
||||
#ifdef ETHERNET_ENABLED
|
||||
#define ETHERNET_CLI_BANNER "MeshCore Room Server CLI"
|
||||
@@ -12,6 +13,17 @@ StdRNG fast_rng;
|
||||
SimpleMeshTables tables;
|
||||
MyMesh the_mesh(board, radio_driver, *new ArduinoMillis(), fast_rng, rtc_clock, tables);
|
||||
|
||||
// CUSTOM (TeTeHacko): dfu, radio silence watchdog, `get boot` -- see NodeMaintenance.h.
|
||||
static NodeMaintenance maint(board, radio_driver);
|
||||
bool maintHandleCommand(uint32_t sender_timestamp, const char* command, char* reply) {
|
||||
return maint.handleCommand(sender_timestamp, command, reply);
|
||||
}
|
||||
|
||||
// CUSTOM (TeTeHacko): binary firmware chunks (REQ_TYPE_FW_OTA), see helpers/FwUpdate.h.
|
||||
int maintHandleRequest(bool admin, const uint8_t* req, int len, uint8_t* reply, int reply_max) {
|
||||
return maint.handleRequest(admin, req, len, reply, reply_max);
|
||||
}
|
||||
|
||||
void halt() {
|
||||
while (1) ;
|
||||
}
|
||||
@@ -26,6 +38,7 @@ void setup() {
|
||||
delay(1000);
|
||||
|
||||
board.begin();
|
||||
maint.printBootDiag();
|
||||
|
||||
#ifdef HAS_EXTERNAL_WATCHDOG
|
||||
external_watchdog.begin();
|
||||
@@ -81,6 +94,7 @@ void setup() {
|
||||
sensors.begin();
|
||||
|
||||
the_mesh.begin(fs);
|
||||
maint.begin(fs, the_mesh.getNodePrefs(), &the_mesh);
|
||||
|
||||
#ifdef DISPLAY_CLASS
|
||||
ui_task.begin(the_mesh.getNodePrefs(), FIRMWARE_BUILD_DATE, FIRMWARE_VERSION, "< Room Server >");
|
||||
@@ -152,6 +166,7 @@ void loop() {
|
||||
#endif
|
||||
|
||||
the_mesh.loop();
|
||||
maint.loop();
|
||||
sensors.loop();
|
||||
#ifdef DISPLAY_CLASS
|
||||
ui_task.loop();
|
||||
|
||||
@@ -103,6 +103,10 @@ class MyMesh : public BaseChatMesh, ContactVisitor {
|
||||
uint8_t unused;
|
||||
uint32_t reserved;
|
||||
|
||||
// No shared_secret/shared_secret_valid in the on-disk record; without
|
||||
// this the flag is indeterminate for every contact loaded at boot.
|
||||
memset(&c, 0, sizeof(c));
|
||||
|
||||
bool success = (file.read(pub_key, 32) == 32);
|
||||
success = success && (file.read((uint8_t *) &c.name, 32) == 32);
|
||||
success = success && (file.read(&c.type, 1) == 1);
|
||||
|
||||
@@ -442,7 +442,15 @@ uint8_t SensorMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t*
|
||||
#endif
|
||||
return 0;
|
||||
}
|
||||
// CUSTOM (TeTeHacko): a blank login has a replay floor too -- replayed, it
|
||||
// gained nothing, but each copy made us send a reply.
|
||||
if (sender_timestamp <= client->last_timestamp) return 0;
|
||||
acl.persistTimestamp(client, sender_timestamp, getRTCClock()->getCurrentTime());
|
||||
client->last_timestamp = sender_timestamp;
|
||||
} else {
|
||||
// CUSTOM (TeTeHacko): capped wrong passwords (LoginGuard.h); a known admin is never locked out
|
||||
ClientInfo* known = acl.getClient(sender.pub_key, PUB_KEY_SIZE);
|
||||
if (login_guard.locked(millis()) && !(known && known->isAdmin())) return 0;
|
||||
uint8_t perms;
|
||||
if (strcmp((char *) data, _prefs.password) == 0) { // check for valid admin password
|
||||
perms = PERM_ACL_ADMIN;
|
||||
@@ -454,6 +462,7 @@ uint8_t SensorMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t*
|
||||
#if MESH_DEBUG
|
||||
MESH_DEBUG_PRINTLN("Invalid password: %s", &data[0]);
|
||||
#endif
|
||||
login_guard.failed(millis()); // CUSTOM (TeTeHacko)
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -464,7 +473,6 @@ uint8_t SensorMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t*
|
||||
MESH_DEBUG_PRINTLN("Possible login replay attack!");
|
||||
return 0; // FATAL: client table is full -OR- replay attack
|
||||
}
|
||||
|
||||
MESH_DEBUG_PRINTLN("Login success!");
|
||||
client->last_timestamp = sender_timestamp;
|
||||
bool saved = client->permissions != 0 && !client->shared_login;
|
||||
@@ -477,6 +485,7 @@ uint8_t SensorMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t*
|
||||
client->permissions = perms;
|
||||
client->shared_login = true;
|
||||
}
|
||||
acl.persistTimestamp(client, sender_timestamp, getRTCClock()->getCurrentTime()); // CUSTOM (TeTeHacko): admin only, so after the role
|
||||
memcpy(client->shared_secret, secret, PUB_KEY_SIZE);
|
||||
}
|
||||
client->last_activity = getRTCClock()->getCurrentTime();
|
||||
@@ -604,6 +613,10 @@ void SensorMesh::handleCommand(ClientInfo* from, uint32_t sender_timestamp, char
|
||||
board.setGpio(val);
|
||||
}
|
||||
sprintf(reply, "%x", board.getGpio());
|
||||
#ifdef RADIO_DIAG
|
||||
// CUSTOM (TeTeHacko): `radiostat` / `radiokick` -- see RadioLibWrappers.cpp.
|
||||
} else if (radio_driver.diagHandleCommand(command, reply)) {
|
||||
#endif
|
||||
} else{
|
||||
_cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
|
||||
}
|
||||
@@ -704,6 +717,7 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i
|
||||
memcpy(×tamp, data, 4);
|
||||
|
||||
if (timestamp > from->last_timestamp) { // prevent replay attacks
|
||||
acl.persistTimestamp(from, timestamp, getRTCClock()->getCurrentTime()); // CUSTOM (TeTeHacko): before acting
|
||||
uint8_t reply_len = handleRequest(from, timestamp, data[4], &data[5], len - 5);
|
||||
if (reply_len == 0) return; // invalid command
|
||||
|
||||
@@ -739,6 +753,7 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i
|
||||
} else if (_reply_echo.matches(data, 5 + strnlen((const char *)&data[5], len - 5))) {
|
||||
MESH_DEBUG_PRINTLN("onPeerDataRecv: text is our own CLI reply");
|
||||
} else if (sender_timestamp > from->last_timestamp) { // prevent replay attacks
|
||||
acl.persistTimestamp(from, sender_timestamp, getRTCClock()->getCurrentTime()); // CUSTOM (TeTeHacko): before acting
|
||||
if (flags == TXT_TYPE_PLAIN) {
|
||||
bool handled = handleIncomingMsg(*from, sender_timestamp, &data[5], flags, len - 5);
|
||||
if (handled) { // if msg was handled then send an ack
|
||||
@@ -953,6 +968,9 @@ void SensorMesh::begin(FILESYSTEM* fs) {
|
||||
|
||||
radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
|
||||
radio_driver.setTxPower(_prefs.tx_power_dbm);
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
_prefs.getRadioPrefs()->applyRxPowerSaving(_prefs.sf, _prefs.bw); // CUSTOM (TeTeHacko)
|
||||
#endif
|
||||
|
||||
board.attachDynamicPrefs(_prefs.getCustom());
|
||||
|
||||
@@ -964,6 +982,7 @@ void SensorMesh::begin(FILESYSTEM* fs) {
|
||||
#if ENV_INCLUDE_GPS == 1
|
||||
applyGpsPrefs();
|
||||
#endif
|
||||
sensors.applyInaShunt(_prefs.ina_shunt_mohm); // CUSTOM (TeTeHacko)
|
||||
}
|
||||
|
||||
bool SensorMesh::formatFileSystem() {
|
||||
@@ -1114,12 +1133,18 @@ void SensorMesh::loop() {
|
||||
if (set_radio_at && millisHasNowPassed(set_radio_at)) { // apply pending (temporary) radio params
|
||||
set_radio_at = 0; // clear timer
|
||||
radio_driver.setParams(pending_freq, pending_bw, pending_sf, pending_cr);
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
_prefs.getRadioPrefs()->applyRxPowerSaving(pending_sf, pending_bw);
|
||||
#endif
|
||||
MESH_DEBUG_PRINTLN("Temp radio params");
|
||||
}
|
||||
|
||||
if (revert_radio_at && millisHasNowPassed(revert_radio_at)) { // revert radio params to orig
|
||||
revert_radio_at = 0; // clear timer
|
||||
radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
_prefs.getRadioPrefs()->applyRxPowerSaving(_prefs.sf, _prefs.bw);
|
||||
#endif
|
||||
MESH_DEBUG_PRINTLN("Radio params restored");
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
#include <helpers/CommonCLI.h>
|
||||
#include <helpers/StatsFormatHelper.h>
|
||||
#include <helpers/ClientACL.h>
|
||||
#include <helpers/LoginGuard.h> // CUSTOM (TeTeHacko)
|
||||
#include <helpers/ReplyEchoGuard.h>
|
||||
#include <helpers/RegionMap.h>
|
||||
#include <RTClib.h>
|
||||
@@ -121,6 +122,11 @@ protected:
|
||||
// Mesh overrides
|
||||
float getAirtimeBudgetFactor() const override;
|
||||
bool allowPacketForward(const mesh::Packet* packet) override;
|
||||
|
||||
// Šířku path hashe volí ODESÍLATEL, takže musí přijít z prefs tohohle uzlu.
|
||||
// Díky tomuhle overridu ji dostanou i volání send*(), která ji nepředávají
|
||||
// explicitně (ACKy, PATH-return, zerohop odpovědi sousedovi).
|
||||
uint8_t getSelfPathHashSize() const override { return _prefs.path_hash_mode + 1; }
|
||||
int calcRxDelay(float score, uint32_t air_time) const override;
|
||||
uint32_t getRetransmitDelay(const mesh::Packet* packet) override;
|
||||
uint32_t getDirectRetransmitDelay(const mesh::Packet* packet) override;
|
||||
@@ -143,6 +149,7 @@ private:
|
||||
unsigned long next_local_advert, next_flood_advert;
|
||||
NodePrefs _prefs;
|
||||
ClientACL acl;
|
||||
LoginGuard login_guard; // CUSTOM (TeTeHacko)
|
||||
ReplyEchoGuard _reply_echo;
|
||||
CommonCLI _cli;
|
||||
uint8_t reply_data[MAX_PACKET_PAYLOAD];
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
#include "SensorMesh.h"
|
||||
#include <helpers/NodeMaintenance.h>
|
||||
|
||||
// CUSTOM (TeTeHacko): dfu, radio silence watchdog, reset reason -- see NodeMaintenance.h.
|
||||
static NodeMaintenance maint(board, radio_driver);
|
||||
|
||||
class MyMesh : public SensorMesh {
|
||||
public:
|
||||
@@ -27,6 +31,7 @@ protected:
|
||||
}
|
||||
|
||||
bool handleCustomCommand(uint32_t sender_timestamp, char* command, char* reply) override {
|
||||
if (maint.handleCommand(sender_timestamp, command, reply)) return true;
|
||||
if (strcmp(command, "magic") == 0) { // example 'custom' command handling
|
||||
strcpy(reply, "**Magic now done**");
|
||||
return true; // handled
|
||||
@@ -52,6 +57,7 @@ void setup() {
|
||||
delay(1000);
|
||||
|
||||
board.begin();
|
||||
maint.printBootDiag();
|
||||
|
||||
#ifdef HAS_EXTERNAL_WATCHDOG
|
||||
external_watchdog.begin();
|
||||
@@ -104,6 +110,7 @@ void setup() {
|
||||
sensors.begin();
|
||||
|
||||
the_mesh.begin(fs);
|
||||
maint.begin(fs, the_mesh.getNodePrefs(), &the_mesh);
|
||||
|
||||
#ifdef DISPLAY_CLASS
|
||||
ui_task.begin(the_mesh.getNodePrefs(), FIRMWARE_BUILD_DATE, FIRMWARE_VERSION, "< Sensor >");
|
||||
@@ -151,6 +158,7 @@ void loop() {
|
||||
board.loop(); // let the board feed its watchdog, run periodic housekeeping
|
||||
|
||||
the_mesh.loop();
|
||||
maint.loop();
|
||||
sensors.loop();
|
||||
#ifdef DISPLAY_CLASS
|
||||
ui_task.loop();
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
stl/
|
||||
*.stl
|
||||
*.3mf
|
||||
@@ -0,0 +1,256 @@
|
||||
// Krabička na dutinový filtr 868 MHz (hamparts; 130 x 58 x 40 mm i s konektory, 380 g, SMA female)
|
||||
// na stožár. Při pohledu zepředu je profil lichoběžník (dno užší než strop),
|
||||
// takže boční stěny jsou zkosené a dívají se dolů. Vývody vedou kolmo na ně,
|
||||
// tedy šikmo dolů, a kabel pod krabičkou udělá odkapovou smyčku sám.
|
||||
// Víko je vpředu na svislé ploše, s těsněním v drážce a šrouby vně těsnění.
|
||||
// Kabel ven průchodkou PG11 (projde jí SMA konektor, viz gland_hole). Tisk: MK4S, PETG.
|
||||
// Těsnění víka: silikon vytvrzený v drážce (TPU díl `gasket` je jen volitelný).
|
||||
//
|
||||
// Montáž třemi stahovacími pásky (UV černé nebo nerez, do 9 mm) na svislou tyč
|
||||
// libovolného průřezu. Tunely jsou zapuštěné v zádech, záda zůstávají rovná a celá.
|
||||
// Dno je trychtýř do odtokové dírky, takže kondenzát vyteče.
|
||||
//
|
||||
// Tisk bez supportu ZÁDY DOLŮ: sloupky rostou z podložky, pod přírubou je náběh 45°,
|
||||
// vstupy tunelů šikmo 45°. Díry pro vývodky jsou kulaté (12,6 mm vodorovně
|
||||
// většinou projde i bez supportu, jinak tree support jen tam); `gland_teardrop` = slza.
|
||||
// Šrouby: víko 14x M3x8 DIN 912 A2 do zatavených vložek M3x5x5, filtr 4x M3x10
|
||||
// s podložkou (uši filtru 4,1 mm) do stejných vložek ve sloupcích.
|
||||
//
|
||||
// Osy: X = šířka, Z = nahoru, Y = hloubka (čelo/víko v y=0, záda na stožár v y=-depth).
|
||||
// Díly: part = "body" | "lid" | "gasket" | "assembly" | "open"
|
||||
//
|
||||
// Rozměry filtru jsou z fotek s metrem a z obkreslení podstavy (17. 10. 2026), ne
|
||||
// posuvkou: tělo ~104 x 58 (výška 45 i se šrouby a rezervou), SMA na obou čelech, mimo střed (~37 mm od jedné dlouhé
|
||||
// hrany), 4 díry 4 mm v rozích 95 x 51 (změřeno), osa SMA 18 mm nad podstavou. Filtr je symetrický, IN/OUT je jedno;
|
||||
// montuje se konektory k horní hraně.
|
||||
|
||||
part = "assembly";
|
||||
|
||||
/* [Filtr] */
|
||||
filter_len = 104; // tělo vodorovně, bez konektorů
|
||||
filter_h = 58; // svisle
|
||||
filter_d = 45; // do hloubky vč. šroubů a rezervy
|
||||
sma_len = 11; // jak daleko SMA trčí z čela
|
||||
sma_z = 37; // osa SMA nad spodní hranou filtru (konektory nahoru)
|
||||
sma_y = 18; // osa SMA od podstavy filtru
|
||||
plug_clear = 22; // za koncem SMA: úhlový konektor kabelu
|
||||
floor_clear = 10; // pod filtrem a nad ním
|
||||
front_clear = 8; // mezi filtrem a víkem
|
||||
standoff = 6; // sloupky pod filtrem
|
||||
mount_dx = 95; // rozteč děr v rozích filtru, podélně
|
||||
mount_dz = 51; // a napříč
|
||||
post_d = 10; // sloupek kolem vložky
|
||||
|
||||
/* [Tvar] */
|
||||
slant = 15; // sklon bočnic od svislice [°]
|
||||
wall = 3;
|
||||
flange = 12; // šířka příruby kolem otvoru (nese drážku i šrouby); 12 = ~238 mm, na MK4 ještě s brimem
|
||||
flange_t = 5; // tloušťka příruby; slepá díra pro vložku pokračuje do náběhu pod ní
|
||||
corner_r = 5; // poloměr vnitřních rohů; ven roste s offsetem (stěna 8, příruba 20),
|
||||
// kulaté rohy se méně odlupují od podložky a náběh má i v rohu 45°
|
||||
|
||||
/* [Těsnění] */
|
||||
groove_off = 1.5; // od vnitřní hrany příruby
|
||||
groove_w = 2.5;
|
||||
groove_d = 2.0;
|
||||
gasket_h = 2.6; // ~30 % komprese
|
||||
gasket_clr = 0.25; // vůle na každé straně drážky
|
||||
|
||||
/* [Šrouby M3 a zatavené vložky M3x5x5] */
|
||||
insert_hole = 4.3; // pro vložku o vnějším průměru 5 mm
|
||||
insert_depth = 5.6; // vložka 5 mm + místo na vytlačený plast
|
||||
screw_hole = 3.4; // průchozí díra ve víku
|
||||
screw_off = 7.5; // osa šroubů od vnitřní hrany příruby; vložka musí minout drážku
|
||||
|
||||
/* [Vývody] */
|
||||
gland_hole = 18.6; // PG11 (závit 18,4 mm): SMA ~9,2 mm přes rohy
|
||||
// projde s vyjmutou a podélně naříznutou vložkou; PG7 = 12.5, ale konektor neprojde
|
||||
gland_dz = 0; // posun díry proti ose SMA (0 = v ose konektoru)
|
||||
gland_teardrop = false; // true = slza bez supportu; kulatá díra líp sedí na závit vývodky
|
||||
drain_hole = 4; // odtok kondenzátu v nejnižším bodě dna; 0 = bez
|
||||
floor_slope = 4; // dno se ze všech stran svažuje k odtoku [°]
|
||||
|
||||
/* [Uchycení: stahovací pásky v zapuštěných tunelech] */
|
||||
tie_w = 10; // šířka tunelu (pásek do 9 mm)
|
||||
tie_gap = 2.5; // výška tunelu
|
||||
tie_zs = [0.15, 0.5, 0.85]; // výšky tunelů jako podíl výšky krabice
|
||||
tie_l = 60; // délka tunelu mezi vstupy (tyč do ~60 mm)
|
||||
tie_skin = 3; // pod tunelem (strana k tyči)
|
||||
tie_root = 2.5; // nad tunelem (strana do krabice) – nese tah pásku
|
||||
|
||||
lid_t = 3;
|
||||
$fn = 48;
|
||||
|
||||
// ---- odvozené rozměry (vnitřek) ----
|
||||
tn = tan(slant);
|
||||
in_h = filter_h + 2 * floor_clear;
|
||||
need_w = filter_len + 2 * (sma_len + plug_clear); // potřeba v úrovni spodní hrany filtru
|
||||
in_wb = need_w - 2 * floor_clear * tn; // vnitřní šířka u dna
|
||||
in_wt = in_wb + 2 * in_h * tn; // vnitřní šířka u stropu
|
||||
in_d = standoff + filter_d + front_clear;
|
||||
back_t = tie_skin + tie_gap + tie_root; // záda s tunely
|
||||
depth = in_d + back_t;
|
||||
in_y0 = -depth + back_t; // vnitřní plocha zad
|
||||
filter_zc = floor_clear + filter_h / 2; // střed filtru (vnitřní z, dno = 0)
|
||||
|
||||
echo(str("vnitřek: dno ", in_wb, " / strop ", in_wt, " x výška ", in_h, " x hloubka ", in_d));
|
||||
echo(str("obrys příruby: ", 2 * (corner_pt(2, -corner_r)[0] + corner_r + wall + flange), " x ", in_h + 2 * (wall + flange)));
|
||||
echo(str("šrouby: vložka od drážky ", screw_off - groove_off - groove_w - insert_hole / 2,
|
||||
", od okraje ", flange - screw_off - insert_hole / 2));
|
||||
|
||||
// Lichoběžník vnitřku posunutý o d ven (rovnoběžně se stěnami), dno vnitřku v z = 0.
|
||||
function trap_pts(d) = let(
|
||||
xb = in_wb / 2 - d * tn + d / cos(slant),
|
||||
xt = in_wb / 2 + (in_h + d) * tn + d / cos(slant))
|
||||
[[-xb, -d], [xb, -d], [xt, in_h + d], [-xt, in_h + d]];
|
||||
|
||||
module trap(d) { polygon(trap_pts(d)); }
|
||||
// Vnitřek se zaoblenými rohy a jeho rovnoběžné offsety: stěna, drážka i příruba mají
|
||||
// všude stejnou šířku a rohy se zaoblují s offsetem (ostrý offset dával v rohu převis ~56°).
|
||||
module outline(d) { offset(r = corner_r + d) offset(delta = -corner_r) trap(0); }
|
||||
|
||||
// vrchol zaobleného rohu `outline(d)` u rohu i lichoběžníku
|
||||
function unit(v) = v / norm(v);
|
||||
function corner_pt(i, d) = let(
|
||||
P = trap_pts(0), p = P[i],
|
||||
u = unit(P[(i + 3) % 4] - p), v = unit(P[(i + 1) % 4] - p),
|
||||
half = acos(u * v) / 2)
|
||||
p + unit(u + v) * (corner_r / sin(half) - corner_r - d);
|
||||
|
||||
// 2D v rovině XZ vytažené v hloubce od y0 do y1
|
||||
module xz(y0, y1) {
|
||||
translate([0, y1, 0]) rotate([90, 0, 0]) linear_extrude(y1 - y0) children();
|
||||
}
|
||||
|
||||
// šrouby v ose příruby: rohy + středy delších hran
|
||||
function screw_pts() = let(
|
||||
d = wall + screw_off,
|
||||
p = trap_pts(d),
|
||||
mid = function(a, b) (a + b) / 2)
|
||||
concat([for (i = [0:3]) corner_pt(i, d)], [mid(p[0], p[1]), mid(p[2], p[3]),
|
||||
mid(p[0], mid(p[0], p[1])), mid(p[1], mid(p[0], p[1])),
|
||||
mid(p[2], mid(p[2], p[3])), mid(p[3], mid(p[2], p[3])),
|
||||
mid(p[1], p[2]), mid(p[3], p[0])]);
|
||||
|
||||
module groove2d(clr = 0) {
|
||||
difference() {
|
||||
outline(wall + groove_off + groove_w - clr);
|
||||
outline(wall + groove_off + clr);
|
||||
}
|
||||
}
|
||||
|
||||
sma_abs_z = floor_clear + sma_z; // osa SMA ve vnitřních z
|
||||
|
||||
module mount_post() {
|
||||
// sloupek na zadní stěně; díra jen do sloupku, ne skrz stěnu
|
||||
difference() {
|
||||
rotate([-90, 0, 0]) cylinder(d = post_d, h = standoff);
|
||||
translate([0, standoff - insert_depth, 0]) rotate([-90, 0, 0])
|
||||
cylinder(d = insert_hole, h = insert_depth + 0.01);
|
||||
}
|
||||
}
|
||||
|
||||
module gland_cut(side) {
|
||||
// kolmo na zkosenou bočnici => osa míří ven a dolů
|
||||
z = sma_abs_z + gland_dz;
|
||||
x = side * (in_wb / 2 + z * tn);
|
||||
translate([x, in_y0 + standoff + sma_y, z])
|
||||
rotate([0, side * (90 + slant), 0])
|
||||
if (gland_teardrop) teardrop(gland_hole, 4 * wall);
|
||||
else cylinder(d = gland_hole, h = 4 * wall, center = true);
|
||||
}
|
||||
|
||||
// válec s převisem 45° ve špičce: osa podle z, špička míří k +y (při tisku nahoru)
|
||||
module teardrop(d, h) {
|
||||
linear_extrude(h, center = true)
|
||||
hull() { circle(d = d); rotate(45) square(d / 2); }
|
||||
}
|
||||
|
||||
// ---- dno jako trychtýř k odtoku ----
|
||||
drain_y = in_y0 + in_d / 2;
|
||||
funnel_h = 8;
|
||||
|
||||
module floor_funnel() {
|
||||
difference() {
|
||||
intersection() {
|
||||
xz(in_y0, 0) outline(0);
|
||||
translate([-in_wt, -depth, 0]) cube([2 * in_wt, depth, funnel_h]);
|
||||
}
|
||||
translate([0, drain_y, 0])
|
||||
linear_extrude(height = funnel_h + 0.01, scale = 2 * funnel_h / tan(floor_slope) / 0.2)
|
||||
square(0.2, center = true);
|
||||
if (drain_hole > 0)
|
||||
translate([0, drain_y, -1]) cylinder(d = drain_hole, h = funnel_h + 2);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- tunely pro stahovací pásky ----
|
||||
// Vedou vodorovně uvnitř zad, na zadní plochu vyúsťují šikmo pod 45°, takže
|
||||
// pásek do tunelu sám zajede a vyjede druhým vstupem. Interiér neprotínají.
|
||||
module tie_cut() {
|
||||
y0 = -depth + tie_skin;
|
||||
translate([-tie_l / 2, y0, -tie_w / 2]) cube([tie_l, tie_gap, tie_w]);
|
||||
for (s = [-1, 1]) hull() {
|
||||
translate([s * tie_l / 2 - 0.01, y0, -tie_w / 2]) cube([0.02, tie_gap, tie_w]);
|
||||
translate([s * (tie_l / 2 + tie_skin) + (s > 0 ? 0 : -tie_gap), -depth - 1, -tie_w / 2])
|
||||
cube([tie_gap, 1.01, tie_w]);
|
||||
}
|
||||
}
|
||||
|
||||
module body() {
|
||||
difference() {
|
||||
union() {
|
||||
xz(-depth, 0) outline(wall);
|
||||
xz(-flange_t, 0) outline(wall + flange);
|
||||
// náběh 45° pod přírubou, aby se dala tisknout zády dolů bez supportu
|
||||
hull() {
|
||||
xz(-flange_t - flange, -flange_t - flange + 0.01) outline(wall);
|
||||
xz(-flange_t - 0.01, -flange_t) outline(wall + flange);
|
||||
}
|
||||
}
|
||||
xz(in_y0, 1) outline(0);
|
||||
// drážka pro těsnění
|
||||
translate([0, 0.01, 0]) xz(-groove_d, 0) groove2d();
|
||||
// šrouby
|
||||
for (p = screw_pts())
|
||||
translate([p[0], 0.01, p[1]]) rotate([90, 0, 0]) cylinder(d = insert_hole, h = insert_depth);
|
||||
for (s = [-1, 1]) gland_cut(s);
|
||||
if (drain_hole > 0)
|
||||
translate([0, drain_y, -wall - 1]) cylinder(d = drain_hole, h = wall + 2);
|
||||
for (f = tie_zs) translate([0, 0, f * in_h]) tie_cut();
|
||||
}
|
||||
floor_funnel();
|
||||
for (x = [-1, 1], z = [-1, 1])
|
||||
translate([x * mount_dx / 2, in_y0, filter_zc + z * mount_dz / 2]) mount_post();
|
||||
}
|
||||
|
||||
module lid() {
|
||||
difference() {
|
||||
xz(0, lid_t) outline(wall + flange);
|
||||
for (p = screw_pts())
|
||||
translate([p[0], lid_t + 1, p[1]]) rotate([90, 0, 0]) cylinder(d = screw_hole, h = lid_t + 2);
|
||||
}
|
||||
}
|
||||
|
||||
module gasket() { xz(-groove_d, -groove_d + gasket_h) groove2d(gasket_clr); }
|
||||
|
||||
module filter_dummy() {
|
||||
color("silver")
|
||||
translate([-filter_len / 2, in_y0 + standoff, floor_clear])
|
||||
cube([filter_len, filter_d, filter_h]);
|
||||
color("gold")
|
||||
for (s = [-1, 1])
|
||||
translate([s * filter_len / 2, in_y0 + standoff + sma_y, sma_abs_z])
|
||||
rotate([0, s * 90, 0]) cylinder(d = 6.4, h = sma_len);
|
||||
}
|
||||
|
||||
// tisk: tělo zády dolů, víko těsnicí plochou dolů, těsnění z TPU naplocho
|
||||
if (part == "body") translate([0, 0, depth]) rotate([90, 0, 0]) body();
|
||||
else if (part == "lid") rotate([90, 0, 0]) lid();
|
||||
else if (part == "gasket") rotate([-90, 0, 0]) translate([0, groove_d, 0]) gasket();
|
||||
else {
|
||||
color("orange", 0.85) body();
|
||||
color("black") gasket();
|
||||
filter_dummy();
|
||||
if (part == "assembly") color("lightblue", 0.35) translate([0, 25, 0]) lid();
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
# Docs website of this fork (https://tth-pub.pages.rfa.cz/meshcore-tth/),
|
||||
# built by .github/docs-site.sh. Its own file, not an INHERIT of upstream's
|
||||
# mkdocs.yml (that one is Material: logo, features, palette): theme
|
||||
# mkdocs-terminal, palette "dark" with docs/_stylesheets/tth.css on top.
|
||||
site_name: MeshCore TTH
|
||||
site_url: https://tth-pub.pages.rfa.cz/meshcore-tth/
|
||||
site_description: MeshCore fork meshcore-tth -- repeater antispam, diagnostics, OTA, Czech mesh defaults
|
||||
repo_name: tth-pub/meshcore-tth
|
||||
repo_url: https://git.rfa.cz/tth-pub/meshcore-tth
|
||||
edit_uri: src/branch/main/docs/
|
||||
# the theme shows neither repo_url nor edit links for a Gitea repo: the
|
||||
# repository is a top-bar entry (nav) and a line in every footer
|
||||
copyright: 'Source: <a href="https://git.rfa.cz/tth-pub/meshcore-tth">git.rfa.cz/tth-pub/meshcore-tth</a> ·'
|
||||
|
||||
theme:
|
||||
name: terminal
|
||||
palette: dark
|
||||
features:
|
||||
# no blinking cursor after the site name (user, 2. 12. 2026)
|
||||
- navigation.top.cursor_animation.hide
|
||||
- navigation.side.indexes
|
||||
|
||||
extra_css:
|
||||
- _stylesheets/tth.css
|
||||
|
||||
plugins:
|
||||
- search
|
||||
|
||||
markdown_extensions:
|
||||
- admonition
|
||||
- github-callouts
|
||||
- attr_list
|
||||
- tables
|
||||
- toc
|
||||
- pymdownx.details
|
||||
- pymdownx.superfences
|
||||
|
||||
# One language for the site: English (every doc in docs/ is English); the
|
||||
# Czech half of the README is one page, "Česky", in the top bar. Titles in
|
||||
# both languages side by side were confusing (user, 2. 12. 2026).
|
||||
nav:
|
||||
- About the fork: index.md
|
||||
- Česky: cs.md
|
||||
- Repository: https://git.rfa.cz/tth-pub/meshcore-tth
|
||||
- Fork meshcore-tth:
|
||||
- Console commands: tth-commands.md
|
||||
- Firmware update by the admin (OTA): ota.md
|
||||
- Power saving: power.md
|
||||
- Budka as a sensor: budka-sensor.md
|
||||
- BLE/LoRa coexistence: ble-lora-coexistence.md
|
||||
- MeshCore (upstream):
|
||||
- Introduction: meshcore.md
|
||||
- FAQ: faq.md
|
||||
- CLI commands: cli_commands.md
|
||||
- Companion CLI: companion_cli.md
|
||||
- Companion protocol: companion_protocol.md
|
||||
- Terminal chat CLI: terminal_chat_cli.md
|
||||
- KISS modem protocol: kiss_modem_protocol.md
|
||||
- Packet format: packet_format.md
|
||||
- Payloads: payloads.md
|
||||
- Stats binary frames: stats_binary_frames.md
|
||||
- Number allocations: number_allocations.md
|
||||
- QR codes: qr_codes.md
|
||||
- Radio presets: radio_presets.md
|
||||
- nRF52 power management: nrf52_power_management.md
|
||||
+127
-6
@@ -13,6 +13,39 @@ extra_configs =
|
||||
variants/*/platformio.ini
|
||||
platformio.local.ini
|
||||
|
||||
; Default BLE pairing PIN. This is a non-secret placeholder; override it with
|
||||
; your real PIN in the git-ignored platformio.local.ini ([secrets] ble_pin=...)
|
||||
; so the real value never lands in the committed tree.
|
||||
; admin_pw: same idea for the mast envs in variants/tth_fleet (ADMIN_PASSWORD).
|
||||
; PlatformIO resolves ${secrets.*} of EVERY env when it loads the config, so a
|
||||
; checkout without platformio.local.ini (tth-upstream-sync CI) fails on the
|
||||
; missing key even when it never builds a mast env. tth-fw-release writes the
|
||||
; real values over it.
|
||||
[secrets]
|
||||
ble_pin = 123456
|
||||
admin_pw = password
|
||||
|
||||
; Admin-pushed OTA (src/helpers/FwUpdate, docs/ota.md): the PUBLIC key
|
||||
; every OTA package signature is checked against, raw Ed25519 hex. Default: the
|
||||
; public OTA key meshcore-ota@tth-pub, the one the -ota release images are
|
||||
; signed with (tools/ota_allowed_signers has it as an ssh key, for the release
|
||||
; checksums). Only images built with -D FW_OTA=1 use it. A self-built image
|
||||
; signed with your own key: [ota] pubkey = <tools/ota_pack.py pubkey --key ...>
|
||||
; in platformio.local.ini.
|
||||
[ota]
|
||||
pubkey = 8777b6e1a8494113b70f41f5ed75bf3f2a8eba9635bab1dc3d20efd1a8398090
|
||||
|
||||
; CUSTOM (TeTeHacko): channels the ChannelFilter deny list applies to
|
||||
; (examples/simple_repeater/ChannelFilter.h). These keys are PUBLIC by
|
||||
; construction, not secrets: hashtag channels derive key = SHA256(name)[:16]
|
||||
; (anyone joins #meshcore by typing the name), and the Public channel key is
|
||||
; the globally published izOH6cXN6mrJ5e26oRXNcg==. Derivation verified live
|
||||
; 5. 9. 2026: SHA256("#meshcore")[:16] hashes to channel byte 0xEF, matching
|
||||
; the on-air packets. Order: #meshcore, Public, #test.
|
||||
[channel_filter]
|
||||
build_flags =
|
||||
-D FILTER_CHANNEL_PSKS='"2fa78a5aef618e7c2a78f0ab5c8869b3,8b3387e9c5cdea6ac9e5edbaa115cd72,9cd8fcf22a47333b591d96a2b848b73f"'
|
||||
|
||||
[arduino_base]
|
||||
framework = arduino
|
||||
monitor_speed = 115200
|
||||
@@ -77,21 +110,54 @@ platform = https://github.com/pioarduino/platform-espressif32/releases/download/
|
||||
|
||||
; ----------------- NRF52 ---------------------
|
||||
|
||||
; nRF52 Adafruit framework package. Committed DEFAULT is a fetchable git pin
|
||||
; (works on CI and on any clone). CUSTOM (TeTeHacko): our fork
|
||||
; tth-pub/Adafruit_nRF52_Arduino, branch tth = meshcore-dev's master d541301
|
||||
; (the BLE-stack patch against rapid connect/disconnect lockup, MeshCore PRs
|
||||
; #1177, #1295) + 7808206: xPortSysTickHandler no longer adds 2^24 ticks when
|
||||
; the tick count is ahead of the RTC -- millis(), uptime and the clock of
|
||||
; mast-rpt-two jumped 16384 s ahead, several times in minutes (2. 12. 2026)
|
||||
; + 45188a6 (adafruit PR #873) and fca5ff3: Wire no longer hangs forever on a
|
||||
; stuck I2C bus, reports a timeout as an error (not as an ACK) and resets the
|
||||
; TWIM after it (tested on a XIAO with SCL tied to GND, 2. 12. 2026).
|
||||
; + 926a22c: synced with #873's head, which took fca5ff3 and added recovery
|
||||
; after a NACK in the same call and ERRORSRC/event clearing (bench x4, 3. 12. 2026).
|
||||
; Public: pub-release builds in tth-pub. The full 40-char SHA is used on purpose:
|
||||
; PlatformIO's shallow fetch choked on the SHORT SHA, which is the whole reason
|
||||
; the local build used a full clone + symlink. That symlink hack now lives ONLY
|
||||
; in the gitignored platformio.local.ini (it redefines [nrf52_fw].pkg), so it
|
||||
; never leaks into the tracked tree and breaks CI again -- it did: a committed
|
||||
; `symlink:///home/user/...` gave PackageException on every nRF52 runner build.
|
||||
[nrf52_fw]
|
||||
pkg = https://git.rfa.cz/tth-pub/Adafruit_nRF52_Arduino.git#926a22c8474eaa10e7c2ea2425be65fb8b45c51f
|
||||
|
||||
[nrf52_base]
|
||||
extends = arduino_base
|
||||
platform = nordicnrf52
|
||||
; CUSTOM (TeTeHacko): exact platform and toolchain (upstream: `nordicnrf52`,
|
||||
; `^1.140201.0`). Unpinned, every build took the newest: on 30. 11. 2026 the
|
||||
; public release went to platform 11.1.0, released that same day, while the
|
||||
; bench and the masts built on 10.12.0. Latest, but by a commit: Renovate
|
||||
; moves these two (.github/renovate.json), its PR builds every public image.
|
||||
; Libraries: platformio.lock (tools/pio_lock.py, moved by tth-lock-refresh).
|
||||
platform = platformio/nordicnrf52@11.1.0
|
||||
platform_packages =
|
||||
; use internal fork that includes patch to ble stack to prevent firmware lockup during rapid connect/disconnect
|
||||
; https://github.com/meshcore-dev/MeshCore/pull/1177
|
||||
; https://github.com/meshcore-dev/MeshCore/pull/1295
|
||||
framework-arduinoadafruitnrf52 @ https://github.com/meshcore-dev/Adafruit_nRF52_Arduino#d541301665b40959682252911e57b11df3ee651a
|
||||
platformio/toolchain-gccarmnoneeabi@^1.140201.0
|
||||
framework-arduinoadafruitnrf52 @ ${nrf52_fw.pkg}
|
||||
platformio/toolchain-gccarmnoneeabi@1.140201.0
|
||||
; Stamping verze pro KAŽDÝ nRF52 env, ne po jednom: 19. 8. 2026 se ukázalo, že
|
||||
; z 585 envů v repu stampovaly DVA, takže `ver` na lavičních deskách hlásil
|
||||
; literál z upstream headeru a z uzlu nešlo poznat, který build na něm je.
|
||||
; U flashované desky je to podmínka, ne komfort (AGENTS.md).
|
||||
extra_scripts = create-uf2.py
|
||||
pre:tools/build_version.py
|
||||
; FwPatch.cpp (delta OTA applier) runs from RAM, see the script's header.
|
||||
pre:tools/ota_ramlib.py
|
||||
build_flags = ${arduino_base.build_flags}
|
||||
-D NRF52_PLATFORM
|
||||
-D LFS_NO_ASSERT=1
|
||||
-D EXTRAFS=1
|
||||
-D FW_OTA_PUBKEY='"${ota.pubkey}"'
|
||||
-D USE_CC310_HW_CRYPTO=1
|
||||
-D SPI_32MHZ_INTERFACE=1
|
||||
lib_deps =
|
||||
${arduino_base.lib_deps}
|
||||
https://github.com/oltaco/CustomLFS#0.2.3
|
||||
@@ -130,6 +196,7 @@ build_flags =
|
||||
-D ENV_INCLUDE_AHTX0=1
|
||||
-D ENV_INCLUDE_BME280=1
|
||||
-D ENV_INCLUDE_BMP280=1
|
||||
-D ENV_INCLUDE_BMP3XX=1
|
||||
-D ENV_INCLUDE_SHTC3=1
|
||||
-D ENV_INCLUDE_SHT4X=1
|
||||
-D ENV_INCLUDE_LPS22HB=1
|
||||
@@ -149,6 +216,7 @@ lib_deps =
|
||||
adafruit/Adafruit AHTX0 @ ^2.0.5
|
||||
adafruit/Adafruit BME280 Library @ ^2.3.0
|
||||
adafruit/Adafruit BMP280 Library @ ^2.6.8
|
||||
adafruit/Adafruit BMP3XX Library @ ^2.1.6
|
||||
adafruit/Adafruit SHTC3 Library @ ^1.0.1
|
||||
sensirion/Sensirion I2C SHT4x @ ^1.1.2
|
||||
arduino-libraries/Arduino_LPS22HB @ ^1.0.2
|
||||
@@ -170,16 +238,69 @@ test_build_src = yes
|
||||
test_ignore = test_kiss_modem
|
||||
build_src_filter =
|
||||
-<*>
|
||||
+<../src/helpers/FwPatch.cpp>
|
||||
+<../src/Utils.cpp>
|
||||
+<../src/Packet.cpp>
|
||||
+<../src/helpers/ConfigSerializer.cpp>
|
||||
+<../src/helpers/DynamicConfigSerializer.cpp>
|
||||
+<../src/helpers/FairnessLimiter.cpp>
|
||||
lib_deps =
|
||||
google/googletest @ 1.17.0
|
||||
|
||||
; Stejné jako [env:native], ale pod AddressSanitizerem. Bounds fixy v parsování
|
||||
; paketů nemění návratovou hodnotu -- odmítnou přesně to, co upstream odmítne až
|
||||
; po přečtení -- takže rozdíl je vidět jenom tady. Testy krmí parser bufferem
|
||||
; alokovaným na přesnou délku rámce, aby bylo čtení za jeho konec skutečná chyba.
|
||||
[env:native_asan]
|
||||
platform = native
|
||||
test_framework = googletest
|
||||
build_flags = -std=c++17
|
||||
-I src
|
||||
-I test/mocks
|
||||
-fsanitize=address,undefined
|
||||
# Bez -fno-sanitize-recover UBSan nalez jen VYPISE a test dobehne uspesne --
|
||||
# takze z te poloviny sanitizeru byla jen ozdoba. ASAN abortuje sam.
|
||||
-fno-sanitize-recover=all
|
||||
# POZOR na diagnostiku: `pio test` u padu sanitizeru vypise jen
|
||||
# "Program received signal SIGHUP" a ASAN report SPOLKNE. Necti z toho, ze
|
||||
# sanitizer nic nenasel -- spust binarku primo:
|
||||
# pio run -e native_asan -t buildprog && .pio/build/native_asan/program
|
||||
# Overeno 2. 9. 2026: pres `pio test` jen SIGHUP, primo pak
|
||||
# "heap-buffer-overflow ... src/Packet.cpp:93 in mesh::Packet::readFrom".
|
||||
-fno-omit-frame-pointer
|
||||
-g -O1
|
||||
build_unflags = -O2
|
||||
test_build_src = yes
|
||||
; test_empty_contact_slots (upstream 20. 10. 2026) jako prvni test vola ed25519
|
||||
; na hostu a UBSan zastavi na `lib/ed25519/fe.c:714: left shift of negative
|
||||
; value` -- idiom referencni implementace ref10, ne nalez v nasem kodu. GCC
|
||||
; nema per-file ignorelist, takze ten test bezi jen v [env:native].
|
||||
test_ignore =
|
||||
test_kiss_modem
|
||||
test_empty_contact_slots
|
||||
; POZOR: musi zustat v zakrytu s [env:native]. Merge upstreamu 2. 9. 2026 pridal
|
||||
; DynamicConfigSerializer.cpp jen tam a tenhle env pak padal na undefined
|
||||
; reference -- coz vypada jako nalez ASANu, a je to jen chybejici prekladova
|
||||
; jednotka.
|
||||
build_src_filter =
|
||||
-<*>
|
||||
+<../src/helpers/FwPatch.cpp>
|
||||
+<../src/Utils.cpp>
|
||||
+<../src/Packet.cpp>
|
||||
+<../src/helpers/ConfigSerializer.cpp>
|
||||
+<../src/helpers/DynamicConfigSerializer.cpp>
|
||||
+<../src/helpers/FairnessLimiter.cpp>
|
||||
lib_deps =
|
||||
google/googletest @ 1.17.0
|
||||
|
||||
[env:native_kiss_modem]
|
||||
platform = native
|
||||
test_framework = googletest
|
||||
; Stampovani i tady: `KissModem::handleGetDeviceName()` pripojuje k vyrobci
|
||||
; FIRMWARE_VERSION, jinak je deska s KISS buildem verzne neidentifikovatelna.
|
||||
; Bez tohohle skriptu se ten symbol na hostu nedefinuje a test env se od
|
||||
; 1. 9. 2026 ani neprelozil ("FIRMWARE_VERSION was not declared").
|
||||
extra_scripts = pre:tools/build_version.py
|
||||
build_flags = -std=c++17
|
||||
-I test/mocks
|
||||
-I src
|
||||
|
||||
+461
@@ -0,0 +1,461 @@
|
||||
; Library lock for PlatformIO (tools/pio_lock.py; PlatformIO has no lockfile).
|
||||
; Per env, every library in .pio/libdeps/<env>, transitive ones included:
|
||||
; `owner/name@version` from the registry, `<remote>#<commit>` of a git library
|
||||
; (pinned in platformio.ini, only checked here) or a file: URI.
|
||||
; CI installs these before building and fails when a build resolved anything
|
||||
; else. Renovate bumps the registry lines; tools/pio_lock.py freeze rewrites
|
||||
; an env from what it resolved.
|
||||
|
||||
[Heltec_t114_companion_radio_ble]
|
||||
adafruit/Adafruit AHTX0@2.0.6
|
||||
adafruit/Adafruit BME280 Library@2.3.0
|
||||
adafruit/Adafruit BME680 Library@2.0.6
|
||||
adafruit/Adafruit BMP085 Library@1.2.4
|
||||
adafruit/Adafruit BMP280 Library@2.6.8
|
||||
adafruit/Adafruit BMP3XX Library@2.1.6
|
||||
adafruit/Adafruit BusIO@1.17.4
|
||||
adafruit/Adafruit GFX Library@2.0.0
|
||||
adafruit/Adafruit INA219@1.2.3
|
||||
adafruit/Adafruit INA260 Library@1.5.4
|
||||
adafruit/Adafruit INA3221 Library@1.0.3
|
||||
adafruit/Adafruit MLX90614 Library@2.1.7
|
||||
adafruit/Adafruit NeoPixel@1.15.6
|
||||
adafruit/Adafruit SH110X@2.1.15
|
||||
adafruit/Adafruit SHTC3 Library@1.0.2
|
||||
adafruit/Adafruit SSD1306@2.5.18
|
||||
adafruit/Adafruit Unified Sensor@1.1.15
|
||||
adafruit/Adafruit_VL53L0X@1.2.5
|
||||
adafruit/RTClib@2.1.4
|
||||
arduino-libraries/Arduino_LPS22HB@1.0.3
|
||||
bblanchon/ArduinoJson@7.4.3
|
||||
densaugeo/base64@1.4.0
|
||||
electroniccats/CayenneLPP@1.6.1
|
||||
https://github.com/oltaco/CustomLFS#b3928ea2d0f46c2533e901c43f471a081c503a3c
|
||||
jgromes/RadioLib@7.8.1
|
||||
melopero/Melopero RV3028@1.2.0
|
||||
robtillaart/INA226@0.6.6
|
||||
rweather/Crypto@0.4.0
|
||||
sensirion/Sensirion Core@0.7.3
|
||||
sensirion/Sensirion I2C SHT4x@1.1.2
|
||||
stevemarple/MicroNMEA@2.0.6
|
||||
|
||||
[Heltec_t114_repeater]
|
||||
adafruit/Adafruit AHTX0@2.0.6
|
||||
adafruit/Adafruit BME280 Library@2.3.0
|
||||
adafruit/Adafruit BME680 Library@2.0.6
|
||||
adafruit/Adafruit BMP085 Library@1.2.4
|
||||
adafruit/Adafruit BMP280 Library@2.6.8
|
||||
adafruit/Adafruit BMP3XX Library@2.1.6
|
||||
adafruit/Adafruit BusIO@1.17.4
|
||||
adafruit/Adafruit GFX Library@2.0.0
|
||||
adafruit/Adafruit INA219@1.2.3
|
||||
adafruit/Adafruit INA260 Library@1.5.4
|
||||
adafruit/Adafruit INA3221 Library@1.0.3
|
||||
adafruit/Adafruit MLX90614 Library@2.1.7
|
||||
adafruit/Adafruit NeoPixel@1.15.6
|
||||
adafruit/Adafruit SH110X@2.1.15
|
||||
adafruit/Adafruit SHTC3 Library@1.0.2
|
||||
adafruit/Adafruit SSD1306@2.5.18
|
||||
adafruit/Adafruit Unified Sensor@1.1.15
|
||||
adafruit/Adafruit_VL53L0X@1.2.5
|
||||
adafruit/RTClib@2.1.4
|
||||
arduino-libraries/Arduino_LPS22HB@1.0.3
|
||||
bblanchon/ArduinoJson@7.4.3
|
||||
electroniccats/CayenneLPP@1.6.1
|
||||
https://github.com/oltaco/CustomLFS#b3928ea2d0f46c2533e901c43f471a081c503a3c
|
||||
jgromes/RadioLib@7.8.1
|
||||
melopero/Melopero RV3028@1.2.0
|
||||
robtillaart/INA226@0.6.6
|
||||
rweather/Crypto@0.4.0
|
||||
sensirion/Sensirion Core@0.7.3
|
||||
sensirion/Sensirion I2C SHT4x@1.1.2
|
||||
stevemarple/MicroNMEA@2.0.6
|
||||
|
||||
[Heltec_v3_companion_radio_ble]
|
||||
adafruit/Adafruit AHTX0@2.0.6
|
||||
adafruit/Adafruit BME280 Library@2.3.0
|
||||
adafruit/Adafruit BME680 Library@2.0.6
|
||||
adafruit/Adafruit BMP085 Library@1.2.4
|
||||
adafruit/Adafruit BMP280 Library@2.6.8
|
||||
adafruit/Adafruit BMP3XX Library@2.1.6
|
||||
adafruit/Adafruit BusIO@1.17.4
|
||||
adafruit/Adafruit GFX Library@2.0.0
|
||||
adafruit/Adafruit INA219@1.2.3
|
||||
adafruit/Adafruit INA260 Library@1.5.4
|
||||
adafruit/Adafruit INA3221 Library@1.0.3
|
||||
adafruit/Adafruit MLX90614 Library@2.1.7
|
||||
adafruit/Adafruit NeoPixel@1.15.6
|
||||
adafruit/Adafruit SH110X@2.1.15
|
||||
adafruit/Adafruit SHTC3 Library@1.0.2
|
||||
adafruit/Adafruit SSD1306@2.5.18
|
||||
adafruit/Adafruit Unified Sensor@1.1.15
|
||||
adafruit/Adafruit_VL53L0X@1.2.5
|
||||
adafruit/RTClib@2.1.4
|
||||
arduino-libraries/Arduino_LPS22HB@1.0.3
|
||||
bblanchon/ArduinoJson@7.4.3
|
||||
densaugeo/base64@1.4.0
|
||||
electroniccats/CayenneLPP@1.6.1
|
||||
jgromes/RadioLib@7.8.1
|
||||
melopero/Melopero RV3028@1.2.0
|
||||
robtillaart/INA226@0.6.6
|
||||
rweather/Crypto@0.4.0
|
||||
sensirion/Sensirion Core@0.7.3
|
||||
sensirion/Sensirion I2C SHT4x@1.1.2
|
||||
stevemarple/MicroNMEA@2.0.6
|
||||
|
||||
[Heltec_v3_repeater]
|
||||
adafruit/Adafruit AHTX0@2.0.6
|
||||
adafruit/Adafruit BME280 Library@2.3.0
|
||||
adafruit/Adafruit BME680 Library@2.0.6
|
||||
adafruit/Adafruit BMP085 Library@1.2.4
|
||||
adafruit/Adafruit BMP280 Library@2.6.8
|
||||
adafruit/Adafruit BMP3XX Library@2.1.6
|
||||
adafruit/Adafruit BusIO@1.17.4
|
||||
adafruit/Adafruit GFX Library@2.0.0
|
||||
adafruit/Adafruit INA219@1.2.3
|
||||
adafruit/Adafruit INA260 Library@1.5.4
|
||||
adafruit/Adafruit INA3221 Library@1.0.3
|
||||
adafruit/Adafruit MLX90614 Library@2.1.7
|
||||
adafruit/Adafruit NeoPixel@1.15.6
|
||||
adafruit/Adafruit SH110X@2.1.15
|
||||
adafruit/Adafruit SHTC3 Library@1.0.2
|
||||
adafruit/Adafruit SSD1306@2.5.18
|
||||
adafruit/Adafruit Unified Sensor@1.1.15
|
||||
adafruit/Adafruit_VL53L0X@1.2.5
|
||||
adafruit/RTClib@2.1.4
|
||||
arduino-libraries/Arduino_LPS22HB@1.0.3
|
||||
bakercp/CRC32@2.0.1
|
||||
bblanchon/ArduinoJson@7.4.3
|
||||
electroniccats/CayenneLPP@1.6.1
|
||||
esp32async/AsyncTCP@3.6.1
|
||||
esp32async/ESPAsyncWebServer@3.10.3
|
||||
file://arch/esp32/AsyncElegantOTA
|
||||
jgromes/RadioLib@7.8.1
|
||||
melopero/Melopero RV3028@1.2.0
|
||||
robtillaart/INA226@0.6.6
|
||||
rweather/Crypto@0.4.0
|
||||
sensirion/Sensirion Core@0.7.3
|
||||
sensirion/Sensirion I2C SHT4x@1.1.2
|
||||
stevemarple/MicroNMEA@2.0.6
|
||||
|
||||
[RAK_4631_companion_radio_ble]
|
||||
adafruit/Adafruit AHTX0@2.0.6
|
||||
adafruit/Adafruit BME280 Library@2.3.0
|
||||
adafruit/Adafruit BME680 Library@2.0.6
|
||||
adafruit/Adafruit BMP085 Library@1.2.4
|
||||
adafruit/Adafruit BMP280 Library@2.6.8
|
||||
adafruit/Adafruit BMP3XX Library@2.1.6
|
||||
adafruit/Adafruit BusIO@1.17.4
|
||||
adafruit/Adafruit GFX Library@2.0.0
|
||||
adafruit/Adafruit INA219@1.2.3
|
||||
adafruit/Adafruit INA260 Library@1.5.4
|
||||
adafruit/Adafruit INA3221 Library@1.0.3
|
||||
adafruit/Adafruit MLX90614 Library@2.1.7
|
||||
adafruit/Adafruit NeoPixel@1.15.6
|
||||
adafruit/Adafruit SH110X@2.1.15
|
||||
adafruit/Adafruit SHTC3 Library@1.0.2
|
||||
adafruit/Adafruit SSD1306@2.5.18
|
||||
adafruit/Adafruit Unified Sensor@1.1.15
|
||||
adafruit/Adafruit_VL53L0X@1.2.5
|
||||
adafruit/RTClib@2.1.4
|
||||
arduino-libraries/Arduino_LPS22HB@1.0.3
|
||||
bblanchon/ArduinoJson@7.4.3
|
||||
boschsensortec/BSEC Software Library@1.8.1492
|
||||
densaugeo/base64@1.4.0
|
||||
electroniccats/CayenneLPP@1.6.1
|
||||
https://github.com/oltaco/CustomLFS#b3928ea2d0f46c2533e901c43f471a081c503a3c
|
||||
jgromes/RadioLib@7.8.1
|
||||
melopero/Melopero RV3028@1.2.0
|
||||
robtillaart/INA226@0.6.6
|
||||
rweather/Crypto@0.4.0
|
||||
sensirion/Sensirion Core@0.7.3
|
||||
sensirion/Sensirion I2C SHT4x@1.1.2
|
||||
sparkfun/SparkFun u-blox GNSS Arduino Library@2.2.29
|
||||
stevemarple/MicroNMEA@2.0.6
|
||||
|
||||
[RAK_4631_repeater]
|
||||
adafruit/Adafruit AHTX0@2.0.6
|
||||
adafruit/Adafruit BME280 Library@2.3.0
|
||||
adafruit/Adafruit BME680 Library@2.0.6
|
||||
adafruit/Adafruit BMP085 Library@1.2.4
|
||||
adafruit/Adafruit BMP280 Library@2.6.8
|
||||
adafruit/Adafruit BMP3XX Library@2.1.6
|
||||
adafruit/Adafruit BusIO@1.17.4
|
||||
adafruit/Adafruit GFX Library@2.0.0
|
||||
adafruit/Adafruit INA219@1.2.3
|
||||
adafruit/Adafruit INA260 Library@1.5.4
|
||||
adafruit/Adafruit INA3221 Library@1.0.3
|
||||
adafruit/Adafruit MLX90614 Library@2.1.7
|
||||
adafruit/Adafruit NeoPixel@1.15.6
|
||||
adafruit/Adafruit SH110X@2.1.15
|
||||
adafruit/Adafruit SHTC3 Library@1.0.2
|
||||
adafruit/Adafruit SSD1306@2.5.18
|
||||
adafruit/Adafruit Unified Sensor@1.1.15
|
||||
adafruit/Adafruit_VL53L0X@1.2.5
|
||||
adafruit/RTClib@2.1.4
|
||||
arduino-libraries/Arduino_LPS22HB@1.0.3
|
||||
bblanchon/ArduinoJson@7.4.3
|
||||
boschsensortec/BSEC Software Library@1.8.1492
|
||||
electroniccats/CayenneLPP@1.6.1
|
||||
https://github.com/oltaco/CustomLFS#b3928ea2d0f46c2533e901c43f471a081c503a3c
|
||||
jgromes/RadioLib@7.8.1
|
||||
melopero/Melopero RV3028@1.2.0
|
||||
robtillaart/INA226@0.6.6
|
||||
rweather/Crypto@0.4.0
|
||||
sensirion/Sensirion Core@0.7.3
|
||||
sensirion/Sensirion I2C SHT4x@1.1.2
|
||||
sparkfun/SparkFun u-blox GNSS Arduino Library@2.2.29
|
||||
stevemarple/MicroNMEA@2.0.6
|
||||
|
||||
[RAK_4631_room_server]
|
||||
adafruit/Adafruit AHTX0@2.0.6
|
||||
adafruit/Adafruit BME280 Library@2.3.0
|
||||
adafruit/Adafruit BME680 Library@2.0.6
|
||||
adafruit/Adafruit BMP085 Library@1.2.4
|
||||
adafruit/Adafruit BMP280 Library@2.6.8
|
||||
adafruit/Adafruit BMP3XX Library@2.1.6
|
||||
adafruit/Adafruit BusIO@1.17.4
|
||||
adafruit/Adafruit GFX Library@2.0.0
|
||||
adafruit/Adafruit INA219@1.2.3
|
||||
adafruit/Adafruit INA260 Library@1.5.4
|
||||
adafruit/Adafruit INA3221 Library@1.0.3
|
||||
adafruit/Adafruit MLX90614 Library@2.1.7
|
||||
adafruit/Adafruit NeoPixel@1.15.6
|
||||
adafruit/Adafruit SH110X@2.1.15
|
||||
adafruit/Adafruit SHTC3 Library@1.0.2
|
||||
adafruit/Adafruit SSD1306@2.5.18
|
||||
adafruit/Adafruit Unified Sensor@1.1.15
|
||||
adafruit/Adafruit_VL53L0X@1.2.5
|
||||
adafruit/RTClib@2.1.4
|
||||
arduino-libraries/Arduino_LPS22HB@1.0.3
|
||||
bblanchon/ArduinoJson@7.4.3
|
||||
boschsensortec/BSEC Software Library@1.8.1492
|
||||
electroniccats/CayenneLPP@1.6.1
|
||||
https://github.com/oltaco/CustomLFS#b3928ea2d0f46c2533e901c43f471a081c503a3c
|
||||
jgromes/RadioLib@7.8.1
|
||||
melopero/Melopero RV3028@1.2.0
|
||||
robtillaart/INA226@0.6.6
|
||||
rweather/Crypto@0.4.0
|
||||
sensirion/Sensirion Core@0.7.3
|
||||
sensirion/Sensirion I2C SHT4x@1.1.2
|
||||
sparkfun/SparkFun u-blox GNSS Arduino Library@2.2.29
|
||||
stevemarple/MicroNMEA@2.0.6
|
||||
|
||||
[SenseCap_Solar_companion_radio_ble]
|
||||
adafruit/Adafruit AHTX0@2.0.6
|
||||
adafruit/Adafruit BME280 Library@2.3.0
|
||||
adafruit/Adafruit BME680 Library@2.0.6
|
||||
adafruit/Adafruit BMP085 Library@1.2.4
|
||||
adafruit/Adafruit BMP280 Library@2.6.8
|
||||
adafruit/Adafruit BMP3XX Library@2.1.6
|
||||
adafruit/Adafruit BusIO@1.17.4
|
||||
adafruit/Adafruit GFX Library@2.0.0
|
||||
adafruit/Adafruit INA219@1.2.3
|
||||
adafruit/Adafruit INA260 Library@1.5.4
|
||||
adafruit/Adafruit INA3221 Library@1.0.3
|
||||
adafruit/Adafruit MLX90614 Library@2.1.7
|
||||
adafruit/Adafruit NeoPixel@1.15.6
|
||||
adafruit/Adafruit SH110X@2.1.15
|
||||
adafruit/Adafruit SHTC3 Library@1.0.2
|
||||
adafruit/Adafruit SSD1306@2.5.18
|
||||
adafruit/Adafruit Unified Sensor@1.1.15
|
||||
adafruit/Adafruit_VL53L0X@1.2.5
|
||||
adafruit/RTClib@2.1.4
|
||||
arduino-libraries/Arduino_LPS22HB@1.0.3
|
||||
bblanchon/ArduinoJson@7.4.3
|
||||
densaugeo/base64@1.4.0
|
||||
electroniccats/CayenneLPP@1.6.1
|
||||
https://github.com/oltaco/CustomLFS#b3928ea2d0f46c2533e901c43f471a081c503a3c
|
||||
jgromes/RadioLib@7.8.1
|
||||
melopero/Melopero RV3028@1.2.0
|
||||
robtillaart/INA226@0.6.6
|
||||
rweather/Crypto@0.4.0
|
||||
sensirion/Sensirion Core@0.7.3
|
||||
sensirion/Sensirion I2C SHT4x@1.1.2
|
||||
stevemarple/MicroNMEA@2.0.6
|
||||
|
||||
[SenseCap_Solar_repeater]
|
||||
adafruit/Adafruit AHTX0@2.0.6
|
||||
adafruit/Adafruit BME280 Library@2.3.0
|
||||
adafruit/Adafruit BME680 Library@2.0.6
|
||||
adafruit/Adafruit BMP085 Library@1.2.4
|
||||
adafruit/Adafruit BMP280 Library@2.6.8
|
||||
adafruit/Adafruit BMP3XX Library@2.1.6
|
||||
adafruit/Adafruit BusIO@1.17.4
|
||||
adafruit/Adafruit GFX Library@1.13.0
|
||||
adafruit/Adafruit GFX Library@2.0.0
|
||||
adafruit/Adafruit INA219@1.2.3
|
||||
adafruit/Adafruit INA260 Library@1.5.4
|
||||
adafruit/Adafruit INA3221 Library@1.0.3
|
||||
adafruit/Adafruit MLX90614 Library@2.1.7
|
||||
adafruit/Adafruit NeoPixel@1.15.6
|
||||
adafruit/Adafruit SH110X@2.1.15
|
||||
adafruit/Adafruit SHTC3 Library@1.0.2
|
||||
adafruit/Adafruit SSD1306@2.5.18
|
||||
adafruit/Adafruit Unified Sensor@1.1.15
|
||||
adafruit/Adafruit_VL53L0X@1.2.5
|
||||
adafruit/RTClib@2.1.4
|
||||
arduino-libraries/Arduino_LPS22HB@1.0.3
|
||||
bblanchon/ArduinoJson@7.4.3
|
||||
electroniccats/CayenneLPP@1.6.1
|
||||
https://github.com/jgromes/RadioLib.git#6d8934836678d8894e3d556550475b37dce3e2b6
|
||||
https://github.com/oltaco/CustomLFS#b3928ea2d0f46c2533e901c43f471a081c503a3c
|
||||
melopero/Melopero RV3028@1.2.0
|
||||
robtillaart/INA226@0.6.6
|
||||
rweather/Crypto@0.4.0
|
||||
sensirion/Sensirion Core@0.7.3
|
||||
sensirion/Sensirion I2C SHT4x@1.1.2
|
||||
stevemarple/MicroNMEA@2.0.6
|
||||
|
||||
[Xiao_nrf52_companion_radio_ble]
|
||||
adafruit/Adafruit AHTX0@2.0.6
|
||||
adafruit/Adafruit BME280 Library@2.3.0
|
||||
adafruit/Adafruit BME680 Library@2.0.6
|
||||
adafruit/Adafruit BMP085 Library@1.2.4
|
||||
adafruit/Adafruit BMP280 Library@2.6.8
|
||||
adafruit/Adafruit BMP3XX Library@2.1.6
|
||||
adafruit/Adafruit BusIO@1.17.4
|
||||
adafruit/Adafruit GFX Library@2.0.0
|
||||
adafruit/Adafruit INA219@1.2.3
|
||||
adafruit/Adafruit INA260 Library@1.5.4
|
||||
adafruit/Adafruit INA3221 Library@1.0.3
|
||||
adafruit/Adafruit MLX90614 Library@2.1.7
|
||||
adafruit/Adafruit NeoPixel@1.15.6
|
||||
adafruit/Adafruit SH110X@2.1.15
|
||||
adafruit/Adafruit SHTC3 Library@1.0.2
|
||||
adafruit/Adafruit SSD1306@2.5.18
|
||||
adafruit/Adafruit Unified Sensor@1.1.15
|
||||
adafruit/Adafruit_VL53L0X@1.2.5
|
||||
adafruit/RTClib@2.1.4
|
||||
arduino-libraries/Arduino_LPS22HB@1.0.3
|
||||
bblanchon/ArduinoJson@7.4.3
|
||||
densaugeo/base64@1.4.0
|
||||
electroniccats/CayenneLPP@1.6.1
|
||||
https://github.com/oltaco/CustomLFS#b3928ea2d0f46c2533e901c43f471a081c503a3c
|
||||
jgromes/RadioLib@7.8.1
|
||||
melopero/Melopero RV3028@1.2.0
|
||||
robtillaart/INA226@0.6.6
|
||||
rweather/Crypto@0.4.0
|
||||
sensirion/Sensirion Core@0.7.3
|
||||
sensirion/Sensirion I2C SHT4x@1.1.2
|
||||
stevemarple/MicroNMEA@2.0.6
|
||||
|
||||
[Xiao_nrf52_repeater]
|
||||
adafruit/Adafruit AHTX0@2.0.6
|
||||
adafruit/Adafruit BME280 Library@2.3.0
|
||||
adafruit/Adafruit BME680 Library@2.0.6
|
||||
adafruit/Adafruit BMP085 Library@1.2.4
|
||||
adafruit/Adafruit BMP280 Library@2.6.8
|
||||
adafruit/Adafruit BMP3XX Library@2.1.6
|
||||
adafruit/Adafruit BusIO@1.17.4
|
||||
adafruit/Adafruit GFX Library@2.0.0
|
||||
adafruit/Adafruit INA219@1.2.3
|
||||
adafruit/Adafruit INA260 Library@1.5.4
|
||||
adafruit/Adafruit INA3221 Library@1.0.3
|
||||
adafruit/Adafruit MLX90614 Library@2.1.7
|
||||
adafruit/Adafruit NeoPixel@1.15.6
|
||||
adafruit/Adafruit SH110X@2.1.15
|
||||
adafruit/Adafruit SHTC3 Library@1.0.2
|
||||
adafruit/Adafruit SSD1306@2.5.18
|
||||
adafruit/Adafruit Unified Sensor@1.1.15
|
||||
adafruit/Adafruit_VL53L0X@1.2.5
|
||||
adafruit/RTClib@2.1.4
|
||||
arduino-libraries/Arduino_LPS22HB@1.0.3
|
||||
bblanchon/ArduinoJson@7.4.3
|
||||
electroniccats/CayenneLPP@1.6.1
|
||||
https://github.com/oltaco/CustomLFS#b3928ea2d0f46c2533e901c43f471a081c503a3c
|
||||
jgromes/RadioLib@7.8.1
|
||||
melopero/Melopero RV3028@1.2.0
|
||||
robtillaart/INA226@0.6.6
|
||||
rweather/Crypto@0.4.0
|
||||
sensirion/Sensirion Core@0.7.3
|
||||
sensirion/Sensirion I2C SHT4x@1.1.2
|
||||
stevemarple/MicroNMEA@2.0.6
|
||||
|
||||
[Xiao_nrf52_room_server]
|
||||
adafruit/Adafruit AHTX0@2.0.6
|
||||
adafruit/Adafruit BME280 Library@2.3.0
|
||||
adafruit/Adafruit BME680 Library@2.0.6
|
||||
adafruit/Adafruit BMP085 Library@1.2.4
|
||||
adafruit/Adafruit BMP280 Library@2.6.8
|
||||
adafruit/Adafruit BMP3XX Library@2.1.6
|
||||
adafruit/Adafruit BusIO@1.17.4
|
||||
adafruit/Adafruit GFX Library@2.0.0
|
||||
adafruit/Adafruit INA219@1.2.3
|
||||
adafruit/Adafruit INA260 Library@1.5.4
|
||||
adafruit/Adafruit INA3221 Library@1.0.3
|
||||
adafruit/Adafruit MLX90614 Library@2.1.7
|
||||
adafruit/Adafruit NeoPixel@1.15.6
|
||||
adafruit/Adafruit SH110X@2.1.15
|
||||
adafruit/Adafruit SHTC3 Library@1.0.2
|
||||
adafruit/Adafruit SSD1306@2.5.18
|
||||
adafruit/Adafruit Unified Sensor@1.1.15
|
||||
adafruit/Adafruit_VL53L0X@1.2.5
|
||||
adafruit/RTClib@2.1.4
|
||||
arduino-libraries/Arduino_LPS22HB@1.0.3
|
||||
bblanchon/ArduinoJson@7.4.3
|
||||
electroniccats/CayenneLPP@1.6.1
|
||||
https://github.com/oltaco/CustomLFS#b3928ea2d0f46c2533e901c43f471a081c503a3c
|
||||
jgromes/RadioLib@7.8.1
|
||||
melopero/Melopero RV3028@1.2.0
|
||||
robtillaart/INA226@0.6.6
|
||||
rweather/Crypto@0.4.0
|
||||
sensirion/Sensirion Core@0.7.3
|
||||
sensirion/Sensirion I2C SHT4x@1.1.2
|
||||
stevemarple/MicroNMEA@2.0.6
|
||||
|
||||
[Xiao_nrf52_sensor]
|
||||
adafruit/Adafruit AHTX0@2.0.6
|
||||
adafruit/Adafruit BME280 Library@2.3.0
|
||||
adafruit/Adafruit BME680 Library@2.0.6
|
||||
adafruit/Adafruit BMP085 Library@1.2.4
|
||||
adafruit/Adafruit BMP280 Library@2.6.8
|
||||
adafruit/Adafruit BMP3XX Library@2.1.6
|
||||
adafruit/Adafruit BusIO@1.17.4
|
||||
adafruit/Adafruit GFX Library@2.0.0
|
||||
adafruit/Adafruit INA219@1.2.3
|
||||
adafruit/Adafruit INA260 Library@1.5.4
|
||||
adafruit/Adafruit INA3221 Library@1.0.3
|
||||
adafruit/Adafruit MLX90614 Library@2.1.7
|
||||
adafruit/Adafruit NeoPixel@1.15.6
|
||||
adafruit/Adafruit SH110X@2.1.15
|
||||
adafruit/Adafruit SHTC3 Library@1.0.2
|
||||
adafruit/Adafruit SSD1306@2.5.18
|
||||
adafruit/Adafruit Unified Sensor@1.1.15
|
||||
adafruit/Adafruit_VL53L0X@1.2.5
|
||||
adafruit/RTClib@2.1.4
|
||||
arduino-libraries/Arduino_LPS22HB@1.0.3
|
||||
bblanchon/ArduinoJson@7.4.3
|
||||
electroniccats/CayenneLPP@1.6.1
|
||||
https://github.com/oltaco/CustomLFS#b3928ea2d0f46c2533e901c43f471a081c503a3c
|
||||
jgromes/RadioLib@7.8.1
|
||||
melopero/Melopero RV3028@1.2.0
|
||||
robtillaart/INA226@0.6.6
|
||||
rweather/Crypto@0.4.0
|
||||
sensirion/Sensirion Core@0.7.3
|
||||
sensirion/Sensirion I2C SHT4x@1.1.2
|
||||
stevemarple/MicroNMEA@2.0.6
|
||||
|
||||
[t1000e_companion_radio_ble]
|
||||
adafruit/Adafruit BusIO@1.17.4
|
||||
adafruit/RTClib@2.1.4
|
||||
bblanchon/ArduinoJson@7.4.3
|
||||
densaugeo/base64@1.4.0
|
||||
electroniccats/CayenneLPP@1.6.1
|
||||
end2endzone/NonBlockingRTTTL@1.4.0
|
||||
https://github.com/oltaco/CustomLFS#b3928ea2d0f46c2533e901c43f471a081c503a3c
|
||||
jgromes/RadioLib@7.8.1
|
||||
melopero/Melopero RV3028@1.2.0
|
||||
rweather/Crypto@0.4.0
|
||||
stevemarple/MicroNMEA@2.0.6
|
||||
|
||||
[t1000e_repeater]
|
||||
adafruit/Adafruit BusIO@1.17.4
|
||||
adafruit/RTClib@2.1.4
|
||||
bblanchon/ArduinoJson@7.4.3
|
||||
electroniccats/CayenneLPP@1.6.1
|
||||
https://github.com/oltaco/CustomLFS#b3928ea2d0f46c2533e901c43f471a081c503a3c
|
||||
jgromes/RadioLib@7.8.1
|
||||
melopero/Melopero RV3028@1.2.0
|
||||
rweather/Crypto@0.4.0
|
||||
stevemarple/MicroNMEA@2.0.6
|
||||
+47
-6
@@ -6,6 +6,16 @@
|
||||
|
||||
#include <math.h>
|
||||
|
||||
#ifdef PWR_DUTY_INSTRUMENT
|
||||
// CUSTOM (TeTeHacko): bench instrument. Pure CPU time spent processing a received
|
||||
// packet (dedup + crypto + routing), independent of BLE/USB background wakes --
|
||||
// unlike the sleep-duty measure. This is the work a radio-side filter could skip
|
||||
// for a dropped packet. Printed by NRF52Board::sleep() (extern below).
|
||||
#include <Arduino.h>
|
||||
uint64_t g_pkt_proc_us = 0;
|
||||
uint32_t g_pkt_proc_count = 0;
|
||||
#endif
|
||||
|
||||
namespace mesh {
|
||||
|
||||
#define MAX_RX_DELAY_MILLIS 32000 // 32 seconds
|
||||
@@ -13,12 +23,13 @@ namespace mesh {
|
||||
#define MIN_TX_BUDGET_AIRTIME_DIV 2 // require at least 1/N of estimated airtime as budget before TX
|
||||
|
||||
#ifndef NOISE_FLOOR_CALIB_INTERVAL
|
||||
#define NOISE_FLOOR_CALIB_INTERVAL 2000 // 2 seconds
|
||||
#define NOISE_FLOOR_CALIB_INTERVAL 10000 // 10 seconds
|
||||
#endif
|
||||
|
||||
void Dispatcher::begin() {
|
||||
n_sent_flood = n_sent_direct = 0;
|
||||
n_recv_flood = n_recv_direct = 0;
|
||||
n_tx_start_fail = n_tx_timeout = 0;
|
||||
_err_flags = 0;
|
||||
radio_nonrx_start = _ms->getMillis();
|
||||
|
||||
@@ -118,9 +129,20 @@ void Dispatcher::loop() {
|
||||
MESH_DEBUG_PRINTLN("%s Dispatcher::loop(): WARNING: outbound packed send timed out!", getLogDateTime());
|
||||
|
||||
_radio->onSendFinished();
|
||||
logTxFail(outbound, 2 + outbound->getPathByteLen() + outbound->payload_len);
|
||||
|
||||
releasePacket(outbound); // return to pool
|
||||
// CUSTOM (TeTeHacko): the send-complete IRQ never arrived (SoftDevice/BLE
|
||||
// preemption can wedge the LoRa driver mid-TX). Requeue with a short
|
||||
// backoff instead of dropping -- a duplicate on air is harmless (hasSeen
|
||||
// dedup), a dropped direct forward is a black hole.
|
||||
n_tx_timeout++;
|
||||
_err_flags |= ERR_EVENT_TX_TIMEOUT;
|
||||
if (outbound->_tx_attempts < MESH_TX_RETRIES) {
|
||||
outbound->_tx_attempts++;
|
||||
_mgr->queueOutbound(outbound, 0, futureMillis(40 + 80 * outbound->_tx_attempts));
|
||||
} else {
|
||||
logTxFail(outbound, 2 + outbound->getPathByteLen() + outbound->payload_len);
|
||||
releasePacket(outbound); // return to pool
|
||||
}
|
||||
outbound = NULL;
|
||||
} else {
|
||||
return; // can't do any more radio activity until send is complete or timed out
|
||||
@@ -204,6 +226,8 @@ void Dispatcher::checkRecv() {
|
||||
} else {
|
||||
if (tryParsePacket(pkt, raw, len)) {
|
||||
pkt->_snr = _radio->getLastSNR() * 4.0f;
|
||||
pkt->_rssi = (int8_t)_radio->getLastRSSI();
|
||||
pkt->_tx_attempts = 0;
|
||||
score = _radio->packetScore(_radio->getLastSNR(), len);
|
||||
air_time = _radio->getEstAirtimeFor(len);
|
||||
rx_air_time += air_time;
|
||||
@@ -259,6 +283,9 @@ void Dispatcher::checkRecv() {
|
||||
}
|
||||
|
||||
void Dispatcher::processRecvPacket(Packet* pkt) {
|
||||
#ifdef PWR_DUTY_INSTRUMENT
|
||||
uint32_t _pwr_t0 = micros();
|
||||
#endif
|
||||
DispatcherAction action = onRecvPacket(pkt);
|
||||
if (action == ACTION_RELEASE) {
|
||||
_mgr->free(pkt);
|
||||
@@ -270,6 +297,10 @@ void Dispatcher::processRecvPacket(Packet* pkt) {
|
||||
|
||||
_mgr->queueOutbound(pkt, priority, futureMillis(_delay));
|
||||
}
|
||||
#ifdef PWR_DUTY_INSTRUMENT
|
||||
g_pkt_proc_us += (uint32_t)(micros() - _pwr_t0);
|
||||
g_pkt_proc_count++;
|
||||
#endif
|
||||
}
|
||||
|
||||
void Dispatcher::checkSend() {
|
||||
@@ -330,9 +361,18 @@ void Dispatcher::checkSend() {
|
||||
if (!success) {
|
||||
MESH_DEBUG_PRINTLN("%s Dispatcher::loop(): ERROR: send start failed!", getLogDateTime());
|
||||
|
||||
logTxFail(outbound, outbound->getRawLength());
|
||||
|
||||
releasePacket(outbound); // return to pool
|
||||
// CUSTOM (TeTeHacko): startTransmit() failing is usually transient
|
||||
// (SPI/BUSY hiccup while the SoftDevice services a BLE connection
|
||||
// event). Requeue with a short backoff instead of dropping.
|
||||
n_tx_start_fail++;
|
||||
_err_flags |= ERR_EVENT_TX_START_FAIL;
|
||||
if (outbound->_tx_attempts < MESH_TX_RETRIES) {
|
||||
outbound->_tx_attempts++;
|
||||
_mgr->queueOutbound(outbound, 0, futureMillis(40 + 80 * outbound->_tx_attempts));
|
||||
} else {
|
||||
logTxFail(outbound, outbound->getRawLength());
|
||||
releasePacket(outbound); // return to pool
|
||||
}
|
||||
outbound = NULL;
|
||||
return;
|
||||
}
|
||||
@@ -360,6 +400,7 @@ Packet* Dispatcher::obtainNewPacket() {
|
||||
} else {
|
||||
pkt->payload_len = pkt->path_len = 0;
|
||||
pkt->_snr = 0;
|
||||
pkt->_tx_attempts = 0;
|
||||
}
|
||||
return pkt;
|
||||
}
|
||||
|
||||
@@ -110,6 +110,17 @@ typedef uint32_t DispatcherAction;
|
||||
#define ERR_EVENT_FULL (1 << 0)
|
||||
#define ERR_EVENT_CAD_TIMEOUT (1 << 1)
|
||||
#define ERR_EVENT_STARTRX_TIMEOUT (1 << 2)
|
||||
#define ERR_EVENT_TX_START_FAIL (1 << 3) // CUSTOM (TeTeHacko): startSendRaw() returned error (radio busy/SPI hiccup)
|
||||
#define ERR_EVENT_TX_TIMEOUT (1 << 4) // CUSTOM (TeTeHacko): send-complete IRQ never came before outbound_expiry
|
||||
|
||||
// CUSTOM (TeTeHacko): how many times a failed TX (start fail or send timeout) is
|
||||
// requeued before the packet is finally dropped. Transient failures are common
|
||||
// when the nRF52 SoftDevice (BLE connection events) preempts the LoRa driver —
|
||||
// measured ~40 % direct-forward loss with an idle BLE connection. A short retry
|
||||
// converts those losses into ~100-300 ms of extra latency.
|
||||
#ifndef MESH_TX_RETRIES
|
||||
#define MESH_TX_RETRIES 3
|
||||
#endif
|
||||
#define ERR_EVENT_DIAG1 (1 << 8) // role-specific error flag
|
||||
|
||||
/**
|
||||
@@ -126,6 +137,7 @@ class Dispatcher {
|
||||
bool prev_isrecv_mode;
|
||||
uint32_t n_sent_flood, n_sent_direct;
|
||||
uint32_t n_recv_flood, n_recv_direct;
|
||||
uint32_t n_tx_start_fail, n_tx_timeout; // CUSTOM (TeTeHacko): TX failure tallies (see MESH_TX_RETRIES)
|
||||
unsigned long tx_budget_ms;
|
||||
unsigned long last_budget_update;
|
||||
unsigned long duty_cycle_window_ms;
|
||||
@@ -188,6 +200,8 @@ public:
|
||||
uint32_t getNumSentDirect() const { return n_sent_direct; }
|
||||
uint32_t getNumRecvFlood() const { return n_recv_flood; }
|
||||
uint32_t getNumRecvDirect() const { return n_recv_direct; }
|
||||
uint32_t getNumTxStartFail() const { return n_tx_start_fail; } // CUSTOM (TeTeHacko)
|
||||
uint32_t getNumTxTimeout() const { return n_tx_timeout; } // CUSTOM (TeTeHacko)
|
||||
void resetStats() {
|
||||
n_sent_flood = n_sent_direct = n_recv_flood = n_recv_direct = 0;
|
||||
_err_flags = 0;
|
||||
|
||||
+74
-19
@@ -11,9 +11,12 @@ void Mesh::loop() {
|
||||
Dispatcher::loop();
|
||||
}
|
||||
|
||||
bool Mesh::allowPacketForward(const mesh::Packet* packet) {
|
||||
bool Mesh::allowPacketForward(const mesh::Packet* packet) {
|
||||
return false; // by default, Transport NOT enabled
|
||||
}
|
||||
bool Mesh::takeForwardingRateLimit(const mesh::Packet* packet) {
|
||||
return true; // by default, rate limiting is not implemented
|
||||
}
|
||||
uint32_t Mesh::getRetransmitDelay(const mesh::Packet* packet) {
|
||||
uint32_t t = (_radio->getEstAirtimeFor(packet->getRawLength()) * 52 / 50) / 2;
|
||||
|
||||
@@ -41,6 +44,10 @@ int Mesh::searchChannelsByHash(const uint8_t* hash, GroupChannel channels[], int
|
||||
DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
|
||||
if (pkt->isRouteDirect() && pkt->getPayloadType() == PAYLOAD_TYPE_TRACE) {
|
||||
if (pkt->path_len < MAX_PATH_SIZE) {
|
||||
// TRACE header is trace_tag(4)+auth_code(4)+flags(1) = 9 bytes. Without this
|
||||
// guard a crafted short TRACE (payload_len < 9) underflows `len` below to a
|
||||
// large value and steers the isHashMatch() read past the payload buffer.
|
||||
if (pkt->payload_len < 9) return ACTION_RELEASE;
|
||||
uint8_t i = 0;
|
||||
uint32_t trace_tag;
|
||||
memcpy(&trace_tag, &pkt->payload[i], 4); i += 4;
|
||||
@@ -55,7 +62,9 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
|
||||
uint16_t offset = (uint16_t)pkt->path_len << path_sz;
|
||||
if (offset >= len) { // TRACE has reached end of given path
|
||||
onTraceRecv(pkt, trace_tag, auth_code, flags, pkt->path, &pkt->payload[i], len);
|
||||
} else if (self_id.isHashMatch(&pkt->payload[i + offset], 1 << path_sz) && allowPacketForward(pkt) && !_tables->wasSeen(pkt)) {
|
||||
} else if ((size_t)i + offset + (1u << path_sz) <= pkt->payload_len
|
||||
&& self_id.isHashMatch(&pkt->payload[i + offset], 1 << path_sz) && allowPacketForward(pkt) && !_tables->wasSeen(pkt)
|
||||
&& takeForwardingRateLimit(pkt)) {
|
||||
_tables->markSeen(pkt);
|
||||
// append SNR (Not hash!)
|
||||
pkt->path[pkt->path_len++] = (int8_t) (pkt->getSNR()*4);
|
||||
@@ -99,11 +108,11 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
|
||||
return ACTION_RELEASE;
|
||||
}
|
||||
|
||||
if (!_tables->wasSeen(pkt)) {
|
||||
if (!_tables->wasSeen(pkt) && takeForwardingRateLimit(pkt)) {
|
||||
_tables->markSeen(pkt);
|
||||
removeSelfFromPath(pkt);
|
||||
|
||||
return ACTION_RETRANSMIT_DELAYED(0, d); // Routed traffic is HIGHEST priority
|
||||
return ACTION_RETRANSMIT_DELAYED(0, d); // Routed traffic is HIGHEST priority
|
||||
}
|
||||
}
|
||||
return ACTION_RELEASE; // this node is NOT the next hop (OR this packet has already been forwarded), so discard.
|
||||
@@ -167,14 +176,20 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
|
||||
uint8_t hash_size = (path_len >> 6) + 1;
|
||||
uint8_t hash_count = path_len & 63;
|
||||
uint8_t* path = &data[k]; k += hash_size*hash_count;
|
||||
uint8_t extra_type = data[k++] & 0x0F; // upper 4 bits reserved for future use
|
||||
uint8_t* extra = &data[k];
|
||||
uint8_t extra_len = len - k; // remainder of packet (may be padded with zeroes!)
|
||||
if (onPeerPathRecv(pkt, j, secret, path, path_len, extra_type, extra, extra_len)) {
|
||||
if (pkt->isRouteFlood()) {
|
||||
// send a reciprocal return path to sender, but send DIRECTLY!
|
||||
mesh::Packet* rpath = createPathReturn(&src_hash, secret, pkt->path, pkt->path_len, 0, NULL, 0);
|
||||
if (rpath) sendDirect(rpath, path, path_len, 500);
|
||||
// path_len comes from the (decrypted) payload and is otherwise unchecked:
|
||||
// without this guard `k` can jump past the `data` buffer (data[k] OOB read)
|
||||
// and `extra_len = len - k` underflows. Require a valid path length and that
|
||||
// the path + trailing extra_type byte fit within the decrypted length.
|
||||
if (Packet::isValidPathLen(path_len) && k < len) {
|
||||
uint8_t extra_type = data[k++] & 0x0F; // upper 4 bits reserved for future use
|
||||
uint8_t* extra = &data[k];
|
||||
uint8_t extra_len = len - k; // remainder of packet (may be padded with zeroes!)
|
||||
if (onPeerPathRecv(pkt, j, secret, path, path_len, extra_type, extra, extra_len)) {
|
||||
if (pkt->isRouteFlood()) {
|
||||
// send a reciprocal return path to sender, but send DIRECTLY!
|
||||
mesh::Packet* rpath = createPathReturn(&src_hash, secret, pkt->path, pkt->path_len, 0, NULL, 0);
|
||||
if (rpath) sendDirect(rpath, path, path_len, 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -344,7 +359,8 @@ void Mesh::removeSelfFromPath(Packet* pkt) {
|
||||
DispatcherAction Mesh::routeRecvPacket(Packet* packet) {
|
||||
uint8_t n = packet->getPathHashCount();
|
||||
if (packet->isRouteFlood() && !packet->isMarkedDoNotRetransmit()
|
||||
&& (n + 1)*packet->getPathHashSize() <= MAX_PATH_SIZE && allowPacketForward(packet)) {
|
||||
&& (n + 1)*packet->getPathHashSize() <= MAX_PATH_SIZE && allowPacketForward(packet)
|
||||
&& takeForwardingRateLimit(packet)) {
|
||||
// append this node's hash to 'path'
|
||||
self_id.copyHashTo(&packet->path[n * packet->getPathHashSize()], packet->getPathHashSize());
|
||||
packet->setPathHashCount(n + 1);
|
||||
@@ -377,7 +393,7 @@ DispatcherAction Mesh::forwardMultipartDirect(Packet* pkt, uint32_t delay_millis
|
||||
}
|
||||
|
||||
void Mesh::routeDirectRecvAcks(Packet* packet, uint32_t delay_millis) {
|
||||
if (!packet->isMarkedDoNotRetransmit()) {
|
||||
if (!packet->isMarkedDoNotRetransmit() && takeForwardingRateLimit(packet)) {
|
||||
uint8_t extra = getExtraAckTransmitCount();
|
||||
while (extra > 0) {
|
||||
auto a1 = createMultiAck(packet->payload, packet->payload_len, extra);
|
||||
@@ -639,6 +655,7 @@ void Mesh::sendFlood(Packet* packet, uint32_t delay_millis, uint8_t path_hash_si
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::sendFlood(): TRACE type not suspported", getLogDateTime());
|
||||
return;
|
||||
}
|
||||
if (path_hash_size == 0) path_hash_size = getSelfPathHashSize();
|
||||
if (path_hash_size == 0 || path_hash_size > 3) {
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::sendFlood(): invalid path_hash_size", getLogDateTime());
|
||||
return;
|
||||
@@ -666,6 +683,7 @@ void Mesh::sendFlood(Packet* packet, uint16_t* transport_codes, uint32_t delay_m
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::sendFlood(): TRACE type not suspported", getLogDateTime());
|
||||
return;
|
||||
}
|
||||
if (path_hash_size == 0) path_hash_size = getSelfPathHashSize();
|
||||
if (path_hash_size == 0 || path_hash_size > 3) {
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::sendFlood(): invalid path_hash_size", getLogDateTime());
|
||||
return;
|
||||
@@ -690,13 +708,36 @@ void Mesh::sendFlood(Packet* packet, uint16_t* transport_codes, uint32_t delay_m
|
||||
sendPacket(packet, pri, delay_millis);
|
||||
}
|
||||
|
||||
void Mesh::sendDirect(Packet* packet, const uint8_t* path, uint8_t path_len, uint32_t delay_millis) {
|
||||
void Mesh::sendDirect(Packet* packet, const uint8_t* path, uint8_t path_len, uint32_t delay_millis, uint8_t path_hash_size) {
|
||||
packet->header &= ~PH_ROUTE_MASK;
|
||||
packet->header |= ROUTE_TYPE_DIRECT;
|
||||
|
||||
if (path_hash_size == 0) path_hash_size = getSelfPathHashSize();
|
||||
|
||||
uint8_t pri;
|
||||
if (packet->getPayloadType() == PAYLOAD_TYPE_TRACE) { // TRACE packets are different
|
||||
// for TRACE packets, path is appended to end of PAYLOAD. (path is used for SNR's)
|
||||
//
|
||||
// CUSTOM (TeTeHacko): a TRACE path is NOT capped at MAX_PATH_SIZE (see the note
|
||||
// below), so this append has to be checked against the payload buffer itself.
|
||||
// The companion guard on CMD_SEND_TRACE_PATH lets path_len reach 178, and a
|
||||
// TRACE header is 9 bytes: 9+176 lands one byte past payload[184]. Measured on
|
||||
// the host over all 194 path_len/path_sz combinations the guard admits -- two
|
||||
// of them write past the end and demonstrably clobber `_snr`, the member that
|
||||
// happens to sit right after the array. Those packets are then dropped by
|
||||
// sendPacket() for exceeding the MTU, which is why nothing ever looked wrong
|
||||
// from the outside. It is still a write out of bounds.
|
||||
//
|
||||
// Same fix as upstream PR #1662 (weebl2000), open and unmerged since Feb 2026.
|
||||
// Its second half -- guarding the non-TRACE branch on path_len > MAX_PATH_SIZE
|
||||
// -- is redundant here: that path goes through Packet::copyPath/writePath,
|
||||
// which already refuses to write more than MAX_PATH_SIZE.
|
||||
if ((size_t)packet->payload_len + path_len > sizeof(packet->payload)) {
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::sendDirect(): TRACE path too long, payload_len=%d path_len=%d",
|
||||
getLogDateTime(), (int)packet->payload_len, (int)path_len);
|
||||
_mgr->free(packet);
|
||||
return;
|
||||
}
|
||||
memcpy(&packet->payload[packet->payload_len], path, path_len); // NOTE: path_len here can be > 64, and NOT in the new scheme
|
||||
packet->payload_len += path_len;
|
||||
|
||||
@@ -704,6 +745,12 @@ void Mesh::sendDirect(Packet* packet, const uint8_t* path, uint8_t path_len, uin
|
||||
pri = 5; // maybe make this configurable
|
||||
} else {
|
||||
packet->path_len = Packet::copyPath(packet->path, path, path_len);
|
||||
// An empty path has no hash-size bits of its own to preserve, and a bare 0 decodes as
|
||||
// 1 byte. Zero-hop DIRECT is the common case for a neighbour reply, so without this a
|
||||
// 2-byte node declares 1 byte on every such reply.
|
||||
if (packet->getPathHashCount() == 0) {
|
||||
packet->setPathHashSizeAndCount(path_hash_size, 0);
|
||||
}
|
||||
if (packet->getPayloadType() == PAYLOAD_TYPE_PATH) {
|
||||
pri = 1; // slightly less priority
|
||||
} else {
|
||||
@@ -714,24 +761,32 @@ void Mesh::sendDirect(Packet* packet, const uint8_t* path, uint8_t path_len, uin
|
||||
sendPacket(packet, pri, delay_millis);
|
||||
}
|
||||
|
||||
void Mesh::sendZeroHop(Packet* packet, uint32_t delay_millis) {
|
||||
void Mesh::sendZeroHop(Packet* packet, uint32_t delay_millis, uint8_t path_hash_size) {
|
||||
packet->header &= ~PH_ROUTE_MASK;
|
||||
packet->header |= ROUTE_TYPE_DIRECT;
|
||||
|
||||
packet->path_len = 0; // path_len of zero means Zero Hop
|
||||
if (path_hash_size == 0) path_hash_size = getSelfPathHashSize();
|
||||
|
||||
// Zero Hop = nulový počet hopů. POZOR, dřív tu bylo `packet->path_len = 0`,
|
||||
// což vynulovalo CELÝ bajt — a v jeho horních dvou bitech bydlí šířka hashe
|
||||
// (Packet.h:85). Každý zerohop paket proto hlásil 1 B bez ohledu na
|
||||
// nastavení uzlu a v analyzerech kreslil dvoubajtový uzel jako jednobajtový.
|
||||
packet->setPathHashSizeAndCount(path_hash_size, 0);
|
||||
|
||||
_tables->markSeen(packet); // mark this packet as already sent in case it is rebroadcast back to us
|
||||
|
||||
sendPacket(packet, 0, delay_millis);
|
||||
}
|
||||
|
||||
void Mesh::sendZeroHop(Packet* packet, uint16_t* transport_codes, uint32_t delay_millis) {
|
||||
void Mesh::sendZeroHop(Packet* packet, uint16_t* transport_codes, uint32_t delay_millis, uint8_t path_hash_size) {
|
||||
packet->header &= ~PH_ROUTE_MASK;
|
||||
packet->header |= ROUTE_TYPE_TRANSPORT_DIRECT;
|
||||
|
||||
if (path_hash_size == 0) path_hash_size = getSelfPathHashSize();
|
||||
packet->transport_codes[0] = transport_codes[0];
|
||||
packet->transport_codes[1] = transport_codes[1];
|
||||
|
||||
packet->path_len = 0; // path_len of zero means Zero Hop
|
||||
packet->setPathHashSizeAndCount(path_hash_size, 0); // viz komentář výš
|
||||
|
||||
_tables->markSeen(packet); // mark this packet as already sent in case it is rebroadcast back to us
|
||||
|
||||
|
||||
+32
-5
@@ -56,6 +56,14 @@ protected:
|
||||
*/
|
||||
virtual bool allowPacketForward(const Packet* packet);
|
||||
|
||||
/**
|
||||
* \brief Takes a token from the rate-limiter, deciding whether this packet should be forwarded.
|
||||
* May CONSUME limiter state, so callers keep it as the LAST condition of a forward decision
|
||||
* and call it at most once per packet. (CUSTOM TeTeHacko: port of upstream proposal #1502.)
|
||||
* \returns true, if the packet should be forwarded
|
||||
*/
|
||||
virtual bool takeForwardingRateLimit(const Packet* packet);
|
||||
|
||||
/**
|
||||
* \returns number of milliseconds delay to apply to retransmitting the given packet.
|
||||
*/
|
||||
@@ -71,6 +79,17 @@ protected:
|
||||
*/
|
||||
virtual uint8_t getExtraAckTransmitCount() const;
|
||||
|
||||
/**
|
||||
* \brief Width (in bytes) of the path hashes this node writes into packets it originates.
|
||||
*
|
||||
* Sender-chosen, so it must come from this node's own prefs. The base class has no prefs
|
||||
* and returns the protocol minimum; firmwares with a NodePrefs override it. Used whenever
|
||||
* a send*() caller does not pass an explicit width.
|
||||
*
|
||||
* \returns 1, 2 or 3
|
||||
*/
|
||||
virtual uint8_t getSelfPathHashSize() const { return 1; }
|
||||
|
||||
/**
|
||||
* \brief Perform search of local DB of peers/contacts.
|
||||
* \returns Number of peers with matching hash
|
||||
@@ -199,29 +218,37 @@ public:
|
||||
/**
|
||||
* \brief send a locally-generated Packet with flood routing
|
||||
*/
|
||||
void sendFlood(Packet* packet, uint32_t delay_millis=0, uint8_t path_hash_size=1);
|
||||
void sendFlood(Packet* packet, uint32_t delay_millis=0, uint8_t path_hash_size=0);
|
||||
|
||||
/**
|
||||
* \brief send a locally-generated Packet with flood routing
|
||||
* \param transport_codes array of 2 codes to attach to packet
|
||||
*/
|
||||
void sendFlood(Packet* packet, uint16_t* transport_codes, uint32_t delay_millis=0, uint8_t path_hash_size=1);
|
||||
void sendFlood(Packet* packet, uint16_t* transport_codes, uint32_t delay_millis=0, uint8_t path_hash_size=0);
|
||||
|
||||
/**
|
||||
* \brief send a locally-generated Packet with Direct routing
|
||||
*
|
||||
* `path_len` is the ENCODED path byte (hash-size bits + hop count), so a non-empty path
|
||||
* carries its own width across unchanged. An EMPTY path has no width to carry, and a bare
|
||||
* 0 decodes as 1 byte -- which is why zero-hop replies used to declare 1 B on a 2 B node.
|
||||
* `path_hash_size` (0 = this node's prefs) fills that gap.
|
||||
*/
|
||||
void sendDirect(Packet* packet, const uint8_t* path, uint8_t path_len, uint32_t delay_millis=0);
|
||||
void sendDirect(Packet* packet, const uint8_t* path, uint8_t path_len, uint32_t delay_millis=0, uint8_t path_hash_size=0);
|
||||
|
||||
/**
|
||||
* \brief send a locally-generated Packet to just neighbor nodes (zero hops)
|
||||
*/
|
||||
void sendZeroHop(Packet* packet, uint32_t delay_millis=0);
|
||||
// `path_hash_size` tu je ze stejného důvodu jako u sendFlood: zerohop paket
|
||||
// sice cestu nenese, ale ta šířka je v hlavičce a analyzery z ní odvozují,
|
||||
// na kolika bajtech uzel jede. Bez toho parametru hlásí každý zerohop 1 B.
|
||||
void sendZeroHop(Packet* packet, uint32_t delay_millis=0, uint8_t path_hash_size=0);
|
||||
|
||||
/**
|
||||
* \brief send a locally-generated Packet to just neighbor nodes (zero hops), with specific transport codes
|
||||
* \param transport_codes array of 2 codes to attach to packet
|
||||
*/
|
||||
void sendZeroHop(Packet* packet, uint16_t* transport_codes, uint32_t delay_millis=0);
|
||||
void sendZeroHop(Packet* packet, uint16_t* transport_codes, uint32_t delay_millis=0, uint8_t path_hash_size=0);
|
||||
|
||||
};
|
||||
|
||||
|
||||
@@ -92,6 +92,26 @@ public:
|
||||
virtual void loop() { /* no op */ }
|
||||
};
|
||||
|
||||
// CUSTOM (TeTeHacko): the time a clock with no other source comes up at.
|
||||
//
|
||||
// tools/build_version.py injects FIRMWARE_BUILD_EPOCH = the moment of compile, so
|
||||
// a freshly flashed board is right to within "time since build" -- seconds on the
|
||||
// bench -- with no GPS, no I2C RTC, nothing carrying a correct time on air and no
|
||||
// host attached. Without it the value is upstream's hardcoded 15 May 2024, which
|
||||
// is where bench-board sat for 811 days and every bench board for 812: the clock had
|
||||
// simply never been set, because setting it was a manual step.
|
||||
//
|
||||
// That is not cosmetic. Mesh.cpp stamps every advert this node transmits from the
|
||||
// RTC, and a receiver drops a stale timestamp as a replay (BaseChatMesh.cpp), so
|
||||
// a wrong clock turns into replies that vanish.
|
||||
//
|
||||
// The fallback is NOT optional: build_version.py is wired in through
|
||||
// ${stamped.extra_scripts}, which is nRF52-only and reaches 7 of the 16 envs in
|
||||
// platformio.local.ini. Upstream envs never define it and must keep compiling.
|
||||
#ifndef FIRMWARE_BUILD_EPOCH
|
||||
#define FIRMWARE_BUILD_EPOCH 1715770351 // 15 May 2024, 8:50pm
|
||||
#endif
|
||||
|
||||
/**
|
||||
* An abstraction of the device's Realtime Clock.
|
||||
*/
|
||||
|
||||
+22
-1
@@ -63,9 +63,30 @@ uint8_t Packet::writeTo(uint8_t dest[]) const {
|
||||
}
|
||||
|
||||
bool Packet::readFrom(const uint8_t src[], uint8_t len) {
|
||||
// CUSTOM (TeTeHacko): every field is bounds-checked against `len` BEFORE it is
|
||||
// read. Upstream reads the header, the transport codes, path_len and the whole
|
||||
// path first and only then asks whether any of it was actually there
|
||||
// (`if (i >= len)`), so a short frame is read past its end and the result is
|
||||
// thrown away afterwards.
|
||||
//
|
||||
// Measured with an ASAN harness that hands readFrom a heap buffer allocated to
|
||||
// exactly `len` bytes: 5 242 880 generated frames hit FOUR distinct
|
||||
// out-of-bounds reads (header, both transport codes, path_len, the path
|
||||
// memcpy). With these guards the same sweep is clean and accepts exactly the
|
||||
// same 1 351 424 frames -- the checks reject nothing that used to parse, they
|
||||
// only stop reading memory that was never received.
|
||||
//
|
||||
// On the device the source is Dispatcher's `raw[MAX_TRANS_UNIT+1]`, a 256-byte
|
||||
// stack buffer, and this reads at most ~70 bytes into it, so what it read was
|
||||
// leftovers from an earlier packet rather than memory outside the array. That
|
||||
// is why it never showed up as a crash -- and why this is hygiene, not a hole.
|
||||
//
|
||||
// Same fix as upstream PR #1666 (weebl2000), open and unmerged since Feb 2026.
|
||||
if (len < 2) return false; // at minimum: header + path_len
|
||||
uint8_t i = 0;
|
||||
header = src[i++];
|
||||
if (hasTransportCodes()) {
|
||||
if (i + 4 >= len) return false; // 4 transport bytes plus the path_len byte
|
||||
memcpy(&transport_codes[0], &src[i], 2); i += 2;
|
||||
memcpy(&transport_codes[1], &src[i], 2); i += 2;
|
||||
} else {
|
||||
@@ -75,9 +96,9 @@ bool Packet::readFrom(const uint8_t src[], uint8_t len) {
|
||||
if (!isValidPathLen(path_len)) return false; // bad encoding
|
||||
|
||||
uint8_t bl = getPathByteLen();
|
||||
if (i + bl >= len) return false; // path plus at least one payload byte must fit
|
||||
memcpy(path, &src[i], bl); i += bl;
|
||||
|
||||
if (i >= len) return false; // bad encoding
|
||||
payload_len = len - i;
|
||||
if (payload_len > sizeof(payload)) return false; // bad encoding
|
||||
memcpy(payload, &src[i], payload_len); //i += payload_len;
|
||||
|
||||
@@ -49,6 +49,8 @@ public:
|
||||
uint8_t path[MAX_PATH_SIZE];
|
||||
uint8_t payload[MAX_PACKET_PAYLOAD];
|
||||
int8_t _snr;
|
||||
int8_t _rssi; // CUSTOM (TeTeHacko): last-hop RSSI (dBm) captured at RX, for the passive mesh analyzer
|
||||
uint8_t _tx_attempts; // CUSTOM (TeTeHacko): failed TX tries so far (RAM only; Dispatcher requeues instead of dropping)
|
||||
|
||||
/**
|
||||
* \brief calculate the hash of payload + type
|
||||
@@ -90,6 +92,7 @@ public:
|
||||
bool isMarkedDoNotRetransmit() const { return header == 0xFF; }
|
||||
|
||||
float getSNR() const { return ((float)_snr) / 4.0f; }
|
||||
int getRSSI() const { return _rssi; }
|
||||
|
||||
/**
|
||||
* \returns the encoded/wire format length of this packet
|
||||
|
||||
@@ -31,6 +31,25 @@ public:
|
||||
|
||||
void setFeat1(uint16_t extra) { _extra1 = extra; }
|
||||
void setFeat2(uint16_t extra) { _extra2 = extra; }
|
||||
void setName(const char* name) { _name = name; }
|
||||
|
||||
/**
|
||||
* \brief bytes left for the name with the fields set so far.
|
||||
*
|
||||
* CUSTOM (TeTeHacko): the name is encoded last and clamped to whatever is
|
||||
* left, so anyone who wants to append to it (battery icon, see
|
||||
* helpers/BatteryIcon.h) has to know the remainder. Deriving it a second
|
||||
* time elsewhere goes stale the moment a field is added -- a copy in
|
||||
* BatteryIcon.h already missed FEAT1/FEAT2 and would have let the UTF-8
|
||||
* clamp cut a glyph in half.
|
||||
*/
|
||||
size_t nameBudget() const {
|
||||
size_t used = 1; // flags
|
||||
if (_has_loc) used += 8; // lat + lon
|
||||
if (_extra1) used += 2;
|
||||
if (_extra2) used += 2;
|
||||
return MAX_ADVERT_DATA_SIZE - used;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief encode the given advertisement data.
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
#pragma once
|
||||
|
||||
// CUSTOM (TeTeHacko): per-origin advert window, ported from DutchMeshCore's
|
||||
// AdvertLimiter (Dutch-MeshCore/MeshCore d26421b0, examples/simple_repeater/
|
||||
// AdvertLimiter.h; same MIT licence as this tree). Behaviour is theirs, names
|
||||
// and the eviction counter are ours.
|
||||
//
|
||||
// Each origin's flood advert is forwarded at most once per window, so a node
|
||||
// that re-advertises every minute (CP1 on the CZ mesh, since 30. 10. 2026:
|
||||
// a flood advert every 60 s, seen by 40-90 observers each) stops being
|
||||
// re-flooded by this repeater while it still stays reachable through it once
|
||||
// per window. FairnessLimiter's advert bucket cannot do that:
|
||||
// it is keyed on 7 bits of the key, so the chatty node and ~8 innocent ones
|
||||
// share a bucket, and loosening it for them lets the chatty one through.
|
||||
//
|
||||
// Origins are keyed on the first 4 bytes of the advert's public key (payload
|
||||
// starts with it). Fixed ring of ADVERT_WINDOW_SIZE entries: once full, the
|
||||
// oldest entry is overwritten -- that origin gets a free pass next time. RAM
|
||||
// only, so after a reboot every origin gets one free pass. Time is millis and
|
||||
// compared with unsigned subtraction, so it survives the 49-day wrap.
|
||||
// Header-only and dependency-free so it runs in the native tests.
|
||||
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
#ifndef ADVERT_WINDOW_SIZE
|
||||
#define ADVERT_WINDOW_SIZE 256 // 8 B each => 2 KB RAM
|
||||
#endif
|
||||
#define ADVERT_WINDOW_KEY_LEN 4
|
||||
#define ADVERT_WINDOW_MAX_HOURS 720 // 30 days; keeps hours*3600*1000 inside uint32
|
||||
|
||||
class AdvertWindow {
|
||||
struct Entry {
|
||||
uint8_t key[ADVERT_WINDOW_KEY_LEN];
|
||||
uint32_t seen_ms;
|
||||
};
|
||||
|
||||
Entry _cache[ADVERT_WINDOW_SIZE];
|
||||
uint16_t _count = 0; // entries in use
|
||||
uint16_t _head = 0; // next entry to overwrite once the cache is full
|
||||
uint16_t _hours = 0; // 0 = off
|
||||
uint32_t _evicted = 0; // origins forgotten because the ring was full
|
||||
|
||||
public:
|
||||
AdvertWindow() { memset(_cache, 0, sizeof(_cache)); }
|
||||
|
||||
void setHours(uint16_t hours) { _hours = hours > ADVERT_WINDOW_MAX_HOURS ? ADVERT_WINDOW_MAX_HOURS : hours; }
|
||||
uint16_t hours() const { return _hours; }
|
||||
int count() const { return _count; }
|
||||
int capacity() const { return ADVERT_WINDOW_SIZE; }
|
||||
// Non-zero = the ring is too small for the mesh: origins fall out before
|
||||
// their window ends and get a pass they should not have had.
|
||||
uint32_t evicted() const { return _evicted; }
|
||||
|
||||
void clear() { _count = 0; _head = 0; }
|
||||
|
||||
// True when the advert from `key` may be forwarded now (and records it),
|
||||
// false when the same origin already passed inside the current window.
|
||||
bool allow(const uint8_t* key, uint32_t now_ms) {
|
||||
if (_hours == 0 || key == nullptr) return true;
|
||||
|
||||
uint32_t window_ms = (uint32_t)_hours * 3600UL * 1000UL;
|
||||
|
||||
for (int i = 0; i < _count; i++) {
|
||||
Entry& e = _cache[i];
|
||||
if (memcmp(e.key, key, ADVERT_WINDOW_KEY_LEN) != 0) continue;
|
||||
if (now_ms - e.seen_ms < window_ms) return false; // unsigned: wrap-safe
|
||||
e.seen_ms = now_ms; // window elapsed: pass, and start a new window
|
||||
return true;
|
||||
}
|
||||
|
||||
Entry* e;
|
||||
if (_count < ADVERT_WINDOW_SIZE) {
|
||||
e = &_cache[_count++];
|
||||
} else {
|
||||
e = &_cache[_head]; // overwrite the oldest entry
|
||||
_head = (uint16_t)((_head + 1) % ADVERT_WINDOW_SIZE);
|
||||
_evicted++;
|
||||
}
|
||||
memcpy(e->key, key, ADVERT_WINDOW_KEY_LEN);
|
||||
e->seen_ms = now_ms;
|
||||
return true;
|
||||
}
|
||||
};
|
||||
@@ -3,19 +3,79 @@
|
||||
#include <Mesh.h>
|
||||
#include <Arduino.h>
|
||||
|
||||
#if defined(NRF52_PLATFORM) && !defined(NO_RETAINED_CLOCK)
|
||||
// CUSTOM (TeTeHacko): the wall clock survives a warm reset (`reboot`, `dfu`,
|
||||
// watchdog, reset pin) in RAM the startup code does not touch. NRF52Board.cpp
|
||||
// holds the record in .noinit -- placed by the linker after .bss, NOT at the top
|
||||
// of RAM: the Adafruit bootloader runs before every boot with its stack starting
|
||||
// at 0x20040000, and an earlier fixed record at 0x2003FFE0 came back overwritten
|
||||
// (7. 8. 2026). Approach from weebl2000/meshcore 9a561fd7.
|
||||
#define RETAINED_CLOCK_NOINIT 1
|
||||
extern "C" {
|
||||
extern uint32_t g_retained_clock[3]; // magic, time, ~time
|
||||
extern uint8_t g_retained_clock_status; // RetainedClockStatus, for the boot printout
|
||||
uint32_t readResetReason(void); // latched by the core's init()
|
||||
}
|
||||
#define RETAINED_CLOCK_MAGIC 0xC10CB0DE
|
||||
enum RetainedClockStatus { RC_NOT_YET, RC_EMPTY, RC_POWER_ON, RC_NOT_NEWER, RC_RESTORED };
|
||||
#endif
|
||||
|
||||
class VolatileRTCClock : public mesh::RTCClock {
|
||||
uint32_t base_time;
|
||||
uint64_t accumulator;
|
||||
unsigned long prev_millis;
|
||||
#ifdef RETAINED_CLOCK_NOINIT
|
||||
bool restore_pending = true;
|
||||
uint32_t last_saved = 0;
|
||||
|
||||
static void save(uint32_t t) {
|
||||
g_retained_clock[1] = t;
|
||||
g_retained_clock[2] = ~t;
|
||||
g_retained_clock[0] = RETAINED_CLOCK_MAGIC; // magic last: a reset mid-write leaves it invalid
|
||||
}
|
||||
// Not in the constructor: static constructors run before the core's init()
|
||||
// latches RESETREAS, so the reset reason would still read 0 there.
|
||||
void restoreOnce() {
|
||||
if (!restore_pending) return;
|
||||
restore_pending = false;
|
||||
uint32_t t = g_retained_clock[1];
|
||||
bool valid = g_retained_clock[0] == RETAINED_CLOCK_MAGIC && g_retained_clock[2] == ~t;
|
||||
if (!valid) { g_retained_clock_status = RC_EMPTY; return; }
|
||||
// No reset bit = power-on/brownout: RAM may still hold the record through a
|
||||
// short outage, but it is stale by however long the power was gone.
|
||||
if (readResetReason() == 0) { g_retained_clock_status = RC_POWER_ON; return; }
|
||||
if (t <= base_time + accumulator / 1000) { g_retained_clock_status = RC_NOT_NEWER; return; }
|
||||
base_time = t; accumulator = 0; prev_millis = millis();
|
||||
g_retained_clock_status = RC_RESTORED;
|
||||
}
|
||||
#endif
|
||||
public:
|
||||
VolatileRTCClock() { base_time = 1715770351; accumulator = 0; prev_millis = millis(); } // 15 May 2024, 8:50pm
|
||||
uint32_t getCurrentTime() override { return base_time + accumulator/1000; }
|
||||
void setCurrentTime(uint32_t time) override { base_time = time; accumulator = 0; prev_millis = millis(); }
|
||||
// FIRMWARE_BUILD_EPOCH = compile time when the build is stamped, else upstream's
|
||||
// 15 May 2024 literal. See the define in MeshCore.h for why this matters.
|
||||
VolatileRTCClock() { base_time = FIRMWARE_BUILD_EPOCH; accumulator = 0; prev_millis = millis(); }
|
||||
uint32_t getCurrentTime() override {
|
||||
#ifdef RETAINED_CLOCK_NOINIT
|
||||
restoreOnce();
|
||||
#endif
|
||||
return base_time + accumulator/1000;
|
||||
}
|
||||
void setCurrentTime(uint32_t time) override {
|
||||
base_time = time; accumulator = 0; prev_millis = millis();
|
||||
#ifdef RETAINED_CLOCK_NOINIT
|
||||
restore_pending = false; // an explicit set wins over whatever was retained
|
||||
save(time); last_saved = time;
|
||||
#endif
|
||||
}
|
||||
|
||||
void tick() override {
|
||||
unsigned long now = millis();
|
||||
accumulator += (now - prev_millis);
|
||||
prev_millis = now;
|
||||
#ifdef RETAINED_CLOCK_NOINIT
|
||||
restoreOnce();
|
||||
uint32_t t = base_time + accumulator / 1000;
|
||||
if (t != last_saved) { save(t); last_saved = t; }
|
||||
#endif
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -13,8 +13,12 @@ void ArduinoSerialInterface::disable() {
|
||||
_isEnabled = false;
|
||||
}
|
||||
|
||||
bool ArduinoSerialInterface::isConnected() const {
|
||||
return true; // no way of knowing, so assume yes
|
||||
bool ArduinoSerialInterface::isConnected() const {
|
||||
#if defined(NRF52_PLATFORM) || defined(ESP32_PLATFORM)
|
||||
return Serial; // operator bool() checks connection (USB CDC DTR, UART init)
|
||||
#else
|
||||
return true; // platforms without operator bool() on Serial have no way of knowing, so assume yes
|
||||
#endif
|
||||
}
|
||||
|
||||
bool ArduinoSerialInterface::isWriteBusy() const {
|
||||
|
||||
@@ -65,7 +65,12 @@ void BaseChatMesh::bootstrapRTCfromContacts() {
|
||||
latest = contacts[i].lastmod;
|
||||
}
|
||||
}
|
||||
if (latest != 0) {
|
||||
// CUSTOM (TeTeHacko): only ever forward. Upstream sets this unconditionally,
|
||||
// which was harmless while the clock started in 2024; ours starts at the build
|
||||
// epoch (or a time retained across a warm reset, read by getCurrentTime()
|
||||
// here), and an old contact would otherwise pull the clock back -- and, on
|
||||
// nRF52, cancel the retained-clock restore it ran ahead of.
|
||||
if (latest != 0 && latest + 1 > getRTCClock()->getCurrentTime()) {
|
||||
getRTCClock()->setCurrentTime(latest + 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,4 +19,18 @@ public:
|
||||
virtual bool isWriteBusy() const = 0;
|
||||
virtual size_t writeFrame(const uint8_t src[], size_t len) = 0;
|
||||
virtual size_t checkRecvFrame(uint8_t dest[]) = 0;
|
||||
|
||||
// Whether the transport carrying the current / most-recent frame is
|
||||
// authenticated. A single-transport interface is trusted by definition
|
||||
// (physically-connected USB, or a MITM-paired BLE link), so the default is
|
||||
// true. Multi-transport wrappers (e.g. SerialDualInterface) override this to
|
||||
// distinguish an unauthenticated local channel (USB) from a paired one, so
|
||||
// callers can gate sensitive commands (key export, PIN read/set).
|
||||
virtual bool isConnectionSecure() const { return true; }
|
||||
|
||||
// CUSTOM (TeTeHacko): a reply that must go back only over the transport the
|
||||
// request came on -- the private key, the BLE PIN. writeFrame() of a
|
||||
// multi-transport wrapper sends to every enabled transport, so a key exported
|
||||
// over paired BLE also went out on USB. Single transports: the same thing.
|
||||
virtual size_t writeReplyFrame(const uint8_t src[], size_t len) { return writeFrame(src, len); }
|
||||
};
|
||||
@@ -0,0 +1,161 @@
|
||||
#pragma once
|
||||
|
||||
// CUSTOM (TeTeHacko): battery state as an icon appended to the advertised
|
||||
// node name.
|
||||
//
|
||||
// Why at all: the node already reports its battery in telemetry, but only
|
||||
// someone who can log into it gets to read that. An icon in the advert reaches
|
||||
// everyone who hears the node, and costs a handful of bytes of app_data.
|
||||
//
|
||||
// The budget is tight. app_data is MAX_ADVERT_DATA_SIZE (32) bytes, of which
|
||||
// the flags take 1 and lat/lon another 8, leaving 23 bytes for the name on a
|
||||
// node that advertises its position. The whole indicator has to fit in what
|
||||
// the name leaves over -- for the deployed names that is 6 bytes.
|
||||
//
|
||||
// Which rules out emoji for the level. Unicode has exactly TWO battery emoji,
|
||||
// U+1F50B and U+1FAAB; there is no "half full" one, and at 4 bytes each a
|
||||
// sun-plus-battery pair costs 7 bytes, one too many. Block elements live in
|
||||
// the BMP, so they are 3 bytes rather than 4, and come in eight steps -- the
|
||||
// most states for the fewest bytes:
|
||||
//
|
||||
// marker U+2600 3 B sun, permanent -- "this is a solar node".
|
||||
// Deliberately WITHOUT the U+FE0F variation
|
||||
// selector, which costs 3 more bytes and buys
|
||||
// only a colour glyph.
|
||||
// level U+2581..88 3 B eight steps of charge
|
||||
//
|
||||
// Sampling rate is a non-issue: a solar node drifts by about 13 mV/day
|
||||
// (measured on mast-repeater-one over 30 days), so even at eight steps the
|
||||
// name changes roughly once a week. The flood advert interval of 25 h is far
|
||||
// finer than the thing being measured.
|
||||
|
||||
#include <MeshCore.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
// Permanent marker, prepended to the level. Empty string disables it.
|
||||
#ifndef BATT_ICON_MARKER
|
||||
#define BATT_ICON_MARKER "☀" // sun, 3 bytes
|
||||
#endif
|
||||
// Level glyphs, low to high. All must be the same byte length.
|
||||
#ifndef BATT_ICON_LEVELS
|
||||
#define BATT_ICON_LEVELS "▁▂▃▄▅▆▇█"
|
||||
#endif
|
||||
#ifndef BATT_ICON_LEVEL_BYTES
|
||||
#define BATT_ICON_LEVEL_BYTES 3
|
||||
#endif
|
||||
// Shown INSTEAD of the level while the node runs on external power, which
|
||||
// nRF52 reports straight from VBUS detect (MainBoard::isExternalPowered()).
|
||||
// That covers the bench, where a board with no cell reads a meaningless
|
||||
// floating VBAT -- better to say "on USB" than to draw a charge level out of
|
||||
// noise. It is 3 bytes like a level glyph, so the budget does not move.
|
||||
#ifndef BATT_ICON_EXTERNAL
|
||||
#define BATT_ICON_EXTERNAL "\u26A1" // high voltage, 3 bytes
|
||||
#endif
|
||||
|
||||
// Scale ends in millivolts for a 1S Li-Ion/LiPo cell -- the same 3300..4200
|
||||
// the dashboards use, so the icon and the Grafana percentage tell one story.
|
||||
#ifndef BATT_ICON_LO_MV
|
||||
#define BATT_ICON_LO_MV 3300
|
||||
#endif
|
||||
#ifndef BATT_ICON_HI_MV
|
||||
#define BATT_ICON_HI_MV 4200
|
||||
#endif
|
||||
// Hysteresis per boundary. Has to clear the measured daily swing of a solar
|
||||
// node under weak sun (38-46 mV) or the level would follow sunrise and
|
||||
// sunset, and stay well under one step (112 mV at eight levels) or the level
|
||||
// could never climb at all.
|
||||
#ifndef BATT_ICON_HYST_MV
|
||||
#define BATT_ICON_HYST_MV 50
|
||||
#endif
|
||||
|
||||
namespace mesh {
|
||||
|
||||
// Number of level glyphs.
|
||||
inline uint8_t battIconLevels() {
|
||||
return (uint8_t)((sizeof(BATT_ICON_LEVELS) - 1) / BATT_ICON_LEVEL_BYTES);
|
||||
}
|
||||
|
||||
// Bytes the indicator adds to the name: marker plus one level glyph.
|
||||
//
|
||||
// Every level is the same width, and that is the point rather than a detail:
|
||||
// a name whose length changed with the charge would be re-truncated by the
|
||||
// UTF-8 clamp at some steps and not others, and every client that hears it
|
||||
// would rewrite the contact.
|
||||
inline size_t battIconWidth() {
|
||||
const size_t lvl = BATT_ICON_LEVEL_BYTES;
|
||||
const size_t ext = sizeof(BATT_ICON_EXTERNAL) - 1;
|
||||
return (sizeof(BATT_ICON_MARKER) - 1) + (lvl > ext ? lvl : ext);
|
||||
}
|
||||
|
||||
// Does the name still fit with the indicator appended?
|
||||
//
|
||||
// `budget` musí přijít z AdvertDataBuilder::nameBudget(), ne z druhého výpočtu
|
||||
// tady: rozpočet závisí i na FEAT1/FEAT2, a kopie, která o nich nevěděla, by
|
||||
// tvrdila o 2-4 bajty víc, než je pravda. Pak by UTF-8 clamp uřízl glyf
|
||||
// vpůli -- přesně to tiché selhání, které tenhle soubor jinde odmítá.
|
||||
inline bool battIconFits(size_t name_len, size_t budget) {
|
||||
return name_len + battIconWidth() <= budget;
|
||||
}
|
||||
|
||||
// Copy the glyph for `level` into dest, which must hold
|
||||
// BATT_ICON_LEVEL_BYTES + 1 bytes.
|
||||
inline void battIconGlyph(char dest[], uint8_t level) {
|
||||
uint8_t n = battIconLevels();
|
||||
if (n == 0) { dest[0] = 0; return; }
|
||||
if (level >= n) level = n - 1;
|
||||
const char* tbl = BATT_ICON_LEVELS;
|
||||
memcpy(dest, tbl + (size_t)level * BATT_ICON_LEVEL_BYTES, BATT_ICON_LEVEL_BYTES);
|
||||
dest[BATT_ICON_LEVEL_BYTES] = 0;
|
||||
}
|
||||
|
||||
// Charge level 0..n-1 for `mv`, with hysteresis against the previous level.
|
||||
//
|
||||
// Asymmetric on purpose: the level drops as soon as the voltage falls below a
|
||||
// boundary, but climbs only once it is hyst_mv clear of one. Falling is the
|
||||
// direction that matters -- an optimistic icon on a node that is browning out
|
||||
// is worse than a pessimistic one on a node that is charging.
|
||||
//
|
||||
// Starting from 0 the climb loop walks up to wherever the voltage actually
|
||||
// is, so a fresh boot settles on the right level (one hysteresis band low,
|
||||
// the safe side) without needing a separate "unknown" state.
|
||||
inline uint8_t battIconLevel(uint8_t prev, uint16_t mv, uint16_t lo_mv, uint16_t hi_mv,
|
||||
uint8_t n, uint16_t hyst_mv) {
|
||||
if (n <= 1 || hi_mv <= lo_mv) return 0;
|
||||
if (prev >= n) prev = n - 1;
|
||||
|
||||
const uint32_t span = (uint32_t)hi_mv - lo_mv;
|
||||
uint8_t lvl = prev;
|
||||
|
||||
// The boundary into level k sits at lo + k*span/n, for k = 1..n-1.
|
||||
while (lvl + 1 < n) {
|
||||
uint32_t edge = lo_mv + (uint32_t)(lvl + 1) * span / n;
|
||||
if ((uint32_t)mv >= edge + hyst_mv) lvl++; else break;
|
||||
}
|
||||
while (lvl > 0) {
|
||||
uint32_t edge = lo_mv + (uint32_t)lvl * span / n;
|
||||
if ((uint32_t)mv < edge) lvl--; else break;
|
||||
}
|
||||
return lvl;
|
||||
}
|
||||
|
||||
// On sampling: one analogRead per decision is deliberate, and it is the same
|
||||
// call that feeds the battery metric (simple_repeater/MyMesh.cpp:482 for
|
||||
// stats, :510 for telemetry). There is no smoothed copy of the voltage
|
||||
// anywhere in the firmware to prefer instead -- what looks steady in Grafana
|
||||
// is steady because the cell is.
|
||||
//
|
||||
// A cell-less XIAO on USB reads bimodally -- measured over 20 reads on x4:
|
||||
// 4160 3760 4160 3760 4140 4150 3750 ... two levels ~390 mV apart, alternating
|
||||
// roughly 50/50. A median over five samples was tried and does NOT help
|
||||
// (spread 420 mV raw vs 380 mV median): it is not an outlier to reject, it is
|
||||
// VBAT floating against the charger with nothing to clamp it.
|
||||
//
|
||||
// It is also not what a deployed node sees. mast-repeater-one, with a real
|
||||
// cell, holds a max-min spread of 0-22 mV over 10-minute windows (queried
|
||||
// from Prometheus). Against a 112 mV step and 50 mV of hysteresis that is
|
||||
// quiet, so the noise is a property of the bench, not of the firmware.
|
||||
// A bench board without a cell WILL step around; that is expected.
|
||||
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
#pragma once
|
||||
|
||||
// CUSTOM (TeTeHacko): the two decisions behind `filter hash add <hex> [secs]`
|
||||
// (throttle a channel byte instead of muting it) and `filter age <min>|off`
|
||||
// (refuse to re-air group texts stamped long ago). Header-only and free of
|
||||
// mesh/Arduino types so both run in the native tests; the glue that feeds them
|
||||
// packets lives in examples/simple_repeater/ChannelFilter.h. Issue tth #3.
|
||||
//
|
||||
// Both ideas come from DutchMeshCore (`filter sender add <name> [secs]`,
|
||||
// 18341f13; `filter age`, 89dbb2bd). Behaviour follows theirs where it matters:
|
||||
// an over-rate message does not extend the throttle window, the first match
|
||||
// after a reboot is a free pass (state is RAM only), the age limit is inactive
|
||||
// while the repeater clock is unset, and a message stamped in the future is
|
||||
// never old.
|
||||
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
#define HASH_THROTTLE_SLOTS 8 // = sizeof(NodePrefs::deny_hash)
|
||||
|
||||
// One throttle per deny-list slot. Slots follow the prefs list order, so the
|
||||
// caller must remove() when it deletes an entry, or later entries would
|
||||
// inherit the wrong window.
|
||||
class HashThrottle {
|
||||
uint32_t _last_ms[HASH_THROTTLE_SLOTS];
|
||||
uint8_t _armed[HASH_THROTTLE_SLOTS]; // 0 = nothing passed since boot/reset
|
||||
|
||||
public:
|
||||
HashThrottle() { reset(); }
|
||||
|
||||
void reset() {
|
||||
memset(_last_ms, 0, sizeof(_last_ms));
|
||||
memset(_armed, 0, sizeof(_armed));
|
||||
}
|
||||
|
||||
void reset(int slot) {
|
||||
if (slot < 0 || slot >= HASH_THROTTLE_SLOTS) return;
|
||||
_last_ms[slot] = 0;
|
||||
_armed[slot] = 0;
|
||||
}
|
||||
|
||||
// Close the gap after the prefs list dropped `slot` (entries above shift down).
|
||||
void remove(int slot) {
|
||||
if (slot < 0 || slot >= HASH_THROTTLE_SLOTS) return;
|
||||
for (int i = slot; i + 1 < HASH_THROTTLE_SLOTS; i++) {
|
||||
_last_ms[i] = _last_ms[i + 1];
|
||||
_armed[i] = _armed[i + 1];
|
||||
}
|
||||
reset(HASH_THROTTLE_SLOTS - 1);
|
||||
}
|
||||
|
||||
// true = this packet may be forwarded. secs 0 = blocked outright. Only a
|
||||
// pass moves the window, so a sender pushing hard still gets exactly one
|
||||
// message per `secs`. Unsigned subtraction survives the millis() wrap.
|
||||
bool pass(int slot, uint16_t secs, uint32_t now_ms) {
|
||||
if (secs == 0 || slot < 0 || slot >= HASH_THROTTLE_SLOTS) return false;
|
||||
if (_armed[slot] && (uint32_t)(now_ms - _last_ms[slot]) < (uint32_t)secs * 1000u) return false;
|
||||
_armed[slot] = 1;
|
||||
_last_ms[slot] = now_ms;
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
// A repeater without RTC or GPS boots at 15 May 2024 (VolatileRTCClock) and
|
||||
// would call every live message old. Anything before 2026-01-01 = clock unset.
|
||||
#define MSG_AGE_CLOCK_VALID_FROM 1767225600UL
|
||||
#define MSG_AGE_MAX_MINUTES 10080 // one week, as in DMC
|
||||
|
||||
enum MsgAgeVerdict {
|
||||
MSG_AGE_OFF, // limit not set
|
||||
MSG_AGE_CLOCK_UNSET, // limit set, but our clock cannot be trusted -> pass
|
||||
MSG_AGE_FRESH,
|
||||
MSG_AGE_OLD,
|
||||
};
|
||||
|
||||
// sender_ts is the 4-byte timestamp at the start of a decrypted group text.
|
||||
// It is the SENDER's clock: a companion running behind looks "old" here, which
|
||||
// is why the limit is opt-in and meant to be generous (days, not minutes).
|
||||
inline MsgAgeVerdict msgAgeCheck(uint32_t sender_ts, uint32_t now, uint16_t max_minutes) {
|
||||
if (max_minutes == 0) return MSG_AGE_OFF;
|
||||
if (now < MSG_AGE_CLOCK_VALID_FROM) return MSG_AGE_CLOCK_UNSET;
|
||||
if (sender_ts >= now) return MSG_AGE_FRESH;
|
||||
return (now - sender_ts > (uint32_t)max_minutes * 60u) ? MSG_AGE_OLD : MSG_AGE_FRESH;
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
#pragma once
|
||||
// CUSTOM (TeTeHacko): strict number arguments for CLI `set` commands.
|
||||
//
|
||||
// atoi()/atof() take any text: "abc" is 0, "300" goes into a uint8_t as 44,
|
||||
// and "nan" is a float that no range check refuses (under -ffast-math, which
|
||||
// the nRF52 builds use, the compiler may even fold that check away). The set
|
||||
// commands then saved the result and answered "OK" -- `set tx 30` on an
|
||||
// SX1262, `set freq abc` (150 MHz after the next boot's clamp), `set flood.max
|
||||
// 300` (44). These helpers accept a whole number (or decimal) in a range and
|
||||
// nothing else: optional surrounding white space and sign, digits, and for the
|
||||
// float a '.' and fraction. No exponent, no hex, no trailing text.
|
||||
|
||||
#include <ctype.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
namespace cli_args {
|
||||
|
||||
// Returns true and sets *out when `s` is an integer in [lo, hi].
|
||||
inline bool parseInt(const char* s, long lo, long hi, long* out) {
|
||||
if (!s) return false;
|
||||
while (isspace((unsigned char)*s)) s++;
|
||||
const char* p = s;
|
||||
if (*p == '+' || *p == '-') p++;
|
||||
if (!isdigit((unsigned char)*p)) return false;
|
||||
char* end;
|
||||
long v = strtol(s, &end, 10);
|
||||
while (isspace((unsigned char)*end)) end++;
|
||||
if (*end != 0) return false;
|
||||
if (v < lo || v > hi) return false;
|
||||
*out = v;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Returns true and sets *out when `s` is a decimal number in [lo, hi].
|
||||
inline bool parseFloat(const char* s, float lo, float hi, float* out) {
|
||||
if (!s) return false;
|
||||
while (isspace((unsigned char)*s)) s++;
|
||||
const char* p = s;
|
||||
if (*p == '+' || *p == '-') p++;
|
||||
bool digits = false;
|
||||
while (isdigit((unsigned char)*p)) { p++; digits = true; }
|
||||
if (*p == '.') {
|
||||
p++;
|
||||
while (isdigit((unsigned char)*p)) { p++; digits = true; }
|
||||
}
|
||||
if (!digits) return false;
|
||||
const char* rest = p;
|
||||
while (isspace((unsigned char)*rest)) rest++;
|
||||
if (*rest != 0) return false; // exponent, "nan", "inf" or trailing text
|
||||
float v = strtof(s, nullptr);
|
||||
if (!(v >= lo && v <= hi)) return false;
|
||||
*out = v;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Strips leading spaces and an optional 3-byte "XX|" prefix (reflected into
|
||||
// `reply`, deducting 3 from `*reply_max` when provided).
|
||||
inline void stripPrefix(const char*& command, char*& reply, int* reply_max = nullptr) {
|
||||
while (*command == ' ') command++;
|
||||
if (strlen(command) > 4 && command[2] == '|') {
|
||||
if (!reply_max || *reply_max >= 3) {
|
||||
memcpy(reply, command, 3);
|
||||
reply += 3;
|
||||
*reply = 0;
|
||||
if (reply_max) *reply_max -= 3;
|
||||
}
|
||||
command += 3;
|
||||
while (*command == ' ') command++;
|
||||
}
|
||||
}
|
||||
|
||||
// Security gate for companion `set pin`: blocked in locked CLI rescue and over
|
||||
// unencrypted local transports (USB), allowed over paired BLE or remote ACL.
|
||||
inline bool canSetPin(uint32_t sender_timestamp, bool cli_rescue, bool locked_node,
|
||||
bool serial_secure, const char** err_out = nullptr) {
|
||||
if (locked_node && cli_rescue) {
|
||||
if (err_out) *err_out = "Error: locked build";
|
||||
return false;
|
||||
}
|
||||
if (sender_timestamp == 0 && !cli_rescue && !serial_secure) {
|
||||
if (err_out) *err_out = "Error: set pin only over paired BLE";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Appends `line` to a paged CLI reply only if it fits with `trailer_reserve`
|
||||
// bytes left for the end marker; returns false when the page is full.
|
||||
inline bool appendLine(char*& dp, const char* reply, int max_len, int trailer_reserve, const char* line) {
|
||||
int ll = (int)strlen(line);
|
||||
if ((dp - reply) + ll + trailer_reserve > max_len) return false;
|
||||
memcpy(dp, line, ll);
|
||||
dp += ll;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace cli_args
|
||||
@@ -50,6 +50,126 @@ void ClientACL::load(FILESYSTEM* fs, const mesh::LocalIdentity& self_id) {
|
||||
file.close();
|
||||
}
|
||||
}
|
||||
loadTimestamps();
|
||||
}
|
||||
|
||||
// CUSTOM (TeTeHacko): /s_acl_ts0 and /s_acl_ts1 are written alternately, each
|
||||
// {pubkey prefix 8, timestamp 4} * n + seq 4 + sha256 tag 4. A write torn by a
|
||||
// power cut leaves the other slot intact, and the floor is the max over both
|
||||
// valid slots, so it can only ever move forward. The next write always goes over
|
||||
// the OLDER slot (lower seq) -- and a torn write means the command it guarded
|
||||
// never ran, so nothing executed is lost.
|
||||
#define ACL_TS_PREFIX 8
|
||||
#define ACL_TS_RECORD (ACL_TS_PREFIX + 4)
|
||||
|
||||
static const char* tsFilename(uint8_t slot) { return slot ? "/s_acl_ts1" : "/s_acl_ts0"; }
|
||||
static uint8_t s_ts_buf[2 * MAX_CLIENTS * ACL_TS_RECORD + 8];
|
||||
|
||||
void ClientACL::loadTimestamps() {
|
||||
uint8_t* buf = s_ts_buf;
|
||||
_num_ts_orphans = 0;
|
||||
_ts_seq = 0;
|
||||
_ts_slot = 0;
|
||||
bool have_newest = false;
|
||||
for (uint8_t slot = 0; slot < 2; slot++) {
|
||||
if (!_fs->exists(tsFilename(slot))) continue;
|
||||
#if defined(RP2040_PLATFORM)
|
||||
File file = _fs->open(tsFilename(slot), "r");
|
||||
#else
|
||||
File file = _fs->open(tsFilename(slot));
|
||||
#endif
|
||||
if (!file) continue;
|
||||
int len = file.read(buf, sizeof(s_ts_buf));
|
||||
file.close();
|
||||
if (len < 8 || (len - 8) % ACL_TS_RECORD != 0) continue;
|
||||
|
||||
uint8_t tag[4];
|
||||
mesh::Utils::sha256(tag, 4, buf, len - 4);
|
||||
if (memcmp(tag, &buf[len - 4], 4) != 0) continue; // torn write: ignore this slot
|
||||
uint32_t seq;
|
||||
memcpy(&seq, &buf[len - 8], 4);
|
||||
if (!have_newest || seq > _ts_seq) {
|
||||
_ts_seq = seq;
|
||||
_ts_slot = slot ^ 1; // next write goes over the other, older slot
|
||||
have_newest = true;
|
||||
}
|
||||
|
||||
for (int ofs = 0; ofs < len - 8; ofs += ACL_TS_RECORD) {
|
||||
uint32_t ts;
|
||||
memcpy(&ts, &buf[ofs + ACL_TS_PREFIX], 4);
|
||||
ClientInfo* c = getClient(&buf[ofs], ACL_TS_PREFIX);
|
||||
if (c) {
|
||||
if (ts > c->saved_timestamp) c->saved_timestamp = ts;
|
||||
continue;
|
||||
}
|
||||
// Not in /s_contacts: a fresh login whose lazy ACL write a reboot beat, or an
|
||||
// evicted guest. Keep the floor, or replaying their login would re-admit them.
|
||||
int j = 0;
|
||||
while (j < _num_ts_orphans && memcmp(_ts_orphans[j].prefix, &buf[ofs], ACL_TS_PREFIX) != 0) j++;
|
||||
if (j == _num_ts_orphans) {
|
||||
if (j == MAX_CLIENTS) continue;
|
||||
memcpy(_ts_orphans[j].prefix, &buf[ofs], ACL_TS_PREFIX);
|
||||
_ts_orphans[j].ts = 0;
|
||||
_num_ts_orphans++;
|
||||
}
|
||||
if (ts > _ts_orphans[j].ts) _ts_orphans[j].ts = ts;
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < num_clients; i++) {
|
||||
clients[i].last_timestamp = clients[i].last_req_timestamp = clients[i].saved_timestamp;
|
||||
}
|
||||
}
|
||||
|
||||
void ClientACL::saveTimestamps() {
|
||||
if (!_fs) return;
|
||||
uint8_t* buf = s_ts_buf;
|
||||
int len = 0;
|
||||
for (int i = 0; i < num_clients; i++) {
|
||||
if (clients[i].saved_timestamp == 0) continue;
|
||||
memcpy(&buf[len], clients[i].id.pub_key, ACL_TS_PREFIX);
|
||||
memcpy(&buf[len + ACL_TS_PREFIX], &clients[i].saved_timestamp, 4);
|
||||
len += ACL_TS_RECORD;
|
||||
}
|
||||
for (int i = 0; i < _num_ts_orphans; i++) {
|
||||
memcpy(&buf[len], _ts_orphans[i].prefix, ACL_TS_PREFIX);
|
||||
memcpy(&buf[len + ACL_TS_PREFIX], &_ts_orphans[i].ts, 4);
|
||||
len += ACL_TS_RECORD;
|
||||
}
|
||||
_ts_seq++;
|
||||
memcpy(&buf[len], &_ts_seq, 4);
|
||||
len += 4;
|
||||
mesh::Utils::sha256(&buf[len], 4, buf, len);
|
||||
len += 4;
|
||||
|
||||
File file = openWrite(_fs, tsFilename(_ts_slot));
|
||||
if (file) {
|
||||
size_t written = file.write(buf, len);
|
||||
file.close();
|
||||
if (written == (size_t)len) _ts_slot ^= 1;
|
||||
}
|
||||
}
|
||||
|
||||
void ClientACL::orphanTimestamp(const ClientInfo* c) {
|
||||
if (c->saved_timestamp == 0) return;
|
||||
if (_num_ts_orphans == MAX_CLIENTS) { // full: drop the oldest
|
||||
memmove(&_ts_orphans[0], &_ts_orphans[1], (MAX_CLIENTS - 1) * sizeof(TsOrphan));
|
||||
_num_ts_orphans--;
|
||||
}
|
||||
memcpy(_ts_orphans[_num_ts_orphans].prefix, c->id.pub_key, ACL_TS_PREFIX);
|
||||
_ts_orphans[_num_ts_orphans].ts = c->saved_timestamp;
|
||||
_num_ts_orphans++;
|
||||
}
|
||||
|
||||
void ClientACL::persistTimestamp(ClientInfo* c, uint32_t sender_timestamp, uint32_t now) {
|
||||
// Admins only. A guest can only read, and anybody gets in as one when the
|
||||
// guest password is empty (the default): its every request would be a flash
|
||||
// write, and its floors would push the admins' out of the orphan list. Its
|
||||
// floor stays in RAM, as upstream.
|
||||
if (!c->isAdmin()) return;
|
||||
if (sender_timestamp <= c->saved_timestamp) return; // retry, or nothing new
|
||||
if (sender_timestamp > now + ACL_TS_MAX_AHEAD) return; // runaway sender clock
|
||||
c->saved_timestamp = sender_timestamp;
|
||||
saveTimestamps();
|
||||
}
|
||||
|
||||
void ClientACL::save(FILESYSTEM* fs, bool (*filter)(ClientInfo*)) {
|
||||
@@ -82,8 +202,12 @@ bool ClientACL::clear() {
|
||||
if (_fs->exists("/s_contacts")) {
|
||||
_fs->remove("/s_contacts");
|
||||
}
|
||||
// The replay floors outlive the ACL: with them gone, a captured password login
|
||||
// would be accepted again.
|
||||
for (int i = 0; i < num_clients; i++) orphanTimestamp(&clients[i]);
|
||||
memset(clients, 0, sizeof(clients));
|
||||
num_clients = 0;
|
||||
saveTimestamps();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -117,12 +241,21 @@ ClientInfo* ClientACL::putClient(const mesh::Identity& id, uint8_t init_perms, b
|
||||
} else {
|
||||
c = oldest_unsaved ? oldest_unsaved : (shared_login ? NULL : oldest); // evict unsaved entries first, shared logins never evict saved ones
|
||||
if (c == NULL) return NULL; // every entry is an admin (or saved), so don't evict
|
||||
orphanTimestamp(c); // CUSTOM (TeTeHacko): keep the evicted client's replay floor
|
||||
}
|
||||
memset(c, 0, sizeof(*c));
|
||||
c->permissions = init_perms;
|
||||
c->shared_login = shared_login;
|
||||
c->id = id;
|
||||
c->out_path_len = OUT_PATH_UNKNOWN;
|
||||
for (int i = 0; i < _num_ts_orphans; i++) { // known before: its replay floor comes back
|
||||
if (memcmp(_ts_orphans[i].prefix, id.pub_key, ACL_TS_PREFIX) == 0) {
|
||||
c->saved_timestamp = c->last_timestamp = c->last_req_timestamp = _ts_orphans[i].ts;
|
||||
_num_ts_orphans--;
|
||||
memmove(&_ts_orphans[i], &_ts_orphans[i + 1], (_num_ts_orphans - i) * sizeof(TsOrphan));
|
||||
break;
|
||||
}
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
@@ -132,6 +265,7 @@ bool ClientACL::applyPermissions(const mesh::LocalIdentity& self_id, const uint8
|
||||
c = getClient(pubkey, key_len);
|
||||
if (c == NULL) return false; // partial pubkey not found
|
||||
|
||||
orphanTimestamp(c);
|
||||
num_clients--; // delete from contacts[]
|
||||
int i = c - clients;
|
||||
while (i < num_clients) {
|
||||
|
||||
+28
-2
@@ -18,8 +18,9 @@ struct ClientInfo {
|
||||
uint8_t out_path_len;
|
||||
uint8_t out_path[MAX_PATH_SIZE];
|
||||
uint8_t shared_secret[PUB_KEY_SIZE];
|
||||
uint32_t last_timestamp; // by THEIR clock (transient)
|
||||
uint32_t last_req_timestamp;
|
||||
uint32_t last_timestamp; // by THEIR clock (restored from /s_acl_ts* on boot)
|
||||
uint32_t saved_timestamp; // last_timestamp as last written to /s_acl_ts*
|
||||
uint32_t last_req_timestamp; // REQ only (upstream split); restored from saved_timestamp too
|
||||
uint32_t last_activity; // by OUR clock (transient)
|
||||
bool shared_login; // logged in with a guest or read-only password, never saved (transient)
|
||||
union {
|
||||
@@ -47,20 +48,45 @@ struct ClientInfo {
|
||||
#define MAX_CLIENTS 32
|
||||
#endif
|
||||
|
||||
// CUSTOM (TeTeHacko): a timestamp further ahead of our clock than this is accepted
|
||||
// but not persisted, so a companion with a runaway RTC cannot lock its admin out
|
||||
// across reboots.
|
||||
#ifndef ACL_TS_MAX_AHEAD
|
||||
#define ACL_TS_MAX_AHEAD (24 * 3600)
|
||||
#endif
|
||||
|
||||
class ClientACL {
|
||||
FILESYSTEM* _fs;
|
||||
ClientInfo clients[MAX_CLIENTS];
|
||||
int num_clients;
|
||||
uint8_t _ts_slot;
|
||||
uint32_t _ts_seq;
|
||||
struct TsOrphan { uint8_t prefix[8]; uint32_t ts; };
|
||||
TsOrphan _ts_orphans[MAX_CLIENTS]; // floors of clients not (or no longer) in clients[]
|
||||
int _num_ts_orphans;
|
||||
|
||||
void loadTimestamps();
|
||||
void saveTimestamps();
|
||||
void orphanTimestamp(const ClientInfo* c);
|
||||
|
||||
public:
|
||||
ClientACL() {
|
||||
memset(clients, 0, sizeof(clients));
|
||||
num_clients = 0;
|
||||
_ts_slot = 0;
|
||||
_ts_seq = 0;
|
||||
_num_ts_orphans = 0;
|
||||
}
|
||||
void load(FILESYSTEM* _fs, const mesh::LocalIdentity& self_id);
|
||||
void save(FILESYSTEM* _fs, bool (*filter)(ClientInfo*)=NULL);
|
||||
bool clear();
|
||||
|
||||
// CUSTOM (TeTeHacko): replay protection that survives a reboot. last_timestamp
|
||||
// used to live only in RAM, so after any reboot a captured command (a `reboot`
|
||||
// among them) was accepted again -- forever. Call this BEFORE acting on an
|
||||
// authenticated packet; it writes the new high-water mark synchronously.
|
||||
void persistTimestamp(ClientInfo* c, uint32_t sender_timestamp, uint32_t now);
|
||||
|
||||
ClientInfo* getClient(const uint8_t* pubkey, int key_len);
|
||||
ClientInfo* putClient(const mesh::Identity& id, uint8_t init_perms, bool shared_login=false); // returns NULL if table is full and all entries are admins (or saved, if shared_login)
|
||||
bool applyPermissions(const mesh::LocalIdentity& self_id, const uint8_t* pubkey, int key_len, uint8_t perms);
|
||||
|
||||
+370
-36
@@ -1,14 +1,23 @@
|
||||
#include <Arduino.h>
|
||||
#include "CliArgs.h"
|
||||
#include "CommonCLI.h"
|
||||
#include "TxtDataHelpers.h"
|
||||
#include "AdvertDataHelpers.h"
|
||||
#include "BatteryIcon.h"
|
||||
#include "TxtDataHelpers.h"
|
||||
#include <RTClib.h>
|
||||
#include <CayenneLPP.h>
|
||||
|
||||
#ifndef BRIDGE_MAX_BAUD
|
||||
#define BRIDGE_MAX_BAUD 115200
|
||||
#endif
|
||||
|
||||
// CUSTOM (TeTeHacko): defined by apps that keep the wall clock in retained RAM
|
||||
// across a soft reset (examples/simple_repeater/main.cpp). Weak, so every build
|
||||
// that does not links fine and the pointer is simply NULL. `clkreboot` has to
|
||||
// clear that record or it would undo itself -- see the call site below.
|
||||
extern "C" void retainedClockInvalidate() __attribute__((weak));
|
||||
|
||||
// Believe it or not, this std C function is busted on some platforms!
|
||||
static uint32_t _atoi(const char* sp) {
|
||||
uint32_t n = 0;
|
||||
@@ -127,7 +136,7 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) { // Legacy
|
||||
|
||||
_prefs->powersaving_enabled = constrain(_prefs->powersaving_enabled, 0, 1);
|
||||
|
||||
_prefs->gps_enabled = constrain(_prefs->gps_enabled, 0, 1);
|
||||
_prefs->gps_enabled = constrain(_prefs->gps_enabled, 0, 2); // 0 off, 1 on, 2 duty cycle
|
||||
_prefs->advert_loc_policy = constrain(_prefs->advert_loc_policy, 0, 2);
|
||||
|
||||
// sanitise settings
|
||||
@@ -167,19 +176,93 @@ void CommonCLI::savePrefs() {
|
||||
_prefs->clearDirty();
|
||||
}
|
||||
|
||||
uint8_t CommonCLI::buildAdvertData(uint8_t node_type, uint8_t* app_data) {
|
||||
// Rozpočet na jméno pro současné nastavení advertu. Staví prázdný builder
|
||||
// a ptá se JEHO, ať `set`, `get` i samotný advert počítají z jednoho místa --
|
||||
// druhá kopie toho výpočtu už jednou zapomněla na FEAT1/FEAT2.
|
||||
size_t CommonCLI::nameBudget() const {
|
||||
if (_prefs->advert_loc_policy == ADVERT_LOC_NONE) {
|
||||
AdvertDataBuilder builder(node_type, _prefs->node_name);
|
||||
return AdvertDataBuilder(ADV_TYPE_NONE).nameBudget();
|
||||
}
|
||||
return AdvertDataBuilder(ADV_TYPE_NONE, NULL, 0.0, 0.0).nameBudget();
|
||||
}
|
||||
|
||||
// Name as it goes on the air: the configured name, plus the solar marker and
|
||||
// either a charge level or the external-power glyph. Returns the bare name in
|
||||
// every other case -- an indicator that does not fit is dropped whole rather
|
||||
// than letting the UTF-8 clamp eat half of it silently.
|
||||
const char* CommonCLI::advertName(size_t budget) {
|
||||
if (!_prefs->batt_icon) return _prefs->node_name;
|
||||
|
||||
size_t nlen = strlen(_prefs->node_name);
|
||||
if (!mesh::battIconFits(nlen, budget)) return _prefs->node_name;
|
||||
|
||||
char glyph[8];
|
||||
if (_board->isExternalPowered()) {
|
||||
// On USB the cell (if any) is being charged and VBAT reads the charger,
|
||||
// not the battery -- a level drawn from it would be fiction.
|
||||
StrHelper::strncpy(glyph, BATT_ICON_EXTERNAL, sizeof(glyph));
|
||||
} else {
|
||||
uint16_t mv = _board->getBattMilliVolts();
|
||||
if (mv == 0) return _prefs->node_name; // board has no battery sense
|
||||
uint16_t lo = _prefs->batt_icon_lo ? _prefs->batt_icon_lo : BATT_ICON_LO_MV;
|
||||
uint16_t hi = _prefs->batt_icon_hi ? _prefs->batt_icon_hi : BATT_ICON_HI_MV;
|
||||
_batt_level = mesh::battIconLevel(_batt_level, mv, lo, hi,
|
||||
mesh::battIconLevels(), BATT_ICON_HYST_MV);
|
||||
mesh::battIconGlyph(glyph, _batt_level);
|
||||
}
|
||||
|
||||
StrHelper::strncpy(_adv_name, _prefs->node_name, sizeof(_adv_name));
|
||||
strncat(_adv_name, BATT_ICON_MARKER, sizeof(_adv_name) - strlen(_adv_name) - 1);
|
||||
strncat(_adv_name, glyph, sizeof(_adv_name) - strlen(_adv_name) - 1);
|
||||
return _adv_name;
|
||||
}
|
||||
|
||||
uint8_t CommonCLI::buildAdvertData(uint8_t node_type, uint8_t* app_data) {
|
||||
// Builder se postaví bez jména, protože rozpočet na jméno závisí na tom, co
|
||||
// v něm už je (poloha, případné FEAT). Teprve pak se jméno doplní -- jinak
|
||||
// by se remainder musel počítat podruhé jinde a rozejít se s encodeTo().
|
||||
if (_prefs->advert_loc_policy == ADVERT_LOC_NONE) {
|
||||
AdvertDataBuilder builder(node_type);
|
||||
builder.setName(advertName(builder.nameBudget()));
|
||||
return builder.encodeTo(app_data);
|
||||
} else if (_prefs->advert_loc_policy == ADVERT_LOC_SHARE) {
|
||||
AdvertDataBuilder builder(node_type, _prefs->node_name, _sensors->node_lat, _sensors->node_lon);
|
||||
AdvertDataBuilder builder(node_type, NULL, _sensors->node_lat, _sensors->node_lon);
|
||||
builder.setName(advertName(builder.nameBudget()));
|
||||
return builder.encodeTo(app_data);
|
||||
} else {
|
||||
AdvertDataBuilder builder(node_type, _prefs->node_name, _prefs->node_lat, _prefs->node_lon);
|
||||
AdvertDataBuilder builder(node_type, NULL, _prefs->node_lat, _prefs->node_lon);
|
||||
builder.setName(advertName(builder.nameBudget()));
|
||||
return builder.encodeTo(app_data);
|
||||
}
|
||||
}
|
||||
|
||||
// CayenneLPP data-payload size (bytes) for a given type; -1 if unknown.
|
||||
// Lets `sensor read` skip a field it doesn't surface without losing sync
|
||||
// (silently dropping the rest of the buffer).
|
||||
static int cayenne_lpp_size(uint8_t type) {
|
||||
switch (type) {
|
||||
case LPP_DIGITAL_INPUT: case LPP_DIGITAL_OUTPUT: case LPP_PRESENCE:
|
||||
case LPP_RELATIVE_HUMIDITY: case LPP_PERCENTAGE: case LPP_SWITCH:
|
||||
return 1;
|
||||
case LPP_ANALOG_INPUT: case LPP_ANALOG_OUTPUT: case LPP_LUMINOSITY:
|
||||
case LPP_TEMPERATURE: case LPP_BAROMETRIC_PRESSURE: case LPP_VOLTAGE:
|
||||
case LPP_CURRENT: case LPP_ALTITUDE: case LPP_CONCENTRATION:
|
||||
case LPP_POWER: case LPP_DIRECTION:
|
||||
return 2;
|
||||
case LPP_COLOUR:
|
||||
return 3;
|
||||
case LPP_GENERIC_SENSOR: case LPP_FREQUENCY: case LPP_DISTANCE:
|
||||
case LPP_ENERGY: case LPP_UNIXTIME:
|
||||
return 4;
|
||||
case LPP_ACCELEROMETER: case LPP_GYROMETER:
|
||||
return 6;
|
||||
case LPP_GPS:
|
||||
return LPP_GPS_SIZE;
|
||||
default:
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* reply) {
|
||||
if (_prefs->getRadioPrefs()->handleCommand(command, sender_timestamp, reply)) { // is a radio CLI command?
|
||||
if (_prefs->getRadioPrefs()->isDirty()) { savePrefs(); }
|
||||
@@ -196,8 +279,18 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
|
||||
} else if (memcmp(command, "reboot", 6) == 0) {
|
||||
_board->reboot(); // doesn't return
|
||||
} else if (memcmp(command, "clkreboot", 9) == 0) {
|
||||
// Reset clock
|
||||
getRTCClock()->setCurrentTime(1715770351); // 15 May 2024, 8:50pm
|
||||
// Reset clock. On a volatile clock this write is redundant -- the reboot
|
||||
// re-runs the constructor, which seeds the same value -- but on a battery
|
||||
// backed I2C RTC it really does rewrite the chip, so it must not put the
|
||||
// year 2024 there. This is also the ONLY way to move a clock BACKWARDS:
|
||||
// `time` and `clock sync` both refuse to, so an over-set clock can only be
|
||||
// fixed by resetting it here and setting it again.
|
||||
//
|
||||
// The retained-RAM copy has to die with it. Otherwise the reboot restores
|
||||
// the very value being thrown away here, and the command silently does
|
||||
// nothing on exactly the nodes that keep their clock across a reset.
|
||||
if (retainedClockInvalidate) retainedClockInvalidate();
|
||||
getRTCClock()->setCurrentTime(FIRMWARE_BUILD_EPOCH);
|
||||
_board->reboot(); // doesn't return
|
||||
} else if (memcmp(command, "advert.zerohop", 14) == 0 && (command[14] == 0 || command[14] == ' ')) {
|
||||
// send zerohop advert
|
||||
@@ -225,7 +318,14 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
|
||||
} else if (memcmp(command, "clock", 5) == 0) {
|
||||
uint32_t now = getRTCClock()->getCurrentTime();
|
||||
DateTime dt = DateTime(now);
|
||||
sprintf(reply, "%02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year());
|
||||
// CUSTOM (TeTeHacko): the epoch goes on the end. The human part is minutes
|
||||
// only, so a host comparing its own clock against this one cannot see a
|
||||
// difference smaller than a minute -- meaning it cannot tell a node that is
|
||||
// 40 s out from one that is exact, and has to leave a >59 s deadband. The
|
||||
// epoch makes the comparison exact. Appended, so anything that only reads
|
||||
// or prints the reply is unaffected.
|
||||
sprintf(reply, "%02d:%02d - %d/%d/%d UTC (epoch %u)", dt.hour(), dt.minute(),
|
||||
dt.day(), dt.month(), dt.year(), (unsigned) now);
|
||||
} else if (memcmp(command, "time ", 5) == 0) { // set time (to epoch seconds)
|
||||
uint32_t secs = _atoi(&command[5]);
|
||||
uint32_t curr = getRTCClock()->getCurrentTime();
|
||||
@@ -252,15 +352,17 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
|
||||
strcpy(reply, "ERR: bad pubkey");
|
||||
}
|
||||
} else if (memcmp(command, "tempradio ", 10) == 0) {
|
||||
strcpy(tmp, &command[10]);
|
||||
StrHelper::strncpy(tmp, &command[10], sizeof(tmp));
|
||||
const char *parts[5];
|
||||
int num = mesh::Utils::parseTextParts(tmp, parts, 5);
|
||||
float freq = num > 0 ? strtof(parts[0], nullptr) : 0.0f;
|
||||
float bw = num > 1 ? strtof(parts[1], nullptr) : 0.0f;
|
||||
uint8_t sf = num > 2 ? atoi(parts[2]) : 0;
|
||||
uint8_t cr = num > 3 ? atoi(parts[3]) : 0;
|
||||
int temp_timeout_mins = num > 4 ? atoi(parts[4]) : 0;
|
||||
if (freq >= 150.0f && freq <= 2500.0f && sf >= 5 && sf <= 12 && cr >= 5 && cr <= 8 && bw >= 7.0f && bw <= 500.0f && temp_timeout_mins > 0) {
|
||||
float freq = 0, bw = 0;
|
||||
long sf_l = 0, cr_l = 0, mins_l = 0;
|
||||
if (num == 5 && cli_args::parseFloat(parts[0], 150.0f, 2500.0f, &freq) &&
|
||||
cli_args::parseFloat(parts[1], 7.0f, 500.0f, &bw) &&
|
||||
cli_args::parseInt(parts[2], 5, 12, &sf_l) && cli_args::parseInt(parts[3], 5, 8, &cr_l) &&
|
||||
cli_args::parseInt(parts[4], 1, 10080, &mins_l)) {
|
||||
uint8_t sf = sf_l, cr = cr_l;
|
||||
int temp_timeout_mins = mins_l;
|
||||
_callbacks->applyTempRadioParams(freq, bw, sf, cr, temp_timeout_mins);
|
||||
sprintf(reply, "OK - temp params for %d mins", temp_timeout_mins);
|
||||
} else {
|
||||
@@ -314,12 +416,16 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
|
||||
strcpy(reply, "null");
|
||||
}
|
||||
} else if (memcmp(command, "sensor set ", 11) == 0) {
|
||||
strcpy(tmp, &command[11]);
|
||||
StrHelper::strncpy(tmp, &command[11], sizeof(tmp));
|
||||
const char *parts[2];
|
||||
int num = mesh::Utils::parseTextParts(tmp, parts, 2, ' ');
|
||||
const char *key = (num > 0) ? parts[0] : "";
|
||||
const char *value = (num > 1) ? parts[1] : "null";
|
||||
if (_sensors->setSettingValue(key, value)) {
|
||||
if (strcmp(key, "ina.shunt") == 0) { // CUSTOM (TeTeHacko): survives a reboot
|
||||
_prefs->ina_shunt_mohm = atof(value);
|
||||
savePrefs();
|
||||
}
|
||||
strcpy(reply, "ok");
|
||||
} else {
|
||||
strcpy(reply, "can't find custom var");
|
||||
@@ -357,6 +463,114 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
|
||||
*(dp-1) = 0; // remove last CR
|
||||
}
|
||||
}
|
||||
} else if (memcmp(command, "i2c", 3) == 0) {
|
||||
// Live bus scan. `sensor read` only shows what got initialised, so a
|
||||
// sensor that is absent and one whose address is wrong look identical
|
||||
// there; this separates the two.
|
||||
// 150 = what one LoRa packet carries, i.e. the smallest reply buffer any
|
||||
// caller of CommonCLI passes (the local console's is far bigger, but
|
||||
// CommonCLI is not told which one it got).
|
||||
int n = _sensors->scanI2C(reply, 150);
|
||||
if (n < 0) strcpy(reply, "no I2C bus on this build");
|
||||
} else if (memcmp(command, "sensor read", 11) == 0) {
|
||||
// Decode the live telemetry (the same CayenneLPP payload sent over the
|
||||
// mesh) into a human-readable line. `sensor list` only exposes settings
|
||||
// (e.g. gps on/off), never the measured values; this lets a console or
|
||||
// bridge pull temperature, humidity, voltage, etc. as plain text.
|
||||
CayenneLPP lpp(128);
|
||||
lpp.reset();
|
||||
// Mirror the node's own mesh telemetry so `sensor read` reflects reality:
|
||||
// battery voltage + attached I2C sensors + built-in MCU temperature. Note
|
||||
// the two temperatures (ambient sensor vs MCU) sit on different LPP
|
||||
// channels, so each field below is keyed by channel to keep them distinct.
|
||||
lpp.addVoltage(TELEM_CHANNEL_SELF, _board->getBattMilliVolts() / 1000.0f);
|
||||
_sensors->querySensors(0xFF, lpp);
|
||||
float mcu_temp = _board->getMCUTemperature();
|
||||
if (!isnan(mcu_temp)) lpp.addTemperature(TELEM_CHANNEL_SELF, mcu_temp);
|
||||
|
||||
const uint8_t* b = lpp.getBuffer();
|
||||
int sz = lpp.getSize();
|
||||
const int CAP = 158; // reply buffer is ~160 bytes on all callers
|
||||
char* dp = reply;
|
||||
*dp = 0;
|
||||
int k = 0;
|
||||
while (k + 2 <= sz && (CAP - (int)(dp - reply)) > 44) {
|
||||
uint8_t ch = b[k];
|
||||
uint8_t type = b[k + 1];
|
||||
int dsz = cayenne_lpp_size(type);
|
||||
if (dsz < 0 || k + 2 + dsz > sz) break; // unknown type / truncated -> stop cleanly
|
||||
const uint8_t* d = &b[k + 2];
|
||||
int rem = CAP - (int)(dp - reply);
|
||||
switch (type) {
|
||||
case LPP_TEMPERATURE:
|
||||
snprintf(dp, rem, "temperature.%d=%s ", ch, StrHelper::ftoa((int16_t)((d[0]<<8)|d[1]) / 10.0f)); break;
|
||||
case LPP_RELATIVE_HUMIDITY:
|
||||
snprintf(dp, rem, "humidity.%d=%s ", ch, StrHelper::ftoa(d[0] / 2.0f)); break;
|
||||
case LPP_BAROMETRIC_PRESSURE:
|
||||
snprintf(dp, rem, "pressure.%d=%s ", ch, StrHelper::ftoa((uint16_t)((d[0]<<8)|d[1]) / 10.0f)); break;
|
||||
case LPP_VOLTAGE:
|
||||
snprintf(dp, rem, "voltage.%d=%s ", ch, StrHelper::ftoa((uint16_t)((d[0]<<8)|d[1]) / 100.0f)); break;
|
||||
case LPP_CURRENT:
|
||||
snprintf(dp, rem, "current.%d=%s ", ch, StrHelper::ftoa((uint16_t)((d[0]<<8)|d[1]) / 1000.0f)); break;
|
||||
case LPP_POWER:
|
||||
snprintf(dp, rem, "power.%d=%d ", ch, (int)(uint16_t)((d[0]<<8)|d[1])); break;
|
||||
case LPP_PERCENTAGE:
|
||||
snprintf(dp, rem, "percent.%d=%d ", ch, (int)d[0]); break;
|
||||
case LPP_ALTITUDE:
|
||||
snprintf(dp, rem, "altitude.%d=%d ", ch, (int)(int16_t)((d[0]<<8)|d[1])); break;
|
||||
case LPP_ANALOG_INPUT:
|
||||
snprintf(dp, rem, "analog.%d=%s ", ch, StrHelper::ftoa((int16_t)((d[0]<<8)|d[1]) / 100.0f)); break;
|
||||
case LPP_LUMINOSITY:
|
||||
snprintf(dp, rem, "lux.%d=%d ", ch, (int)(uint16_t)((d[0]<<8)|d[1])); break;
|
||||
case LPP_GPS: {
|
||||
int32_t lat = ((int32_t)d[0]<<16)|(d[1]<<8)|d[2];
|
||||
int32_t lon = ((int32_t)d[3]<<16)|(d[4]<<8)|d[5];
|
||||
int32_t alt = ((int32_t)d[6]<<16)|(d[7]<<8)|d[8];
|
||||
if (lat & 0x800000) lat |= 0xFF000000; // sign-extend 24-bit
|
||||
if (lon & 0x800000) lon |= 0xFF000000;
|
||||
if (alt & 0x800000) alt |= 0xFF000000;
|
||||
snprintf(dp, rem, "gps.%d=", ch); dp = strchr(dp, 0);
|
||||
snprintf(dp, CAP-(int)(dp-reply), "%s,", StrHelper::ftoa(lat / 10000.0f)); dp = strchr(dp, 0);
|
||||
snprintf(dp, CAP-(int)(dp-reply), "%s,", StrHelper::ftoa(lon / 10000.0f)); dp = strchr(dp, 0);
|
||||
snprintf(dp, CAP-(int)(dp-reply), "%s ", StrHelper::ftoa(alt / 100.0f)); break;
|
||||
}
|
||||
default: break; // known size but not surfaced -> skip (already advanced)
|
||||
}
|
||||
dp = strchr(dp, 0);
|
||||
k += 2 + dsz;
|
||||
}
|
||||
if (dp == reply) {
|
||||
strcpy(reply, "no telemetry");
|
||||
} else if (*(dp-1) == ' ') {
|
||||
*(dp-1) = 0; // trim trailing space
|
||||
}
|
||||
#if ENV_INCLUDE_GPS == 1
|
||||
} else if (memcmp(command, "gps duty", 8) == 0) {
|
||||
// Power GPS only around a clock sync. For a node that runs GPS purely for
|
||||
// the (volatile) RTC this is the same service at a fraction of the power;
|
||||
// position keeps coming from prefs, see `set advert.loc`. Duty owns the cadence,
|
||||
// so a `gps period` left over would fight it.
|
||||
if (_sensors->setSettingValue("gps", "2")) {
|
||||
_prefs->getGpsPrefs()->setGpsPeriod(*_sensors, 0);
|
||||
_prefs->gps_enabled = 2;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Error, gps toggle not found");
|
||||
}
|
||||
} else if (strcmp(command, "gps") == 0 && _prefs->gps_enabled == 2) {
|
||||
// Duty cycle: the receiver is off most of the time BY DESIGN, so the
|
||||
// generic "on, inactive" would read as a dead GPS. Say which.
|
||||
LocationProvider * l = _sensors->getLocationProvider();
|
||||
if (l != NULL) {
|
||||
sprintf(reply, "> duty, %s, %s, %ld sats",
|
||||
l->isActive() ? "awake" : "asleep",
|
||||
l->hasValidFix() ? "fix" : "no fix",
|
||||
l->satellitesCount());
|
||||
} else {
|
||||
strcpy(reply, "Error, gps provider not found");
|
||||
}
|
||||
#endif
|
||||
} else if (_prefs->getGpsPrefs()->handleCommand(command, *_sensors, reply)) {
|
||||
if (_prefs->getGpsPrefs()->isDirty()) savePrefs();
|
||||
} else if (memcmp(command, "region", 6) == 0) {
|
||||
@@ -526,7 +740,16 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
if (isValidName(&config[5])) {
|
||||
StrHelper::strncpy(_prefs->node_name, &config[5], sizeof(_prefs->node_name));
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
// Přejmenování může vytlačit zapnutou ikonku z advertu, a to je změna,
|
||||
// kterou by nikdo neviděl: `set batt.icon` i `get batt.icon` na to
|
||||
// upozorňují, ale rename je ta cesta, kterou operátor jde později --
|
||||
// a bez tohohle by mu indikátor zmizel ze vzduchu bez jediné hlášky.
|
||||
if (_prefs->batt_icon && !mesh::battIconFits(strlen(_prefs->node_name), nameBudget())) {
|
||||
sprintf(reply, "OK - ALE jméno má %d B, s ikonkou se vejde jen %d B - batt.icon se zahodí",
|
||||
(int)strlen(_prefs->node_name), (int)(nameBudget() - mesh::battIconWidth()));
|
||||
} else {
|
||||
strcpy(reply, "OK");
|
||||
}
|
||||
} else {
|
||||
strcpy(reply, "Error, bad chars");
|
||||
}
|
||||
@@ -535,18 +758,28 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
savePrefs();
|
||||
strcpy(reply, _prefs->disable_fwd ? "OK - repeat is now OFF" : "OK - repeat is now ON");
|
||||
} else if (memcmp(config, "lat ", 4) == 0) {
|
||||
_prefs->node_lat = atof(&config[4]);
|
||||
_prefs->getGpsPrefs()->applyGuardReference(*_sensors);
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
float v;
|
||||
if (cli_args::parseFloat(&config[4], -90.0f, 90.0f, &v)) {
|
||||
_prefs->node_lat = v;
|
||||
_prefs->getGpsPrefs()->applyGuardReference(*_sensors);
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Error, must be -90..90");
|
||||
}
|
||||
} else if (memcmp(config, "lon ", 4) == 0) {
|
||||
_prefs->node_lon = atof(&config[4]);
|
||||
_prefs->getGpsPrefs()->applyGuardReference(*_sensors);
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
float v;
|
||||
if (cli_args::parseFloat(&config[4], -180.0f, 180.0f, &v)) {
|
||||
_prefs->node_lon = v;
|
||||
_prefs->getGpsPrefs()->applyGuardReference(*_sensors);
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Error, must be -180..180");
|
||||
}
|
||||
} else if (memcmp(config, "flood.max.unscoped ", 19) == 0) {
|
||||
uint8_t m = atoi(&config[19]);
|
||||
if (m <= 64) {
|
||||
long m; // was uint8_t = atoi(): "300" became 44 and passed
|
||||
if (cli_args::parseInt(&config[19], 0, 64, &m)) {
|
||||
_prefs->flood_max_unscoped = m;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
@@ -554,8 +787,8 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
strcpy(reply, "Error, max 64");
|
||||
}
|
||||
} else if (memcmp(config, "flood.max.advert ", 17) == 0) {
|
||||
uint8_t m = atoi(&config[17]);
|
||||
if (m <= 64) {
|
||||
long m; // was uint8_t = atoi(): "300" became 44 and passed
|
||||
if (cli_args::parseInt(&config[17], 0, 64, &m)) {
|
||||
_prefs->flood_max_advert = m;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
@@ -563,8 +796,8 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
strcpy(reply, "Error, max 64");
|
||||
}
|
||||
} else if (memcmp(config, "flood.max ", 10) == 0) {
|
||||
uint8_t m = atoi(&config[10]);
|
||||
if (m <= 64) {
|
||||
long m; // was uint8_t = atoi(): "300" became 44 and passed
|
||||
if (cli_args::parseInt(&config[10], 0, 64, &m)) {
|
||||
_prefs->flood_max = m;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
@@ -602,9 +835,14 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
strcpy(reply, "OK");
|
||||
}
|
||||
} else if (sender_timestamp == 0 && memcmp(config, "freq ", 5) == 0) {
|
||||
_prefs->freq = atof(&config[5]);
|
||||
savePrefs();
|
||||
strcpy(reply, "OK - reboot to apply");
|
||||
float f; // was atof(): "abc" saved 0, i.e. 150 MHz after the next boot's clamp
|
||||
if (cli_args::parseFloat(&config[5], 150.0f, 2500.0f, &f)) {
|
||||
_prefs->freq = f;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK - reboot to apply");
|
||||
} else {
|
||||
strcpy(reply, "Error, must be 150-2500 MHz");
|
||||
}
|
||||
#ifdef WITH_BRIDGE
|
||||
} else if (memcmp(config, "bridge.enabled ", 15) == 0) {
|
||||
_prefs->bridge_enabled = memcmp(&config[15], "on", 2) == 0;
|
||||
@@ -654,8 +892,45 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
#endif
|
||||
} else if (memcmp(config, "batt.icon.lo ", 13) == 0 || memcmp(config, "batt.icon.hi ", 13) == 0) {
|
||||
bool is_lo = config[10] == 'l';
|
||||
int mv = atoi(&config[13]);
|
||||
if (mv != 0 && (mv < 2500 || mv > 4500)) {
|
||||
strcpy(reply, "Error: expected 2500..4500, or 0 for default");
|
||||
} else {
|
||||
if (is_lo) _prefs->batt_icon_lo = mv; else _prefs->batt_icon_hi = mv;
|
||||
savePrefs();
|
||||
uint16_t lo = _prefs->batt_icon_lo ? _prefs->batt_icon_lo : BATT_ICON_LO_MV;
|
||||
uint16_t hi = _prefs->batt_icon_hi ? _prefs->batt_icon_hi : BATT_ICON_HI_MV;
|
||||
if (hi <= lo) {
|
||||
strcpy(reply, "OK - WARNING: hi <= lo, level will stay at 0");
|
||||
} else {
|
||||
sprintf(reply, "OK - scale %d..%d mV, %d levels, step %d mV",
|
||||
(uint32_t)lo, (uint32_t)hi, (uint32_t)mesh::battIconLevels(),
|
||||
(uint32_t)((hi - lo) / mesh::battIconLevels()));
|
||||
}
|
||||
}
|
||||
} else if (memcmp(config, "batt.icon ", 10) == 0) {
|
||||
_prefs->batt_icon = memcmp(&config[10], "on", 2) == 0 ? 1 : 0;
|
||||
savePrefs();
|
||||
if (!_prefs->batt_icon) {
|
||||
strcpy(reply, "off");
|
||||
} else if (!mesh::battIconFits(strlen(_prefs->node_name), nameBudget())) {
|
||||
// Say so now rather than let the operator wonder why nothing shows up:
|
||||
// the icon is dropped whole when it doesn't fit.
|
||||
sprintf(reply, "on - BUT name is %d B, max %d B with icon - icon omitted",
|
||||
(int)strlen(_prefs->node_name),
|
||||
(int)(nameBudget() - mesh::battIconWidth()));
|
||||
} else {
|
||||
strcpy(reply, "on - shows on next advert");
|
||||
}
|
||||
} else if (memcmp(config, "adc.multiplier ", 15) == 0) {
|
||||
_prefs->adc_multiplier = atof(&config[15]);
|
||||
float m;
|
||||
if (!cli_args::parseFloat(&config[15], 0.0f, 10.0f, &m)) {
|
||||
strcpy(reply, "Error, must be 0-10 (0 = board default)");
|
||||
return;
|
||||
}
|
||||
_prefs->adc_multiplier = m;
|
||||
if (_board->setAdcMultiplier(_prefs->adc_multiplier)) {
|
||||
savePrefs();
|
||||
if (_prefs->adc_multiplier == 0.0f) {
|
||||
@@ -697,6 +972,30 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
|
||||
void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* reply) {
|
||||
const char* config = &command[4];
|
||||
#ifdef LOCKED_NODE
|
||||
// CUSTOM (TeTeHacko): a locked node gives its secrets to nobody -- not to the
|
||||
// USB console (no login: whoever holds the board), not to the BLE console, not
|
||||
// to an admin over the mesh. docs/locked-bootloader.md, point 4.
|
||||
if (memcmp(config, "prv.key", 7) == 0 || memcmp(config, "guest.password", 14) == 0 ||
|
||||
memcmp(config, "bridge.secret", 13) == 0) {
|
||||
strcpy(reply, "Error: locked build");
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
#if defined(NRF52_PLATFORM)
|
||||
// CUSTOM (TeTeHacko): which silicon, and whether SWD can read the flash
|
||||
// (docs/locked-bootloader.md, point 5). Variant xxF0 and later = rev3, where
|
||||
// the hardware closes the debug port unless the firmware opens it on every
|
||||
// boot -- ours never does; rev1/rev2 obey UICR.APPROTECT alone (0xFF = open).
|
||||
if (memcmp(config, "chip", 4) == 0 && config[4] == 0) {
|
||||
uint32_t v = NRF_FICR->INFO.VARIANT;
|
||||
uint32_t ap = NRF_UICR->APPROTECT;
|
||||
sprintf(reply, "> nRF%lx %c%c%c%c, uicr.approtect %08lx (%s)", (unsigned long)NRF_FICR->INFO.PART,
|
||||
(char)(v >> 24), (char)(v >> 16), (char)(v >> 8), (char)v, (unsigned long)ap,
|
||||
(ap & 0xFF) == 0xFF ? "open" : "protected");
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
if (memcmp(config, "allow.read.only", 15) == 0) {
|
||||
sprintf(reply, "> %s", _prefs->allow_read_only ? "on" : "off");
|
||||
} else if (memcmp(config, "flood.advert.interval", 21) == 0) {
|
||||
@@ -726,6 +1025,37 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
int len = _callbacks->getSelfId().writeTo(prv_key, PRV_KEY_SIZE);
|
||||
mesh::Utils::toHex(tmp, prv_key, len);
|
||||
sprintf(reply, "> %s", tmp);
|
||||
} else if (memcmp(config, "batt.icon.lo", 12) == 0) {
|
||||
sprintf(reply, "> %d", (uint32_t)(_prefs->batt_icon_lo ? _prefs->batt_icon_lo : BATT_ICON_LO_MV));
|
||||
} else if (memcmp(config, "batt.icon.hi", 12) == 0) {
|
||||
sprintf(reply, "> %d", (uint32_t)(_prefs->batt_icon_hi ? _prefs->batt_icon_hi : BATT_ICON_HI_MV));
|
||||
} else if (memcmp(config, "batt.icon", 9) == 0) {
|
||||
// Report what actually goes on the air, not just the flag: the indicator
|
||||
// is dropped when the name leaves no room, and the voltage is the only way
|
||||
// to tell "not there yet" from "board reads nothing".
|
||||
if (!_prefs->batt_icon) {
|
||||
strcpy(reply, "> off");
|
||||
} else if (!mesh::battIconFits(strlen(_prefs->node_name), nameBudget())) {
|
||||
strcpy(reply, "> on (omitted, name too long)");
|
||||
} else if (_board->isExternalPowered()) {
|
||||
strcpy(reply, "> on (external power)");
|
||||
} else {
|
||||
uint16_t mv = _board->getBattMilliVolts();
|
||||
if (mv == 0) {
|
||||
strcpy(reply, "> on (omitted, no battery reading)");
|
||||
} else {
|
||||
// What the NEXT advert would carry, not what the last one did: the
|
||||
// state only advances in advertName(), so reporting the stored level
|
||||
// had `get` disagreeing with the advert that went out moments later.
|
||||
// Predicting is read-only -- _batt_level is deliberately not updated.
|
||||
uint16_t lo = _prefs->batt_icon_lo ? _prefs->batt_icon_lo : BATT_ICON_LO_MV;
|
||||
uint16_t hi = _prefs->batt_icon_hi ? _prefs->batt_icon_hi : BATT_ICON_HI_MV;
|
||||
uint8_t n = mesh::battIconLevels();
|
||||
uint8_t next = mesh::battIconLevel(_batt_level, mv, lo, hi, n, BATT_ICON_HYST_MV);
|
||||
sprintf(reply, "> on (level %d/%d, %d mV, scale %d..%d)",
|
||||
(uint32_t)(next + 1), (uint32_t)n, (uint32_t)mv, (uint32_t)lo, (uint32_t)hi);
|
||||
}
|
||||
}
|
||||
} else if (memcmp(config, "name", 4) == 0) {
|
||||
sprintf(reply, "> %s", _prefs->node_name);
|
||||
} else if (memcmp(config, "repeat", 6) == 0) {
|
||||
@@ -843,7 +1173,11 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
sprintf(reply, "No extra SF configured");
|
||||
}
|
||||
} else {
|
||||
sprintf(reply, "??: %s", config);
|
||||
// CUSTOM (TeTeHacko): bounded echo, as the `set` branch does. An unbounded
|
||||
// sprintf put a remote `get <167 chars>` (172 B reply) into the 164 B the
|
||||
// repeater and room server leave for it (temp[169] minus the 5 B header).
|
||||
strcpy(reply, "??: ");
|
||||
StrHelper::strncpy(&reply[4], config, 160-5);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -70,14 +70,43 @@ public:
|
||||
uint8_t advert_loc_policy = 0;
|
||||
uint32_t discovery_mod_timestamp = 0;
|
||||
float adc_multiplier = 0;
|
||||
float ina_shunt_mohm = 0; // CUSTOM (TeTeHacko): INA shunt in mOhm, 0 = build default
|
||||
char owner_info[120];
|
||||
uint8_t rx_boosted_gain = 0; // power settings
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
RxPowerSavingConfig rxps; // CUSTOM (TeTeHacko): RX duty cycle, off by default
|
||||
#endif
|
||||
uint8_t radio_fem_rxgain = 0; // LoRa FEM RX gain setting
|
||||
uint8_t radio_fem_txgain = 0; // LoRa FEM TX gain setting
|
||||
uint8_t path_hash_mode = 0; // which path mode to use when sending
|
||||
uint8_t loop_detect = 0;
|
||||
uint8_t cad_enabled = 0; // hardware Channel Activity Detection before TX (boolean)
|
||||
uint8_t extra_sf[4];
|
||||
// CUSTOM (TeTeHacko): antispam knobs of simple_repeater. Live here so that the
|
||||
// existing savePrefs()/loadPrefs() machinery persists them; other examples
|
||||
// just leave them at defaults.
|
||||
uint8_t fairness_enabled = 0; // FairnessLimiter runtime kill switch
|
||||
char filter_deny[128]; // channel-filter deny list, comma-separated node names
|
||||
// channel hashes (payload[0] of GRP_TXT/GRP_DATA) this node refuses to forward,
|
||||
// keyless -- works on private channels too. See ChannelFilter.h (`filter hash`).
|
||||
uint8_t deny_hash[8];
|
||||
uint8_t deny_hash_n = 0;
|
||||
uint16_t deny_hash_secs[8]; // per entry: 0 = block, else pass one per N s (throttle)
|
||||
uint16_t filter_age_min = 0; // drop decrypted group texts older than this; 0 = off
|
||||
uint8_t filter_dry_run = 0; // count `filter` verdicts, forward anyway
|
||||
// Battery state as an icon on the advertised name (see BatteryIcon.h).
|
||||
// Off by default: it costs bytes of the name, so it has to be asked for.
|
||||
uint8_t batt_icon = 0; // boolean
|
||||
uint16_t batt_icon_lo = 0; // scale bottom in mV; 0 = BATT_ICON_LO_MV
|
||||
uint16_t batt_icon_hi = 0; // scale top in mV; 0 = BATT_ICON_HI_MV
|
||||
// FairnessLimiter runtime tuning; 0 = use the firmware build default.
|
||||
uint8_t fair_group_cap = 0, fair_sender_cap = 0, fair_advert_cap = 0;
|
||||
uint16_t fair_group_refill_s = 0, fair_sender_refill_s = 0, fair_advert_refill_s = 0;
|
||||
uint16_t fair_advert_hours = 0; // per-origin advert window, hours; 0 = off
|
||||
uint8_t fair_dry_run = 0; // count FairnessLimiter verdicts, forward anyway
|
||||
// Radio silence watchdog (RadioSilenceWatchdog.h, simple_repeater): minutes
|
||||
// without a received frame before the receiver is re-armed, then rebooted; 0 = off.
|
||||
uint16_t radio_silence_min = 0;
|
||||
|
||||
private:
|
||||
class RadioPrefs : public CommonRadioPrefs {
|
||||
@@ -101,9 +130,20 @@ private:
|
||||
def("agc_int", _parent->agc_reset_interval);
|
||||
def("hash_mode", _parent->path_hash_mode);
|
||||
def("multi_ack", _parent->multi_acks);
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
def("rxps_en", _parent->rxps.enabled);
|
||||
def("rxps_rx_us", _parent->rxps.rx_us);
|
||||
def("rxps_sleep_us", _parent->rxps.sleep_us);
|
||||
def("rxps_level", _parent->rxps.level);
|
||||
def("rxps_preamble", _parent->rxps.preamble);
|
||||
#endif
|
||||
def("rsilence", _parent->radio_silence_min);
|
||||
}
|
||||
public:
|
||||
RadioPrefs(NodePrefs* parent) : _parent(parent) { }
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
RxPowerSavingConfig* getRxPowerSavingConfig() override { return &_parent->rxps; }
|
||||
#endif
|
||||
// CommonRadioPrefs interface
|
||||
float getFreq() const override { return _parent->freq; }
|
||||
void setFreq(float f) override { _parent->freq = f; markDirty(); }
|
||||
@@ -208,7 +248,11 @@ private:
|
||||
protected:
|
||||
void structure() override {
|
||||
def("adc_mult", _parent->adc_multiplier);
|
||||
def("ina_shunt", _parent->ina_shunt_mohm);
|
||||
def("pwr_sav_en", _parent->powersaving_enabled);
|
||||
def("bicon", _parent->batt_icon);
|
||||
def("bicon_lo", _parent->batt_icon_lo);
|
||||
def("bicon_hi", _parent->batt_icon_hi);
|
||||
}
|
||||
public:
|
||||
PowerPrefs(NodePrefs* parent) : _parent(parent) { }
|
||||
@@ -224,6 +268,21 @@ private:
|
||||
def("f_max_uns", _parent->flood_max_unscoped);
|
||||
def("f_max_adv", _parent->flood_max_advert);
|
||||
def("loop", _parent->loop_detect);
|
||||
def("fair_en", _parent->fairness_enabled);
|
||||
def("f_deny", _parent->filter_deny, sizeof(_parent->filter_deny));
|
||||
def("f_dhash", (void*)_parent->deny_hash, sizeof(_parent->deny_hash));
|
||||
def("f_dhash_n", _parent->deny_hash_n);
|
||||
def("f_dhash_s", (void*)_parent->deny_hash_secs, sizeof(_parent->deny_hash_secs));
|
||||
def("f_age", _parent->filter_age_min);
|
||||
def("f_dry", _parent->filter_dry_run);
|
||||
def("fair_gcap", _parent->fair_group_cap);
|
||||
def("fair_scap", _parent->fair_sender_cap);
|
||||
def("fair_acap", _parent->fair_advert_cap);
|
||||
def("fair_grf", _parent->fair_group_refill_s);
|
||||
def("fair_srf", _parent->fair_sender_refill_s);
|
||||
def("fair_arf", _parent->fair_advert_refill_s);
|
||||
def("fair_advh", _parent->fair_advert_hours);
|
||||
def("fair_dry", _parent->fair_dry_run);
|
||||
}
|
||||
public:
|
||||
RepeatPrefs(NodePrefs* parent) : _parent(parent) { }
|
||||
@@ -271,6 +330,9 @@ public:
|
||||
ro_password[0] = 0;
|
||||
bridge_secret[0] = 0;
|
||||
owner_info[0] = 0;
|
||||
filter_deny[0] = 0;
|
||||
memset(deny_hash, 0, sizeof(deny_hash));
|
||||
memset(deny_hash_secs, 0, sizeof(deny_hash_secs));
|
||||
}
|
||||
|
||||
CommonRadioPrefs* getRadioPrefs() { return &radio; }
|
||||
@@ -345,8 +407,14 @@ class CommonCLI {
|
||||
RegionMap* _region_map;
|
||||
ClientACL* _acl;
|
||||
char tmp[PRV_KEY_SIZE*2 + 4];
|
||||
// Name handed to AdvertDataBuilder, which keeps the pointer until encodeTo();
|
||||
// it has to outlive buildAdvertData(), hence a member and not a local.
|
||||
char _adv_name[sizeof(NodePrefs::node_name) + 8];
|
||||
uint8_t _batt_level = 0; // hysteresis state, see BatteryIcon.h
|
||||
|
||||
mesh::RTCClock* getRTCClock() { return _rtc; }
|
||||
const char* advertName(size_t budget);
|
||||
size_t nameBudget() const;
|
||||
void savePrefs();
|
||||
void loadPrefsInt(FILESYSTEM* _fs, const char* filename);
|
||||
|
||||
|
||||
@@ -7,6 +7,10 @@
|
||||
bool CommonGpsPrefs::setGpsEnabled(SensorManager& sensors, bool enabled) {
|
||||
LocationProvider* location = sensors.getLocationProvider();
|
||||
if (location == nullptr) return false;
|
||||
// `gps duty` (setting "2") runs in the sensor manager, above the provider:
|
||||
// on/off has to leave it there too, or its loop keeps cycling the receiver
|
||||
const char* mode = sensors.getSettingByKey("gps");
|
||||
if (mode != nullptr && strcmp(mode, "2") == 0) sensors.setSettingValue("gps", enabled ? "1" : "0");
|
||||
location->setGpsOn(enabled);
|
||||
setGpsEnabled(enabled);
|
||||
return true;
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
#include "CommonRadioPrefs.h"
|
||||
#include "CliArgs.h"
|
||||
#include "TxtDataHelpers.h"
|
||||
#include "Utils.h"
|
||||
#include "target.h"
|
||||
#include <ctype.h>
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
#include "radiolib/RXPowerSavingCLI.h"
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -17,8 +21,48 @@ bool looksLikeANumber(const char* s) {
|
||||
return isdigit((unsigned char)*s) || *s == '.';
|
||||
}
|
||||
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
RxPowerSavingControl* rxpsControl() {
|
||||
#ifdef WRAPPER_CLASS
|
||||
return &radio_driver;
|
||||
#else
|
||||
return nullptr;
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
// CUSTOM (TeTeHacko): the radio's verdict on the last setTxPower(), where the
|
||||
// driver keeps one (RadioLibWrapper); other drivers (ESP-NOW) count as accepted.
|
||||
template <class R>
|
||||
auto lastTxPowerStatus(R& r, int) -> decltype(r.getLastTxPowerStatus()) { return r.getLastTxPowerStatus(); }
|
||||
template <class R>
|
||||
int16_t lastTxPowerStatus(R&, long) { return 0; }
|
||||
|
||||
#ifdef MAX_LORA_TX_POWER
|
||||
constexpr long TX_POWER_MAX = MAX_LORA_TX_POWER;
|
||||
#else
|
||||
constexpr long TX_POWER_MAX = 30; // the same ceiling as the prefs load clamp
|
||||
#endif
|
||||
|
||||
} // namespace
|
||||
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
bool CommonRadioPrefs::applyRxPowerSaving(uint8_t sf, float bw) {
|
||||
_active_sf = sf;
|
||||
_active_bw = bw;
|
||||
RxPowerSavingConfig* config = getRxPowerSavingConfig();
|
||||
if (!config) return false;
|
||||
// temporary radio parameters must not overwrite the saved automatic periods
|
||||
RxPowerSavingConfig active = *config;
|
||||
return applyRxPowerSavingConfig(&active, sf, bw, rxpsControl());
|
||||
}
|
||||
|
||||
bool CommonRadioPrefs::isRxPowerSavingCalibrationActive() const {
|
||||
const auto* control = rxpsControl();
|
||||
return control && control->isRxPowerSavingCalibrationActive();
|
||||
}
|
||||
#endif
|
||||
|
||||
bool CommonRadioPrefs::getByKey(const char* key, char* value, size_t max_len) {
|
||||
if (strcmp(key, "fem_rxgain") == 0) {
|
||||
snprintf(value, max_len, "%d", (uint32_t)getFEMRxGain());
|
||||
@@ -32,12 +76,12 @@ bool CommonRadioPrefs::getByKey(const char* key, char* value, size_t max_len) {
|
||||
}
|
||||
bool CommonRadioPrefs::setByKey(const char* key, const char* value) {
|
||||
if (strcmp(key, "fem_rxgain") == 0) {
|
||||
setFEMRxGain(atoi(value));
|
||||
setFEMRxGain(atoi(value) ? 1 : 0); // boolean, as the prefs load clamps it
|
||||
markDirty();
|
||||
return true;
|
||||
}
|
||||
if (strcmp(key, "fem_txgain") == 0) {
|
||||
setFEMTxGain(atoi(value));
|
||||
setFEMTxGain(atoi(value) ? 1 : 0); // boolean, as the prefs load clamps it
|
||||
markDirty();
|
||||
return true;
|
||||
}
|
||||
@@ -45,6 +89,30 @@ bool CommonRadioPrefs::setByKey(const char* key, const char* value) {
|
||||
}
|
||||
|
||||
bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timestamp, char* reply) {
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
if (strncmp(command, "get radio.rxps", 14) == 0 && (command[14] == 0 || command[14] == ' ')) {
|
||||
const char* suffix = command + 14;
|
||||
while (*suffix == ' ') ++suffix;
|
||||
if (*suffix) return false;
|
||||
auto* config = getRxPowerSavingConfig();
|
||||
if (!config) { strcpy(reply, "Error: unsupported"); return true; }
|
||||
const uint8_t sf = _active_sf ? _active_sf : getSpreadFactor();
|
||||
const float bw = _active_sf ? _active_bw : getBandwidth();
|
||||
RxPowerSavingConfig active = *config;
|
||||
normalizeRxPowerSavingConfig(&active, sf, bw,
|
||||
rxPowerSavingCaptureCost(rxpsControl()), rxPowerSavingTransition(rxpsControl()));
|
||||
RXPowerSavingCLI::get(&active, rxpsControl(), sf, bw, reply, 160);
|
||||
return true;
|
||||
}
|
||||
if (strncmp(command, "set radio.rxps ", 15) == 0) {
|
||||
auto* config = getRxPowerSavingConfig();
|
||||
if (!config) { strcpy(reply, "Error: unsupported"); return true; }
|
||||
if (RXPowerSavingCLI::set(command + 15,
|
||||
_active_sf ? _active_sf : getSpreadFactor(), _active_sf ? _active_bw : getBandwidth(),
|
||||
config, rxpsControl(), reply, 160)) markDirty();
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
if (strcmp(command, "get radio") == 0) {
|
||||
char freq[16], bw[16];
|
||||
strcpy(freq, StrHelper::ftoa(getFreq()));
|
||||
@@ -57,16 +125,29 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest
|
||||
strcpy(tmp, &command[10]);
|
||||
const char *parts[4];
|
||||
int num = mesh::Utils::parseTextParts(tmp, parts, 4);
|
||||
float freq = num > 0 ? strtof(parts[0], nullptr) : 0.0f;
|
||||
float bw = num > 1 ? strtof(parts[1], nullptr) : 0.0f;
|
||||
uint8_t sf = num > 2 ? atoi(parts[2]) : 0;
|
||||
uint8_t cr = num > 3 ? atoi(parts[3]) : 0;
|
||||
if (freq >= 150.0f && freq <= 2500.0f && sf >= 5 && sf <= 12 && cr >= 5 && cr <= 8 && bw >= 7.0f && bw <= 500.0f) {
|
||||
float freq = 0, bw = 0;
|
||||
long sf_l = 0, cr_l = 0;
|
||||
if (num == 4 && cli_args::parseFloat(parts[0], 150.0f, 2500.0f, &freq) &&
|
||||
cli_args::parseFloat(parts[1], 7.0f, 500.0f, &bw) &&
|
||||
cli_args::parseInt(parts[2], 5, 12, &sf_l) && cli_args::parseInt(parts[3], 5, 8, &cr_l)) {
|
||||
uint8_t sf = sf_l, cr = cr_l;
|
||||
setSpreadFactor(sf);
|
||||
setCodingRate(cr);
|
||||
setFreq(freq);
|
||||
setBandwidth(bw);
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
// the RXPS timing is in symbols: a new SF/BW can make it invalid
|
||||
auto* rxps = getRxPowerSavingConfig();
|
||||
const bool timing_ok = !rxps || !rxps->enabled || normalizeRxPowerSavingConfig(
|
||||
rxps, sf, bw, rxPowerSavingCaptureCost(rxpsControl()), rxPowerSavingTransition(rxpsControl()));
|
||||
if (!timing_ok && rxpsControl()) {
|
||||
rxpsControl()->setRxPowerSaving(false, rxps->rx_us, rxps->sleep_us);
|
||||
rxpsControl()->setRxPowerSavingConfigError(true);
|
||||
}
|
||||
strcpy(reply, timing_ok ? "OK - reboot to apply" : "OK - reboot to apply; RXPS continuous: invalid timing");
|
||||
#else
|
||||
strcpy(reply, "OK - reboot to apply");
|
||||
#endif
|
||||
} else {
|
||||
strcpy(reply, "Error, invalid radio params");
|
||||
}
|
||||
@@ -120,8 +201,13 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "set int.thresh ", 15) == 0) {
|
||||
setIntThresh(atoi(&command[15]));
|
||||
strcpy(reply, "OK");
|
||||
long t;
|
||||
if (cli_args::parseInt(&command[15], 0, 255, &t)) {
|
||||
setIntThresh(t);
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Error, must be 0-255");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -155,8 +241,23 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "set tx ", 7) == 0) {
|
||||
setTxPower(atoi(&command[7]));
|
||||
radio_driver.setTxPower(getTxPower());
|
||||
// CUSTOM (TeTeHacko): was atoi() straight into the prefs and "OK" -- out of
|
||||
// range or not a number got saved, and the radio could refuse it silently
|
||||
// (SX1262 takes -9..22 and keeps its old power). Only a power the radio
|
||||
// took is saved now.
|
||||
long dbm;
|
||||
if (!cli_args::parseInt(&command[7], -9, TX_POWER_MAX, &dbm)) {
|
||||
sprintf(reply, "Error, must be -9..%d", (int)TX_POWER_MAX);
|
||||
return true;
|
||||
}
|
||||
int8_t old_dbm = getTxPower();
|
||||
radio_driver.setTxPower((int8_t)dbm);
|
||||
if (lastTxPowerStatus(radio_driver, 0) != 0) {
|
||||
radio_driver.setTxPower(old_dbm);
|
||||
sprintf(reply, "Error, radio refuses %d dBm (kept %d)", (int)dbm, (int)old_dbm);
|
||||
return true;
|
||||
}
|
||||
setTxPower((int8_t)dbm);
|
||||
strcpy(reply, "OK");
|
||||
return true;
|
||||
}
|
||||
@@ -166,8 +267,8 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "set rxdelay ", 12) == 0) {
|
||||
float db = atof(&command[12]);
|
||||
if (db >= 0 && db <= 20.0f) {
|
||||
float db;
|
||||
if (cli_args::parseFloat(&command[12], 0, 20.0f, &db)) {
|
||||
setRxDelay(db);
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
@@ -181,8 +282,11 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "set agc.reset.interval ", 23) == 0) {
|
||||
int secs = atoi(&command[23]);
|
||||
secs = constrain(secs, 0, 255 * 4);
|
||||
long secs;
|
||||
if (!cli_args::parseInt(&command[23], 0, 255 * 4, &secs)) {
|
||||
strcpy(reply, "Error, must be 0-1020");
|
||||
return true;
|
||||
}
|
||||
setAgcResetInt((uint16_t) secs);
|
||||
sprintf(reply, "OK - interval rounded to %d", (uint32_t) getAgcResetInt());
|
||||
return true;
|
||||
@@ -194,8 +298,8 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest
|
||||
}
|
||||
if (memcmp(command, "set path.hash.mode ", 19) == 0) {
|
||||
const char* config = command + 19;
|
||||
uint8_t mode = atoi(config);
|
||||
if (mode < 3) {
|
||||
long mode;
|
||||
if (cli_args::parseInt(config, 0, 2, &mode)) {
|
||||
setHashMode(mode);
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
@@ -209,8 +313,13 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "set multi.acks ", 15) == 0) {
|
||||
setMultiAcks(atoi(&command[15]));
|
||||
strcpy(reply, "OK");
|
||||
long n;
|
||||
if (cli_args::parseInt(&command[15], 0, 1, &n)) {
|
||||
setMultiAcks(n);
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Error, must be 0 or 1");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -219,8 +328,8 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "set txdelay ", 12) == 0) {
|
||||
float f = atof(&command[12]);
|
||||
if (f >= 0 && f <= 2.0f) {
|
||||
float f;
|
||||
if (cli_args::parseFloat(&command[12], 0, 2.0f, &f)) {
|
||||
setFloodTxDelay(f);
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
@@ -234,8 +343,8 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "set direct.txdelay ", 19) == 0) {
|
||||
float f = atof(&command[19]);
|
||||
if (f >= 0 && f <= 2.0f) {
|
||||
float f;
|
||||
if (cli_args::parseFloat(&command[19], 0, 2.0f, &f)) {
|
||||
setDirectTxDelay(f);
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
#pragma once
|
||||
#include "ConfigSerializer.h"
|
||||
#include "KeyValueStore.h"
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
#include "radiolib/RXPowerSaving.h"
|
||||
#endif
|
||||
|
||||
class CommonRadioPrefs : public ConfigSerializer, public KeyValueStore {
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
uint8_t _active_sf = 0; // what the radio runs now (tempradio differs from prefs)
|
||||
float _active_bw = 0;
|
||||
#endif
|
||||
protected:
|
||||
CommonRadioPrefs() { }
|
||||
public:
|
||||
@@ -59,6 +66,15 @@ public:
|
||||
|
||||
bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply);
|
||||
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
// CUSTOM (TeTeHacko): RXPS, see radiolib/RXPowerSaving.h. Prefs that carry an
|
||||
// RXPS config override getRxPowerSavingConfig(); apply after every change of
|
||||
// the radio's SF/BW (the timing is in symbols).
|
||||
virtual RxPowerSavingConfig* getRxPowerSavingConfig() { return nullptr; }
|
||||
bool applyRxPowerSaving(uint8_t sf, float bw);
|
||||
bool isRxPowerSavingCalibrationActive() const;
|
||||
#endif
|
||||
|
||||
bool setByKey(const char* key, const char* value) override; // for dynamic key/value access
|
||||
bool getByKey(const char* key, char* value, size_t max_len) override;
|
||||
};
|
||||
@@ -55,6 +55,7 @@ public:
|
||||
uint8_t default_scope_key[16];
|
||||
float tz_offset = 0;
|
||||
float adc_multiplier = 0; // battery ADC multiplier, 0 = board default
|
||||
float ina_shunt_mohm = 0; // CUSTOM (TeTeHacko): INA shunt in mOhm, 0 = build default
|
||||
#ifdef ENABLE_WIFI_INTERFACE
|
||||
#ifndef WIFI_SSID
|
||||
#define WIFI_SSID ""
|
||||
@@ -235,6 +236,7 @@ private:
|
||||
def("tel_env", _parent->telemetry_mode_env);
|
||||
def("tz_offset", _parent->tz_offset);
|
||||
def("adc_mult", _parent->adc_multiplier);
|
||||
def("ina_shunt", _parent->ina_shunt_mohm);
|
||||
}
|
||||
public:
|
||||
CompanionPrefs(NodePrefs* parent) : _parent(parent) { }
|
||||
|
||||
@@ -223,12 +223,14 @@ public:
|
||||
return; // ESP-IDF preserves system time across deep sleep
|
||||
}
|
||||
// All other resets (power-on, crash, WDT, brownout) lose system time.
|
||||
// Restore from RTC backup if valid, otherwise use hardcoded seed.
|
||||
// Restore from RTC backup if valid, otherwise seed with the build time
|
||||
// (stamped builds) or RTC_TIME_MIN, whichever is newer.
|
||||
uint32_t seed = FIRMWARE_BUILD_EPOCH > RTC_TIME_MIN ? FIRMWARE_BUILD_EPOCH : RTC_TIME_MIN;
|
||||
struct timeval tv;
|
||||
if (_rtc_backup_magic == RTC_BACKUP_MAGIC && _rtc_backup_time > RTC_TIME_MIN) {
|
||||
if (_rtc_backup_magic == RTC_BACKUP_MAGIC && _rtc_backup_time > seed) {
|
||||
tv.tv_sec = _rtc_backup_time;
|
||||
} else {
|
||||
tv.tv_sec = RTC_TIME_MIN;
|
||||
tv.tv_sec = seed;
|
||||
}
|
||||
tv.tv_usec = 0;
|
||||
settimeofday(&tv, NULL);
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
#include "FairnessLimiter.h"
|
||||
|
||||
#include <MeshCore.h>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
uint8_t FairnessLimiter::peekGroup(const uint8_t* hash) {
|
||||
auto i = group_idx(hash);
|
||||
if (i >= GROUP_MAP_SIZE) {
|
||||
return 0;
|
||||
}
|
||||
return group_map[i];
|
||||
}
|
||||
|
||||
bool FairnessLimiter::takeGroup(const uint8_t* hash) {
|
||||
auto i = group_idx(hash);
|
||||
bool allow = false;
|
||||
if (i < GROUP_MAP_SIZE && group_map[i] > 0) {
|
||||
group_map[i]--;
|
||||
allow = true;
|
||||
} else {
|
||||
denied_group++;
|
||||
if (i < GROUP_MAP_SIZE && group_deny[i] != 0xFFFF) group_deny[i]++;
|
||||
}
|
||||
MESH_DEBUG_PRINTLN("FAIR, group=%02X allow=%u", (uint32_t)hash[0], (uint32_t)allow);
|
||||
return allow;
|
||||
}
|
||||
|
||||
void FairnessLimiter::refillGroup() {
|
||||
for (int i = 0; i < GROUP_MAP_SIZE; i++) {
|
||||
if (group_map[i] < group_cap) {
|
||||
group_map[i]++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t FairnessLimiter::peekSenderNormal(const uint8_t* hash) {
|
||||
auto i = sender_normal_idx(hash);
|
||||
if (i >= SENDER_NORMAL_MAP_SIZE) {
|
||||
return 0;
|
||||
}
|
||||
return sender_normal_map[i];
|
||||
}
|
||||
|
||||
bool FairnessLimiter::takeSenderNormal(const uint8_t* hash) {
|
||||
auto i = sender_normal_idx(hash);
|
||||
bool allow = false;
|
||||
if (i < SENDER_NORMAL_MAP_SIZE && sender_normal_map[i] > 0) {
|
||||
sender_normal_map[i]--;
|
||||
allow = true;
|
||||
} else {
|
||||
denied_sender_normal++;
|
||||
if (i < SENDER_NORMAL_MAP_SIZE && sender_normal_deny[i] != 0xFFFF) sender_normal_deny[i]++;
|
||||
}
|
||||
MESH_DEBUG_PRINTLN("FAIR, sender=%02X prio=normal allow=%u", (uint32_t)hash[0], (uint32_t)allow);
|
||||
return allow;
|
||||
}
|
||||
|
||||
void FairnessLimiter::refillSenderNormal() {
|
||||
for (int i = 0; i < SENDER_NORMAL_MAP_SIZE; i++) {
|
||||
if (sender_normal_map[i] < sender_normal_cap) {
|
||||
sender_normal_map[i]++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t FairnessLimiter::peekSenderLow(const uint8_t* hash) {
|
||||
auto i = sender_low_idx(hash);
|
||||
if (i >= SENDER_LOW_MAP_SIZE) {
|
||||
return 0;
|
||||
}
|
||||
return sender_low_map[i];
|
||||
}
|
||||
|
||||
bool FairnessLimiter::takeSenderLow(const uint8_t* hash) {
|
||||
auto i = sender_low_idx(hash);
|
||||
bool allow = false;
|
||||
if (i < SENDER_LOW_MAP_SIZE && sender_low_map[i] > 0) {
|
||||
sender_low_map[i]--;
|
||||
allow = true;
|
||||
} else {
|
||||
denied_sender_low++;
|
||||
if (i < SENDER_LOW_MAP_SIZE && sender_low_deny[i] != 0xFFFF) sender_low_deny[i]++;
|
||||
}
|
||||
MESH_DEBUG_PRINTLN("FAIR, sender=%02X prio=low allow=%u", (uint32_t)hash[0], (uint32_t)allow);
|
||||
return allow;
|
||||
}
|
||||
|
||||
void FairnessLimiter::refillSenderLow() {
|
||||
for (int i = 0; i < SENDER_LOW_MAP_SIZE; i++) {
|
||||
if (sender_low_map[i] < sender_low_cap) {
|
||||
sender_low_map[i]++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool FairnessLimiter::allowPacket(const mesh::Packet* pkt, uint32_t now_ms) {
|
||||
last_shed = FAIR_SHED_NONE;
|
||||
// Don't limit versions we don't understand.
|
||||
if (pkt->getPayloadVer() != PAYLOAD_VER_1) {
|
||||
return true;
|
||||
}
|
||||
|
||||
#if FAIRNESS_ALLOW_DIRECT
|
||||
// Don't limit direct
|
||||
if (!pkt->isRouteFlood()) {
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
|
||||
uint8_t hash[1] = { 0x00 };
|
||||
auto type = pkt->getPayloadType();
|
||||
|
||||
// Per-origin advert window -- flood adverts only, ahead of the buckets. The
|
||||
// payload starts with the origin's public key.
|
||||
if (type == PAYLOAD_TYPE_ADVERT && pkt->isRouteFlood() && pkt->payload_len >= ADVERT_WINDOW_KEY_LEN
|
||||
&& !advert_window.allow(pkt->payload, now_ms)) {
|
||||
denied_window++;
|
||||
MESH_DEBUG_PRINTLN("FAIR, advert window origin=%02X%02X%02X%02X dry=%u", (uint32_t)pkt->payload[0],
|
||||
(uint32_t)pkt->payload[1], (uint32_t)pkt->payload[2], (uint32_t)pkt->payload[3],
|
||||
(uint32_t)dry_run);
|
||||
return shed(FAIR_SHED_WINDOW);
|
||||
}
|
||||
|
||||
if (!buckets_enabled) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Packets by group channel hash
|
||||
if (type == PAYLOAD_TYPE_GRP_TXT || type == PAYLOAD_TYPE_GRP_DATA) {
|
||||
if (pkt->payload_len < 1) return true; // malformed, not ours to judge
|
||||
hash[0] = pkt->payload[0];
|
||||
return takeGroup(hash) || shed(FAIR_SHED_GROUP);
|
||||
}
|
||||
|
||||
// Packets with a plaintext 1-byte src hash at payload[1] (see Mesh.cpp,
|
||||
// PAYLOAD_TYPE_PATH/REQ/RESPONSE/TXT_MSG parse: dest_hash, then src_hash)
|
||||
if (type == PAYLOAD_TYPE_PATH || type == PAYLOAD_TYPE_REQ || type == PAYLOAD_TYPE_RESPONSE ||
|
||||
type == PAYLOAD_TYPE_TXT_MSG || type == PAYLOAD_TYPE_ANON_REQ) {
|
||||
if (pkt->payload_len < 2) return true; // malformed, not ours to judge
|
||||
hash[0] = pkt->payload[1];
|
||||
return takeSenderNormal(hash) || shed(FAIR_SHED_SENDER);
|
||||
}
|
||||
|
||||
if (type == PAYLOAD_TYPE_ADVERT) {
|
||||
if (pkt->payload_len < 1) return true; // malformed, not ours to judge
|
||||
hash[0] = pkt->payload[0]; // first byte of sender pub key
|
||||
return takeSenderLow(hash) || shed(FAIR_SHED_ADVERT);
|
||||
}
|
||||
|
||||
// Not classified (allowed through):
|
||||
// PAYLOAD_TYPE_ACK, PAYLOAD_TYPE_TRACE, PAYLOAD_TYPE_MULTIPART,
|
||||
// PAYLOAD_TYPE_CONTROL, PAYLOAD_TYPE_RAW_CUSTOM
|
||||
return true;
|
||||
}
|
||||
|
||||
// Append the busiest deny buckets of one category to `out`. Repeated max-scan
|
||||
// over a small array (<=128) -- picks up to `top` entries, busiest first, and
|
||||
// skips a bucket once emitted by nulling a scratch copy. Returns chars written.
|
||||
static int fmt_deny_cat(char* out, int max_len, const char* label,
|
||||
uint16_t* deny, int size, uint8_t cap, int top) {
|
||||
int w = snprintf(out, max_len, "%s(cap %u):", label, (unsigned)cap);
|
||||
if (w < 0 || w >= max_len) return (w < 0) ? 0 : max_len - 1;
|
||||
bool any = false;
|
||||
for (int n = 0; n < top; n++) {
|
||||
int best = -1;
|
||||
uint16_t best_v = 0;
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (deny[i] > best_v) { best_v = deny[i]; best = i; }
|
||||
}
|
||||
if (best < 0) break; // no non-zero left
|
||||
int adv = snprintf(out + w, max_len - w, " %02x=%u", (unsigned)best, (unsigned)best_v);
|
||||
if (adv < 0 || adv >= max_len - w) { out[w] = 0; break; } // no room, stop clean
|
||||
w += adv;
|
||||
any = true;
|
||||
deny[best] = 0; // consumed for the next pass; `deny` is formatGrid's scratch copy
|
||||
}
|
||||
if (!any) {
|
||||
int adv = snprintf(out + w, max_len - w, " -");
|
||||
if (adv > 0 && adv < max_len - w) w += adv;
|
||||
}
|
||||
return w;
|
||||
}
|
||||
|
||||
int FairnessLimiter::formatGrid(char* out, int max_len) const {
|
||||
if (max_len <= 0) return 0;
|
||||
// Work on scratch copies so the busiest-first selection can null entries as
|
||||
// it consumes them without disturbing the live counters. Plain locals (~448 B
|
||||
// on the stack) -- called only from the main-loop CLI path, never an ISR.
|
||||
uint16_t g[GROUP_MAP_SIZE], sn[SENDER_NORMAL_MAP_SIZE], sl[SENDER_LOW_MAP_SIZE];
|
||||
memcpy(g, group_deny, sizeof(g));
|
||||
memcpy(sn, sender_normal_deny, sizeof(sn));
|
||||
memcpy(sl, sender_low_deny, sizeof(sl));
|
||||
|
||||
int w = 0;
|
||||
w += fmt_deny_cat(out + w, max_len - w, "group", g, GROUP_MAP_SIZE, group_cap, 6);
|
||||
if (w < max_len - 2) { int a = snprintf(out + w, max_len - w, " | "); if (a > 0) w += a; }
|
||||
w += fmt_deny_cat(out + w, max_len - w, "sender", sn, SENDER_NORMAL_MAP_SIZE, sender_normal_cap, 6);
|
||||
if (w < max_len - 2) { int a = snprintf(out + w, max_len - w, " | "); if (a > 0) w += a; }
|
||||
w += fmt_deny_cat(out + w, max_len - w, "advert", sl, SENDER_LOW_MAP_SIZE, sender_low_cap, 4);
|
||||
return w;
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
#pragma once
|
||||
|
||||
// CUSTOM (TeTeHacko): port of Beanow's "fairness limiter" (upstream proposal
|
||||
// meshcore-dev/MeshCore#1502, branch beanow/wp-repeat). Token-bucket rate
|
||||
// limiting of FORWARDED packets, bucketed by the 1-byte identifiers that are
|
||||
// already in the clear on the air -- so it needs no protocol change and no
|
||||
// decryption. It is an approximation by design: buckets collide (masks below)
|
||||
// and every key is sender-controlled, so this is containment of accidental or
|
||||
// lazy floods, not security. DIRECT (routed) traffic is never limited.
|
||||
//
|
||||
// Deviations from Beanow's branch, on purpose:
|
||||
// * no RTCClock dependency -- it was only feeding log timestamps; logging
|
||||
// goes through MESH_DEBUG_PRINTLN like the rest of this tree, which also
|
||||
// lets the class run in native unit tests without a clock mock.
|
||||
// * allowPacket() bounds-checks payload_len before reading payload bytes.
|
||||
// The whole CI suite runs under ASAN because of earlier OOB parses; a
|
||||
// limiter keyed on payload[1] must not be the next one.
|
||||
|
||||
#include <Packet.h>
|
||||
#include <stdint.h>
|
||||
#include "AdvertWindow.h"
|
||||
|
||||
// Sender hashes 0x00 and 0xFF are NOT special here. Our firmware never creates
|
||||
// such an identity (re-roll on create, validatePrivateKey() on import), but the
|
||||
// mesh still carries them: over 30 days (Sep-Oct 2026, CZ mesh) 50 floods of
|
||||
// REQ/PATH/TXT_MSG/RESPONSE came from 0x00/0xFF senders -- older identities and
|
||||
// other implementations. And for ANON_REQ payload[1] is the first byte of a
|
||||
// random ephemeral key, so "always deny" also dropped 2 in 256 anonymous
|
||||
// requests from anyone. Denying them always (as the original branch did)
|
||||
// dropped every such flood; now they are limited like any other bucket.
|
||||
// Note: mask, cap and refill interval are highly connected parameters.
|
||||
#define GROUP_MASK 0b00011111 // 5-bit address
|
||||
#define SENDER_NORMAL_MASK 0b00111111 // 6-bit address
|
||||
#define SENDER_LOW_MASK 0b01111111 // 7-bit address
|
||||
|
||||
// Refill intervals: ONE token per bucket per interval. Steady-state rate is
|
||||
// 1/interval, cap bounds the burst. Overridable per env from platformio ini.
|
||||
//
|
||||
// Sized from real traffic (6 Sep - 6 Oct 2026: 207k floods heard on the CZ
|
||||
// mesh at one-site, replayed through this limiter with
|
||||
// tools/fairness_replay.py -- rerun it when the traffic changes). The zero-loss frontier
|
||||
// over those 30 days was group 60 s/cap 60, sender 10 s/cap 60, advert 600 s/
|
||||
// cap 12; the defaults below keep about 2x headroom on top. The busiest
|
||||
// legitimate channel runs ~26 msg/h around the clock, so the limiter is a net
|
||||
// for runaway floods (the bot that prompted it sent ~330 msg/h), not a quota.
|
||||
// The earlier defaults (cap 20/30/4, refill 180 s/240 s/7200 s) would have
|
||||
// shed 9 % of channel messages, 15 % of sender-keyed traffic and 15 % of adverts.
|
||||
#ifndef FAIRNESS_GROUP_REFILL_MS
|
||||
#define FAIRNESS_GROUP_REFILL_MS (30 * 1000)
|
||||
#endif
|
||||
#ifndef FAIRNESS_SENDER_NORMAL_REFILL_MS
|
||||
#define FAIRNESS_SENDER_NORMAL_REFILL_MS (10 * 1000)
|
||||
#endif
|
||||
#ifndef FAIRNESS_SENDER_LOW_REFILL_MS
|
||||
#define FAIRNESS_SENDER_LOW_REFILL_MS (10 * 60 * 1000)
|
||||
#endif
|
||||
|
||||
// Capacity (max burst) per bucket. uint8_t, so at most 255.
|
||||
#ifndef FAIRNESS_GROUP_CAP
|
||||
#define FAIRNESS_GROUP_CAP 100
|
||||
#endif
|
||||
#ifndef FAIRNESS_SENDER_NORMAL_CAP
|
||||
#define FAIRNESS_SENDER_NORMAL_CAP 150
|
||||
#endif
|
||||
#ifndef FAIRNESS_SENDER_LOW_CAP
|
||||
#define FAIRNESS_SENDER_LOW_CAP 30
|
||||
#endif
|
||||
|
||||
// Simply allow all direct messages?
|
||||
#ifndef FAIRNESS_ALLOW_DIRECT
|
||||
#define FAIRNESS_ALLOW_DIRECT 1
|
||||
#endif
|
||||
|
||||
// Derived from the masks, WONT fit in uint8 when full 0xFF mask.
|
||||
#define GROUP_MAP_SIZE (GROUP_MASK + 1)
|
||||
#define SENDER_NORMAL_MAP_SIZE (SENDER_NORMAL_MASK + 1)
|
||||
#define SENDER_LOW_MAP_SIZE (SENDER_LOW_MASK + 1)
|
||||
|
||||
/**
|
||||
* A token bucket rate limiter, which attempts to limit by sender or group channel.
|
||||
*
|
||||
* It provides some mitigation against accidental spam, as well as DoS attacks.
|
||||
* However it's merely an approximation, as there will be ID collisions and easy
|
||||
* ways to game it.
|
||||
*
|
||||
* Until a V2 protocol provides new means of limiting, the goal is a "better than
|
||||
* nothing" reduction in wasteful repeats, freeing airtime for useful repeats.
|
||||
*/
|
||||
// Why a packet was shed (lastShed()). WINDOW = per-origin advert window.
|
||||
enum FairShed : uint8_t { FAIR_SHED_NONE = 0, FAIR_SHED_GROUP, FAIR_SHED_SENDER, FAIR_SHED_ADVERT, FAIR_SHED_WINDOW,
|
||||
FAIR_SHED_N };
|
||||
|
||||
class FairnessLimiter {
|
||||
// Capacity of when a bucket is full. Runtime-settable (setGroupCap etc.) so
|
||||
// limits can be loosened over RF admin without a reflash -- 0 to a setter
|
||||
// resets to the build default below.
|
||||
uint8_t group_cap = FAIRNESS_GROUP_CAP, sender_normal_cap = FAIRNESS_SENDER_NORMAL_CAP,
|
||||
sender_low_cap = FAIRNESS_SENDER_LOW_CAP;
|
||||
|
||||
// Deny stats
|
||||
uint32_t denied_group = 0, denied_sender_normal = 0, denied_sender_low = 0;
|
||||
// Token buckets
|
||||
uint8_t sender_normal_map[SENDER_NORMAL_MAP_SIZE] = {};
|
||||
uint8_t sender_low_map[SENDER_LOW_MAP_SIZE] = {};
|
||||
uint8_t group_map[GROUP_MAP_SIZE] = {};
|
||||
// Per-bucket deny counters -- the "grid": which hash buckets we are actually
|
||||
// shedding, so a shed is visible instead of a bare total. Saturating uint16.
|
||||
uint16_t group_deny[GROUP_MAP_SIZE] = {};
|
||||
uint16_t sender_normal_deny[SENDER_NORMAL_MAP_SIZE] = {};
|
||||
uint16_t sender_low_deny[SENDER_LOW_MAP_SIZE] = {};
|
||||
|
||||
// Per-origin advert window (issue #2), runs ahead of the advert bucket so a
|
||||
// repeat advert never takes a token a legitimate one would need.
|
||||
AdvertWindow advert_window;
|
||||
uint32_t denied_window = 0;
|
||||
// Buckets on/off (`fairness on|off`); the window has its own switch (hours).
|
||||
bool buckets_enabled = true;
|
||||
// Dry-run (issue #1): every verdict is counted as if enforced, but the packet
|
||||
// is forwarded anyway -- sizes a setting on a live mast before it bites.
|
||||
bool dry_run = false;
|
||||
FairShed last_shed = FAIR_SHED_NONE;
|
||||
// Estimated airtime of what was shed (or would have been, in dry-run), ms,
|
||||
// per FairShed reason. Fed by the caller, which owns the radio.
|
||||
uint32_t shed_air_ms[FAIR_SHED_N] = {};
|
||||
|
||||
bool shed(FairShed why) { last_shed = why; return dry_run; }
|
||||
|
||||
public:
|
||||
FairnessLimiter() {}
|
||||
|
||||
uint8_t peekGroup(const uint8_t* hash);
|
||||
void refillGroup();
|
||||
uint8_t peekSenderNormal(const uint8_t* hash);
|
||||
void refillSenderNormal();
|
||||
uint8_t peekSenderLow(const uint8_t* hash);
|
||||
void refillSenderLow();
|
||||
|
||||
/**
|
||||
* \brief Classify the packet and take a token from the matching bucket.
|
||||
* CONSUMES a token when one is available -- call it only for a packet that
|
||||
* would otherwise be forwarded, and only once per packet.
|
||||
* \returns true if the packet should be forwarded
|
||||
*/
|
||||
bool allowPacket(const mesh::Packet* pkt, uint32_t now_ms);
|
||||
// Without a clock: the advert window sees every call at t=0. For tests and
|
||||
// callers that never enable the window.
|
||||
bool allowPacket(const mesh::Packet* pkt) { return allowPacket(pkt, 0); }
|
||||
|
||||
// What the LAST allowPacket() call shed (FAIR_SHED_NONE = passed on its
|
||||
// merits). In dry-run it is set although allowPacket() returned true.
|
||||
FairShed lastShed() const { return last_shed; }
|
||||
void addShedAirtime(FairShed why, uint32_t ms) { if (why < FAIR_SHED_N) shed_air_ms[why] += ms; }
|
||||
uint32_t shedAirtimeMs(FairShed why) const { return why < FAIR_SHED_N ? shed_air_ms[why] : 0; }
|
||||
|
||||
void setBucketsEnabled(bool on) { buckets_enabled = on; }
|
||||
bool bucketsEnabled() const { return buckets_enabled; }
|
||||
void setDryRun(bool on) { dry_run = on; }
|
||||
bool dryRun() const { return dry_run; }
|
||||
|
||||
AdvertWindow& advertWindow() { return advert_window; }
|
||||
const AdvertWindow& advertWindow() const { return advert_window; }
|
||||
uint32_t deniedWindow() const { return denied_window; }
|
||||
|
||||
// Inspect stats
|
||||
uint32_t deniedSenderNormal() const { return denied_sender_normal; }
|
||||
uint32_t deniedSenderLow() const { return denied_sender_low; }
|
||||
uint32_t deniedGroup() const { return denied_group; }
|
||||
|
||||
// Runtime cap tuning (0 = restore the build default for that bucket).
|
||||
void setGroupCap(uint8_t c) { group_cap = c ? c : FAIRNESS_GROUP_CAP; }
|
||||
void setSenderNormalCap(uint8_t c) { sender_normal_cap = c ? c : FAIRNESS_SENDER_NORMAL_CAP; }
|
||||
void setSenderLowCap(uint8_t c) { sender_low_cap = c ? c : FAIRNESS_SENDER_LOW_CAP; }
|
||||
uint8_t groupCap() const { return group_cap; }
|
||||
uint8_t senderNormalCap() const { return sender_normal_cap; }
|
||||
uint8_t senderLowCap() const { return sender_low_cap; }
|
||||
|
||||
// The grid: append "<pfx>=<count>" for each bucket with denies, per category,
|
||||
// busiest first, into `out` (bounded by max_len). Returns chars written.
|
||||
// `pfx` is the low bits of the sender/channel hash -- cross-reference the
|
||||
// observer feed / CoreScope to map a hot bucket back to an actual node.
|
||||
int formatGrid(char* out, int max_len) const;
|
||||
|
||||
static int sender_normal_idx(const uint8_t* hash) { return hash[0] & SENDER_NORMAL_MASK; }
|
||||
static int sender_low_idx(const uint8_t* hash) { return hash[0] & SENDER_LOW_MASK; }
|
||||
static int group_idx(const uint8_t* hash) { return hash[0] & GROUP_MASK; }
|
||||
|
||||
protected:
|
||||
bool takeSenderNormal(const uint8_t* hash);
|
||||
bool takeSenderLow(const uint8_t* hash);
|
||||
bool takeGroup(const uint8_t* hash);
|
||||
};
|
||||
@@ -0,0 +1,214 @@
|
||||
// CUSTOM (TeTeHacko): in-place delta update, see FwPatch.h.
|
||||
//
|
||||
// C++ file on purpose: `helpers/*.cpp` is in every nRF52 env's build_src_filter,
|
||||
// a .c file would need a filter entry in each of them. detools compiles as C++
|
||||
// unchanged. Only nRF52 and the native test build it (ARDUINO without
|
||||
// NRF52_PLATFORM = ESP32/RP2040/STM32, nothing to do there).
|
||||
//
|
||||
// This translation unit compiles the vendored detools + heatshrink decoder
|
||||
// (src/helpers/fwpatch/detools, unmodified, see README.tth.md there) together
|
||||
// with the driver below. On the node tools/ota_ramlib.py moves the whole object
|
||||
// to RAM and redirects memcpy/memset to the local copies at the bottom, so not a
|
||||
// single instruction or table of the real run lives in the flash it rewrites
|
||||
// (tools/ota_check_ramfunc.sh checks the result).
|
||||
|
||||
#if defined(NRF52_PLATFORM) || !defined(ARDUINO)
|
||||
|
||||
// --- vendored code, configured here instead of editing it ------------------------
|
||||
#define HEATSHRINK_CONFIG_H // skip the vendored config, these values win
|
||||
#define HEATSHRINK_DYNAMIC_ALLOC 0
|
||||
#define HEATSHRINK_STATIC_INPUT_BUFFER_SIZE 256
|
||||
#define HEATSHRINK_STATIC_WINDOW_BITS 11 // tools/ota_pack.py must use the same
|
||||
#define HEATSHRINK_STATIC_LOOKAHEAD_BITS 10
|
||||
#define HEATSHRINK_DEBUGGING_LOGS 0
|
||||
#define HEATSHRINK_USE_INDEX 0
|
||||
|
||||
#define DETOOLS_CONFIG_FILE_IO 0
|
||||
#define DETOOLS_CONFIG_COMPRESSION_NONE 0
|
||||
#define DETOOLS_CONFIG_COMPRESSION_LZMA 0
|
||||
#define DETOOLS_CONFIG_COMPRESSION_CRLE 0
|
||||
#define DETOOLS_CONFIG_COMPRESSION_HEATSHRINK 1
|
||||
|
||||
#include "FwPatch.h"
|
||||
|
||||
#include "fwpatch/detools/detools.c"
|
||||
#include "fwpatch/detools/heatshrink/heatshrink_decoder.c"
|
||||
|
||||
// --- driver --------------------------------------------------------------------
|
||||
|
||||
// keeps GCC from turning these byte loops back into memcpy/memset calls
|
||||
#define FWP_NOLIBC __attribute__((optimize("no-tree-loop-distribute-patterns")))
|
||||
|
||||
static uint8_t g_page[FWP_PAGE];
|
||||
static struct detools_apply_patch_in_place_t g_dt;
|
||||
|
||||
#define NO_PAGE ((uintptr_t)-1)
|
||||
|
||||
FWP_NOLIBC static void fwp_copy(uint8_t *d, const uint8_t *s, uint32_t n) {
|
||||
while (n--)
|
||||
*d++ = *s++;
|
||||
}
|
||||
|
||||
static void flush_page(fwp_job *j) {
|
||||
if (j->page_addr == NO_PAGE) return;
|
||||
if (!j->dry) j->write(j->mem_base + j->page_addr, g_page, FWP_PAGE);
|
||||
j->page_addr = NO_PAGE;
|
||||
}
|
||||
|
||||
static int in_shift_phase(void) {
|
||||
return g_dt.state == detools_apply_patch_state_init_t;
|
||||
}
|
||||
|
||||
static int cb_read(void *arg, void *dst, uintptr_t src, size_t size) {
|
||||
fwp_job *j = (fwp_job *)arg;
|
||||
uint8_t *d = (uint8_t *)dst;
|
||||
if (src > j->mem_size || size > j->mem_size - src) return j->err = FWP_ERR_ARGS;
|
||||
if (!in_shift_phase() && src < j->written_end) return j->err = FWP_ERR_OVERREAD;
|
||||
while (size > 0) {
|
||||
uintptr_t a = src;
|
||||
size_t n = size;
|
||||
if (j->dry && src >= j->shift_low && src < j->shift_high) {
|
||||
// the real run moved this page up by `shift`; the original still sits there
|
||||
a = src - j->shift;
|
||||
if (src + n > j->shift_high) n = j->shift_high - src;
|
||||
} else if (j->dry && src < j->shift_low && src + n > j->shift_low) {
|
||||
n = j->shift_low - src;
|
||||
}
|
||||
fwp_copy(d, (const uint8_t *)(j->mem_base + a), (uint32_t)n);
|
||||
d += n;
|
||||
src += n;
|
||||
size -= n;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int cb_erase(void *arg, uintptr_t addr, size_t size) {
|
||||
fwp_job *j = (fwp_job *)arg;
|
||||
if ((addr % FWP_PAGE) != 0 || size == 0 || size > FWP_PAGE || addr + FWP_PAGE > j->mem_size)
|
||||
return j->err = FWP_ERR_ARGS;
|
||||
flush_page(j);
|
||||
if (j->tick) j->tick();
|
||||
if (in_shift_phase()) {
|
||||
if (j->dry) {
|
||||
if (addr < j->shift_low) j->shift_low = (uint32_t)addr;
|
||||
if (addr + FWP_PAGE > j->shift_high) j->shift_high = (uint32_t)(addr + FWP_PAGE);
|
||||
}
|
||||
} else {
|
||||
if (addr != j->written_end) return j->err = FWP_ERR_ORDER;
|
||||
j->written_end = (uint32_t)(addr + size);
|
||||
}
|
||||
if (!j->dry) j->erase(j->mem_base + addr);
|
||||
for (uint32_t i = 0; i < FWP_PAGE; i++)
|
||||
g_page[i] = 0xFF;
|
||||
j->page_addr = addr;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int cb_write(void *arg, uintptr_t dst, void *src, size_t size) {
|
||||
fwp_job *j = (fwp_job *)arg;
|
||||
if (j->page_addr == NO_PAGE || dst < j->page_addr || size > FWP_PAGE - (dst - j->page_addr))
|
||||
return j->err = FWP_ERR_ORDER;
|
||||
fwp_copy(&g_page[dst - j->page_addr], (const uint8_t *)src, (uint32_t)size);
|
||||
if (j->dry && !in_shift_phase()) j->sink(j->sink_ctx, (const uint8_t *)src, (uint32_t)size);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int get_usize(const uint8_t *p, uint32_t n, uint32_t *pos, uint32_t *out) {
|
||||
uint32_t v = 0, off = 0;
|
||||
uint8_t b;
|
||||
if (*pos >= n) return -1;
|
||||
b = p[(*pos)++];
|
||||
if (b & 0x40) return -1; // negative
|
||||
v = b & 0x3f;
|
||||
off = 6;
|
||||
while (b & 0x80) {
|
||||
if (*pos >= n || off > 28) return -1;
|
||||
b = p[(*pos)++];
|
||||
v |= (uint32_t)(b & 0x7f) << off;
|
||||
off += 7;
|
||||
}
|
||||
*out = v;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int fwp_header(const uint8_t *patch, uint32_t n, uint32_t *memory_size, uint32_t *segment_size,
|
||||
uint32_t *shift, uint32_t *from_size, uint32_t *to_size) {
|
||||
uint32_t pos = 1;
|
||||
if (n < 1 || ((patch[0] >> 4) & 0x7) != PATCH_TYPE_IN_PLACE) return -1;
|
||||
if ((patch[0] & 0xf) != COMPRESSION_HEATSHRINK) return -2;
|
||||
if (get_usize(patch, n, &pos, memory_size) || get_usize(patch, n, &pos, segment_size) ||
|
||||
get_usize(patch, n, &pos, shift) || get_usize(patch, n, &pos, from_size) ||
|
||||
get_usize(patch, n, &pos, to_size))
|
||||
return -3;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int fwp_run(fwp_job *j) {
|
||||
uint32_t mem, seg, shift, from, to;
|
||||
int res;
|
||||
|
||||
j->err = 0;
|
||||
j->detools_err = 0;
|
||||
j->to_size = 0;
|
||||
j->page_addr = NO_PAGE;
|
||||
j->written_end = 0;
|
||||
j->shift_low = (uint32_t)-1;
|
||||
j->shift_high = 0;
|
||||
j->dt = &g_dt;
|
||||
|
||||
if ((j->mem_base % FWP_PAGE) != 0 || (j->mem_size % FWP_PAGE) != 0) return FWP_ERR_ARGS;
|
||||
if (j->dry ? j->sink == 0 : (j->erase == 0 || j->write == 0)) return FWP_ERR_ARGS;
|
||||
if (fwp_header(j->patch, j->patch_size, &mem, &seg, &shift, &from, &to) != 0) return FWP_ERR_ARGS;
|
||||
if (mem != j->mem_size || from != j->from_size || seg != FWP_PAGE) return FWP_ERR_SIZE;
|
||||
// shift 0 would make detools erase a page before reading it (shift loop)
|
||||
if (shift == 0 || (shift % FWP_PAGE) != 0 || to == 0 || to > mem) return FWP_ERR_SHIFT;
|
||||
j->shift = shift;
|
||||
|
||||
detools_apply_patch_in_place_init(&g_dt, cb_read, cb_write, cb_erase, NULL, NULL, j->patch_size, j);
|
||||
res = detools_apply_patch_in_place_process(&g_dt, j->patch, j->patch_size);
|
||||
if (res == 0) res = detools_apply_patch_in_place_finalize(&g_dt);
|
||||
if (j->err) return j->err; // ours is the more specific diagnosis
|
||||
if (res < 0) {
|
||||
j->detools_err = -res;
|
||||
return FWP_ERR_DETOOLS - (-res);
|
||||
}
|
||||
flush_page(j);
|
||||
if ((uint32_t)res != to || j->written_end < to) return FWP_ERR_SIZE;
|
||||
j->to_size = to;
|
||||
return 0;
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
// --- RAM copies of the libc calls the compiler and detools emit -----------
|
||||
// tools/ota_ramlib.py renames memcpy/memset/memmove in this object to these, so
|
||||
// the real run never jumps back into flash libc.
|
||||
FWP_NOLIBC void *fwp_memcpy(void *d, const void *s, size_t n) {
|
||||
uint8_t *dd = (uint8_t *)d;
|
||||
const uint8_t *ss = (const uint8_t *)s;
|
||||
while (n--)
|
||||
*dd++ = *ss++;
|
||||
return d;
|
||||
}
|
||||
FWP_NOLIBC void *fwp_memset(void *d, int c, size_t n) {
|
||||
uint8_t *dd = (uint8_t *)d;
|
||||
while (n--)
|
||||
*dd++ = (uint8_t)c;
|
||||
return d;
|
||||
}
|
||||
FWP_NOLIBC void *fwp_memmove(void *d, const void *s, size_t n) {
|
||||
uint8_t *dd = (uint8_t *)d;
|
||||
const uint8_t *ss = (const uint8_t *)s;
|
||||
if (dd < ss) {
|
||||
while (n--)
|
||||
*dd++ = *ss++;
|
||||
} else {
|
||||
dd += n;
|
||||
ss += n;
|
||||
while (n--)
|
||||
*--dd = *--ss;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
} // extern "C"
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,77 @@
|
||||
#pragma once
|
||||
|
||||
// CUSTOM (TeTeHacko): in-place delta update of the running image, the core of
|
||||
// FwUpdate's `format 2` packages. Plain C on purpose: the very same file runs in
|
||||
// the native unit test (fake flash) and on the node, where its code is moved to
|
||||
// RAM (tools/ota_ramlib.py), because a real run rewrites the flash the firmware
|
||||
// executes from.
|
||||
//
|
||||
// The patch is a detools "in-place" patch (heatshrink 11/10, segment = one flash
|
||||
// page). detools first moves the old image up by `shift` bytes, then writes the
|
||||
// new image page by page from the start, reading old bytes only above the page
|
||||
// it is writing. Two modes, one code path:
|
||||
//
|
||||
// dry no flash is touched. Reads from the shifted area are redirected to the
|
||||
// untouched original, every page of the new image goes to `sink` in
|
||||
// order (hash + CRC). A read the real run could not serve (data already
|
||||
// overwritten) fails the run. This is `fw verify`.
|
||||
// real erase/write through the callbacks, pages buffered in RAM so the flash
|
||||
// only ever sees whole, word-aligned pages. This is `fw apply`.
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define FWP_PAGE 4096u
|
||||
|
||||
// Error codes (negative). detools errors come through as -(100 + detools code).
|
||||
#define FWP_ERR_ARGS -1 // bad job (alignment, sizes)
|
||||
#define FWP_ERR_SHIFT -2 // shift not a positive multiple of a page
|
||||
#define FWP_ERR_OVERREAD -3 // the patch reads data a real run would have overwritten
|
||||
#define FWP_ERR_ORDER -4 // a write outside the page being built
|
||||
#define FWP_ERR_SIZE -5 // header sizes do not match the job
|
||||
#define FWP_ERR_DETOOLS -100
|
||||
|
||||
typedef struct fwp_job {
|
||||
// in
|
||||
uintptr_t mem_base; // address of memory offset 0 (APP_START on the node)
|
||||
uint32_t mem_size; // must equal the patch's memory_size
|
||||
uint32_t from_size; // must equal the patch's from_size (the running image)
|
||||
const uint8_t *patch; // memory-mapped patch
|
||||
uint32_t patch_size;
|
||||
int dry;
|
||||
void (*erase)(uintptr_t addr); // real: one page
|
||||
void (*write)(uintptr_t addr, const uint8_t *src, uint32_t n); // real: one page
|
||||
void (*sink)(void *ctx, const uint8_t *p, uint32_t n); // dry: new image, in order
|
||||
void *sink_ctx;
|
||||
void (*tick)(void); // optional, called once per page (watchdog)
|
||||
|
||||
// out
|
||||
uint32_t to_size; // size of the new image
|
||||
uint32_t shift;
|
||||
int detools_err;
|
||||
|
||||
// private
|
||||
void *dt; // struct detools_apply_patch_in_place_t *
|
||||
uintptr_t page_addr; // page being built (memory offset), or UINTPTR_MAX
|
||||
uint32_t shift_low; // shifted area so far, [shift_low, shift_high) (dry)
|
||||
uint32_t shift_high;
|
||||
uint32_t written_end; // end of the new image written so far (memory offset)
|
||||
int err;
|
||||
} fwp_job;
|
||||
|
||||
// Runs the whole patch. 0 = success (to_size set), negative = FWP_ERR_*.
|
||||
int fwp_run(fwp_job *j);
|
||||
|
||||
// Reads only the patch header: memory_size, segment_size, shift_size, from_size,
|
||||
// to_size. 0 on success. Used before the transfer completes and on the PC side
|
||||
// tests.
|
||||
int fwp_header(const uint8_t *patch, uint32_t n, uint32_t *memory_size, uint32_t *segment_size,
|
||||
uint32_t *shift, uint32_t *from_size, uint32_t *to_size);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,140 @@
|
||||
#pragma once
|
||||
|
||||
// CUSTOM (TeTeHacko): firmware update pushed by an admin, no bootloader change.
|
||||
// Design and the reasons behind it: docs/ota.md.
|
||||
//
|
||||
// Two package formats, one signed 256 B manifest:
|
||||
// 1 deflate-compressed full image, staged in the free flash above the running
|
||||
// one, inflated over it by a RAM routine;
|
||||
// 2 detools in-place DELTA against the running image (FwPatch.cpp), staged in
|
||||
// the top FW_OTA_PATCH_AREA below InternalFS. The manifest names the base
|
||||
// (sha256 of the running image) and the node refuses a package for another
|
||||
// base as soon as the manifest chunks arrive.
|
||||
// For both, the node checks it completely (signature, hashes, a dry-run inflate), and
|
||||
// only then, on an explicit `fw apply`, disables the SoftDevice and runs a copy
|
||||
// routine from RAM that inflates the image over itself. The bootloader settings
|
||||
// page gets the CRC of the new image FIRST, so a power cut mid-copy leaves a
|
||||
// node that stays in the bootloader (BLE/USB DFU recovers it) instead of one
|
||||
// that jumps into half an image.
|
||||
//
|
||||
// fw status state, progress, battery
|
||||
// fw begin <bytes> start a transfer of a package (tools/ota_pack.py);
|
||||
// over the mesh only a delta (<= FW_OTA_PATCH_AREA)
|
||||
// fw w <offset> <base64> one chunk, offset a multiple of FW_OTA_CHUNK
|
||||
// fw missing first missing chunk offsets (for resending)
|
||||
// fw verify signature + hashes + dry-run inflate
|
||||
// fw apply [force] [downgrade] battery gate, then copy and reboot; both
|
||||
// arguments local only (no downgrade over the mesh)
|
||||
// fw ver target and build epoch a package for this image needs
|
||||
// fw abort forget the staged package
|
||||
// fw bl print the bootloader settings page
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <Mesh.h>
|
||||
|
||||
#ifndef FW_OTA_CHUNK
|
||||
#define FW_OTA_CHUNK 96 // base64 = 128 chars, fits the 160 B CLI line
|
||||
#endif
|
||||
// Received data is tracked in units of FW_OTA_UNIT bytes, so text chunks (96 B)
|
||||
// and binary chunks (FW_OTA_BCHUNK) can both land in it.
|
||||
#define FW_OTA_UNIT 32
|
||||
#define FW_OTA_BCHUNK 128 // binary chunk: 4 units; the companion host frame (176 B) limits it
|
||||
|
||||
// Binary request carrying firmware data (over the mesh, admin only). Upstream
|
||||
// request types are 0x01..0x07; 0xF0 is far from them on purpose.
|
||||
// [0xF0]['w'][sid u16][offset u32 LE][len u8][crc16 of sid..len + data][data] chunk,
|
||||
// no reply; a bad crc is dropped. The
|
||||
// length is explicit (the node only sees
|
||||
// the decrypted size padded to 16 B); sid
|
||||
// is the session from `fw begin <bytes>
|
||||
// <sid>`, chunks of another session are
|
||||
// dropped -- stale chunks of an earlier
|
||||
// transfer did arrive late on the bench and
|
||||
// replaced the new manifest.
|
||||
// [0xF0]['m'] reply: [state][units u16][count u16]
|
||||
// [missing unit index u16 ...]
|
||||
// state: 0 idle, 1 receiving, 2 ready, 3 failed, 4 busy (manifest/verify)
|
||||
#define REQ_TYPE_FW_OTA 0xF0
|
||||
#ifndef FW_OTA_MIN_MV
|
||||
#define FW_OTA_MIN_MV 3800 // ~50 % of a Li-ion cell at rest
|
||||
#endif
|
||||
|
||||
#ifndef FW_OTA_PATCH_AREA
|
||||
#define FW_OTA_PATCH_AREA 0x10000 // delta packages (manifest + patch) up to 64 kB
|
||||
#endif
|
||||
|
||||
#define FW_OTA_MANIFEST_SIZE 256
|
||||
|
||||
class FwUpdate {
|
||||
public:
|
||||
FwUpdate(mesh::MainBoard &board) : _board(board) {}
|
||||
|
||||
// sender_timestamp == 0 means the local console.
|
||||
bool handleCommand(uint32_t sender_timestamp, const char *command, char *reply);
|
||||
// Binary REQ_TYPE_FW_OTA payload (req[0] is the type). Returns the reply
|
||||
// length, 0 = no reply. The caller checks that the sender is an admin.
|
||||
int handleBinary(const uint8_t *req, int len, uint8_t *reply, int reply_max);
|
||||
void loop();
|
||||
|
||||
private:
|
||||
enum State : uint8_t { IDLE, RECEIVING, READY, FAILED };
|
||||
// Heavy work (ed25519, sha256 of the running image, the dry run) is never done
|
||||
// inside a command handler: over the mesh that runs deep in the packet path,
|
||||
// and on x1 (13. 11. 2026) the manifest check there overflowed the stack --
|
||||
// hardfault in RadioLib's SPI code moments later. The handler queues it,
|
||||
// loop() runs it with a shallow stack, `fw status` reports the result.
|
||||
enum Job : uint8_t { JOB_NONE, JOB_MANIFEST, JOB_VERIFY };
|
||||
|
||||
void cmdStatus(char *reply);
|
||||
void cmdBegin(uint32_t sender_timestamp, const char *arg, char *reply);
|
||||
void cmdWrite(uint32_t sender_timestamp, const char *arg, char *reply);
|
||||
void cmdMissing(char *reply);
|
||||
void cmdVerify(char *reply);
|
||||
void doVerify();
|
||||
void cmdApply(uint32_t sender_timestamp, const char *arg, char *reply);
|
||||
void cmdBootloader(char *reply);
|
||||
uint16_t battMinMv(); // 5 reads 100 ms apart: loop() only, never a handler
|
||||
const char *battGate(uint16_t mv, bool force); // NULL = ok
|
||||
uint32_t received() const; // units
|
||||
uint32_t units() const { return (_total + FW_OTA_UNIT - 1) / FW_OTA_UNIT; }
|
||||
bool haveUnit(uint32_t u) const { return _have[u >> 3] & (1 << (u & 7)); }
|
||||
const char *writeAt(uint32_t off, const uint8_t *buf, int len); // NULL = ok
|
||||
bool checkManifest(); // signature, target, base; sets _err
|
||||
const uint8_t *baseSha(); // sha256 of the running image, computed once
|
||||
|
||||
mesh::MainBoard &_board;
|
||||
State _state = IDLE;
|
||||
uint32_t _stage = 0; // flash address of the package
|
||||
uint32_t _total = 0; // package size (manifest + blob)
|
||||
uint32_t _raw_size = 0;
|
||||
uint16_t _crc = 0;
|
||||
uint8_t _format = 0;
|
||||
Job _job = JOB_NONE;
|
||||
bool _manifest_ok = false;
|
||||
// Any part of the transfer came over the mesh (remote CLI or a binary
|
||||
// request). Then only a DELTA is accepted: a full image is ~300 kB, hours of
|
||||
// airtime on a shared channel -- it goes over USB or the BLE console.
|
||||
bool _remote = false;
|
||||
bool _older = false; // the package is not newer than this image (manifest build_epoch)
|
||||
bool _base_known = false;
|
||||
uint8_t _base_sha[32];
|
||||
// The manifest is checked from this RAM copy, not from the stage in flash: three
|
||||
// bench runs failed with "wrong base image" while the node's base and the
|
||||
// package's matched exactly -- the check had read an older package's manifest
|
||||
// that was still in flash at the same address. _flash_diff records a readback
|
||||
// mismatch after the flush, for diagnosis (`fw status`).
|
||||
uint8_t _mani[FW_OTA_MANIFEST_SIZE];
|
||||
uint16_t _sid = 0; // transfer session, 0 = none given (text-only senders)
|
||||
// diagnosis of the "wrong base image" hunt (13. 11. 2026): who wrote the manifest
|
||||
uint16_t _w_bin = 0, _w_drop = 0, _w_bad = 0, _w_txt = 0;
|
||||
char _mani_src = '-';
|
||||
uint32_t _mani_off = 0;
|
||||
bool _flash_diff = false;
|
||||
char _version[48] = { 0 };
|
||||
char _err[64] = { 0 };
|
||||
unsigned long _apply_at = 0;
|
||||
bool _apply_force = false;
|
||||
char _apply_err[40] = { 0 }; // why loop() refused the queued apply
|
||||
static constexpr uint32_t MAX_UNITS = (0xED000 - 0x27000) / FW_OTA_UNIT + 1; // whole stage
|
||||
uint8_t _have[(MAX_UNITS + 7) / 8];
|
||||
};
|
||||
@@ -0,0 +1,41 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
// CUSTOM (TeTeHacko): a cap on wrong passwords. Upstream checks every login,
|
||||
// so a password can be guessed over the air as fast as the channel carries
|
||||
// packets, from a fresh identity each time, and a wrong one is not even
|
||||
// answered. After LOGIN_FAIL_MAX wrong passwords within LOGIN_FAIL_SECS no
|
||||
// password is checked until that window ends.
|
||||
//
|
||||
// The caller lets a client that is already an admin in the ACL through anyway:
|
||||
// a login is encrypted with the sender's key, so nobody can send one in an
|
||||
// admin's name, and a guessing attack cannot lock the admins out.
|
||||
//
|
||||
// Times are millis(), compared by difference: a clock set backwards or the
|
||||
// 49-day wrap cannot stretch the window.
|
||||
|
||||
#ifndef LOGIN_FAIL_MAX
|
||||
#define LOGIN_FAIL_MAX 4
|
||||
#endif
|
||||
#ifndef LOGIN_FAIL_SECS
|
||||
#define LOGIN_FAIL_SECS 180
|
||||
#endif
|
||||
|
||||
class LoginGuard {
|
||||
uint32_t _since = 0; // millis() of the first failure in the window
|
||||
uint16_t _fails = 0;
|
||||
|
||||
bool inWindow(uint32_t now_ms) const { return now_ms - _since < LOGIN_FAIL_SECS * 1000UL; }
|
||||
|
||||
public:
|
||||
bool locked(uint32_t now_ms) const { return _fails >= LOGIN_FAIL_MAX && inWindow(now_ms); }
|
||||
|
||||
void failed(uint32_t now_ms) {
|
||||
if (_fails == 0 || !inWindow(now_ms)) {
|
||||
_since = now_ms;
|
||||
_fails = 0;
|
||||
}
|
||||
if (_fails < LOGIN_FAIL_MAX) _fails++;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,81 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
// CUSTOM (TeTeHacko): battery thresholds of a solar node, settable at runtime.
|
||||
//
|
||||
// remote-mast (11/2026) faces east and gets no direct sun in winter: -50 mV a day
|
||||
// with consumption unchanged. Upstream NRF52_POWER_MANAGEMENT only refuses to
|
||||
// BOOT below a compiled threshold; nothing switches a RUNNING node off, so the
|
||||
// cell runs down to the brown-out and the panel then restarts the node on a
|
||||
// cell that cannot hold it. Two thresholds, both in mV, 0 = off:
|
||||
//
|
||||
// bootlock checked once at boot: below it the node goes to SYSTEMOFF and the
|
||||
// board's LPCOMP wakes it when the battery recovers
|
||||
// cutoff checked while running: CUTOFF_SAMPLES readings in a row below it
|
||||
// (one every CHECK_MS, so a TX dip cannot trigger it) and the node
|
||||
// goes to the same SYSTEMOFF
|
||||
//
|
||||
// cutoff must stay below bootlock: a node switched off at the cutoff then only
|
||||
// starts again once the battery is past bootlock, which is the hysteresis.
|
||||
// External power (USB) disarms the cutoff, a reading under 1 V is an ADC glitch
|
||||
// and is ignored. The LPCOMP wake level is hardware (a fraction of VDD), not
|
||||
// one of these.
|
||||
//
|
||||
// Pure logic, no Arduino: driven from NodeMaintenance, tested on the host.
|
||||
class LowVoltageGuard {
|
||||
public:
|
||||
static constexpr uint16_t MIN_MV = 3000;
|
||||
static constexpr uint16_t MAX_MV = 4200;
|
||||
static constexpr uint32_t CHECK_MS = 60000;
|
||||
static constexpr uint8_t CUTOFF_SAMPLES = 3;
|
||||
static constexpr uint16_t GLITCH_MV = 1000;
|
||||
|
||||
void begin(uint32_t now, uint16_t bootlock_mv, uint16_t cutoff_mv) {
|
||||
_bootlock = bootlock_mv;
|
||||
_cutoff = cutoff_mv;
|
||||
_last_check = now;
|
||||
_low = 0;
|
||||
}
|
||||
|
||||
uint16_t bootlock() const { return _bootlock; }
|
||||
uint16_t cutoff() const { return _cutoff; }
|
||||
uint8_t lowSamples() const { return _low; }
|
||||
|
||||
// NULL if the pair is acceptable, else the reason (for the CLI reply).
|
||||
static const char* validate(uint16_t bootlock_mv, uint16_t cutoff_mv) {
|
||||
if (bootlock_mv != 0 && (bootlock_mv < MIN_MV || bootlock_mv > MAX_MV)) return "bootlock out of range";
|
||||
if (cutoff_mv != 0 && (cutoff_mv < MIN_MV || cutoff_mv > MAX_MV)) return "cutoff out of range";
|
||||
if (cutoff_mv != 0 && bootlock_mv != 0 && cutoff_mv >= bootlock_mv) return "cutoff must be below bootlock";
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool set(uint16_t bootlock_mv, uint16_t cutoff_mv) {
|
||||
if (validate(bootlock_mv, cutoff_mv)) return false;
|
||||
_bootlock = bootlock_mv;
|
||||
_cutoff = cutoff_mv;
|
||||
_low = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
// True when poll() would take a reading: read the battery only then (the ADC
|
||||
// read is not free on every board -- SenseCAP waits 10 ms for the divider).
|
||||
bool due(uint32_t now) const { return (uint32_t)(now - _last_check) >= CHECK_MS; }
|
||||
|
||||
// Returns true when the node should switch off now.
|
||||
bool poll(uint32_t now, uint16_t batt_mv, bool external_power) {
|
||||
if (!due(now)) return false;
|
||||
_last_check = now;
|
||||
if (_cutoff == 0 || external_power) { _low = 0; return false; }
|
||||
if (batt_mv < GLITCH_MV) return false; // not a reading, keep the count
|
||||
if (batt_mv >= _cutoff) { _low = 0; return false; }
|
||||
if (_low < CUTOFF_SAMPLES) _low++;
|
||||
return _low >= CUTOFF_SAMPLES;
|
||||
}
|
||||
|
||||
private:
|
||||
uint16_t _bootlock = 0;
|
||||
uint16_t _cutoff = 0;
|
||||
uint32_t _last_check = 0;
|
||||
uint8_t _low = 0;
|
||||
};
|
||||
@@ -26,6 +26,7 @@ private:
|
||||
|
||||
bool _enabled = false;
|
||||
RegisteredInterface _interfaces[MAX_INTERFACES] = {};
|
||||
int _last_rx = -1; // CUSTOM (TeTeHacko): slot of the most recent frame's transport
|
||||
|
||||
public:
|
||||
bool addInterface(InterfaceType type, BaseSerialInterface* iface) {
|
||||
@@ -57,6 +58,7 @@ public:
|
||||
for(int i = 0; i < MAX_INTERFACES; i++){
|
||||
if(_interfaces[i].instance == iface){
|
||||
_interfaces[i] = {};
|
||||
if (_last_rx == i) _last_rx = -1;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -184,11 +186,13 @@ public:
|
||||
}
|
||||
|
||||
// try to read a frame from any enabled interface
|
||||
for(auto iface : _interfaces){
|
||||
for(int i = 0; i < MAX_INTERFACES; i++){
|
||||
auto& iface = _interfaces[i];
|
||||
if(iface.instance && iface.instance->isEnabled()){
|
||||
size_t frameSize = iface.instance->checkRecvFrame(dest);
|
||||
if(frameSize > 0){
|
||||
return frameSize;
|
||||
_last_rx = i;
|
||||
return frameSize;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -197,4 +201,30 @@ public:
|
||||
return 0;
|
||||
}
|
||||
|
||||
// CUSTOM (TeTeHacko): only a frame that came over (MITM-paired) Bluetooth is
|
||||
// authenticated. USB, a hardware UART, WiFi and Ethernet carry no pairing, so
|
||||
// the companion's key-export / PIN gates (89eb71ab) refuse them. Without this
|
||||
// override the base class answered `true` for everything: the gates written
|
||||
// for SerialDualInterface went dead when the v1.17 merge replaced it with
|
||||
// this class, and USB could export the key and read or set the BLE PIN.
|
||||
// A build with no Bluetooth (USB-only companion) has nothing to pair over, so
|
||||
// its one transport stays trusted, as BaseSerialInterface defines it.
|
||||
bool isConnectionSecure() const override {
|
||||
bool has_ble = false;
|
||||
for (const auto& iface : _interfaces) {
|
||||
if (iface.instance && iface.type == InterfaceType::Bluetooth) has_ble = true;
|
||||
}
|
||||
if (!has_ble) return true;
|
||||
if (_last_rx < 0) return false;
|
||||
const auto& iface = _interfaces[_last_rx];
|
||||
return iface.instance && iface.type == InterfaceType::Bluetooth && iface.instance->isConnectionSecure();
|
||||
}
|
||||
|
||||
size_t writeReplyFrame(const uint8_t src[], size_t len) override {
|
||||
if (!_enabled || len == 0 || _last_rx < 0) return 0;
|
||||
auto* iface = _interfaces[_last_rx].instance;
|
||||
if (!iface || !iface->isEnabled()) return 0;
|
||||
return iface->writeFrame(src, len);
|
||||
}
|
||||
|
||||
};
|
||||
+116
-5
@@ -1,5 +1,52 @@
|
||||
#if defined(NRF52_PLATFORM)
|
||||
#include "NRF52Board.h"
|
||||
|
||||
#if !defined(NO_RETAINED_CLOCK)
|
||||
// CUSTOM (TeTeHacko): the wall-clock record VolatileRTCClock carries across a warm
|
||||
// reset (ArduinoHelpers.h). .noinit: the startup code neither copies nor zeroes it.
|
||||
extern "C" {
|
||||
uint32_t g_retained_clock[3] __attribute__((section(".noinit")));
|
||||
uint8_t g_retained_clock_status = 0;
|
||||
// `clkreboot` (CommonCLI.cpp, weak) -- otherwise the record would put the
|
||||
// clock it is throwing away straight back after the reboot.
|
||||
void retainedClockInvalidate() { g_retained_clock[0] = 0; }
|
||||
}
|
||||
#endif
|
||||
|
||||
// CUSTOM (TeTeHacko): hardfault recorder. On a fault, save the stacked PC/LR/PSR
|
||||
// to g_hardfault_record and reset; simple_repeater/main.cpp prints it on the next
|
||||
// boot. Both halves had to move here (18. 10. 2026):
|
||||
// - The record lived at a fixed 0x2003FFF0, the top of RAM, which is where the
|
||||
// Adafruit bootloader's stack lands on the reset after the fault. .noinit
|
||||
// (after .bss) survives, same as the retained clock.
|
||||
// - The handler was a patch in the framework's utility/debug.cpp and it NEVER
|
||||
// linked: the core is built as an archive, the startup's weak
|
||||
// HardFault_Handler already satisfies the vector table, so the linker never
|
||||
// pulled debug.o in (nm on any build showed only the weak symbol). An object
|
||||
// of the application is always linked, so a strong definition here wins.
|
||||
// debug.o would only come in with CFG_DEBUG (dbgPrintVersion() in the core's
|
||||
// main.cpp), which would then be a duplicate symbol -- no env sets it.
|
||||
#define HARDFAULT_MAGIC 0xFA010DEB
|
||||
extern "C" {
|
||||
uint32_t g_hardfault_record[4] __attribute__((section(".noinit"))); // magic, pc, lr, psr
|
||||
|
||||
void HardFault_c_handler(uint32_t* sp) {
|
||||
g_hardfault_record[1] = sp[6]; // stacked PC
|
||||
g_hardfault_record[2] = sp[5]; // stacked LR
|
||||
g_hardfault_record[3] = sp[7]; // stacked xPSR
|
||||
g_hardfault_record[0] = HARDFAULT_MAGIC;
|
||||
NVIC_SystemReset();
|
||||
}
|
||||
|
||||
__attribute__((naked)) void HardFault_Handler(void) {
|
||||
__asm volatile(
|
||||
"tst lr, #4 \n"
|
||||
"ite eq \n"
|
||||
"mrseq r0, msp \n"
|
||||
"mrsne r0, psp \n"
|
||||
"b HardFault_c_handler \n");
|
||||
}
|
||||
}
|
||||
#include <target.h>
|
||||
|
||||
#include <bluefruit.h>
|
||||
@@ -241,10 +288,7 @@ void NRF52Board::pwrmgtWakeArmVbus() {
|
||||
}
|
||||
#endif
|
||||
|
||||
void NRF52BoardDCDC::begin() {
|
||||
NRF52Board::begin();
|
||||
|
||||
// Enable DC/DC converter for improved power efficiency
|
||||
static void enableNrf52Dcdc() {
|
||||
uint8_t sd_enabled = 0;
|
||||
sd_softdevice_is_enabled(&sd_enabled);
|
||||
if (sd_enabled) {
|
||||
@@ -254,6 +298,22 @@ void NRF52BoardDCDC::begin() {
|
||||
}
|
||||
}
|
||||
|
||||
void NRF52BoardDCDC::begin() {
|
||||
NRF52Board::begin();
|
||||
|
||||
// Enable DC/DC converter for improved power efficiency
|
||||
enableNrf52Dcdc();
|
||||
}
|
||||
|
||||
void NRF52BoardDCDC::onBootComplete() {
|
||||
NRF52Board::onBootComplete();
|
||||
|
||||
// SoftDevice (Bluefruit.begin()) starts after board.begin(). On XIAO x4
|
||||
// (11/2026) DCDCEN read 1 after boot with or without this call, so it is a
|
||||
// safeguard in case a SoftDevice/board combination resets NRF_POWER to LDO.
|
||||
enableNrf52Dcdc();
|
||||
}
|
||||
|
||||
bool NRF52Board::isExternalPowered() {
|
||||
// Check if SoftDevice is enabled before using its API
|
||||
uint8_t sd_enabled = 0;
|
||||
@@ -268,20 +328,49 @@ bool NRF52Board::isExternalPowered() {
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef PWR_DUTY_INSTRUMENT
|
||||
// CUSTOM (TeTeHacko): bench instrument (opt-in, -D PWR_DUTY_INSTRUMENT). Measures
|
||||
// what share of wall time the MCU is awake: the loop calls sleep() every pass, so
|
||||
// the gap between a sleep() return and the next sleep() entry is CPU-awake time,
|
||||
// and the WFE span inside is asleep. Combined with `recv` from stats-packets it
|
||||
// gives the CPU cost per received packet (the part a radio-side filter could cut).
|
||||
// Prints one line to Serial every ~10 s. No effect unless the flag is set.
|
||||
static uint64_t s_awake_us = 0, s_asleep_us = 0;
|
||||
static uint32_t s_last_exit_us = 0, s_wakes = 0, s_report_us = 0;
|
||||
static bool s_have_exit = false;
|
||||
// Pure per-packet CPU time, measured in Dispatcher::processRecvPacket (immune to
|
||||
// BLE/USB background wakes, unlike the awake/asleep duty above).
|
||||
extern uint64_t g_pkt_proc_us;
|
||||
extern uint32_t g_pkt_proc_count;
|
||||
#endif
|
||||
|
||||
void NRF52Board::sleep(uint32_t secs) {
|
||||
// Clear FPU interrupt flags to avoid insomnia
|
||||
// see errata 87 for details https://docs.nordicsemi.com/bundle/errata_nRF52840_Rev3/page/ERR/nRF52840/Rev3/latest/anomaly_840_87.html
|
||||
#if (__FPU_USED == 1)
|
||||
__set_FPSCR(__get_FPSCR() & ~(0x0000009F));
|
||||
__set_FPSCR(__get_FPSCR() & ~(0x0000009F));
|
||||
(void) __get_FPSCR();
|
||||
NVIC_ClearPendingIRQ(FPU_IRQn);
|
||||
#endif
|
||||
|
||||
// Clear pending CRYPTOCELL interrupt to avoid WFE/sd_app_evt_wait() insomnia.
|
||||
// Adafruit_nRFCrypto polls CC310 with CRYPTOCELL_IRQn disabled in NVIC, so
|
||||
// completed crypto/TRNG calls leave it pending (same workaround as Adafruit
|
||||
// core wiring.c / port_cmsis_systick.c).
|
||||
#ifdef NRF_CRYPTOCELL
|
||||
NVIC_ClearPendingIRQ(CRYPTOCELL_IRQn);
|
||||
#endif
|
||||
|
||||
// On nRF52, we use event-driven sleep instead of timed sleep
|
||||
// The 'secs' parameter is ignored - we wake on any interrupt
|
||||
uint8_t sd_enabled = 0;
|
||||
sd_softdevice_is_enabled(&sd_enabled);
|
||||
|
||||
#ifdef PWR_DUTY_INSTRUMENT
|
||||
uint32_t t_enter = micros();
|
||||
if (s_have_exit) s_awake_us += (uint32_t)(t_enter - s_last_exit_us);
|
||||
#endif
|
||||
|
||||
if (sd_enabled) {
|
||||
// first call processes pending softdevice events, second call sleeps.
|
||||
sd_app_evt_wait();
|
||||
@@ -292,10 +381,32 @@ void NRF52Board::sleep(uint32_t secs) {
|
||||
__WFE();
|
||||
__WFE();
|
||||
}
|
||||
|
||||
#ifdef PWR_DUTY_INSTRUMENT
|
||||
uint32_t t_exit = micros();
|
||||
s_asleep_us += (uint32_t)(t_exit - t_enter);
|
||||
s_last_exit_us = t_exit;
|
||||
s_have_exit = true;
|
||||
s_wakes++;
|
||||
if ((uint32_t)(t_exit - s_report_us) >= 10000000UL) {
|
||||
s_report_us = t_exit;
|
||||
uint64_t tot = s_awake_us + s_asleep_us;
|
||||
uint32_t permille = tot ? (uint32_t)((s_awake_us * 1000) / tot) : 0;
|
||||
Serial.printf("PWRDUTY awake_ms=%lu asleep_ms=%lu wakes=%lu duty_permille=%lu pkt_us=%lu pkt_n=%lu\r\n",
|
||||
(unsigned long)(s_awake_us / 1000), (unsigned long)(s_asleep_us / 1000),
|
||||
(unsigned long)s_wakes, (unsigned long)permille,
|
||||
(unsigned long)(g_pkt_proc_us), (unsigned long)g_pkt_proc_count);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// Temperature from NRF52 MCU
|
||||
float NRF52Board::getMCUTemperature() {
|
||||
// With the SoftDevice enabled, TEMP is a SoftDevice-protected peripheral
|
||||
// (the SD uses it for RC oscillator calibration). Direct register access
|
||||
// raises an APP_MEMACC SoftDevice fault -> firmware reboot. This is why
|
||||
// BLE-enabled repeater builds crashed on every telemetry request. Use the
|
||||
// sd_temp_get() SVC in that case.
|
||||
uint8_t sd_enabled = 0;
|
||||
sd_softdevice_is_enabled(&sd_enabled);
|
||||
if (sd_enabled) {
|
||||
|
||||
@@ -71,6 +71,14 @@ public:
|
||||
#ifdef PWRMGT_LPCOMP_AIN
|
||||
bool getWakeLpcompSupported() const override { return true; }
|
||||
#endif
|
||||
// CUSTOM (TeTeHacko): entry points for runtime battery thresholds
|
||||
// (PWRMGT_RUNTIME, helpers/LowVoltageGuard.h via NodeMaintenance). The boot
|
||||
// check reads only voltage_bootlock; the wake is armed by initiateShutdown().
|
||||
bool bootVoltageCheck(uint16_t bootlock_mv) {
|
||||
PowerMgtConfig c = { 0, 0, bootlock_mv };
|
||||
return checkBootVoltage(&c);
|
||||
}
|
||||
void lowVoltageShutdown() { initiateShutdown(SHUTDOWN_REASON_LOW_VOLTAGE); }
|
||||
#endif
|
||||
};
|
||||
|
||||
@@ -85,5 +93,6 @@ class NRF52BoardDCDC : virtual public NRF52Board {
|
||||
public:
|
||||
NRF52BoardDCDC() {}
|
||||
virtual void begin() override;
|
||||
virtual void onBootComplete() override;
|
||||
};
|
||||
#endif
|
||||
@@ -0,0 +1,474 @@
|
||||
#include "NodeMaintenance.h"
|
||||
|
||||
// CUSTOM (TeTeHacko): moved out of examples/simple_repeater/main.cpp (4. 11. 2026),
|
||||
// history included.
|
||||
|
||||
#define RADIO_SILENCE_FILE "/rsilence"
|
||||
|
||||
#ifndef RADIO_TXSTALL_MIN
|
||||
#define RADIO_TXSTALL_MIN 15
|
||||
#endif
|
||||
|
||||
#if defined(NRF52_PLATFORM)
|
||||
extern "C" {
|
||||
void enterUf2Dfu(void);
|
||||
void enterSerialDfu(void);
|
||||
void enterOTADfu(void);
|
||||
extern uint32_t g_hardfault_record[4]; // NRF52Board.cpp, .noinit: magic, pc, lr, psr
|
||||
}
|
||||
#endif
|
||||
|
||||
// Why did this board last restart? The core latches NRF_POWER->RESETREAS in
|
||||
// init() before clearing it, and it is the only thing that distinguishes
|
||||
// "somebody typed `dfu`" from "the CPU locked up" or "the power went away" after
|
||||
// the fact -- the hole hit while chasing boards that vanished from USB after `dfu`.
|
||||
// The hardfault record is saved by the patched HardFault_Handler (framework
|
||||
// debug.cpp) in g_hardfault_record, .noinit (NRF52Board.cpp) -- the old fixed
|
||||
// 0x2003FFF0 at the end of RAM was where the bootloader's stack lands on reset.
|
||||
void NodeMaintenance::printBootDiag() {
|
||||
#if defined(NRF52_PLATFORM)
|
||||
uint32_t rr = readResetReason();
|
||||
_reset_reason = rr;
|
||||
// The build epoch belongs next to it: it is what the clock comes up at when
|
||||
// nothing else sets it, so without it printed you cannot tell "fell back to
|
||||
// the build epoch" from "restored something" -- and comparing against the
|
||||
// epoch of a DIFFERENT build of the same tree invents discrepancies that are
|
||||
// not there. Cost one wrong conclusion here.
|
||||
Serial.printf("boot: FIRMWARE_BUILD_EPOCH=%lu\n", (unsigned long) FIRMWARE_BUILD_EPOCH);
|
||||
Serial.printf("boot: RESETREAS=0x%08lX%s%s%s%s%s\n", (unsigned long)rr,
|
||||
rr == 0 ? " (none set = power-on/brownout: power was removed)" : "",
|
||||
(rr & 0x01) ? " RESETPIN" : "",
|
||||
(rr & 0x02) ? " WATCHDOG" : "",
|
||||
(rr & 0x04) ? " SREQ(sw reset, e.g. `dfu`/`reboot`)" : "",
|
||||
(rr & 0x08) ? " LOCKUP(!)" : "");
|
||||
|
||||
volatile uint32_t* hf = g_hardfault_record;
|
||||
if (hf[0] == 0xFA010DEB) {
|
||||
_hardfault[0] = hf[1]; _hardfault[1] = hf[2]; _hardfault[2] = hf[3];
|
||||
_hardfault_seen = true;
|
||||
Serial.printf("!!! HARDFAULT before last reboot: PC=%08lX LR=%08lX PSR=%08lX\n",
|
||||
(unsigned long)hf[1], (unsigned long)hf[2], (unsigned long)hf[3]);
|
||||
hf[0] = 0; // printed once; `get boot` keeps it until the next reset
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// --- radio silence watchdog (#6), see RadioSilenceWatchdog.h ----------------
|
||||
// Reboots it caused and the threshold backoff survive power loss in a small file,
|
||||
// written only right before such a reboot and once when the radio proves itself.
|
||||
|
||||
void NodeMaintenance::silenceLoad(uint8_t* backoff) {
|
||||
*backoff = 0;
|
||||
if (!_fs || !_fs->exists(RADIO_SILENCE_FILE)) return;
|
||||
#if defined(RP2040_PLATFORM)
|
||||
File f = _fs->open(RADIO_SILENCE_FILE, "r");
|
||||
#else
|
||||
File f = _fs->open(RADIO_SILENCE_FILE);
|
||||
#endif
|
||||
if (!f) return;
|
||||
if (f.read((uint8_t*)&_silence_reboots, sizeof(_silence_reboots)) != sizeof(_silence_reboots)) {
|
||||
_silence_reboots = 0;
|
||||
}
|
||||
if (f.read(backoff, 1) != 1) *backoff = 0;
|
||||
f.close();
|
||||
}
|
||||
|
||||
void NodeMaintenance::silenceSave(uint8_t backoff) {
|
||||
if (!_fs) return;
|
||||
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
|
||||
_fs->remove(RADIO_SILENCE_FILE);
|
||||
File f = _fs->open(RADIO_SILENCE_FILE, FILE_O_WRITE);
|
||||
#elif defined(RP2040_PLATFORM)
|
||||
File f = _fs->open(RADIO_SILENCE_FILE, "w");
|
||||
#else
|
||||
File f = _fs->open(RADIO_SILENCE_FILE, "w", true);
|
||||
#endif
|
||||
if (!f) return;
|
||||
f.write((const uint8_t*)&_silence_reboots, sizeof(_silence_reboots));
|
||||
f.write(&backoff, 1);
|
||||
f.close();
|
||||
}
|
||||
|
||||
void NodeMaintenance::begin(FILESYSTEM* fs, NodePrefs* prefs, CommonCLICallbacks* callbacks) {
|
||||
_fs = fs;
|
||||
_prefs = prefs;
|
||||
_callbacks = callbacks;
|
||||
#ifdef NODE_PWR_GUARD
|
||||
pwrBegin(); // first: below the bootlock nothing else should run
|
||||
#endif
|
||||
uint8_t backoff;
|
||||
silenceLoad(&backoff);
|
||||
_silence.begin(millis(), radioActivity(), backoff);
|
||||
_silence.setMinutes(_prefs->radio_silence_min);
|
||||
_txstall.begin(millis(), _radio.getPacketsSent(), 0);
|
||||
_txstall.setMinutes(RADIO_TXSTALL_MIN);
|
||||
Serial.printf("boot: radio silence watchdog %u min, reboots %lu, backoff x%u\n",
|
||||
(unsigned) _silence.minutes(), (unsigned long) _silence_reboots,
|
||||
(unsigned) (1u << _silence.backoff()));
|
||||
}
|
||||
|
||||
void NodeMaintenance::loop(int tx_queued, int tx_due) {
|
||||
dfuTick();
|
||||
#ifdef NODE_PWR_GUARD
|
||||
pwrTick();
|
||||
#endif
|
||||
txStallTick(tx_queued, tx_due);
|
||||
#ifdef FW_OTA
|
||||
_fw.loop();
|
||||
#endif
|
||||
switch (_silence.poll(millis(), radioActivity())) {
|
||||
case RadioSilenceWatchdog::KICK_RX:
|
||||
Serial.printf("radio silence: nothing received for %lu min, re-arming RX\n",
|
||||
(unsigned long) (_silence.quietMs(millis()) / 60000));
|
||||
_radio.kickRx();
|
||||
break;
|
||||
case RadioSilenceWatchdog::REBOOT:
|
||||
Serial.printf("radio silence: still nothing after %lu min, rebooting\n",
|
||||
(unsigned long) (_silence.quietMs(millis()) / 60000));
|
||||
_silence_reboots++;
|
||||
silenceSave(_silence.nextBackoff());
|
||||
delay(100); // let the line out
|
||||
_board.reboot();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (_silence.takeBackoffCleared()) silenceSave(0);
|
||||
}
|
||||
|
||||
// --- TX stall watchdog ----------------------------------------------------------
|
||||
// The other half of the silence watchdog: a node that hears fine but no longer
|
||||
// transmits. mast-three, 14. 11. 2026, during an rxps trial: `sent` frozen for 6+
|
||||
// hours with the outbound queue full (32), RX counting, no tx_start_fail, no
|
||||
// tx_timeout, no CAD timeout -- so no adverts, no replies, no admin login over
|
||||
// the mesh, and nothing the silence watchdog could see. `rxps off` did not bring
|
||||
// TX back, a reboot did. The cause is not known, so this keys on the symptom:
|
||||
// packets waiting while the sent counter does not move. Never normal -- the
|
||||
// longest legitimate holds (airtime budget, CAD retries) are seconds.
|
||||
// Same staging as the silence watchdog: re-arm the radio (clears latched IRQ
|
||||
// flags), then reboot. No persisted backoff: a node that cannot send is useless
|
||||
// either way, and the queue-length/due numbers in the log say where it hung.
|
||||
void NodeMaintenance::txStallTick(int tx_queued, int tx_due) {
|
||||
_tx_queued = tx_queued;
|
||||
_tx_due = tx_due;
|
||||
uint32_t now = millis();
|
||||
if (tx_queued <= 0) { // nothing waiting (or not reported): nothing can stall
|
||||
_txstall.begin(now, _radio.getPacketsSent(), 0);
|
||||
return;
|
||||
}
|
||||
switch (_txstall.poll(now, _radio.getPacketsSent())) {
|
||||
case RadioSilenceWatchdog::KICK_RX:
|
||||
Serial.printf("tx stall: %d queued (%d due), nothing sent for %lu min, re-arming radio\n",
|
||||
tx_queued, tx_due, (unsigned long) (_txstall.quietMs(now) / 60000));
|
||||
_radio.kickRx();
|
||||
break;
|
||||
case RadioSilenceWatchdog::REBOOT:
|
||||
Serial.printf("tx stall: %d queued (%d due), still nothing sent after %lu min, rebooting\n",
|
||||
tx_queued, tx_due, (unsigned long) (_txstall.quietMs(now) / 60000));
|
||||
_silence_reboots++;
|
||||
silenceSave(_silence.backoff());
|
||||
delay(100); // let the line out
|
||||
_board.reboot();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
bool NodeMaintenance::txStallCommand(const char* command, char* reply) {
|
||||
if (strcmp(command, "get radio.txstall") == 0) {
|
||||
if (_tx_queued < 0) {
|
||||
strcpy(reply, "> n/a (this role does not report its queue)");
|
||||
} else if (_txstall.minutes() == 0) {
|
||||
strcpy(reply, "> off");
|
||||
} else {
|
||||
sprintf(reply, "> %u min, queued %d (due %d), no TX for %lu min, stage %u",
|
||||
(unsigned) _txstall.minutes(), _tx_queued, _tx_due,
|
||||
_tx_queued > 0 ? (unsigned long) (_txstall.quietMs(millis()) / 60000) : 0UL,
|
||||
(unsigned) _txstall.stage());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "set radio.txstall ", 18) == 0) {
|
||||
const char* arg = &command[18];
|
||||
bool numeric = *arg != 0 && strspn(arg, "0123456789") == strlen(arg);
|
||||
int m = strcmp(arg, "off") == 0 ? 0 : (numeric ? atoi(arg) : -1);
|
||||
if (m < 0 || m > RadioSilenceWatchdog::MAX_MINUTES) {
|
||||
sprintf(reply, "ERR - minutes 0..%u (0/off = disabled)", (unsigned) RadioSilenceWatchdog::MAX_MINUTES);
|
||||
return true;
|
||||
}
|
||||
_txstall.setMinutes((uint16_t) m);
|
||||
strcpy(reply, "OK (until reboot)");
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool NodeMaintenance::silenceCommand(const char* command, char* reply) {
|
||||
if (strcmp(command, "get radio.reboots") == 0) {
|
||||
sprintf(reply, "> %lu", (unsigned long) _silence_reboots);
|
||||
return true;
|
||||
}
|
||||
if (strcmp(command, "get radio.silence") == 0) {
|
||||
if (_silence.minutes() == 0) {
|
||||
strcpy(reply, "> off");
|
||||
} else {
|
||||
sprintf(reply, "> %u min (now x%u), quiet %lu min, stage %u",
|
||||
(unsigned) _silence.minutes(), (unsigned) (1u << _silence.backoff()),
|
||||
(unsigned long) (_silence.quietMs(millis()) / 60000), (unsigned) _silence.stage());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "set radio.silence ", 18) == 0) {
|
||||
const char* arg = &command[18];
|
||||
bool numeric = *arg != 0 && strspn(arg, "0123456789") == strlen(arg);
|
||||
int m = strcmp(arg, "off") == 0 ? 0 : (numeric ? atoi(arg) : -1);
|
||||
if (m < 0 || m > RadioSilenceWatchdog::MAX_MINUTES) {
|
||||
sprintf(reply, "ERR - minutes 0..%u (0/off = disabled)", (unsigned) RadioSilenceWatchdog::MAX_MINUTES);
|
||||
return true;
|
||||
}
|
||||
_prefs->radio_silence_min = (uint16_t) m;
|
||||
_callbacks->savePrefs();
|
||||
_silence.setMinutes((uint16_t) m);
|
||||
strcpy(reply, "OK");
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// --- dfu [uf2|serial|ota] ------------------------------------------------------
|
||||
// Reboot straight into the bootloader, deterministically.
|
||||
//
|
||||
// This is what the 1200-baud touch was a bad approximation of. The Adafruit
|
||||
// bootloader picks its mode from GPREGRET at boot, and the core exposes exactly
|
||||
// that (cores/nRF5/wiring.c): reset_mcu() writes the magic and calls
|
||||
// NVIC_SystemReset().
|
||||
// uf2 0x57 mass-storage drive, drop a .uf2 on it <- the usual one
|
||||
// serial 0x4e CDC only, for adafruit-nrfutil; no drive appears
|
||||
// ota 0xA8 BLE DFU
|
||||
// The touch only ever requested the *serial* mode, and on this build it worked
|
||||
// about half the time: twice it wedged a board out of USB and BLE entirely, with
|
||||
// no self-recovery (400 s) and no way back but a physical replug. This has no
|
||||
// such failure mode -- it is the same call the core makes, from a command.
|
||||
//
|
||||
// LOCAL ONLY. Over the mesh this would strand a node in a bootloader that waits
|
||||
// forever, on a mast, with no way back but a visit. sender_timestamp == 0 is the
|
||||
// same "physically present" test CommonCLI uses for `erase` and `set freq`.
|
||||
|
||||
// Deferred so the reply reaches the console first -- the reset never returns.
|
||||
void NodeMaintenance::dfuTick() {
|
||||
#if defined(NRF52_PLATFORM)
|
||||
if (_dfu_at == 0 || (long)(millis() - _dfu_at) < 0) return;
|
||||
_dfu_at = 0;
|
||||
// Detach USB before the reset instead of letting the reset
|
||||
// yank it out from under the host.
|
||||
//
|
||||
// Measured 4. 8. 2026: 3 of 8 `dfu` commands left the board dead on USB *and*
|
||||
// BLE, recoverable only by a physical replug. The kernel log is unambiguous
|
||||
// about what that is and is not:
|
||||
//
|
||||
// good: usb 7-9: USB disconnect -> 3 s later idProduct=0045 (bootloader)
|
||||
// bad: usb 7-6: USB disconnect -> nothing, ever
|
||||
//
|
||||
// CORRECTION, same evening: "no enumeration errors, therefore the board is
|
||||
// wedged" was WRONG, and worth leaving here as a warning. The identical
|
||||
// signature -- disconnect, then nothing, no errors, port reporting
|
||||
// `not attached` -- was later produced on a KNOWN GOOD board purely by
|
||||
// toggling the root-hub port's `disable` from the host. So the log tells you
|
||||
// the host stopped seeing a device; it does NOT tell you why, and a missing
|
||||
// error message is not evidence of a dead board.
|
||||
//
|
||||
// What is still true: the failure follows resets that happen with USB active,
|
||||
// in BOTH directions (app->bootloader and bootloader->app), and a reset via
|
||||
// the RESET pin -- the double tap -- has never failed. That is what this
|
||||
// change is aimed at, and it is a hypothesis about the transition, not a
|
||||
// diagnosis of the chip.
|
||||
//
|
||||
// reset_mcu() (core wiring.c) disables the SoftDevice and resets with USBD
|
||||
// still enabled and possibly mid-transfer. Detaching first drops D+ while the
|
||||
// application is still alive and in control, which gives the host an
|
||||
// unambiguous disconnect and leaves USBD in a defined state at reset.
|
||||
//
|
||||
// Honest scope: this removes a class of race, it is NOT yet proven to be the
|
||||
// cause -- the failure is intermittent, so only a run of trials can say. The
|
||||
// RESETREAS line printed at boot is the other half of the instrument.
|
||||
// Dropping the D+ pullup directly rather than through TinyUSBDevice.detach():
|
||||
// one register write, no dependency on the USB stack's headers being reachable
|
||||
// from here, and it is exactly what detach() does on this chip.
|
||||
NRF_USBD->USBPULLUP = 0;
|
||||
delay(150);
|
||||
if (_dfu_mode == 1) enterSerialDfu();
|
||||
else if (_dfu_mode == 2) enterOTADfu();
|
||||
else enterUf2Dfu();
|
||||
#endif
|
||||
}
|
||||
|
||||
bool NodeMaintenance::dfuCommand(uint32_t sender_timestamp, const char* command, char* reply) {
|
||||
if (memcmp(command, "dfu", 3) != 0 || (command[3] != 0 && command[3] != ' ')) return false;
|
||||
#if defined(NRF52_PLATFORM)
|
||||
if (sender_timestamp != 0) {
|
||||
strcpy(reply, "ERR: dfu is local-only (would strand the node in the bootloader)");
|
||||
return true;
|
||||
}
|
||||
const char* arg = (command[3] == ' ') ? &command[4] : "";
|
||||
while (*arg == ' ') arg++;
|
||||
if (strcmp(arg, "serial") == 0) {
|
||||
strcpy(reply, "OK - rebooting into serial DFU (CDC only, no drive)");
|
||||
} else if (strcmp(arg, "ota") == 0) {
|
||||
strcpy(reply, "OK - rebooting into BLE OTA DFU");
|
||||
} else if (arg[0] == 0 || strcmp(arg, "uf2") == 0) {
|
||||
strcpy(reply, "OK - rebooting into UF2 (drive appears in a few seconds)");
|
||||
} else {
|
||||
strcpy(reply, "ERR: dfu [uf2|serial|ota]");
|
||||
return true;
|
||||
}
|
||||
_dfu_at = millis() + 700;
|
||||
if (_dfu_at == 0) _dfu_at = 1;
|
||||
_dfu_mode = (strcmp(arg, "serial") == 0) ? 1 : (strcmp(arg, "ota") == 0 ? 2 : 0);
|
||||
#else
|
||||
strcpy(reply, "ERR: not an nRF52 board");
|
||||
#endif
|
||||
return true;
|
||||
}
|
||||
|
||||
bool NodeMaintenance::handleCommand(uint32_t sender_timestamp, const char* command, char* reply) {
|
||||
if (dfuCommand(sender_timestamp, command, reply)) return true;
|
||||
#ifdef FW_OTA
|
||||
if (_fw.handleCommand(sender_timestamp, command, reply)) return true;
|
||||
#endif
|
||||
if (silenceCommand(command, reply)) return true;
|
||||
if (txStallCommand(command, reply)) return true;
|
||||
#ifdef NODE_PWR_GUARD
|
||||
if (pwrCommand(command, reply)) return true;
|
||||
#endif
|
||||
if (strcmp(command, "get boot") == 0) {
|
||||
#if defined(NRF52_PLATFORM)
|
||||
if (_hardfault_seen) {
|
||||
sprintf(reply, "> RESETREAS=0x%08lX, HARDFAULT before it: PC=%08lX LR=%08lX PSR=%08lX",
|
||||
(unsigned long) _reset_reason, (unsigned long) _hardfault[0],
|
||||
(unsigned long) _hardfault[1], (unsigned long) _hardfault[2]);
|
||||
} else {
|
||||
sprintf(reply, "> RESETREAS=0x%08lX, no hardfault", (unsigned long) _reset_reason);
|
||||
}
|
||||
#else
|
||||
strcpy(reply, "> not recorded on this platform");
|
||||
#endif
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// --- battery thresholds (PWRMGT_RUNTIME), see helpers/LowVoltageGuard.h ---------
|
||||
// Saved in their own small file, not in the prefs: no prefs-layout change, and a
|
||||
// node without the file runs on the build defaults.
|
||||
#ifdef NODE_PWR_GUARD
|
||||
|
||||
#define PWR_GUARD_FILE "/pwr_guard"
|
||||
#ifndef PWRMGT_BOOTLOCK_DEFAULT
|
||||
#ifdef PWRMGT_VOLTAGE_BOOTLOCK
|
||||
#define PWRMGT_BOOTLOCK_DEFAULT PWRMGT_VOLTAGE_BOOTLOCK
|
||||
#else
|
||||
#define PWRMGT_BOOTLOCK_DEFAULT 0
|
||||
#endif
|
||||
#endif
|
||||
#ifndef PWRMGT_CUTOFF_DEFAULT
|
||||
#define PWRMGT_CUTOFF_DEFAULT 0
|
||||
#endif
|
||||
|
||||
static void fmtMv(char* out, uint16_t mv) {
|
||||
if (mv == 0) strcpy(out, "off"); else sprintf(out, "%u mV", (unsigned) mv);
|
||||
}
|
||||
|
||||
void NodeMaintenance::pwrBegin() {
|
||||
uint16_t v[2] = { PWRMGT_BOOTLOCK_DEFAULT, PWRMGT_CUTOFF_DEFAULT };
|
||||
if (_fs && _fs->exists(PWR_GUARD_FILE)) {
|
||||
#if defined(RP2040_PLATFORM)
|
||||
File f = _fs->open(PWR_GUARD_FILE, "r");
|
||||
#else
|
||||
File f = _fs->open(PWR_GUARD_FILE);
|
||||
#endif
|
||||
if (f) {
|
||||
uint16_t r[2];
|
||||
if (f.read((uint8_t*) r, sizeof(r)) == sizeof(r) && !LowVoltageGuard::validate(r[0], r[1])) {
|
||||
v[0] = r[0]; v[1] = r[1];
|
||||
}
|
||||
f.close();
|
||||
}
|
||||
}
|
||||
_pwr.begin(millis(), v[0], v[1]);
|
||||
Serial.printf("boot: pwr bootlock %u mV, cutoff %u mV (0 = off), battery %u mV\n",
|
||||
(unsigned) v[0], (unsigned) v[1], (unsigned) _board.getBattMilliVolts());
|
||||
// Below the bootlock this does not return: SYSTEMOFF until the LPCOMP wakes it.
|
||||
// Also latches the reset/shutdown reasons, so it runs with the bootlock off too.
|
||||
nrf().bootVoltageCheck(v[0]);
|
||||
}
|
||||
|
||||
void NodeMaintenance::pwrSave() {
|
||||
if (!_fs) return;
|
||||
uint16_t v[2] = { _pwr.bootlock(), _pwr.cutoff() };
|
||||
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
|
||||
_fs->remove(PWR_GUARD_FILE);
|
||||
File f = _fs->open(PWR_GUARD_FILE, FILE_O_WRITE);
|
||||
#elif defined(RP2040_PLATFORM)
|
||||
File f = _fs->open(PWR_GUARD_FILE, "w");
|
||||
#else
|
||||
File f = _fs->open(PWR_GUARD_FILE, "w", true);
|
||||
#endif
|
||||
if (!f) return;
|
||||
f.write((const uint8_t*) v, sizeof(v));
|
||||
f.close();
|
||||
}
|
||||
|
||||
void NodeMaintenance::pwrTick() {
|
||||
uint32_t now = millis();
|
||||
if (!_pwr.due(now)) return;
|
||||
uint16_t mv = _board.getBattMilliVolts();
|
||||
if (_pwr.poll(now, mv, _board.isExternalPowered())) {
|
||||
Serial.printf("pwr: battery %u mV, below the cutoff %u mV %u times in a row, switching off\n",
|
||||
(unsigned) mv, (unsigned) _pwr.cutoff(), (unsigned) LowVoltageGuard::CUTOFF_SAMPLES);
|
||||
delay(100); // let the line out
|
||||
nrf().lowVoltageShutdown(); // does not return; the LPCOMP wakes it
|
||||
}
|
||||
}
|
||||
|
||||
bool NodeMaintenance::pwrCommand(const char* command, char* reply) {
|
||||
char a[12], b[12];
|
||||
if (strcmp(command, "get pwr") == 0) {
|
||||
fmtMv(a, _pwr.bootlock());
|
||||
fmtMv(b, _pwr.cutoff());
|
||||
uint8_t why = nrf().getShutdownReason();
|
||||
sprintf(reply, "> bootlock %s, cutoff %s, battery %u mV (at boot %u)%s, last off: %s",
|
||||
a, b, (unsigned) _board.getBattMilliVolts(), (unsigned) nrf().getBootVoltage(),
|
||||
_board.isExternalPowered() ? ", USB" : "", nrf().getShutdownReasonString(why));
|
||||
return true;
|
||||
}
|
||||
bool is_boot = strncmp(command, "set pwr.bootlock ", 17) == 0;
|
||||
bool is_cut = strncmp(command, "set pwr.cutoff ", 15) == 0;
|
||||
if (!is_boot && !is_cut) return false;
|
||||
const char* arg = command + (is_boot ? 17 : 15);
|
||||
uint16_t mv = (strcmp(arg, "off") == 0) ? 0 : (uint16_t) atoi(arg);
|
||||
uint16_t boot = is_boot ? mv : _pwr.bootlock();
|
||||
uint16_t cut = is_cut ? mv : _pwr.cutoff();
|
||||
const char* err = LowVoltageGuard::validate(boot, cut);
|
||||
if (err) {
|
||||
sprintf(reply, "Error: %s (%u-%u mV or off)", err,
|
||||
(unsigned) LowVoltageGuard::MIN_MV, (unsigned) LowVoltageGuard::MAX_MV);
|
||||
return true;
|
||||
}
|
||||
// No threshold above the battery right now: a mast admin would lock the node
|
||||
// out -- it would not start after a reboot, or switch off within minutes.
|
||||
uint16_t batt = _board.getBattMilliVolts();
|
||||
if (mv != 0 && !_board.isExternalPowered() && batt >= LowVoltageGuard::GLITCH_MV && mv >= batt) {
|
||||
sprintf(reply, "Error: battery is %u mV now, a threshold of %u mV would lock the node out",
|
||||
(unsigned) batt, (unsigned) mv);
|
||||
return true;
|
||||
}
|
||||
_pwr.set(boot, cut);
|
||||
pwrSave();
|
||||
fmtMv(a, _pwr.bootlock());
|
||||
fmtMv(b, _pwr.cutoff());
|
||||
sprintf(reply, "OK - bootlock %s, cutoff %s", a, b);
|
||||
return true;
|
||||
}
|
||||
|
||||
#endif // NODE_PWR_GUARD
|
||||
@@ -0,0 +1,121 @@
|
||||
#pragma once
|
||||
|
||||
// CUSTOM (TeTeHacko): upkeep that belongs to the BOARD, not to the node's role --
|
||||
// so every build with a text console gets it, not only the repeater.
|
||||
//
|
||||
// It grew in examples/simple_repeater/main.cpp, because every node of ours on the
|
||||
// mesh is a repeater and each feature was written for the problem at hand on a
|
||||
// mast. That left the sensor on the birdhouse (x4) without `dfu` (flashable only
|
||||
// with the 1200-baud touch) and without the radio silence watchdog, although it
|
||||
// was the first node seen deaf (31. 10. 2026). Living here, it costs a role one
|
||||
// line per hook, and the upstream files it touches stay one added line each.
|
||||
//
|
||||
// dfu [uf2|serial|ota] reboot into the bootloader (local console only)
|
||||
// fw ... admin-pushed firmware update, see helpers/FwUpdate.h
|
||||
// (only with -D FW_OTA=1: the experimental -ota images)
|
||||
// set radio.silence <min> radio silence watchdog, 0/off = disabled (#6)
|
||||
// get radio.silence threshold, backoff, quiet time, stage
|
||||
// get radio.reboots reboots done by the watchdog, survives power loss
|
||||
// get radio.txstall TX stall watchdog: threshold, queue, time without TX
|
||||
// set radio.txstall <min> 0/off = disabled; RAM only, RADIO_TXSTALL_MIN at boot
|
||||
// get boot why the board last reset, and the hardfault record
|
||||
// get pwr battery thresholds, battery now and at boot, last shutdown
|
||||
// set pwr.bootlock <mV> don't start below it, sleep until the battery recovers
|
||||
// set pwr.cutoff <mV> switch a running node off below it; 0/off = disabled
|
||||
// (both only with -D PWRMGT_RUNTIME, nRF52 power management,
|
||||
// see helpers/LowVoltageGuard.h)
|
||||
//
|
||||
// Wiring (see simple_sensor/main.cpp):
|
||||
// setup(): maint.printBootDiag() early, maint.begin(fs, prefs, cb) after the
|
||||
// mesh has loaded its prefs
|
||||
// loop(): maint.loop(), or maint.loop(queued, due) to arm the TX stall
|
||||
// watchdog (outbound packets in total / due now)
|
||||
// commands: if (maint.handleCommand(sender_timestamp, command, reply)) return;
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <Mesh.h>
|
||||
#include <helpers/CommonCLI.h>
|
||||
#ifdef FW_OTA
|
||||
#include <helpers/FwUpdate.h>
|
||||
#endif
|
||||
#include <helpers/RadioSilenceWatchdog.h>
|
||||
#include <helpers/LowVoltageGuard.h>
|
||||
#if defined(NRF52_PLATFORM) && defined(NRF52_POWER_MANAGEMENT) && defined(PWRMGT_RUNTIME)
|
||||
#include <helpers/NRF52Board.h>
|
||||
#define NODE_PWR_GUARD 1
|
||||
#endif
|
||||
#include <helpers/radiolib/RadioLibWrappers.h>
|
||||
|
||||
class NodeMaintenance {
|
||||
public:
|
||||
#ifdef FW_OTA
|
||||
NodeMaintenance(mesh::MainBoard& board, RadioLibWrapper& radio) : _board(board), _radio(radio), _fw(board) { }
|
||||
#else
|
||||
NodeMaintenance(mesh::MainBoard& board, RadioLibWrapper& radio) : _board(board), _radio(radio) { }
|
||||
#endif
|
||||
|
||||
// Prints (and latches for `get boot`) the reset reason and the hardfault record.
|
||||
// The record is cleared once read, so call it once, as early as Serial is up.
|
||||
void printBootDiag();
|
||||
|
||||
void begin(FILESYSTEM* fs, NodePrefs* prefs, CommonCLICallbacks* callbacks);
|
||||
// tx_queued < 0: the role does not report its queue, no TX stall watchdog.
|
||||
void loop(int tx_queued = -1, int tx_due = -1);
|
||||
|
||||
// sender_timestamp == 0 means the local console (the same test CommonCLI uses
|
||||
// for `erase`); `dfu` refuses anything else.
|
||||
bool handleCommand(uint32_t sender_timestamp, const char* command, char* reply);
|
||||
|
||||
// Binary request from a logged-in client (REQ_TYPE_FW_OTA, firmware chunks).
|
||||
// Returns the reply length, 0 = no reply. Admins only.
|
||||
int handleRequest(bool admin, const uint8_t* req, int len, uint8_t* reply, int reply_max) {
|
||||
#ifdef FW_OTA
|
||||
if (!admin || len < 1 || req[0] != REQ_TYPE_FW_OTA) return 0;
|
||||
return _fw.handleBinary(req, len, reply, reply_max);
|
||||
#else
|
||||
(void)admin; (void)req; (void)len; (void)reply; (void)reply_max;
|
||||
return 0; // a classic image: no firmware update, the request is dropped
|
||||
#endif
|
||||
}
|
||||
|
||||
private:
|
||||
uint32_t radioActivity() const { return _radio.getPacketsRecv() + _radio.getPacketsRecvErrors(); }
|
||||
void silenceLoad(uint8_t* backoff);
|
||||
void silenceSave(uint8_t backoff);
|
||||
bool dfuCommand(uint32_t sender_timestamp, const char* command, char* reply);
|
||||
bool silenceCommand(const char* command, char* reply);
|
||||
void txStallTick(int tx_queued, int tx_due);
|
||||
bool txStallCommand(const char* command, char* reply);
|
||||
void dfuTick();
|
||||
#ifdef NODE_PWR_GUARD
|
||||
void pwrBegin();
|
||||
void pwrTick();
|
||||
void pwrSave();
|
||||
bool pwrCommand(const char* command, char* reply);
|
||||
NRF52Board& nrf() { return static_cast<NRF52Board&>(_board); }
|
||||
#endif
|
||||
|
||||
mesh::MainBoard& _board;
|
||||
RadioLibWrapper& _radio;
|
||||
FILESYSTEM* _fs = NULL;
|
||||
NodePrefs* _prefs = NULL;
|
||||
CommonCLICallbacks* _callbacks = NULL;
|
||||
|
||||
#ifdef FW_OTA
|
||||
FwUpdate _fw;
|
||||
#endif
|
||||
RadioSilenceWatchdog _silence;
|
||||
uint32_t _silence_reboots = 0;
|
||||
RadioSilenceWatchdog _txstall; // same staging, `activity` = packets sent
|
||||
#ifdef NODE_PWR_GUARD
|
||||
LowVoltageGuard _pwr;
|
||||
#endif
|
||||
int _tx_queued = -1, _tx_due = -1;
|
||||
|
||||
unsigned long _dfu_at = 0; // 0 = nothing armed
|
||||
uint8_t _dfu_mode = 0; // 0=uf2 1=serial 2=ota
|
||||
|
||||
uint32_t _reset_reason = 0;
|
||||
uint32_t _hardfault[3] = {0, 0, 0}; // pc, lr, psr; pc 0 = none
|
||||
bool _hardfault_seen = false;
|
||||
};
|
||||
@@ -0,0 +1,113 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
// CUSTOM (TeTeHacko, tth/meshcore-tth#6): a receiver that went deaf while the
|
||||
// main loop keeps running. The hardware watchdog only catches a frozen loop, and
|
||||
// two of our nodes have been found deaf with the loop alive -- bench-sensor on
|
||||
// 31. 10. 2026 (recv frozen for minutes, a reboot revived it) and mast-three on
|
||||
// 2. 11. after a BLE OTA (recv 0, tx_timeout 4 for 17 minutes, a reboot fixed it).
|
||||
//
|
||||
// Silence is judged by whether the receive counter MOVES, never by comparing
|
||||
// timestamps: taking the largest of several millis() stamps aliased across the
|
||||
// 32-bit wrap and reset healthy radios for weeks in another fork (Dutch-MeshCore
|
||||
// d8ffae32). Received packets and receive errors both count -- a CRC error still
|
||||
// proves the front end hears something.
|
||||
//
|
||||
// Staged: after `minutes` without a received frame the receiver is re-armed
|
||||
// (clear IRQ, startReceive -- covers an interrupt that never reached the MCU);
|
||||
// if that does not bring anything in within a step, the node reboots. There is
|
||||
// no in-between full chip re-init: it would have to restore every parameter
|
||||
// begin() applies, and a radio silently left on its default frequency is worse
|
||||
// than the fault (chendo 9a9a716a hit exactly that). AGC resets already run on
|
||||
// their own interval where configured.
|
||||
//
|
||||
// A quiet site must not turn this into a reboot loop: every reboot by this
|
||||
// watchdog doubles the threshold for the next boot (up to x16), and the first
|
||||
// frame received after boot clears it. The caller persists `backoff()` across
|
||||
// the reboot and reports `takeBackoffCleared()` so it can rewrite it.
|
||||
//
|
||||
// Pure logic, no Arduino: driven from the repeater loop, tested on the host.
|
||||
class RadioSilenceWatchdog {
|
||||
public:
|
||||
enum Action : uint8_t { NONE = 0, KICK_RX, REBOOT };
|
||||
|
||||
static constexpr uint32_t CHECK_MS = 30000; // evaluate at most this often
|
||||
static constexpr uint32_t MIN_STEP_MS = 5 * 60000; // kick -> reboot, at least
|
||||
static constexpr uint16_t MAX_MINUTES = 1440; // 24 h
|
||||
static constexpr uint8_t MAX_BACKOFF = 4; // threshold x16 at most
|
||||
|
||||
void begin(uint32_t now, uint32_t activity, uint8_t backoff) {
|
||||
_last_activity = activity;
|
||||
_quiet_since = _last_check = now;
|
||||
_backoff = backoff > MAX_BACKOFF ? MAX_BACKOFF : backoff;
|
||||
_stage = 0;
|
||||
_backoff_cleared = false;
|
||||
}
|
||||
|
||||
void setMinutes(uint16_t minutes) {
|
||||
_minutes = minutes > MAX_MINUTES ? MAX_MINUTES : minutes;
|
||||
_stage = 0;
|
||||
}
|
||||
uint16_t minutes() const { return _minutes; }
|
||||
|
||||
// `activity`: any counter that moves when the radio receives something.
|
||||
Action poll(uint32_t now, uint32_t activity) {
|
||||
if ((uint32_t)(now - _last_check) < CHECK_MS) return NONE;
|
||||
_last_check = now;
|
||||
|
||||
if (activity != _last_activity) {
|
||||
_last_activity = activity;
|
||||
_quiet_since = now;
|
||||
_stage = 0;
|
||||
if (_backoff) {
|
||||
_backoff = 0;
|
||||
_backoff_cleared = true;
|
||||
}
|
||||
return NONE;
|
||||
}
|
||||
if (_minutes == 0) {
|
||||
_stage = 0;
|
||||
return NONE;
|
||||
}
|
||||
|
||||
uint32_t quiet = (uint32_t)(now - _quiet_since);
|
||||
uint32_t threshold = thresholdMs();
|
||||
if (_stage == 0 && quiet >= threshold) {
|
||||
_stage = 1;
|
||||
return KICK_RX;
|
||||
}
|
||||
if (_stage == 1 && quiet >= threshold + stepMs()) {
|
||||
_stage = 2; // stays here: the caller reboots
|
||||
return REBOOT;
|
||||
}
|
||||
return NONE;
|
||||
}
|
||||
|
||||
uint32_t thresholdMs() const { return ((uint32_t)_minutes * 60000UL) << _backoff; }
|
||||
uint32_t stepMs() const {
|
||||
uint32_t step = thresholdMs() / 4;
|
||||
return step < MIN_STEP_MS ? MIN_STEP_MS : step;
|
||||
}
|
||||
uint32_t quietMs(uint32_t now) const { return (uint32_t)(now - _quiet_since); }
|
||||
uint8_t stage() const { return _stage; }
|
||||
uint8_t backoff() const { return _backoff; }
|
||||
// Backoff for the boot after a reboot by this watchdog.
|
||||
uint8_t nextBackoff() const { return _backoff < MAX_BACKOFF ? _backoff + 1 : MAX_BACKOFF; }
|
||||
|
||||
// True once after the radio proved itself and the persisted backoff went stale.
|
||||
bool takeBackoffCleared() {
|
||||
bool c = _backoff_cleared;
|
||||
_backoff_cleared = false;
|
||||
return c;
|
||||
}
|
||||
|
||||
private:
|
||||
uint32_t _last_activity = 0;
|
||||
uint32_t _quiet_since = 0;
|
||||
uint32_t _last_check = 0;
|
||||
uint16_t _minutes = 0;
|
||||
uint8_t _backoff = 0;
|
||||
uint8_t _stage = 0;
|
||||
bool _backoff_cleared = false;
|
||||
};
|
||||
@@ -280,6 +280,27 @@ bool RegionMap::removeRegion(const RegionEntry& region) {
|
||||
return true; // success
|
||||
}
|
||||
|
||||
int RegionMap::putDefaults(const char* csv) {
|
||||
int n = 0;
|
||||
char name[sizeof(regions[0].name)];
|
||||
while (csv && *csv) {
|
||||
int len = 0;
|
||||
while (csv[len] && csv[len] != ',') len++;
|
||||
if (len > 0 && len < (int)sizeof(name)) {
|
||||
memcpy(name, csv, len);
|
||||
name[len] = 0;
|
||||
auto r = putRegion(name, wildcard.id);
|
||||
if (r) {
|
||||
r->flags = 0; // flood allowed, same as `region put`
|
||||
n++;
|
||||
}
|
||||
}
|
||||
csv += len;
|
||||
if (*csv == ',') csv++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
bool RegionMap::clear() {
|
||||
num_regions = 0;
|
||||
return true; // success
|
||||
|
||||
@@ -49,6 +49,9 @@ public:
|
||||
void setDefaultRegion(const RegionEntry* def);
|
||||
bool removeRegion(const RegionEntry& region);
|
||||
bool clear();
|
||||
// CUSTOM (TeTeHacko): `region put <name>` for each name of a comma-separated
|
||||
// list (flood allowed, parent = wildcard). Returns how many it put.
|
||||
int putDefaults(const char* csv);
|
||||
void resetFrom(const RegionMap& src) { num_regions = 0; next_id = src.next_id; }
|
||||
int getCount() const { return num_regions; }
|
||||
const RegionEntry* getByIdx(int i) const { return ®ions[i]; }
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <CayenneLPP.h>
|
||||
#include <stdio.h>
|
||||
#include "sensors/LocationProvider.h"
|
||||
|
||||
#define TELEM_PERM_BASE 0x01 // 'base' permission includes battery
|
||||
@@ -9,6 +10,30 @@
|
||||
|
||||
#define TELEM_CHANNEL_SELF 1 // LPP data channel for 'self' device
|
||||
|
||||
// GPS duty cycle (`gps duty`, gps_enabled == 2). A repeater that runs GPS only
|
||||
// for the clock does not need a continuous fix: the receiver is powered just
|
||||
// long enough to sync the RTC, then cut. On a solar node this is the single
|
||||
// biggest lever there is -- an L76K draws 25-35 mA, an order of magnitude more
|
||||
// than the whole radio + MCU budget it is being spent next to.
|
||||
#ifndef GPS_DUTY_SYNC_INTERVAL_SECS
|
||||
// Once a day. The LF crystal (USE_LFXO) is +-20 ppm, plus ~40 ppm at -10 C:
|
||||
// ~5 s/day, far below what the mesh notices (replay window, login
|
||||
// timestamps). A reboot syncs at once regardless (setSettingValue "2").
|
||||
// 30 min (upstream's TIME_SYNC_INTERVAL) cost 0.25-0.75 mA for nothing.
|
||||
#define GPS_DUTY_SYNC_INTERVAL_SECS 86400
|
||||
#endif
|
||||
#ifndef GPS_DUTY_MAX_AWAKE_SECS
|
||||
// Cap on one sync attempt: a blocked sky must not turn duty cycle back into
|
||||
// "always on". A cold fix is tens of seconds, so this is deliberately loose.
|
||||
#define GPS_DUTY_MAX_AWAKE_SECS 300
|
||||
#endif
|
||||
#ifndef GPS_DUTY_RETRY_SECS
|
||||
// Backoff after a window that produced no fix (antenna, snow, indoors).
|
||||
// Each failed window is MAX_AWAKE at 46 mA: hourly that was 3.8 mA, ~16 %
|
||||
// of a mast node, exactly when snow covers the dome; 6 h makes it 0.64 mA.
|
||||
#define GPS_DUTY_RETRY_SECS 21600
|
||||
#endif
|
||||
|
||||
class SensorManager {
|
||||
public:
|
||||
double node_lat, node_lon; // modify these, if you want to affect Advert location
|
||||
@@ -25,6 +50,35 @@ public:
|
||||
virtual LocationProvider* getLocationProvider() { return NULL; }
|
||||
virtual bool isGPSDetected() const { return false; }
|
||||
|
||||
// Asked for when someone with LOCATION permission requests telemetry, so a
|
||||
// duty-cycled receiver does not answer with a position that is up to
|
||||
// GPS_DUTY_SYNC_INTERVAL_SECS old for the rest of that window.
|
||||
//
|
||||
// It deliberately does NOT wait for the fix -- the reply is assembled and
|
||||
// sent synchronously (BaseChatMesh.cpp), while a warm fix measured on a
|
||||
// T1000-E took ~65 s. So this request answers with what is known and pulls
|
||||
// the next window forward; the FOLLOWING request gets the fresh position.
|
||||
// With a periodic collector that costs one cycle and needs no scheduling.
|
||||
virtual void requestLocationRefresh() { }
|
||||
|
||||
// CUSTOM (TeTeHacko): the INA shunt (mOhm) from prefs back into the driver
|
||||
// after boot; 0 = keep the build's value. A no-op without an INA chip.
|
||||
void applyInaShunt(float mohm) {
|
||||
if (mohm <= 0) return;
|
||||
char v[16];
|
||||
snprintf(v, sizeof(v), "%.3f", mohm);
|
||||
setSettingValue("ina.shunt", v);
|
||||
}
|
||||
|
||||
// Live I2C scan, written into dest as text. Returns the number of devices
|
||||
// that answered, or -1 when the platform has no bus to scan.
|
||||
//
|
||||
// begin() already scans the bus, but only into a MESH_DEBUG log nobody has on
|
||||
// a deployed node -- so "is that sensor actually there?" was answerable only
|
||||
// by inference from telemetry, and inference is what produced a build flag
|
||||
// pointing INA226 at 0x40 to dodge a false detect at 0x44 (SHT41's address).
|
||||
virtual int scanI2C(char* dest, size_t max_len) { (void)dest; (void)max_len; return -1; }
|
||||
|
||||
// Helper functions to manage setting by keys (useful in many places ...)
|
||||
const char* getSettingByKey(const char* key) {
|
||||
int num = getNumSettings();
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
#pragma once
|
||||
|
||||
// Upstream backport (TeTeHacko): https://github.com/meshcore-dev/MeshCore/pull/1779
|
||||
// Makes the BLE companion usable over USB while BLE is disconnected.
|
||||
// Once the PR is merged upstream, this file just takes the upstream version on rebase.
|
||||
|
||||
#include "ArduinoSerialInterface.h"
|
||||
|
||||
template <typename BLEInterface>
|
||||
class SerialDualInterface : public BaseSerialInterface {
|
||||
BLEInterface _ble;
|
||||
ArduinoSerialInterface _usb;
|
||||
bool _bleWasConnected;
|
||||
bool _lastFrameFromBle;
|
||||
|
||||
public:
|
||||
SerialDualInterface() : _bleWasConnected(false), _lastFrameFromBle(false) { }
|
||||
|
||||
void begin(const char* prefix, char* name, uint32_t pin_code, Stream& serial) {
|
||||
_ble.begin(prefix, name, pin_code);
|
||||
_usb.begin(serial);
|
||||
}
|
||||
|
||||
// enable/disable only control BLE, USB is always available
|
||||
void enable() override {
|
||||
_ble.enable();
|
||||
}
|
||||
|
||||
void disable() override {
|
||||
_ble.disable();
|
||||
}
|
||||
|
||||
bool isEnabled() const override {
|
||||
return _ble.isEnabled() || _usb.isEnabled();
|
||||
}
|
||||
|
||||
bool isConnected() const override {
|
||||
return _ble.isConnected() || _usb.isConnected();
|
||||
}
|
||||
|
||||
// Only frames received over the MITM-paired BLE link are authenticated;
|
||||
// frames received over USB are unauthenticated (physical presence only).
|
||||
bool isConnectionSecure() const override {
|
||||
return _lastFrameFromBle;
|
||||
}
|
||||
|
||||
bool isWriteBusy() const override {
|
||||
if (_ble.isConnected()) return _ble.isWriteBusy();
|
||||
return _usb.isWriteBusy();
|
||||
}
|
||||
|
||||
size_t writeFrame(const uint8_t src[], size_t len) override {
|
||||
if (_ble.isConnected()) return _ble.writeFrame(src, len);
|
||||
return _usb.writeFrame(src, len);
|
||||
}
|
||||
|
||||
size_t checkRecvFrame(uint8_t dest[]) override {
|
||||
// Always call BLE first, it needs polling for send queue draining
|
||||
// and advertising watchdog, even when USB is the active transport
|
||||
size_t n = _ble.checkRecvFrame(dest);
|
||||
|
||||
bool bleNow = _ble.isConnected();
|
||||
if (bleNow != _bleWasConnected) {
|
||||
if (bleNow) {
|
||||
// BLE just connected, wait for any pending USB write to finish
|
||||
while (_usb.isWriteBusy()) { }
|
||||
_usb.disable();
|
||||
} else {
|
||||
// BLE just disconnected, re-enable USB (resets state machine,
|
||||
// discarding any stale bytes from the previous session)
|
||||
_usb.enable();
|
||||
}
|
||||
_bleWasConnected = bleNow;
|
||||
}
|
||||
|
||||
// Dock behaviour: while a USB host is connected (card sitting in the dock),
|
||||
// stop BLE advertising so the node stays quiet on 2.4 GHz and the app talks
|
||||
// over USB; resume advertising once undocked. Only advertising is gated --
|
||||
// an already-established BLE link is left untouched (never force-disconnect).
|
||||
if (!bleNow) {
|
||||
bool docked = _usb.isConnected();
|
||||
if (docked && _ble.isEnabled()) {
|
||||
_ble.disable();
|
||||
} else if (!docked && !_ble.isEnabled()) {
|
||||
_ble.enable();
|
||||
}
|
||||
}
|
||||
|
||||
if (n > 0) { // got a BLE frame
|
||||
_lastFrameFromBle = true;
|
||||
return n;
|
||||
}
|
||||
|
||||
// Only check USB when BLE is not connected
|
||||
if (!bleNow) {
|
||||
n = _usb.checkRecvFrame(dest);
|
||||
if (n > 0) _lastFrameFromBle = false;
|
||||
return n;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
@@ -52,6 +52,23 @@ public:
|
||||
void markSeen(const mesh::Packet* packet) override {
|
||||
uint8_t hash[MAX_HASH_SIZE];
|
||||
packet->calculatePacketHash(hash);
|
||||
|
||||
// CUSTOM (TeTeHacko): idempotent, the way the single hasSeen() this replaced
|
||||
// was -- that one inserted only when the hash was absent. 1.17 split it into
|
||||
// wasSeen() + markSeen(), and while every receive-side caller still gates on
|
||||
// !wasSeen(), the SEND paths (Mesh::sendFlood, sendDirect, sendZeroHop) call
|
||||
// this one unguarded. Every re-send of the same packet then occupies another
|
||||
// slot of a fixed 160-entry ring, which shortens the dedup window and lets a
|
||||
// late echo of our own flood read as new traffic -- and on a repeater that
|
||||
// means rebroadcasting it.
|
||||
//
|
||||
// Cost is one extra 160x8 byte scan per send, which is nothing against LoRa
|
||||
// airtime. Fix taken from ALLFATHER-BV/meshcomod e62be9b (MIT).
|
||||
const uint8_t* sp = _hashes;
|
||||
for (int i = 0; i < MAX_PACKET_HASHES; i++, sp += MAX_HASH_SIZE) {
|
||||
if (memcmp(hash, sp, MAX_HASH_SIZE) == 0) return; // already recorded
|
||||
}
|
||||
|
||||
memcpy(&_hashes[_next_idx * MAX_HASH_SIZE], hash, MAX_HASH_SIZE);
|
||||
_next_idx = (_next_idx + 1) % MAX_PACKET_HASHES;
|
||||
}
|
||||
|
||||
@@ -40,16 +40,20 @@ public:
|
||||
uint32_t n_sent_flood,
|
||||
uint32_t n_sent_direct,
|
||||
uint32_t n_recv_flood,
|
||||
uint32_t n_recv_direct) {
|
||||
sprintf(reply,
|
||||
"{\"recv\":%u,\"sent\":%u,\"flood_tx\":%u,\"direct_tx\":%u,\"flood_rx\":%u,\"direct_rx\":%u,\"recv_errors\":%u}",
|
||||
uint32_t n_recv_direct,
|
||||
uint32_t n_tx_start_fail = 0, // CUSTOM (TeTeHacko): TX failure tallies
|
||||
uint32_t n_tx_timeout = 0) { // (defaults keep other callers unchanged)
|
||||
sprintf(reply,
|
||||
"{\"recv\":%u,\"sent\":%u,\"flood_tx\":%u,\"direct_tx\":%u,\"flood_rx\":%u,\"direct_rx\":%u,\"recv_errors\":%u,\"tx_start_fail\":%u,\"tx_timeout\":%u}",
|
||||
driver.getPacketsRecv(),
|
||||
driver.getPacketsSent(),
|
||||
n_sent_flood,
|
||||
n_sent_direct,
|
||||
n_recv_flood,
|
||||
n_recv_direct,
|
||||
driver.getPacketsRecvErrors()
|
||||
driver.getPacketsRecvErrors(),
|
||||
n_tx_start_fail,
|
||||
n_tx_timeout
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
bsdiff/sais.c based on sais-lite 2.4.1 <https://sites.google.com/site/yuta256/sais>:
|
||||
Copyright (c) 2008-2010 Yuta Mori. (MIT License)
|
||||
|
||||
Other files:
|
||||
|
||||
BSD 2-Clause License
|
||||
|
||||
Copyright 2003-2005, Colin Percival (Original C implementation)
|
||||
Copyright (c) 2019, Erik Moqvist
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
@@ -0,0 +1,15 @@
|
||||
# Vendored: detools 0.53.0 (C apply side) + heatshrink decoder
|
||||
|
||||
Source: https://github.com/eerimoq/detools, commit `53d1f47` (2025-12-17),
|
||||
files `c/detools.{c,h}` and `c/heatshrink/*`, copied **unmodified**.
|
||||
Licences: detools BSD-2-Clause (`LICENSE`, includes bsdiff/sais notices),
|
||||
heatshrink ISC (`heatshrink/README.rst`).
|
||||
|
||||
Used only by `src/helpers/FwPatch.cpp`, which `#include`s both `.c` files and
|
||||
configures them there (heatshrink 11/10 static, heatshrink-only detools, no
|
||||
file I/O) -- so nothing in this directory needs editing. Nothing here is in any
|
||||
`build_src_filter` on its own.
|
||||
|
||||
Updating: copy the same files from a new tag, then `pio test -e native -f
|
||||
test_fwpatch` and `-e native_asan`, and `tools/ota_check_ramfunc.sh` on a
|
||||
device build (the real run executes this code from RAM).
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,640 @@
|
||||
/**
|
||||
* BSD 2-Clause License
|
||||
*
|
||||
* Copyright (c) 2019-2020, Erik Moqvist
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
*
|
||||
* * Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the documentation
|
||||
* and/or other materials provided with the distribution.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#ifndef DETOOLS_H
|
||||
#define DETOOLS_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Configuration.
|
||||
*
|
||||
* Define any of the defines below to 0 to disable given feature.
|
||||
*/
|
||||
|
||||
#ifndef DETOOLS_CONFIG_FILE_IO
|
||||
# define DETOOLS_CONFIG_FILE_IO 1
|
||||
#endif
|
||||
|
||||
#ifndef DETOOLS_CONFIG_COMPRESSION_NONE
|
||||
# define DETOOLS_CONFIG_COMPRESSION_NONE 1
|
||||
#endif
|
||||
|
||||
#ifndef DETOOLS_CONFIG_COMPRESSION_LZMA
|
||||
# define DETOOLS_CONFIG_COMPRESSION_LZMA 1
|
||||
#endif
|
||||
|
||||
#ifndef DETOOLS_CONFIG_COMPRESSION_CRLE
|
||||
# define DETOOLS_CONFIG_COMPRESSION_CRLE 1
|
||||
#endif
|
||||
|
||||
#ifndef DETOOLS_CONFIG_COMPRESSION_HEATSHRINK
|
||||
# define DETOOLS_CONFIG_COMPRESSION_HEATSHRINK 1
|
||||
#endif
|
||||
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
#define DETOOLS_VERSION "0.53.0"
|
||||
|
||||
/* Error codes. */
|
||||
#define DETOOLS_OK 0
|
||||
#define DETOOLS_NOT_IMPLEMENTED 1
|
||||
#define DETOOLS_NOT_DONE 2
|
||||
#define DETOOLS_BAD_PATCH_TYPE 3
|
||||
#define DETOOLS_BAD_COMPRESSION 4
|
||||
#define DETOOLS_INTERNAL_ERROR 5
|
||||
#define DETOOLS_LZMA_INIT 6
|
||||
#define DETOOLS_LZMA_DECODE 7
|
||||
#define DETOOLS_OUT_OF_MEMORY 8
|
||||
#define DETOOLS_CORRUPT_PATCH 9
|
||||
#define DETOOLS_IO_FAILED 10
|
||||
#define DETOOLS_ALREADY_DONE 11
|
||||
#define DETOOLS_FILE_OPEN_FAILED 12
|
||||
#define DETOOLS_FILE_CLOSE_FAILED 13
|
||||
#define DETOOLS_FILE_READ_FAILED 14
|
||||
#define DETOOLS_FILE_WRITE_FAILED 15
|
||||
#define DETOOLS_FILE_SEEK_FAILED 16
|
||||
#define DETOOLS_FILE_TELL_FAILED 17
|
||||
#define DETOOLS_SHORT_HEADER 18
|
||||
#define DETOOLS_NOT_ENOUGH_PATCH_DATA 19
|
||||
#define DETOOLS_HEATSHRINK_SINK 20
|
||||
#define DETOOLS_HEATSHRINK_POLL 21
|
||||
#define DETOOLS_STEP_SET_FAILED 22
|
||||
#define DETOOLS_STEP_GET_FAILED 23
|
||||
#define DETOOLS_ALREADY_FAILED 24
|
||||
#define DETOOLS_CORRUPT_PATCH_OVERFLOW 25
|
||||
#define DETOOLS_CORRUPT_PATCH_CRLE_KIND 26
|
||||
#define DETOOLS_HEATSHRINK_HEADER 27
|
||||
|
||||
/**
|
||||
* Read callback.
|
||||
*
|
||||
* @param[in] arg_p User data passed to detools_apply_patch_init().
|
||||
* @param[out] buf_p Buffer to read into.
|
||||
* @param[in] size Number of bytes to read.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
typedef int (*detools_read_t)(void *arg_p, uint8_t *buf_p, size_t size);
|
||||
|
||||
/**
|
||||
* Write callback.
|
||||
*
|
||||
* @param[in] arg_p User data passed to detools_apply_patch_init().
|
||||
* @param[in] buf_p Buffer to write.
|
||||
* @param[in] size Number of bytes to write.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
typedef int (*detools_write_t)(void *arg_p, const uint8_t *buf_p, size_t size);
|
||||
|
||||
/**
|
||||
* Seek from current position callback.
|
||||
*
|
||||
* @param[in] arg_p User data passed to detools_apply_patch_init().
|
||||
* @param[in] offset Offset to seek to from current position.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
typedef int (*detools_seek_t)(void *arg_p, int offset);
|
||||
|
||||
/**
|
||||
* Memory read callback.
|
||||
*
|
||||
* @param[in] arg_p User data passed to detools_apply_patch_init().
|
||||
* @param[out] dst_p Buffer to read into.
|
||||
* @param[in] src Address to read from.
|
||||
* @param[in] size Number of bytes to read.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
typedef int (*detools_mem_read_t)(void *arg_p,
|
||||
void *dst_p,
|
||||
uintptr_t src,
|
||||
size_t size);
|
||||
|
||||
/**
|
||||
* Memory write callback.
|
||||
*
|
||||
* @param[in] arg_p User data passed to detools_apply_patch_init().
|
||||
* @param[in] dst Address to write to.
|
||||
* @param[in] addr src_p Buffer to write from.
|
||||
* @param[in] size Number of bytes to write.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
typedef int (*detools_mem_write_t)(void *arg_p,
|
||||
uintptr_t dst,
|
||||
void *src_p,
|
||||
size_t size);
|
||||
|
||||
/**
|
||||
* Memory erase callback.
|
||||
*
|
||||
* @param[in] arg_p User data passed to detools_apply_patch_init().
|
||||
* @param[in] addr Address to erase from.
|
||||
* @param[in] size Number of bytes to erase.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
typedef int (*detools_mem_erase_t)(void *arg_p, uintptr_t addr, size_t size);
|
||||
|
||||
/**
|
||||
* State read callback.
|
||||
*
|
||||
* @param[in] arg_p User data passed to detools_apply_patch_init().
|
||||
* @param[out] buf_p Buffer to read into.
|
||||
* @param[in] size Number of bytes to read.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
typedef int (*detools_state_read_t)(void *arg_p, void *buf_p, size_t size);
|
||||
|
||||
/**
|
||||
* State write callback.
|
||||
*
|
||||
* @param[in] arg_p User data passed to detools_apply_patch_init().
|
||||
* @param[in] buf_p Buffer to write.
|
||||
* @param[in] size Number of bytes to write.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
typedef int (*detools_state_write_t)(void *arg_p, const void *buf_p, size_t size);
|
||||
|
||||
/**
|
||||
* Step set callback.
|
||||
*
|
||||
* @param[in] arg_p User data passed to detools_apply_patch_init().
|
||||
* @param[in] step Step to set. Later read by the step get callback.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
typedef int (*detools_step_set_t)(void *arg_p, int step);
|
||||
|
||||
/**
|
||||
* Step get callback.
|
||||
*
|
||||
* @param[in] arg_p User data passed to detools_apply_patch_init().
|
||||
* @param[out] step_p Outputs the most recently set step by the set
|
||||
* callback, or zero(0) if not yet set.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
typedef int (*detools_step_get_t)(void *arg_p, int *step_p);
|
||||
|
||||
struct detools_apply_patch_size_t {
|
||||
int state;
|
||||
int value;
|
||||
int offset;
|
||||
bool is_signed;
|
||||
};
|
||||
|
||||
struct detools_apply_patch_patch_reader_none_t {
|
||||
size_t patch_size;
|
||||
size_t patch_offset;
|
||||
};
|
||||
|
||||
#if DETOOLS_CONFIG_COMPRESSION_LZMA == 1
|
||||
|
||||
#include <lzma.h>
|
||||
|
||||
struct detools_apply_patch_patch_reader_lzma_t {
|
||||
lzma_stream stream;
|
||||
uint8_t *input_p;
|
||||
uint8_t *output_p;
|
||||
size_t output_size;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
#if DETOOLS_CONFIG_COMPRESSION_HEATSHRINK == 1
|
||||
|
||||
#include "heatshrink_decoder.h"
|
||||
|
||||
struct detools_apply_patch_patch_reader_heatshrink_t {
|
||||
int8_t window_sz2;
|
||||
int8_t lookahead_sz2;
|
||||
heatshrink_decoder *decoder_p;
|
||||
#if HEATSHRINK_DYNAMIC_ALLOC == 0
|
||||
heatshrink_decoder decoder;
|
||||
#endif
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
enum detools_unpack_usize_state_t {
|
||||
detools_unpack_usize_state_first_t = 0,
|
||||
detools_unpack_usize_state_consecutive_t
|
||||
};
|
||||
|
||||
struct detools_unpack_usize_t {
|
||||
enum detools_unpack_usize_state_t state;
|
||||
int value;
|
||||
int offset;
|
||||
};
|
||||
|
||||
enum detools_crle_state_t {
|
||||
detools_crle_state_idle_t = 0,
|
||||
detools_crle_state_scattered_size_t,
|
||||
detools_crle_state_scattered_data_t,
|
||||
detools_crle_state_repeated_repetitions_t,
|
||||
detools_crle_state_repeated_data_t,
|
||||
detools_crle_state_repeated_data_read_t
|
||||
};
|
||||
|
||||
struct detools_apply_patch_patch_reader_crle_t {
|
||||
enum detools_crle_state_t state;
|
||||
union {
|
||||
struct {
|
||||
size_t number_of_bytes_left;
|
||||
struct detools_unpack_usize_t size;
|
||||
} scattered;
|
||||
struct {
|
||||
uint8_t value;
|
||||
size_t number_of_bytes_left;
|
||||
struct detools_unpack_usize_t size;
|
||||
} repeated;
|
||||
} kind;
|
||||
};
|
||||
|
||||
struct detools_apply_patch_patch_reader_t {
|
||||
struct detools_apply_patch_chunk_t *patch_chunk_p;
|
||||
struct detools_apply_patch_size_t size;
|
||||
union {
|
||||
#if DETOOLS_CONFIG_COMPRESSION_NONE == 1
|
||||
struct detools_apply_patch_patch_reader_none_t none;
|
||||
#endif
|
||||
#if DETOOLS_CONFIG_COMPRESSION_LZMA == 1
|
||||
struct detools_apply_patch_patch_reader_lzma_t lzma;
|
||||
#endif
|
||||
#if DETOOLS_CONFIG_COMPRESSION_CRLE == 1
|
||||
struct detools_apply_patch_patch_reader_crle_t crle;
|
||||
#endif
|
||||
#if DETOOLS_CONFIG_COMPRESSION_HEATSHRINK == 1
|
||||
struct detools_apply_patch_patch_reader_heatshrink_t heatshrink;
|
||||
#endif
|
||||
} compression;
|
||||
int (*destroy)(struct detools_apply_patch_patch_reader_t *self_p);
|
||||
int (*decompress)(struct detools_apply_patch_patch_reader_t *self_p,
|
||||
uint8_t *buf_p,
|
||||
size_t *size_p);
|
||||
};
|
||||
|
||||
struct detools_apply_patch_chunk_t {
|
||||
const uint8_t *buf_p;
|
||||
size_t size;
|
||||
size_t offset;
|
||||
};
|
||||
|
||||
enum detools_apply_patch_state_t {
|
||||
detools_apply_patch_state_init_t = 0,
|
||||
detools_apply_patch_state_dfpatch_size_t,
|
||||
detools_apply_patch_state_diff_size_t,
|
||||
detools_apply_patch_state_diff_data_t,
|
||||
detools_apply_patch_state_extra_size_t,
|
||||
detools_apply_patch_state_extra_data_t,
|
||||
detools_apply_patch_state_adjustment_t,
|
||||
detools_apply_patch_state_done_t,
|
||||
detools_apply_patch_state_failed_t
|
||||
};
|
||||
|
||||
enum detools_apply_patch_init_state_t {
|
||||
detools_apply_patch_init_state_fixed_header_t = 0,
|
||||
detools_apply_patch_init_state_to_size_t
|
||||
};
|
||||
|
||||
/**
|
||||
* The apply patch data structure.
|
||||
*/
|
||||
struct detools_apply_patch_t {
|
||||
detools_read_t from_read;
|
||||
detools_seek_t from_seek;
|
||||
size_t patch_size;
|
||||
detools_write_t to_write;
|
||||
void *arg_p;
|
||||
enum detools_apply_patch_state_t state;
|
||||
enum detools_apply_patch_init_state_t init_state;
|
||||
int compression;
|
||||
size_t patch_offset;
|
||||
size_t to_offset;
|
||||
size_t to_size;
|
||||
int from_offset;
|
||||
size_t chunk_size;
|
||||
struct detools_apply_patch_patch_reader_t patch_reader;
|
||||
struct detools_apply_patch_chunk_t chunk;
|
||||
struct detools_apply_patch_size_t size;
|
||||
};
|
||||
|
||||
enum detools_apply_patch_in_place_init_state_t {
|
||||
detools_apply_patch_in_place_init_state_fixed_header_t = 0,
|
||||
detools_apply_patch_in_place_init_state_memory_size_t,
|
||||
detools_apply_patch_in_place_init_state_segment_size_t,
|
||||
detools_apply_patch_in_place_init_state_shift_size_t,
|
||||
detools_apply_patch_in_place_init_state_from_size_t,
|
||||
detools_apply_patch_in_place_init_state_to_size_t
|
||||
};
|
||||
|
||||
/**
|
||||
* The in-place apply patch data structure.
|
||||
*/
|
||||
struct detools_apply_patch_in_place_t {
|
||||
detools_mem_read_t mem_read;
|
||||
detools_mem_write_t mem_write;
|
||||
detools_mem_erase_t mem_erase;
|
||||
detools_step_set_t step_set;
|
||||
detools_step_get_t step_get;
|
||||
size_t patch_size;
|
||||
void *arg_p;
|
||||
enum detools_apply_patch_state_t state;
|
||||
enum detools_apply_patch_in_place_init_state_t init_state;
|
||||
int compression;
|
||||
int ongoing_step;
|
||||
size_t to_pos;
|
||||
size_t to_size;
|
||||
size_t from_size;
|
||||
size_t memory_size;
|
||||
size_t segment_size;
|
||||
size_t shift_size;
|
||||
size_t chunk_size;
|
||||
struct {
|
||||
size_t index;
|
||||
int from_offset;
|
||||
size_t to_offset;
|
||||
size_t to_size;
|
||||
size_t to_pos;
|
||||
} segment;
|
||||
struct detools_apply_patch_patch_reader_t patch_reader;
|
||||
struct detools_apply_patch_chunk_t chunk;
|
||||
struct detools_apply_patch_size_t size;
|
||||
};
|
||||
|
||||
/**
|
||||
* Initialize given apply patch object.
|
||||
*
|
||||
* @param[out] self_p Apply patch object to initialize.
|
||||
* @param[in] from_read Callback to read from-data.
|
||||
* @param[in] from_seek Callback to seek from current position in from-data.
|
||||
* @param[in] patch_size Patch size in bytes. Not used if
|
||||
* `detools_apply_patch_restore()` is called
|
||||
* immediately after this function.
|
||||
* @param[in] to_write Destination callback.
|
||||
* @param[in] arg_p Argument passed to the callbacks.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
int detools_apply_patch_init(struct detools_apply_patch_t *self_p,
|
||||
detools_read_t from_read,
|
||||
detools_seek_t from_seek,
|
||||
size_t patch_size,
|
||||
detools_write_t to_write,
|
||||
void *arg_p);
|
||||
|
||||
/**
|
||||
* Dump given apply patch object state. Call
|
||||
* `detools_apply_patch_restore()` to restore an apply patch object to
|
||||
* the dumped state.
|
||||
*
|
||||
* @param[in] self_p Apply patch object to dump.
|
||||
* @param[in] write Write callback.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
int detools_apply_patch_dump(struct detools_apply_patch_t *self_p,
|
||||
detools_state_write_t state_write);
|
||||
|
||||
/**
|
||||
* Restore given apply patch object to given dumped
|
||||
* state.
|
||||
*
|
||||
* `detools_apply_patch_get_to_offset()` and
|
||||
* `detools_apply_patch_get_patch_offset()` are often called after
|
||||
* this function to restore the to and patch streams.
|
||||
*
|
||||
* @param[in,out] self_p Initialized apply patch object to restore.
|
||||
* @param[in] read Callback to read the dumped state.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
int detools_apply_patch_restore(struct detools_apply_patch_t *self_p,
|
||||
detools_state_read_t state_read);
|
||||
|
||||
/**
|
||||
* Get the current to stream offset. Often used to restore the to
|
||||
* stream after restore.
|
||||
*
|
||||
* @param[in] self_p Apply patch object.
|
||||
*
|
||||
* @return The current to stream offset.
|
||||
*/
|
||||
size_t detools_apply_patch_get_to_offset(struct detools_apply_patch_t *self_p);
|
||||
|
||||
/**
|
||||
* Get the current patch stream offset. Often used to restore the
|
||||
* patch stream after restore.
|
||||
*
|
||||
* @param[in] self_p Apply patch object.
|
||||
*
|
||||
* @return The current patch stream offset.
|
||||
*/
|
||||
size_t detools_apply_patch_get_patch_offset(struct detools_apply_patch_t *self_p);
|
||||
|
||||
/**
|
||||
* Call this function repeatedly until all patch data has been
|
||||
* processed or an error occurres. Call detools_apply_patch_finalize()
|
||||
* to finalize the patching, even if an error occurred.
|
||||
*
|
||||
* @param[in,out] self_p Initialized apply patch object.
|
||||
* @param[in] patch_p Next chunk of the patch.
|
||||
* @param[in] size Patch buffer size.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
int detools_apply_patch_process(struct detools_apply_patch_t *self_p,
|
||||
const uint8_t *patch_p,
|
||||
size_t size);
|
||||
|
||||
/**
|
||||
* Call once after all data has been processed to finalize the
|
||||
* patching. The value returned from this function should be ignored
|
||||
* if an error occurred in detools_apply_patch_process().
|
||||
*
|
||||
* @param[in,out] self_p Initialized apply patch object.
|
||||
*
|
||||
* @return Size of to-data in bytes if the patch was applied
|
||||
* successfully, or negative error code.
|
||||
*/
|
||||
int detools_apply_patch_finalize(struct detools_apply_patch_t *self_p);
|
||||
|
||||
/**
|
||||
* Initialize given in-place apply patch object.
|
||||
*
|
||||
* @param[out] self_p In-place apply patch object to initialize.
|
||||
* @param[in] mem_read Callback to read data.
|
||||
* @param[in] mem_write Callback to write data.
|
||||
* @param[in] mem_erase Callback to erase data.
|
||||
* @param[in] step_set Callback to set the step.
|
||||
* @param[in] step_get Callback to get the step.
|
||||
* @param[in] patch_size Patch size in bytes.
|
||||
* @param[in] arg_p Argument passed to the callbacks.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
int detools_apply_patch_in_place_init(
|
||||
struct detools_apply_patch_in_place_t *self_p,
|
||||
detools_mem_read_t mem_read,
|
||||
detools_mem_write_t mem_write,
|
||||
detools_mem_erase_t mem_erase,
|
||||
detools_step_set_t step_set,
|
||||
detools_step_get_t step_get,
|
||||
size_t patch_size,
|
||||
void *arg_p);
|
||||
|
||||
/**
|
||||
* Call this function repeatedly until all patch data has been
|
||||
* processed or an error occurres. Call
|
||||
* detools_apply_patch_in_place_finalize() to finalize the patching,
|
||||
* even if an error occurred.
|
||||
*
|
||||
* @param[in,out] self_p Initialized apply patch object.
|
||||
* @param[in] patch_p Next chunk of the patch.
|
||||
* @param[in] size Patch buffer size.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
int detools_apply_patch_in_place_process(
|
||||
struct detools_apply_patch_in_place_t *self_p,
|
||||
const uint8_t *patch_p,
|
||||
size_t size);
|
||||
|
||||
/**
|
||||
* Call once after all data has been processed to finalize the
|
||||
* patching. The value returned from this function should be ignored
|
||||
* if an error occurred in detools_apply_patch_in_place_process().
|
||||
*
|
||||
* @param[in,out] self_p Initialized apply patch object.
|
||||
*
|
||||
* @return Size of to-data in bytes if the patch was applied
|
||||
* successfully, or negative error code.
|
||||
*/
|
||||
int detools_apply_patch_in_place_finalize(
|
||||
struct detools_apply_patch_in_place_t *self_p);
|
||||
|
||||
/**
|
||||
* Apply given patch using read, write and seek callbacks.
|
||||
*
|
||||
* @param[in] from_read Source read callback.
|
||||
* @param[in] from_seek Source seek callback.
|
||||
* @param[in] patch_read Patch read callback.
|
||||
* @param[in] patch_size Patch size in bytes.
|
||||
* @param[in] to_write Destination write callback.
|
||||
* @param[in] arg_p Argument passed to all callbacks.
|
||||
*
|
||||
* @return Size of to-data in bytes or negative error code.
|
||||
*/
|
||||
int detools_apply_patch_callbacks(detools_read_t from_read,
|
||||
detools_seek_t from_seek,
|
||||
detools_read_t patch_read,
|
||||
size_t patch_size,
|
||||
detools_write_t to_write,
|
||||
void *arg_p);
|
||||
|
||||
/**
|
||||
* Apply given in-place patch using read, write and erase callbacks.
|
||||
*
|
||||
* @param[in] mem_read Callback to read data.
|
||||
* @param[in] mem_write Callback to write data.
|
||||
* @param[in] mem_erase Callback to erase data.
|
||||
* @param[in] step_set Callback to set the step.
|
||||
* @param[in] step_get Callback to get the step.
|
||||
* @param[in] patch_read Patch read callback.
|
||||
* @param[in] patch_size Patch size in bytes.
|
||||
* @param[in] arg_p Argument passed to the callbacks.
|
||||
*
|
||||
* @return Size of to-data in bytes or negative error code.
|
||||
*/
|
||||
int detools_apply_patch_in_place_callbacks(detools_mem_read_t mem_read,
|
||||
detools_mem_write_t mem_write,
|
||||
detools_mem_erase_t mem_erase,
|
||||
detools_step_set_t step_set,
|
||||
detools_step_get_t step_get,
|
||||
detools_read_t patch_read,
|
||||
size_t patch_size,
|
||||
void *arg_p);
|
||||
|
||||
#if DETOOLS_CONFIG_FILE_IO == 1
|
||||
|
||||
/**
|
||||
* Apply given patch file to given from file and write the output to
|
||||
* given to file.
|
||||
*
|
||||
* @param[in] from_p Source file name.
|
||||
* @param[in] patch_p Patch file name.
|
||||
* @param[in] to_p Destination file name.
|
||||
*
|
||||
* @return Size of to-data in bytes or negative error code.
|
||||
*/
|
||||
int detools_apply_patch_filenames(const char *from_p,
|
||||
const char *patch_p,
|
||||
const char *to_p);
|
||||
|
||||
/**
|
||||
* Apply given patch file to given memory file.
|
||||
*
|
||||
* @param[in] memory_p Memory file name.
|
||||
* @param[in] patch_p Patch file name.
|
||||
* @param[in] step_set Callback to set the step.
|
||||
* @param[in] step_get Callback to get the step.
|
||||
*
|
||||
* @return Size of to-data in bytes or negative error code.
|
||||
*/
|
||||
int detools_apply_patch_in_place_filenames(const char *memory_p,
|
||||
const char *patch_p,
|
||||
detools_step_set_t step_set,
|
||||
detools_step_get_t step_get);
|
||||
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Get the error string for given error code.
|
||||
*
|
||||
* @param[in] Error code.
|
||||
*
|
||||
* @return Error string.
|
||||
*/
|
||||
const char *detools_error_as_string(int error);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,4 @@
|
||||
The files in this folder are copied from the heatshrink project,
|
||||
https://github.com/atomicobject/heatshrink.
|
||||
|
||||
Licensed under the ISC License.
|
||||
@@ -0,0 +1,20 @@
|
||||
#ifndef HEATSHRINK_H
|
||||
#define HEATSHRINK_H
|
||||
|
||||
#define HEATSHRINK_AUTHOR "Scott Vokes <scott.vokes@atomicobject.com>"
|
||||
#define HEATSHRINK_URL "https://github.com/atomicobject/heatshrink"
|
||||
|
||||
/* Version 0.4.1 */
|
||||
#define HEATSHRINK_VERSION_MAJOR 0
|
||||
#define HEATSHRINK_VERSION_MINOR 4
|
||||
#define HEATSHRINK_VERSION_PATCH 1
|
||||
|
||||
#define HEATSHRINK_MIN_WINDOW_BITS 4
|
||||
#define HEATSHRINK_MAX_WINDOW_BITS 15
|
||||
|
||||
#define HEATSHRINK_MIN_LOOKAHEAD_BITS 3
|
||||
|
||||
#define HEATSHRINK_LITERAL_MARKER 0x01
|
||||
#define HEATSHRINK_BACKREF_MARKER 0x00
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,26 @@
|
||||
#ifndef HEATSHRINK_CONFIG_H
|
||||
#define HEATSHRINK_CONFIG_H
|
||||
|
||||
/* Should functionality assuming dynamic allocation be used? */
|
||||
#ifndef HEATSHRINK_DYNAMIC_ALLOC
|
||||
#define HEATSHRINK_DYNAMIC_ALLOC 0
|
||||
#endif
|
||||
|
||||
#if HEATSHRINK_DYNAMIC_ALLOC
|
||||
/* Optional replacement of malloc/free */
|
||||
#define HEATSHRINK_MALLOC(SZ) malloc(SZ)
|
||||
#define HEATSHRINK_FREE(P, SZ) free(P)
|
||||
#else
|
||||
/* Required parameters for static configuration */
|
||||
#define HEATSHRINK_STATIC_INPUT_BUFFER_SIZE 256
|
||||
#define HEATSHRINK_STATIC_WINDOW_BITS 8
|
||||
#define HEATSHRINK_STATIC_LOOKAHEAD_BITS 7
|
||||
#endif
|
||||
|
||||
/* Turn on logging for debugging. */
|
||||
#define HEATSHRINK_DEBUGGING_LOGS 0
|
||||
|
||||
/* Use indexing for faster compression. (This requires additional space.) */
|
||||
#define HEATSHRINK_USE_INDEX 0
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,367 @@
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "heatshrink_decoder.h"
|
||||
|
||||
/* States for the polling state machine. */
|
||||
typedef enum {
|
||||
HSDS_TAG_BIT, /* tag bit */
|
||||
HSDS_YIELD_LITERAL, /* ready to yield literal byte */
|
||||
HSDS_BACKREF_INDEX_MSB, /* most significant byte of index */
|
||||
HSDS_BACKREF_INDEX_LSB, /* least significant byte of index */
|
||||
HSDS_BACKREF_COUNT_MSB, /* most significant byte of count */
|
||||
HSDS_BACKREF_COUNT_LSB, /* least significant byte of count */
|
||||
HSDS_YIELD_BACKREF, /* ready to yield back-reference */
|
||||
} HSD_state;
|
||||
|
||||
#if HEATSHRINK_DEBUGGING_LOGS
|
||||
#include <stdio.h>
|
||||
#include <ctype.h>
|
||||
#include <assert.h>
|
||||
#define LOG(...) fprintf(stderr, __VA_ARGS__)
|
||||
#define ASSERT(X) assert(X)
|
||||
static const char *state_names[] = {
|
||||
"tag_bit",
|
||||
"yield_literal",
|
||||
"backref_index_msb",
|
||||
"backref_index_lsb",
|
||||
"backref_count_msb",
|
||||
"backref_count_lsb",
|
||||
"yield_backref",
|
||||
};
|
||||
#else
|
||||
#define LOG(...) /* no-op */
|
||||
#define ASSERT(X) /* no-op */
|
||||
#endif
|
||||
|
||||
typedef struct {
|
||||
uint8_t *buf; /* output buffer */
|
||||
size_t buf_size; /* buffer size */
|
||||
size_t *output_size; /* bytes pushed to buffer, so far */
|
||||
} output_info;
|
||||
|
||||
#define NO_BITS ((uint16_t)-1)
|
||||
|
||||
/* Forward references. */
|
||||
static uint16_t get_bits(heatshrink_decoder *hsd, uint8_t count);
|
||||
static void push_byte(heatshrink_decoder *hsd, output_info *oi, uint8_t byte);
|
||||
|
||||
#if HEATSHRINK_DYNAMIC_ALLOC
|
||||
heatshrink_decoder *heatshrink_decoder_alloc(uint16_t input_buffer_size,
|
||||
uint8_t window_sz2,
|
||||
uint8_t lookahead_sz2) {
|
||||
if ((window_sz2 < HEATSHRINK_MIN_WINDOW_BITS) ||
|
||||
(window_sz2 > HEATSHRINK_MAX_WINDOW_BITS) ||
|
||||
(input_buffer_size == 0) ||
|
||||
(lookahead_sz2 < HEATSHRINK_MIN_LOOKAHEAD_BITS) ||
|
||||
(lookahead_sz2 >= window_sz2)) {
|
||||
return NULL;
|
||||
}
|
||||
size_t buffers_sz = (1 << window_sz2) + input_buffer_size;
|
||||
size_t sz = sizeof(heatshrink_decoder) + buffers_sz;
|
||||
heatshrink_decoder *hsd = HEATSHRINK_MALLOC(sz);
|
||||
if (hsd == NULL) { return NULL; }
|
||||
hsd->input_buffer_size = input_buffer_size;
|
||||
hsd->window_sz2 = window_sz2;
|
||||
hsd->lookahead_sz2 = lookahead_sz2;
|
||||
heatshrink_decoder_reset(hsd);
|
||||
LOG("-- allocated decoder with buffer size of %zu (%zu + %u + %u)\n",
|
||||
sz, sizeof(heatshrink_decoder), (1 << window_sz2), input_buffer_size);
|
||||
return hsd;
|
||||
}
|
||||
|
||||
void heatshrink_decoder_free(heatshrink_decoder *hsd) {
|
||||
size_t buffers_sz = (1 << hsd->window_sz2) + hsd->input_buffer_size;
|
||||
size_t sz = sizeof(heatshrink_decoder) + buffers_sz;
|
||||
HEATSHRINK_FREE(hsd, sz);
|
||||
(void)sz; /* may not be used by free */
|
||||
}
|
||||
#endif
|
||||
|
||||
void heatshrink_decoder_reset(heatshrink_decoder *hsd) {
|
||||
size_t buf_sz = 1 << HEATSHRINK_DECODER_WINDOW_BITS(hsd);
|
||||
size_t input_sz = HEATSHRINK_DECODER_INPUT_BUFFER_SIZE(hsd);
|
||||
memset(hsd->buffers, 0, buf_sz + input_sz);
|
||||
hsd->state = HSDS_TAG_BIT;
|
||||
hsd->input_size = 0;
|
||||
hsd->input_index = 0;
|
||||
hsd->bit_index = 0x00;
|
||||
hsd->current_byte = 0x00;
|
||||
hsd->output_count = 0;
|
||||
hsd->output_index = 0;
|
||||
hsd->head_index = 0;
|
||||
}
|
||||
|
||||
/* Copy SIZE bytes into the decoder's input buffer, if it will fit. */
|
||||
HSD_sink_res heatshrink_decoder_sink(heatshrink_decoder *hsd,
|
||||
uint8_t *in_buf, size_t size, size_t *input_size) {
|
||||
if ((hsd == NULL) || (in_buf == NULL) || (input_size == NULL)) {
|
||||
return HSDR_SINK_ERROR_NULL;
|
||||
}
|
||||
|
||||
size_t rem = HEATSHRINK_DECODER_INPUT_BUFFER_SIZE(hsd) - hsd->input_size;
|
||||
if (rem == 0) {
|
||||
*input_size = 0;
|
||||
return HSDR_SINK_FULL;
|
||||
}
|
||||
|
||||
size = rem < size ? rem : size;
|
||||
LOG("-- sinking %zd bytes\n", size);
|
||||
/* copy into input buffer (at head of buffers) */
|
||||
memcpy(&hsd->buffers[hsd->input_size], in_buf, size);
|
||||
hsd->input_size += size;
|
||||
*input_size = size;
|
||||
return HSDR_SINK_OK;
|
||||
}
|
||||
|
||||
|
||||
/*****************
|
||||
* Decompression *
|
||||
*****************/
|
||||
|
||||
#define BACKREF_COUNT_BITS(HSD) (HEATSHRINK_DECODER_LOOKAHEAD_BITS(HSD))
|
||||
#define BACKREF_INDEX_BITS(HSD) (HEATSHRINK_DECODER_WINDOW_BITS(HSD))
|
||||
|
||||
// States
|
||||
static HSD_state st_tag_bit(heatshrink_decoder *hsd);
|
||||
static HSD_state st_yield_literal(heatshrink_decoder *hsd,
|
||||
output_info *oi);
|
||||
static HSD_state st_backref_index_msb(heatshrink_decoder *hsd);
|
||||
static HSD_state st_backref_index_lsb(heatshrink_decoder *hsd);
|
||||
static HSD_state st_backref_count_msb(heatshrink_decoder *hsd);
|
||||
static HSD_state st_backref_count_lsb(heatshrink_decoder *hsd);
|
||||
static HSD_state st_yield_backref(heatshrink_decoder *hsd,
|
||||
output_info *oi);
|
||||
|
||||
HSD_poll_res heatshrink_decoder_poll(heatshrink_decoder *hsd,
|
||||
uint8_t *out_buf, size_t out_buf_size, size_t *output_size) {
|
||||
if ((hsd == NULL) || (out_buf == NULL) || (output_size == NULL)) {
|
||||
return HSDR_POLL_ERROR_NULL;
|
||||
}
|
||||
*output_size = 0;
|
||||
|
||||
output_info oi;
|
||||
oi.buf = out_buf;
|
||||
oi.buf_size = out_buf_size;
|
||||
oi.output_size = output_size;
|
||||
|
||||
while (1) {
|
||||
LOG("-- poll, state is %d (%s), input_size %d\n",
|
||||
hsd->state, state_names[hsd->state], hsd->input_size);
|
||||
uint8_t in_state = hsd->state;
|
||||
switch (in_state) {
|
||||
case HSDS_TAG_BIT:
|
||||
hsd->state = st_tag_bit(hsd);
|
||||
break;
|
||||
case HSDS_YIELD_LITERAL:
|
||||
hsd->state = st_yield_literal(hsd, &oi);
|
||||
break;
|
||||
case HSDS_BACKREF_INDEX_MSB:
|
||||
hsd->state = st_backref_index_msb(hsd);
|
||||
break;
|
||||
case HSDS_BACKREF_INDEX_LSB:
|
||||
hsd->state = st_backref_index_lsb(hsd);
|
||||
break;
|
||||
case HSDS_BACKREF_COUNT_MSB:
|
||||
hsd->state = st_backref_count_msb(hsd);
|
||||
break;
|
||||
case HSDS_BACKREF_COUNT_LSB:
|
||||
hsd->state = st_backref_count_lsb(hsd);
|
||||
break;
|
||||
case HSDS_YIELD_BACKREF:
|
||||
hsd->state = st_yield_backref(hsd, &oi);
|
||||
break;
|
||||
default:
|
||||
return HSDR_POLL_ERROR_UNKNOWN;
|
||||
}
|
||||
|
||||
/* If the current state cannot advance, check if input or output
|
||||
* buffer are exhausted. */
|
||||
if (hsd->state == in_state) {
|
||||
if (*output_size == out_buf_size) { return HSDR_POLL_MORE; }
|
||||
return HSDR_POLL_EMPTY;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static HSD_state st_tag_bit(heatshrink_decoder *hsd) {
|
||||
uint32_t bits = get_bits(hsd, 1); // get tag bit
|
||||
if (bits == NO_BITS) {
|
||||
return HSDS_TAG_BIT;
|
||||
} else if (bits) {
|
||||
return HSDS_YIELD_LITERAL;
|
||||
} else if (HEATSHRINK_DECODER_WINDOW_BITS(hsd) > 8) {
|
||||
return HSDS_BACKREF_INDEX_MSB;
|
||||
} else {
|
||||
hsd->output_index = 0;
|
||||
return HSDS_BACKREF_INDEX_LSB;
|
||||
}
|
||||
}
|
||||
|
||||
static HSD_state st_yield_literal(heatshrink_decoder *hsd,
|
||||
output_info *oi) {
|
||||
/* Emit a repeated section from the window buffer, and add it (again)
|
||||
* to the window buffer. (Note that the repetition can include
|
||||
* itself.)*/
|
||||
if (*oi->output_size < oi->buf_size) {
|
||||
uint16_t byte = get_bits(hsd, 8);
|
||||
if (byte == NO_BITS) { return HSDS_YIELD_LITERAL; } /* out of input */
|
||||
uint8_t *buf = &hsd->buffers[HEATSHRINK_DECODER_INPUT_BUFFER_SIZE(hsd)];
|
||||
uint16_t mask = (1 << HEATSHRINK_DECODER_WINDOW_BITS(hsd)) - 1;
|
||||
uint8_t c = byte & 0xFF;
|
||||
LOG("-- emitting literal byte 0x%02x ('%c')\n", c, isprint(c) ? c : '.');
|
||||
buf[hsd->head_index++ & mask] = c;
|
||||
push_byte(hsd, oi, c);
|
||||
return HSDS_TAG_BIT;
|
||||
} else {
|
||||
return HSDS_YIELD_LITERAL;
|
||||
}
|
||||
}
|
||||
|
||||
static HSD_state st_backref_index_msb(heatshrink_decoder *hsd) {
|
||||
uint8_t bit_ct = BACKREF_INDEX_BITS(hsd);
|
||||
ASSERT(bit_ct > 8);
|
||||
uint16_t bits = get_bits(hsd, bit_ct - 8);
|
||||
LOG("-- backref index (msb), got 0x%04x (+1)\n", bits);
|
||||
if (bits == NO_BITS) { return HSDS_BACKREF_INDEX_MSB; }
|
||||
hsd->output_index = bits << 8;
|
||||
return HSDS_BACKREF_INDEX_LSB;
|
||||
}
|
||||
|
||||
static HSD_state st_backref_index_lsb(heatshrink_decoder *hsd) {
|
||||
uint8_t bit_ct = BACKREF_INDEX_BITS(hsd);
|
||||
uint16_t bits = get_bits(hsd, bit_ct < 8 ? bit_ct : 8);
|
||||
LOG("-- backref index (lsb), got 0x%04x (+1)\n", bits);
|
||||
if (bits == NO_BITS) { return HSDS_BACKREF_INDEX_LSB; }
|
||||
hsd->output_index |= bits;
|
||||
hsd->output_index++;
|
||||
uint8_t br_bit_ct = BACKREF_COUNT_BITS(hsd);
|
||||
hsd->output_count = 0;
|
||||
return (br_bit_ct > 8) ? HSDS_BACKREF_COUNT_MSB : HSDS_BACKREF_COUNT_LSB;
|
||||
}
|
||||
|
||||
static HSD_state st_backref_count_msb(heatshrink_decoder *hsd) {
|
||||
uint8_t br_bit_ct = BACKREF_COUNT_BITS(hsd);
|
||||
ASSERT(br_bit_ct > 8);
|
||||
uint16_t bits = get_bits(hsd, br_bit_ct - 8);
|
||||
LOG("-- backref count (msb), got 0x%04x (+1)\n", bits);
|
||||
if (bits == NO_BITS) { return HSDS_BACKREF_COUNT_MSB; }
|
||||
hsd->output_count = bits << 8;
|
||||
return HSDS_BACKREF_COUNT_LSB;
|
||||
}
|
||||
|
||||
static HSD_state st_backref_count_lsb(heatshrink_decoder *hsd) {
|
||||
uint8_t br_bit_ct = BACKREF_COUNT_BITS(hsd);
|
||||
uint16_t bits = get_bits(hsd, br_bit_ct < 8 ? br_bit_ct : 8);
|
||||
LOG("-- backref count (lsb), got 0x%04x (+1)\n", bits);
|
||||
if (bits == NO_BITS) { return HSDS_BACKREF_COUNT_LSB; }
|
||||
hsd->output_count |= bits;
|
||||
hsd->output_count++;
|
||||
return HSDS_YIELD_BACKREF;
|
||||
}
|
||||
|
||||
static HSD_state st_yield_backref(heatshrink_decoder *hsd,
|
||||
output_info *oi) {
|
||||
size_t count = oi->buf_size - *oi->output_size;
|
||||
if (count > 0) {
|
||||
size_t i = 0;
|
||||
if (hsd->output_count < count) count = hsd->output_count;
|
||||
uint8_t *buf = &hsd->buffers[HEATSHRINK_DECODER_INPUT_BUFFER_SIZE(hsd)];
|
||||
uint16_t mask = (1 << HEATSHRINK_DECODER_WINDOW_BITS(hsd)) - 1;
|
||||
uint16_t neg_offset = hsd->output_index;
|
||||
LOG("-- emitting %zu bytes from -%u bytes back\n", count, neg_offset);
|
||||
ASSERT(neg_offset <= mask + 1);
|
||||
ASSERT(count <= (size_t)(1 << BACKREF_COUNT_BITS(hsd)));
|
||||
|
||||
for (i=0; i<count; i++) {
|
||||
uint8_t c = buf[(hsd->head_index - neg_offset) & mask];
|
||||
push_byte(hsd, oi, c);
|
||||
buf[hsd->head_index & mask] = c;
|
||||
hsd->head_index++;
|
||||
LOG(" -- ++ 0x%02x\n", c);
|
||||
}
|
||||
hsd->output_count -= count;
|
||||
if (hsd->output_count == 0) { return HSDS_TAG_BIT; }
|
||||
}
|
||||
return HSDS_YIELD_BACKREF;
|
||||
}
|
||||
|
||||
/* Get the next COUNT bits from the input buffer, saving incremental progress.
|
||||
* Returns NO_BITS on end of input, or if more than 15 bits are requested. */
|
||||
static uint16_t get_bits(heatshrink_decoder *hsd, uint8_t count) {
|
||||
uint16_t accumulator = 0;
|
||||
int i = 0;
|
||||
if (count > 15) { return NO_BITS; }
|
||||
LOG("-- popping %u bit(s)\n", count);
|
||||
|
||||
/* If we aren't able to get COUNT bits, suspend immediately, because we
|
||||
* don't track how many bits of COUNT we've accumulated before suspend. */
|
||||
if (hsd->input_size == 0) {
|
||||
if (hsd->bit_index < (1 << (count - 1))) { return NO_BITS; }
|
||||
}
|
||||
|
||||
for (i = 0; i < count; i++) {
|
||||
if (hsd->bit_index == 0x00) {
|
||||
if (hsd->input_size == 0) {
|
||||
LOG(" -- out of bits, suspending w/ accumulator of %u (0x%02x)\n",
|
||||
accumulator, accumulator);
|
||||
return NO_BITS;
|
||||
}
|
||||
hsd->current_byte = hsd->buffers[hsd->input_index++];
|
||||
LOG(" -- pulled byte 0x%02x\n", hsd->current_byte);
|
||||
if (hsd->input_index == hsd->input_size) {
|
||||
hsd->input_index = 0; /* input is exhausted */
|
||||
hsd->input_size = 0;
|
||||
}
|
||||
hsd->bit_index = 0x80;
|
||||
}
|
||||
accumulator <<= 1;
|
||||
if (hsd->current_byte & hsd->bit_index) {
|
||||
accumulator |= 0x01;
|
||||
if (0) {
|
||||
LOG(" -- got 1, accumulator 0x%04x, bit_index 0x%02x\n",
|
||||
accumulator, hsd->bit_index);
|
||||
}
|
||||
} else {
|
||||
if (0) {
|
||||
LOG(" -- got 0, accumulator 0x%04x, bit_index 0x%02x\n",
|
||||
accumulator, hsd->bit_index);
|
||||
}
|
||||
}
|
||||
hsd->bit_index >>= 1;
|
||||
}
|
||||
|
||||
if (count > 1) { LOG(" -- accumulated %08x\n", accumulator); }
|
||||
return accumulator;
|
||||
}
|
||||
|
||||
HSD_finish_res heatshrink_decoder_finish(heatshrink_decoder *hsd) {
|
||||
if (hsd == NULL) { return HSDR_FINISH_ERROR_NULL; }
|
||||
switch (hsd->state) {
|
||||
case HSDS_TAG_BIT:
|
||||
return hsd->input_size == 0 ? HSDR_FINISH_DONE : HSDR_FINISH_MORE;
|
||||
|
||||
/* If we want to finish with no input, but are in these states, it's
|
||||
* because the 0-bit padding to the last byte looks like a backref
|
||||
* marker bit followed by all 0s for index and count bits. */
|
||||
case HSDS_BACKREF_INDEX_LSB:
|
||||
case HSDS_BACKREF_INDEX_MSB:
|
||||
case HSDS_BACKREF_COUNT_LSB:
|
||||
case HSDS_BACKREF_COUNT_MSB:
|
||||
return hsd->input_size == 0 ? HSDR_FINISH_DONE : HSDR_FINISH_MORE;
|
||||
|
||||
/* If the output stream is padded with 0xFFs (possibly due to being in
|
||||
* flash memory), also explicitly check the input size rather than
|
||||
* uselessly returning MORE but yielding 0 bytes when polling. */
|
||||
case HSDS_YIELD_LITERAL:
|
||||
return hsd->input_size == 0 ? HSDR_FINISH_DONE : HSDR_FINISH_MORE;
|
||||
|
||||
default:
|
||||
return HSDR_FINISH_MORE;
|
||||
}
|
||||
}
|
||||
|
||||
static void push_byte(heatshrink_decoder *hsd, output_info *oi, uint8_t byte) {
|
||||
LOG(" -- pushing byte: 0x%02x ('%c')\n", byte, isprint(byte) ? byte : '.');
|
||||
oi->buf[(*oi->output_size)++] = byte;
|
||||
(void)hsd;
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
#ifndef HEATSHRINK_DECODER_H
|
||||
#define HEATSHRINK_DECODER_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include "heatshrink_common.h"
|
||||
#include "heatshrink_config.h"
|
||||
|
||||
typedef enum {
|
||||
HSDR_SINK_OK, /* data sunk, ready to poll */
|
||||
HSDR_SINK_FULL, /* out of space in internal buffer */
|
||||
HSDR_SINK_ERROR_NULL=-1, /* NULL argument */
|
||||
} HSD_sink_res;
|
||||
|
||||
typedef enum {
|
||||
HSDR_POLL_EMPTY, /* input exhausted */
|
||||
HSDR_POLL_MORE, /* more data remaining, call again w/ fresh output buffer */
|
||||
HSDR_POLL_ERROR_NULL=-1, /* NULL arguments */
|
||||
HSDR_POLL_ERROR_UNKNOWN=-2,
|
||||
} HSD_poll_res;
|
||||
|
||||
typedef enum {
|
||||
HSDR_FINISH_DONE, /* output is done */
|
||||
HSDR_FINISH_MORE, /* more output remains */
|
||||
HSDR_FINISH_ERROR_NULL=-1, /* NULL arguments */
|
||||
} HSD_finish_res;
|
||||
|
||||
#if HEATSHRINK_DYNAMIC_ALLOC
|
||||
#define HEATSHRINK_DECODER_INPUT_BUFFER_SIZE(BUF) \
|
||||
((BUF)->input_buffer_size)
|
||||
#define HEATSHRINK_DECODER_WINDOW_BITS(BUF) \
|
||||
((BUF)->window_sz2)
|
||||
#define HEATSHRINK_DECODER_LOOKAHEAD_BITS(BUF) \
|
||||
((BUF)->lookahead_sz2)
|
||||
#else
|
||||
#define HEATSHRINK_DECODER_INPUT_BUFFER_SIZE(_) \
|
||||
HEATSHRINK_STATIC_INPUT_BUFFER_SIZE
|
||||
#define HEATSHRINK_DECODER_WINDOW_BITS(_) \
|
||||
(HEATSHRINK_STATIC_WINDOW_BITS)
|
||||
#define HEATSHRINK_DECODER_LOOKAHEAD_BITS(BUF) \
|
||||
(HEATSHRINK_STATIC_LOOKAHEAD_BITS)
|
||||
#endif
|
||||
|
||||
typedef struct {
|
||||
uint16_t input_size; /* bytes in input buffer */
|
||||
uint16_t input_index; /* offset to next unprocessed input byte */
|
||||
uint16_t output_count; /* how many bytes to output */
|
||||
uint16_t output_index; /* index for bytes to output */
|
||||
uint16_t head_index; /* head of window buffer */
|
||||
uint8_t state; /* current state machine node */
|
||||
uint8_t current_byte; /* current byte of input */
|
||||
uint8_t bit_index; /* current bit index */
|
||||
|
||||
#if HEATSHRINK_DYNAMIC_ALLOC
|
||||
/* Fields that are only used if dynamically allocated. */
|
||||
uint8_t window_sz2; /* window buffer bits */
|
||||
uint8_t lookahead_sz2; /* lookahead bits */
|
||||
uint16_t input_buffer_size; /* input buffer size */
|
||||
|
||||
/* Input buffer, then expansion window buffer */
|
||||
uint8_t buffers[];
|
||||
#else
|
||||
/* Input buffer, then expansion window buffer */
|
||||
uint8_t buffers[(1 << HEATSHRINK_DECODER_WINDOW_BITS(_))
|
||||
+ HEATSHRINK_DECODER_INPUT_BUFFER_SIZE(_)];
|
||||
#endif
|
||||
} heatshrink_decoder;
|
||||
|
||||
#if HEATSHRINK_DYNAMIC_ALLOC
|
||||
/* Allocate a decoder with an input buffer of INPUT_BUFFER_SIZE bytes,
|
||||
* an expansion buffer size of 2^WINDOW_SZ2, and a lookahead
|
||||
* size of 2^lookahead_sz2. (The window buffer and lookahead sizes
|
||||
* must match the settings used when the data was compressed.)
|
||||
* Returns NULL on error. */
|
||||
heatshrink_decoder *heatshrink_decoder_alloc(uint16_t input_buffer_size,
|
||||
uint8_t expansion_buffer_sz2, uint8_t lookahead_sz2);
|
||||
|
||||
/* Free a decoder. */
|
||||
void heatshrink_decoder_free(heatshrink_decoder *hsd);
|
||||
#endif
|
||||
|
||||
/* Reset a decoder. */
|
||||
void heatshrink_decoder_reset(heatshrink_decoder *hsd);
|
||||
|
||||
/* Sink at most SIZE bytes from IN_BUF into the decoder. *INPUT_SIZE is set to
|
||||
* indicate how many bytes were actually sunk (in case a buffer was filled). */
|
||||
HSD_sink_res heatshrink_decoder_sink(heatshrink_decoder *hsd,
|
||||
uint8_t *in_buf, size_t size, size_t *input_size);
|
||||
|
||||
/* Poll for output from the decoder, copying at most OUT_BUF_SIZE bytes into
|
||||
* OUT_BUF (setting *OUTPUT_SIZE to the actual amount copied). */
|
||||
HSD_poll_res heatshrink_decoder_poll(heatshrink_decoder *hsd,
|
||||
uint8_t *out_buf, size_t out_buf_size, size_t *output_size);
|
||||
|
||||
/* Notify the dencoder that the input stream is finished.
|
||||
* If the return value is HSDR_FINISH_MORE, there is still more output, so
|
||||
* call heatshrink_decoder_poll and repeat. */
|
||||
HSD_finish_res heatshrink_decoder_finish(heatshrink_decoder *hsd);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,4 @@
|
||||
// CUSTOM (TeTeHacko): forwarding header, not part of detools. detools.h includes
|
||||
// "heatshrink_decoder.h" expecting it on the include path; this keeps every env
|
||||
// free of an extra -I flag. See README.tth.md.
|
||||
#include "heatshrink/heatshrink_decoder.h"
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
#include <RadioLib.h>
|
||||
#include "MeshCore.h"
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
#include "RXPowerSaving.h" // MC_TCXO_DELAY_US
|
||||
#endif
|
||||
|
||||
class CustomSX1262 : public SX1262 {
|
||||
uint32_t _preambleMillis = 66;
|
||||
@@ -12,6 +15,68 @@ class CustomSX1262 : public SX1262 {
|
||||
public:
|
||||
CustomSX1262(Module *mod) : SX1262(mod) { }
|
||||
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
// CUSTOM (TeTeHacko): RXPS support, from EasySkyMesh PowerSaving v18.
|
||||
// The sleep -> RX transition RadioLib subtracts from a duty-cycle sleep;
|
||||
// protected in the RadioLib base, read through here.
|
||||
uint32_t getTcxoDelay() const { return tcxoDelay; }
|
||||
|
||||
// RadioLib's begin() installs a 5000 us TCXO startup delay, which is also the
|
||||
// floor of every duty-cycle sleep. MC_TCXO_DELAY_US (1600, 4x the worst of
|
||||
// five measured modules) is written afterwards and the RC calibrations redone.
|
||||
// Every variant reaches the radio through this class (std_init() calls it).
|
||||
int16_t begin(float freq = 434.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7,
|
||||
uint8_t syncWord = RADIOLIB_SX126X_SYNC_WORD_PRIVATE, int8_t power = 10,
|
||||
uint16_t preambleLength = 8, float tcxoVoltage = 1.6,
|
||||
bool useRegulatorLDO = false) {
|
||||
int16_t state = SX1262::begin(freq, bw, sf, cr, syncWord, power, preambleLength,
|
||||
tcxoVoltage, useRegulatorLDO);
|
||||
if (state == RADIOLIB_ERR_NONE) state = applyMeshCoreTcxoDelay();
|
||||
return state;
|
||||
}
|
||||
|
||||
// tcxoVoltage read back from the chip object: begin() zeroes it when it falls
|
||||
// back to an XTAL, and a TCXO supply on DIO3 of a board without one is worse
|
||||
// than a long delay.
|
||||
int16_t applyMeshCoreTcxoDelay() {
|
||||
if (tcxoVoltage <= 0.0f) return RADIOLIB_ERR_NONE;
|
||||
int16_t state = setTCXO(tcxoVoltage, MC_TCXO_DELAY_US);
|
||||
RADIOLIB_ASSERT(state);
|
||||
state = calibrate(RADIOLIB_SX126X_CALIBRATE_ALL);
|
||||
delay(50);
|
||||
return state;
|
||||
}
|
||||
|
||||
int16_t startReceiveDutyCycle(uint32_t rxPeriod, uint32_t sleepPeriod,
|
||||
RadioLibIrqFlags_t irqFlags = RADIOLIB_IRQ_RX_DEFAULT_FLAGS,
|
||||
RadioLibIrqFlags_t irqMask = RADIOLIB_IRQ_RX_DEFAULT_MASK) {
|
||||
int16_t state = SX1262::startReceiveDutyCycle(rxPeriod, sleepPeriod, irqFlags, irqMask);
|
||||
if (state == RADIOLIB_ERR_NONE) {
|
||||
// RadioLib stages RX through standby, which leaves a host-controlled
|
||||
// RXEN switch in IDLE; set it back to RX for the whole duty cycle.
|
||||
this->mod->setRfSwitchState(Module::MODE_RX);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
// BUSY is high in the duty cycle's sleep phase.
|
||||
bool isChipBusy() {
|
||||
uint32_t busy = this->mod->getGpio();
|
||||
return busy != RADIOLIB_NC && this->mod->hal->digitalRead(busy);
|
||||
}
|
||||
|
||||
int16_t stopRTC() {
|
||||
uint8_t rtcStop = 0x00;
|
||||
int16_t state = writeRegister(RADIOLIB_SX126X_REG_RTC_CTRL, &rtcStop, 1);
|
||||
RADIOLIB_ASSERT(state);
|
||||
uint8_t rtcEvent = 0;
|
||||
state = readRegister(RADIOLIB_SX126X_REG_EVENT_MASK, &rtcEvent, 1);
|
||||
RADIOLIB_ASSERT(state);
|
||||
rtcEvent |= 0x02;
|
||||
return writeRegister(RADIOLIB_SX126X_REG_EVENT_MASK, &rtcEvent, 1);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef RP2040_PLATFORM
|
||||
bool std_init(SPIClassRP2040* spi = NULL)
|
||||
#else
|
||||
@@ -162,4 +227,27 @@ class CustomSX1262 : public SX1262 {
|
||||
readRegister(RADIOLIB_SX126X_REG_RX_GAIN, &rxGain, 1);
|
||||
return (rxGain == RADIOLIB_SX126X_RX_GAIN_BOOSTED);
|
||||
}
|
||||
|
||||
#ifdef RADIO_DIAG
|
||||
// CUSTOM (TeTeHacko): public views of SX126x commands RadioLib keeps
|
||||
// protected, for `radiostat` (RadioLibWrappers.cpp). Reads only.
|
||||
// SX126x::getStatus() reads ZERO data bytes and so always returns 0 (RadioLib
|
||||
// 7.7.1); the status comes back on the NOP after the opcode, done by hand.
|
||||
uint8_t diagStatus() {
|
||||
#ifdef P_LORA_NSS
|
||||
uint8_t out[2] = { RADIOLIB_SX126X_CMD_GET_STATUS, RADIOLIB_SX126X_CMD_NOP }, in[2] = { 0, 0 };
|
||||
uint32_t t0 = millis();
|
||||
while (mod->hal->digitalRead(mod->getGpio()) && millis() - t0 < 20) { } // BUSY
|
||||
mod->hal->spiBeginTransaction();
|
||||
mod->hal->digitalWrite(P_LORA_NSS, mod->hal->GpioLevelLow);
|
||||
mod->hal->spiTransfer(out, 2, in);
|
||||
mod->hal->digitalWrite(P_LORA_NSS, mod->hal->GpioLevelHigh);
|
||||
mod->hal->spiEndTransaction();
|
||||
return in[1];
|
||||
#else
|
||||
return getStatus();
|
||||
#endif
|
||||
}
|
||||
uint16_t diagDeviceErrors() { return getDeviceErrors(); }
|
||||
#endif
|
||||
};
|
||||
@@ -12,7 +12,19 @@ class CustomSX1262Wrapper : public RadioLibWrapper {
|
||||
public:
|
||||
CustomSX1262Wrapper(CustomSX1262& radio, mesh::MainBoard& board) : RadioLibWrapper(radio, board) { }
|
||||
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
// The duty-cycle sleep floor is this board's TCXO delay + 1000 us (RadioLib
|
||||
// subtracts it from the sleep; below it the register underflows).
|
||||
uint32_t rxPowerSavingTransitionUs() const override {
|
||||
return ((CustomSX1262 *)_radio)->getTcxoDelay() + 1000;
|
||||
}
|
||||
bool supportsRxPowerSaving() const override { return true; }
|
||||
#endif
|
||||
|
||||
void setParams(float freq, float bw, uint8_t sf, uint8_t cr) override {
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
prepareForRadioConfig();
|
||||
#endif
|
||||
((CustomSX1262 *)_radio)->setFrequency(freq);
|
||||
((CustomSX1262 *)_radio)->setSpreadingFactor(sf);
|
||||
((CustomSX1262 *)_radio)->setBandwidth(bw);
|
||||
@@ -28,14 +40,33 @@ public:
|
||||
((CustomSX1262 *)_radio)->getLoRaRxHeaderInfo(NULL, &crc);
|
||||
return crc;
|
||||
}
|
||||
bool isReceivingPacket() override {
|
||||
bool isReceivingPacket() override {
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
// In the sleep phase (BUSY high) an SPI probe of the IRQ flags would wake the
|
||||
// chip and break the cycle -- and there is nothing to receive. Outside RXPS
|
||||
// this stays a real channel check: Dispatcher::checkSend() relies on it.
|
||||
if (_rx_ps_armed && ((CustomSX1262 *)_radio)->isChipBusy()) return false;
|
||||
#endif
|
||||
return ((CustomSX1262 *)_radio)->isReceiving();
|
||||
}
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
bool isChipBusy() override { return ((CustomSX1262 *)_radio)->isChipBusy(); }
|
||||
#endif
|
||||
#if defined(LORA_POLL_IRQ) || defined(PIN_DIAG)
|
||||
// CUSTOM (TeTeHacko): SX126x native status bits. TIMEOUT is in the mask because
|
||||
// an RX window that expires has to end the wait too -- with the DIO1 line dead
|
||||
// nothing else would ever release it.
|
||||
uint32_t irqDoneMask() const override {
|
||||
return RADIOLIB_SX126X_IRQ_TX_DONE | RADIOLIB_SX126X_IRQ_RX_DONE | RADIOLIB_SX126X_IRQ_TIMEOUT;
|
||||
}
|
||||
#endif
|
||||
float getCurrentRSSI() override {
|
||||
return ((CustomSX1262 *)_radio)->getRSSI(false);
|
||||
}
|
||||
#ifndef WITH_RX_POWERSAVING // with it, the base class answers from the values cached at RX
|
||||
float getLastRSSI() const override { return ((CustomSX1262 *)_radio)->getRSSI(); }
|
||||
float getLastSNR() const override { return ((CustomSX1262 *)_radio)->getSNR(); }
|
||||
#endif
|
||||
|
||||
float packetScore(float snr, int packet_len) override {
|
||||
int sf = ((CustomSX1262 *)_radio)->spreadingFactor;
|
||||
@@ -43,11 +74,17 @@ public:
|
||||
}
|
||||
uint8_t getSpreadingFactor() const override { return ((CustomSX1262 *)_radio)->spreadingFactor; }
|
||||
virtual void powerOff() override {
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
if (_rx_ps_armed) stopReceiveDutyCycle();
|
||||
#endif
|
||||
((CustomSX1262 *)_radio)->sleep(false);
|
||||
}
|
||||
|
||||
bool supportsRxBoostedGain() const override { return true; }
|
||||
bool setRxBoostedGainMode(bool en) override {
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
prepareForRadioConfig();
|
||||
#endif
|
||||
return ((CustomSX1262 *)_radio)->setRxBoostedGainMode(en) == RADIOLIB_ERR_NONE;
|
||||
}
|
||||
bool getRxBoostedGainMode() const override {
|
||||
@@ -55,4 +92,47 @@ public:
|
||||
}
|
||||
|
||||
void doResetAGC() override { sx126xResetAGC((SX126x *)_radio, getRxBoostedGainMode()); }
|
||||
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
protected:
|
||||
int16_t armDutyCycle(RadioLibIrqFlags_t irq_flags, RadioLibIrqFlags_t irq_mask,
|
||||
uint32_t* eff_rx_us, uint32_t* eff_sleep_us) override {
|
||||
// RadioLib programs exactly what is asked (it subtracts the wake-up
|
||||
// transition from the sleep internally).
|
||||
*eff_rx_us = _rx_ps_rx_us;
|
||||
*eff_sleep_us = _rx_ps_sleep_us;
|
||||
return ((CustomSX1262 *)_radio)->startReceiveDutyCycle(_rx_ps_rx_us, _rx_ps_sleep_us, irq_flags, irq_mask);
|
||||
}
|
||||
int16_t stopDutyCycleHardware() override {
|
||||
int16_t standby_err = _radio->standby();
|
||||
int16_t rtc_err = ((CustomSX1262 *)_radio)->stopRTC();
|
||||
return standby_err != RADIOLIB_ERR_NONE ? standby_err : rtc_err;
|
||||
}
|
||||
// continuous RX keeps the preamble-detect IRQ, like CustomSX1262::startReceive()
|
||||
int16_t startContinuousReceive() override { return ((CustomSX1262 *)_radio)->startReceive(); }
|
||||
public:
|
||||
#endif
|
||||
|
||||
#ifdef RADIO_DIAG
|
||||
protected:
|
||||
// CUSTOM (TeTeHacko): `radiostat`, chip side. mode: 2 STBY_RC, 3 STBY_XOSC,
|
||||
// 4 FS, 5 RX, 6 TX; cmd: 2 data available, 3 timeout, 4 processing error,
|
||||
// 5 exec failure. Pin levels are read back, so -1 = not wired.
|
||||
int diagChip(char* out, int sz) override {
|
||||
CustomSX1262* r = (CustomSX1262 *)_radio;
|
||||
uint8_t s = r->diagStatus();
|
||||
int dio1 = -1, rxen = -1;
|
||||
#ifdef P_LORA_DIO_1
|
||||
if ((uint32_t) P_LORA_DIO_1 != (uint32_t) RADIOLIB_NC) dio1 = digitalRead(P_LORA_DIO_1);
|
||||
#endif
|
||||
#ifdef SX126X_RXEN
|
||||
if ((uint32_t) SX126X_RXEN != (uint32_t) RADIOLIB_NC) rxen = digitalRead(SX126X_RXEN);
|
||||
#endif
|
||||
return snprintf(out, sz, " mode=%u cmd=%u irq=0x%04lx deverr=0x%04x rssi=%d dio1=%d rxen=%d boost=%d",
|
||||
(unsigned) ((s >> 4) & 7), (unsigned) ((s >> 1) & 7),
|
||||
(unsigned long) r->getIrqFlags(), (unsigned) r->diagDeviceErrors(),
|
||||
(int) r->getRSSI(false), dio1, rxen, (int) r->getRxBoostedGainMode());
|
||||
}
|
||||
public:
|
||||
#endif
|
||||
};
|
||||
Loaded 100 of 176 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user