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)