Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion platformio.ini
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ platform = https://github.com/pioarduino/platform-espressif32/releases/download/
framework = arduino
build_type = release
board_build.partitions = partitions.csv
extra_scripts = pre:scripts/gen_gzip_assets.py
extra_scripts =
pre:scripts/gen_gzip_assets.py
pre:scripts/bake_git_commit.py
monitor_speed = 115200
monitor_filters = direct, printable
build_flags =
Expand Down
106 changes: 106 additions & 0 deletions scripts/bake_git_commit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
"""Bake the short git commit into src/gen/FirmwareBuildCommit.h.

Runs as a PlatformIO `pre:` hook. Only src/FirmwareBuildInfo.cpp includes the
header, and it is rewritten only when the commit changes, so a new commit
recompiles that one file. Without git (source archive, missing binary, timeout)
the commit is "unknown" and the build continues.
"""

import os
import re
import subprocess

UNKNOWN = "unknown"
COMMIT_RE = re.compile(r"^[0-9a-f]{4,40}$")
HEADER_REL = os.path.join("src", "gen", "FirmwareBuildCommit.h")
GIT_ENV_DROP = ("GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_OBJECT_DIRECTORY")


def git_env():
"""The caller's environment without the overrides that redirect HEAD.

An exported GIT_DIR makes git read another checkout's HEAD while
--show-toplevel still reports project_dir, which would defeat the
nested-archive guard.
"""
return {k: v for k, v in os.environ.items() if k not in GIT_ENV_DROP}


def sanitize_commit(raw):
text = (raw or "").strip()
return text if COMMIT_RE.match(text) else UNKNOWN


def toplevel_matches(project_dir, git="git", timeout=5):
"""True only when project_dir is itself the git work-tree root.

git searches parent directories, so an archive extracted inside another
checkout would otherwise bake that checkout's commit.
"""
try:
result = subprocess.run(
[git, "-C", project_dir, "rev-parse", "--show-toplevel"],
capture_output=True, text=True, timeout=timeout, check=False,
env=git_env())
except (OSError, subprocess.SubprocessError):
return False
top = (result.stdout or "").strip()
if result.returncode != 0 or not top:
return False
return os.path.realpath(top) == os.path.realpath(project_dir)


def read_commit(project_dir, git="git", timeout=5):
try:
result = subprocess.run(
[git, "-C", project_dir, "rev-parse", "--short=7", "HEAD"],
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
capture_output=True, text=True, timeout=timeout, check=False,
env=git_env())
except (OSError, subprocess.SubprocessError):
return UNKNOWN
if result.returncode != 0:
return UNKNOWN
commit = sanitize_commit(result.stdout)
if commit == UNKNOWN:
return UNKNOWN
if not toplevel_matches(project_dir, git, timeout):
return UNKNOWN
return commit


def render_header(commit):
return ("#pragma once\n"
"// Generated by scripts/bake_git_commit.py. Do not edit.\n"
'#define FW_GIT_COMMIT "%s"\n' % commit)


def write_if_changed(path, content):
try:
with open(path, "r", encoding="utf-8") as fh:
if fh.read() == content:
return False
except OSError:
pass
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = path + ".tmp"
with open(tmp, "w", encoding="utf-8") as fh:
fh.write(content)
os.replace(tmp, path)
return True


def bake(project_dir, git="git"):
commit = read_commit(project_dir, git)
changed = write_if_changed(os.path.join(project_dir, HEADER_REL),
render_header(commit))
print("git-commit: %s (%s)" % (commit, "regenerated" if changed else "unchanged"))
return commit


try:
Import("env") # noqa: F821 (PlatformIO SConscript context)
except NameError:
env = None

if env is not None:
bake(env.subst("$PROJECT_DIR"))
12 changes: 12 additions & 0 deletions src/FirmwareBuildInfo.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#include "FirmwareBuildInfo.h"

// Sole includer of the generated header, so a new commit rebuilds only this file.
#if __has_include("gen/FirmwareBuildCommit.h")
#include "gen/FirmwareBuildCommit.h"
#endif

