From e440eb1a6b474d394eab864671e8bfc5d4555e54 Mon Sep 17 00:00:00 2001 From: TeTeHacko Date: Fri, 4 Dec 2026 01:18:20 +0100 Subject: [PATCH 1/3] Repeater, room server, sensor, companion: the same commit builds into the same firmware, byte for byte MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Changelog: Repeater, room server, sensor, companion: the same commit builds into the same firmware, byte for byte (anyone can check a release against the source) Changelog-cs: Repeater, room server, sensor, companion: ze stejného commitu vznikne bajtově stejný firmware (vydání se dá ověřit proti zdrojákům) --- .github/workflows/pub-release.yml | 30 +++++++++++++ src/helpers/sensors/GpsGuard.h | 3 +- tools/README.md | 3 +- tools/build_version.py | 75 ++++++++++++++++++++----------- tools/ccache_wrap.py | 42 +++++++++++++++++ 5 files changed, 125 insertions(+), 28 deletions(-) create mode 100644 tools/ccache_wrap.py diff --git a/.github/workflows/pub-release.yml b/.github/workflows/pub-release.yml index 7b5f88ce0..c280da31d 100644 --- a/.github/workflows/pub-release.yml +++ b/.github/workflows/pub-release.yml @@ -203,6 +203,34 @@ jobs: - name: Setup Build Environment uses: ./.github/actions/setup-build-environment + - name: Setup ccache + shell: bash + run: | + set -euo pipefail + if ! command -v ccache >/dev/null; then + SUDO="$(command -v sudo || true)" + $SUDO apt-get update -qq + $SUDO apt-get install -y -qq ccache + fi + ccache --version | head -1 + { + [ -f tools/ccache_wrap.py ] && echo "PLATFORMIO_EXTRA_SCRIPTS=pre:tools/ccache_wrap.py" + echo "CCACHE_DIR=$HOME/.cache/ccache" + echo "CCACHE_MAXSIZE=2G" + echo "CCACHE_COMPILERCHECK=content" + echo "CCACHE_BASEDIR=$GITHUB_WORKSPACE" + echo "CCACHE_NOHASHDIR=true" + } >>"$GITHUB_ENV" + + - name: Compiler cache + uses: actions/cache@v5 + with: + path: ~/.cache/ccache + key: ccache-pub-${{ hashFiles('platformio.ini', 'platformio.lock') }}-${{ github.run_id }} + restore-keys: | + ccache-pub-${{ hashFiles('platformio.ini', 'platformio.lock') }}- + ccache-pub- + - name: Build and package id: build env: @@ -355,9 +383,11 @@ jobs: 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 } + ccache -z >/dev/null 2>&1 || true t1=$SECONDS par compile "${arts[@]}" echo "compiled ${#arts[@]} artifacts in $((SECONDS - t1)) s ($PARALLEL at a time)" + ccache -s || true 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/, diff --git a/src/helpers/sensors/GpsGuard.h b/src/helpers/sensors/GpsGuard.h index abed984d1..21d61aaef 100644 --- a/src/helpers/sensors/GpsGuard.h +++ b/src/helpers/sensors/GpsGuard.h @@ -125,8 +125,7 @@ public: // Plausible GPS time window: not before this firmware was built, at most 10 years after. static uint32_t minEpoch() { - static const uint32_t min_epoch = DateTime(__DATE__, __TIME__).unixtime() - 86400; - return min_epoch; + return (uint32_t)FIRMWARE_BUILD_EPOCH - 86400UL; } static uint32_t maxEpoch() { return minEpoch() + 10UL * 365 * 86400; } diff --git a/tools/README.md b/tools/README.md index 231428cb0..d80ed2327 100644 --- a/tools/README.md +++ b/tools/README.md @@ -43,7 +43,8 @@ a different board. | `xiao_serial_dfu.sh` | XIAO with a text console over USB serial DFU: no drive, no mount, no root | | `ble_flash_node.sh` | BLE OTA of a node out of reach of a cable, with the checks around it (silence, services, version) | | `ble_dfu.py` | legacy Nordic DFU over BLE for the Adafruit nRF52 bootloader (buttonless, both phases). An `AdaDFU` bootloader (XIAO, SenseCap Solar) gets 20 B packets from the start: the legacy DFU takes no bigger ones, and finding out mid-image is too late (the app is already erased, the XIAO then comes back as USB DFU only). Slow (~10 min for 400 kB): for repeated bench swaps use the `-ota` images and `ota_push.py` | -| `build_version.py` | PlatformIO pre-script: real version and build time for `ver` | +| `build_version.py` | PlatformIO pre-script: real version and UTC build timestamp (`SOURCE_DATE_EPOCH` / HEAD commit time on clean trees, current time when dirty) scoped to project sources so library/framework builds stay cacheable | +| `ccache_wrap.py` | PlatformIO pre-script: wraps all C/C++ compiler invocations (framework, libraries, project) with `ccache` via `AddBuildMiddleware` (no-op if `ccache` is absent) | | `pio_lock.py` | library lock for PlatformIO (`platformio.lock`): `install` the locked versions before a build, `check` that nothing else resolved, `freeze` a resolution, `moved` against git | | `bl_sign_pkg.py` | DFU zip for a board with the signed (`SIGNED_FW`) Adafruit bootloader: `adafruit-nrfutil dfu genpkg --key-file` with its two Python 3 bugs on that path fixed | | `bl_verify_pkg.py` | checks a DFU zip the way the signed bootloader will (device type, ECDSA P-256 over the init packet, image length and hash) | diff --git a/tools/build_version.py b/tools/build_version.py index a7ada3af9..4d1d4e267 100644 --- a/tools/build_version.py +++ b/tools/build_version.py @@ -11,9 +11,12 @@ # extra_scripts = ${nrf52_base.extra_scripts} # pre:tools/build_version.py # -# Injects FIRMWARE_VERSION (-tth-, '+' = dirty tree) and -# FIRMWARE_BUILD_DATE (compile time). NOTE: the define changes every build = -# full rebuild each time (~10-30 s) -- the price for an always-fresh timestamp. +# Injects FIRMWARE_VERSION (-tth, '+' = dirty tree), +# FIRMWARE_BUILD_DATE, FIRMWARE_BUILD_EPOCH and FW_OTA_TARGET into project +# sources only (not libraries or framework, so ccache hits direct mode across +# commits and variants). Clean trees stamp the HEAD commit timestamp in UTC +# (or SOURCE_DATE_EPOCH if set) for byte-reproducible builds; dirty trees stamp +# the current UTC time. # # SCons script, not a module: `Import` and `env` are SCons builtins and # Import("env") has to come first, hence the file-wide ruff exemption. @@ -32,7 +35,7 @@ Import("env") import os import re import subprocess -from datetime import datetime +from datetime import datetime, timezone def git(cwd, *args): @@ -99,26 +102,24 @@ if len(version) > VER_LIMIT: # yymmdd hhmm = exactly 11. Not pretty, but complete and sortable; the readable # "%d %b %Y %H:%M" is 17 and lost its time to the 12-byte field. -now = datetime.now() -build_date = now.strftime("%y%m%d %H%M")[:DATE_LIMIT] +# +# Reproducible builds: honor SOURCE_DATE_EPOCH when set; otherwise use the HEAD +# commit timestamp (UTC) for clean trees so two builds of the same commit +# produce identical bytes regardless of wall clock or host timezone. Dirty +# trees still stamp the current UTC time so bench iterations stay distinct. +sde = os.environ.get("SOURCE_DATE_EPOCH", "").strip() +if sde: + build_epoch = int(sde) +elif not dirty and sha != "nogit": + try: + build_epoch = int(git(cwd, "log", "-1", "--format=%ct", "HEAD")) + except Exception: + build_epoch = int(datetime.now(timezone.utc).timestamp()) +else: + build_epoch = int(datetime.now(timezone.utc).timestamp()) -# The same instant as an epoch, which VolatileRTCClock uses as its base_time -# instead of the hardcoded 15 May 2024 (src/helpers/ArduinoHelpers.h). This is -# the ONLY way a node gets a sane clock with no GPS, no I2C RTC, nothing -# carrying a correct time on air, and no host attached -- i.e. a bench board. -# It is not cosmetic: the RTC stamps every advert the node transmits, and a -# receiver drops a stale timestamp as a replay, so a 2024 clock turns into -# dropped replies. Measured 7. 8. 2026: bench-board had run 811 days behind since -# deployment and every board on the bench was 812 days behind, all because -# `time ` was a manual step nobody performed. -# -# NOT StringifyMacro: this has to reach the compiler as the integer 1786095587, -# not as the string "1786095587". SCons renders a (name, value) tuple as -# -Dname=value verbatim. -# -# Costs no extra rebuilds -- FIRMWARE_BUILD_DATE already changes every build, so -# the tree is already fully recompiled each time. -build_epoch = int(now.timestamp()) +now = datetime.fromtimestamp(build_epoch, timezone.utc) +build_date = now.strftime("%y%m%d %H%M")[:DATE_LIMIT] # src/helpers/FwUpdate refuses a package built for another target: the env, # plus the image variant when one env is released as several @@ -129,10 +130,34 @@ ota_target = env["PIOENV"] + ("-" + ota_variant if ota_variant else "") if len(ota_target) > 47: # Manifest.target[48] in FwUpdate.cpp, NUL-terminated raise SystemExit("build_version.py: OTA target %r longer than 47 chars" % ota_target) -env.Append(CPPDEFINES=[ +# Scope the volatile version/timestamp/target defines to project sources only +# (src/, examples/, variants/, test/) rather than global env CPPDEFINES. +# Libraries and the Arduino framework never reference them, and keeping those +# flags off their compiler command lines lets ccache hit direct mode across +# commits, timestamps and OTA variants. +_stamp_defines = [ ("FIRMWARE_VERSION", env.StringifyMacro(version)), ("FIRMWARE_BUILD_DATE", env.StringifyMacro(build_date)), ("FIRMWARE_BUILD_EPOCH", str(build_epoch)), ("FW_OTA_TARGET", env.StringifyMacro(ota_target)), -]) +] +_proj_root = os.path.realpath(cwd) +_libdeps_root = os.path.realpath(env.subst("$PROJECT_LIBDEPS_DIR")) +_lib_root = os.path.realpath(os.path.join(cwd, "lib")) +_stamped_envs = set() + + +def _stamp_project(e, node): + if id(e) not in _stamped_envs: + src = os.path.realpath(node.srcnode().get_abspath()) + if src.startswith(_proj_root + os.sep) and not ( + src.startswith(_libdeps_root + os.sep) + or src.startswith(_lib_root + os.sep) + ): + _stamped_envs.add(id(e)) + e.Append(CPPDEFINES=_stamp_defines) + return node + + +env.AddBuildMiddleware(_stamp_project) print("build_version.py: %s (Build: %s, epoch %d)" % (version, build_date, build_epoch)) diff --git a/tools/ccache_wrap.py b/tools/ccache_wrap.py new file mode 100644 index 000000000..e190bc90e --- /dev/null +++ b/tools/ccache_wrap.py @@ -0,0 +1,42 @@ +# SPDX-License-Identifier: MIT +# PlatformIO extra script: wrap every C/C++ compiler invocation with ccache. +# +# Usage (CI or local): +# PLATFORMIO_EXTRA_SCRIPTS=pre:tools/ccache_wrap.py pio run -e +# +# Uses env.AddBuildMiddleware so the wrapper applies to every cloned SCons +# environment -- framework, libraries and project sources -- across both nRF52 +# and ESP32. A `post:` script that only mutates `env["CC"/"CXX"]` misses +# `projenv` and already-cloned library/framework builders (~85% of nRF52 units +# and 100% of ESP32 units). +# +# No-op when `ccache` is not on PATH. +# +# SCons script, not a module: `Import` and `env` are SCons builtins. +# ruff: noqa: F821, E402 +# mypy: disable-error-code="name-defined" +if __name__ == "__main__": + with open(__file__) as _f: + for _ln in _f: + if not _ln.startswith("#"): + break + if "SPDX-License-Identifier" not in _ln: + print(_ln[2:].rstrip() if _ln.startswith("# ") else "") + raise SystemExit(0) + +Import("env") +import shutil + +if shutil.which("ccache"): + _wrapped_envs = set() + + def _wrap_ccache(e, node): + if id(e) not in _wrapped_envs: + _wrapped_envs.add(id(e)) + for var in ("CC", "CXX"): + cur = e.get(var) + if cur and not str(cur).startswith("ccache "): + e.Replace(**{var: "ccache " + str(cur)}) + return node + + env.AddBuildMiddleware(_wrap_ccache) From 681d38b7782fbfda80fe1a1c095b3dcdb52b399e Mon Sep 17 00:00:00 2001 From: TeTeHacko Date: Fri, 4 Dec 2026 01:16:01 +0100 Subject: [PATCH 2/3] Repeater, room server, sensor, companion: propagate SOURCE_DATE_EPOCH to compiler subprocesses Changelog: - --- tools/build_version.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tools/build_version.py b/tools/build_version.py index 4d1d4e267..6ee9a55f3 100644 --- a/tools/build_version.py +++ b/tools/build_version.py @@ -121,6 +121,12 @@ else: now = datetime.fromtimestamp(build_epoch, timezone.utc) build_date = now.strftime("%y%m%d %H%M")[:DATE_LIMIT] +# Propagate SOURCE_DATE_EPOCH into every compiler/tool subprocess so GCC also +# evaluates any __DATE__/__TIME__ macros inside third-party libraries or the +# Arduino framework deterministically (and ccache gets 100% hits). +os.environ["SOURCE_DATE_EPOCH"] = str(build_epoch) +env["ENV"]["SOURCE_DATE_EPOCH"] = str(build_epoch) + # src/helpers/FwUpdate refuses a package built for another target: the env, # plus the image variant when one env is released as several # (FW_OTA_VARIANT=observer-ota -> "SenseCap_Solar_repeater-observer-ota"), or a From 3d66aaf3969ab6265f04fbc28af8b71ef30e5955 Mon Sep 17 00:00:00 2001 From: TeTeHacko Date: Fri, 4 Dec 2026 01:37:37 +0100 Subject: [PATCH 3/3] CI: export SOURCE_DATE_EPOCH for ESP32 and normalize DFU zip timestamps Changelog: - --- .github/workflows/pub-release.yml | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/.github/workflows/pub-release.yml b/.github/workflows/pub-release.yml index c280da31d..fc1bace04 100644 --- a/.github/workflows/pub-release.yml +++ b/.github/workflows/pub-release.yml @@ -215,6 +215,7 @@ jobs: ccache --version | head -1 { [ -f tools/ccache_wrap.py ] && echo "PLATFORMIO_EXTRA_SCRIPTS=pre:tools/ccache_wrap.py" + echo "SOURCE_DATE_EPOCH=$(git log -1 --format=%ct HEAD)" echo "CCACHE_DIR=$HOME/.cache/ccache" echo "CCACHE_MAXSIZE=2G" echo "CCACHE_COMPILERCHECK=content" @@ -341,11 +342,10 @@ jobs: 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 (+ + # 1) install the platforms. One env per distinct platform (+ # platform_packages) installs those first, one at a time -- they - # are shared in ~/.platformio, concurrent installs would race. + # are shared in ~/.platformio (restored by actions/cache above), + # 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 @@ -399,8 +399,20 @@ jobs: 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 + # Normalize ZIP entry timestamps to SOURCE_DATE_EPOCH so the DFU + # zip (and SHA256SUMS) is byte-for-byte reproducible across runs. + python3 -c ' + import datetime, os, sys, zipfile + ts = datetime.datetime.fromtimestamp(int(os.environ["SOURCE_DATE_EPOCH"]), datetime.timezone.utc) + dt = (ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second - (ts.second % 2)) + src, dst = sys.argv[1], sys.argv[2] + with zipfile.ZipFile(src, "r") as zin, zipfile.ZipFile(dst, "w", compression=zipfile.ZIP_STORED) as zout: + for info in zin.infolist(): + data = zin.read(info.filename) + info.date_time = dt + zout.writestr(info, data) + ' "$b/firmware.zip" "$dist/$env$suffix-$TAG.zip" 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"