#ifndef FW_GIT_COMMIT
#define FW_GIT_COMMIT "unknown"
#endif

const char* firmwareBuildCommit() { return FW_GIT_COMMIT; }
68 changes: 68 additions & 0 deletions src/FirmwareBuildInfo.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#ifndef FIRMWARE_BUILD_INFO_H
#define FIRMWARE_BUILD_INFO_H

#include <cstddef>
#include <cstdio>
#include <cstring>

// Short git commit baked in at build time, or "unknown".
const char* firmwareBuildCommit();

// PlatformIO env name; the OTA page downloads spoolsense_scanner_<board>.bin
// by this string. XIAO must precede BOARD_ESP32_C6: its env defines both.
inline const char* firmwareBoardName() {
#if defined(BOARD_SEEED_XIAO_ESP32_C6)
return "seeed_xiao_esp32c6";
#elif defined(BOARD_ESP32_C6)
return "esp32c6";
#elif defined(BOARD_ESP32_C5)
return "esp32c5";
#elif defined(BOARD_ESP32_C3)
return "esp32c3";
#elif defined(BOARD_S3_DEVKITC)
return "esp32s3devkitc";
#elif defined(BOARD_ESP32_S3)
return "esp32s3zero";
#else
return "esp32dev";
#endif
}

// Writes "SpoolSense <version> (<commit>) <board>"; null or empty parts become
// "unknown". Returns snprintf's result, or 0 when out is null or size is 0.
inline int formatFirmwareLine(char* out, size_t size, const char* version,
const char* commit, const char* board) {
if (!out || size == 0) return 0;
auto part = [](const char* s) { return (s && *s) ? s : "unknown"; };
return std::snprintf(out, size, "SpoolSense %s (%s) %s",
part(version), part(commit), part(board));
}

// Writes "<identity line>\n<log>" into out (size bytes, NUL-terminated).
// Returns the number of characters written, or 0 when out is null or size is
// 0. The log is truncated to fit; log may overlap out.
inline int formatLogsWithIdentity(char* out, size_t size, const char* version,
const char* commit, const char* board,
const char* log) {
if (!out || size == 0) return 0;
int n = formatFirmwareLine(out, size, version, commit, board);
if (n < 0) return 0;
size_t pos = (static_cast<size_t>(n) < size) ? static_cast<size_t>(n)
: size - 1;
if (pos + 1 < size) {
out[pos] = '\n';
pos++;
}
out[pos] = '\0';
if (log) {
size_t room = size - pos - 1;
size_t len = std::strlen(log);
if (len > room) len = room;
std::memmove(out + pos, log, len);
pos += len;
out[pos] = '\0';
}
return static_cast<int>(pos);
}

#endif // FIRMWARE_BUILD_INFO_H
33 changes: 13 additions & 20 deletions src/WebServerManager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
#include "OpenTag3DLogo.h"
#include "OpenSpoolLogo.h"
#include "LogBuffer.h"
#include "FirmwareBuildInfo.h"
#include "ConfigurationManager.h"
#include "NFCManager.h"
#include "U1Manager.h"
Expand Down Expand Up @@ -408,12 +409,20 @@ void WebServerManager::handleLogViewer() {
}

void WebServerManager::handleApiLogs() {
char* buf = (char*)malloc(4097);
// Identity line (fits in 96, same bound as the boot line) + '\n' +
// log (<= 4096) + NUL, so /logs always starts with the identity.
const size_t kIdentityMax = 96;
const size_t kLogMax = 4096;
const size_t total = kIdentityMax + 1 + kLogMax + 1;
char* buf = (char*)malloc(total);
if (!buf) {
_server.send(500, "text/plain", "out of memory");
return;
}
LogBuffer::getInstance().getLog(buf, 4097);
char* logs = buf + kIdentityMax + 1;
LogBuffer::getInstance().getLog(logs, kLogMax + 1);
formatLogsWithIdentity(buf, total, FIRMWARE_VERSION, firmwareBuildCommit(),
firmwareBoardName(), logs);
_server.send(200, "text/plain", buf);
free(buf);
}
Expand Down Expand Up @@ -1220,24 +1229,8 @@ void WebServerManager::handleApiPostConfig() {
void WebServerManager::handleApiVersion() {
JsonDocument doc;
doc["version"] = FIRMWARE_VERSION;
// Matches the PlatformIO env / release-asset naming for each target.
// XIAO must precede BOARD_ESP32_C6 — its env defines both flags, and the
// OTA page downloads spoolsense_scanner_<board>.bin by this string.
#if defined(BOARD_SEEED_XIAO_ESP32_C6)
doc["board"] = "seeed_xiao_esp32c6";
#elif defined(BOARD_ESP32_C6)
doc["board"] = "esp32c6";
#elif defined(BOARD_ESP32_C5)
doc["board"] = "esp32c5";
#elif defined(BOARD_ESP32_C3)
doc["board"] = "esp32c3";
#elif defined(BOARD_S3_DEVKITC)
doc["board"] = "esp32s3devkitc";
#elif defined(BOARD_ESP32_S3)
doc["board"] = "esp32s3zero";
#else
doc["board"] = "esp32dev";
#endif
doc["board"] = firmwareBoardName();
doc["build"] = firmwareBuildCommit();
String body;
serializeJson(doc, body);
_server.send(200, "application/json", body);
Expand Down
8 changes: 8 additions & 0 deletions src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
#include "HardwareNFCConnectionPN532.h"
#include "HardwareNFCConnectionRC522.h"
#include "BoardPins.h"
#include "FirmwareBuildInfo.h"
#include <Wire.h>

// main.cpp — ESP32 firmware entry point and hardware init. Manages WiFi, AP mode, NTP, display/LED/
Expand Down Expand Up @@ -267,6 +268,13 @@ void setup() {
#endif
delay(1000);
Serial.println("=== Starting setup ===");
{
char line[96];
formatFirmwareLine(line, sizeof(line), FIRMWARE_VERSION, firmwareBuildCommit(),
firmwareBoardName());
// /logs prepends this line itself; keep it on serial only.
Serial.println(line);
}

// ConfigurationManager MUST init before any hardware — it reads NVS to gate feature initialization
if (!ConfigurationManager::getInstance().begin()) {
Expand Down
46 changes: 43 additions & 3 deletions test/native/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,16 @@ CFLAGS = -std=c11 -DNATIVE_TEST -I../../lib/openprinttag -I../../lib/opentag3d
OPT_OBJS = openprinttag_lib.o cbor_native.o
OT3D_OBJS = opentag3d_lib.o

PYTHON ?= python3
FWB_SRCS = test_firmware_build.cpp ../../src/FirmwareBuildInfo.cpp
FWB_DEPS = $(FWB_SRCS) ../../src/FirmwareBuildInfo.h
FWB_VARIANTS = test_firmware_build test_firmware_build_xiao test_firmware_build_c6 \
test_firmware_build_c5 test_firmware_build_c3 \
test_firmware_build_s3devkitc test_firmware_build_s3zero

.PHONY: all clean test test_deduction_manager_compile

all: test_deduction_tracker test_deduction_manager_compile test_raw_write_sidecar test_printer_manager test_opt_ndef_bounds test_diagnostics test_tft_landscape_layout test_tigertag_parser test_bambutag_parser test_write_uid_guard test_cc_sizing test_spool_cache test_opentag3d_runner test_ndef_mime_builder test_raw_write_slot
all: test_deduction_tracker test_deduction_manager_compile test_raw_write_sidecar test_printer_manager test_opt_ndef_bounds test_diagnostics test_tft_landscape_layout test_tigertag_parser test_bambutag_parser test_write_uid_guard test_cc_sizing test_spool_cache test_opentag3d_runner test_ndef_mime_builder test_raw_write_slot $(FWB_VARIANTS)

openprinttag_lib.o: ../../lib/openprinttag/openprinttag_lib.c
$(CC) $(CFLAGS) -c -o $@ $<
Expand Down Expand Up @@ -65,7 +72,28 @@ test_raw_write_slot: test_raw_write_slot.cpp ../../src/RawWriteSlot.h ../../src/
test_ndef_mime_builder: test_ndef_mime_builder.cpp ../../src/NdefMimeBuilder.h
$(CXX) $(CXXFLAGS) -o $@ test_ndef_mime_builder.cpp

test: test_deduction_tracker test_deduction_manager_compile test_raw_write_sidecar test_printer_manager test_opt_ndef_bounds test_diagnostics test_tft_landscape_layout test_tigertag_parser test_bambutag_parser test_write_uid_guard test_cc_sizing test_spool_cache test_opentag3d_runner test_ndef_mime_builder test_raw_write_slot
test_firmware_build: $(FWB_DEPS)
$(CXX) $(CXXFLAGS) -DEXPECT_BOARD=\"esp32dev\" -o $@ $(FWB_SRCS)

test_firmware_build_xiao: $(FWB_DEPS)
$(CXX) $(CXXFLAGS) -DBOARD_ESP32_C6=1 -DBOARD_SEEED_XIAO_ESP32_C6=1 -DEXPECT_BOARD=\"seeed_xiao_esp32c6\" -o $@ $(FWB_SRCS)

test_firmware_build_c6: $(FWB_DEPS)
$(CXX) $(CXXFLAGS) -DBOARD_ESP32_C6=1 -DEXPECT_BOARD=\"esp32c6\" -o $@ $(FWB_SRCS)

test_firmware_build_c5: $(FWB_DEPS)
$(CXX) $(CXXFLAGS) -DBOARD_ESP32_C5=1 -DEXPECT_BOARD=\"esp32c5\" -o $@ $(FWB_SRCS)

test_firmware_build_c3: $(FWB_DEPS)
$(CXX) $(CXXFLAGS) -DBOARD_ESP32_C3=1 -DEXPECT_BOARD=\"esp32c3\" -o $@ $(FWB_SRCS)

test_firmware_build_s3devkitc: $(FWB_DEPS)
$(CXX) $(CXXFLAGS) -DBOARD_ESP32_S3=1 -DBOARD_S3_DEVKITC=1 -DEXPECT_BOARD=\"esp32s3devkitc\" -o $@ $(FWB_SRCS)

test_firmware_build_s3zero: $(FWB_DEPS)
$(CXX) $(CXXFLAGS) -DBOARD_ESP32_S3=1 -DBOARD_S3_ZERO=1 -DEXPECT_BOARD=\"esp32s3zero\" -o $@ $(FWB_SRCS)

test: test_deduction_tracker test_deduction_manager_compile test_raw_write_sidecar test_printer_manager test_opt_ndef_bounds test_diagnostics test_tft_landscape_layout test_tigertag_parser test_bambutag_parser test_write_uid_guard test_cc_sizing test_spool_cache test_opentag3d_runner test_ndef_mime_builder test_raw_write_slot $(FWB_VARIANTS)
@echo ""
@echo "=== Running PrinterManager tests ==="
@./test_printer_manager
Expand Down Expand Up @@ -109,8 +137,20 @@ test: test_deduction_tracker test_deduction_manager_compile test_raw_write_sidec
@echo "=== Running raw write slot tests ==="
@./test_raw_write_slot
@echo ""
@echo "=== Running firmware build info tests ==="
@./test_firmware_build
@./test_firmware_build_xiao
@./test_firmware_build_c6
@./test_firmware_build_c5
@./test_firmware_build_c3
@./test_firmware_build_s3devkitc
@./test_firmware_build_s3zero
@echo ""
@echo "=== Running git commit bake tests ==="
@$(PYTHON) -B test_bake_git_commit.py
@echo ""

clean:
rm -f test_printer_manager test_opt_ndef_bounds test_diagnostics \
test_tft_landscape_layout test_tigertag_parser test_bambutag_parser \
test_deduction_tracker test_raw_write_sidecar test_write_uid_guard test_cc_sizing test_spool_cache test_opentag3d_runner test_ndef_mime_builder test_raw_write_slot *.o
test_deduction_tracker test_raw_write_sidecar test_write_uid_guard test_cc_sizing test_spool_cache test_opentag3d_runner test_ndef_mime_builder test_raw_write_slot $(FWB_VARIANTS) *.o
Loading
Loading