1 Commits
Author SHA1 Message Date
kkallas dd915b5a74 Technician tool v0.7
Imported from the Google Drive folder 004-technician_tool/v0.7.
2026-09-28 19:11:20 +02:00
29 changed files with 8429 additions and 3981 deletions

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
# Technician tool v0.7 - changes
## Serial reading (firmware 1.0.16+, see firmware-diagnostics-what-changed.md)
- `KOTA: <record> key=value` lines are parsed into fields (`core/logline.py`, kind `KOTA`) and interpreted
directly by the engine (`diag/engine.py` `_kota_*`, knowledge in `diag/kota.py`) instead of regex rules:
boot, i2c, rtc, sd, matter, mic, health, status, led, restart.
- Exact status LED (colour + pattern + meaning) from `led` lines; `status` lines give the reason and a
status finding that is resolved when the status changes. Cyan LED supported.
- Restart cause from `last_restart=` / `restart reason=`; state before a restart from `led previous_boot`.
- Error IDs `[E-XX-NN]`: looked up in `diag/error_ids.csv` (copy of the firmware's docs/error_ids.csv);
shown with the technician action. Old message rules still match (ID prefix is stripped for matching).
- Diagnosis panel: new "Box self-report" section; log view filter "KOTA diagnostics + errors".
- Matter QR dialog uses the exact QR/manual code reported by the box.
- Older firmware (v1.0) is still diagnosed as before.
## Flashing
- Only `.bin` files in the tool's `firmware/` folder can be flashed (import / developer library removed,
no manifest needed). The list shows the compile date read from the firmware itself, newest first.
- "Refresh list" and "Open firmware folder" buttons; broken or duplicate files are listed as "Not offered".
- Flash verification compares the 8-digit build hash from the `KOTA: boot` line.
Note: the KOTA lines are tested against lines built from the firmware source; the firmware has not yet
been confirmed on hardware.
+1 -1
View File
@@ -1,3 +1,3 @@
"""KOTA sensorbox technician tool.""" """KOTA sensorbox technician tool."""
__version__ = "0.6.0" __version__ = "0.7.0"
+202 -146
View File
@@ -1,146 +1,202 @@
"""Serial byte stream -> framed, cleaned, parsed log lines. """Serial byte stream -> framed, cleaned, parsed log lines.
ESP-IDF log format: "<L> (<ms since boot>) <TAG>: <message>", optionally ESP-IDF log format: "<L> (<ms since boot>) <TAG>: <message>", optionally
wrapped in ANSI colour codes. ROM/bootloader output (boot banner, reset wrapped in ANSI colour codes. ROM/bootloader output (boot banner, reset
reason) has no level prefix and is classified separately, since a boot reason) has no level prefix and is classified separately, since a boot
banner is the only reliable reboot marker. banner is the only reliable reboot marker.
"""
Firmware 1.0.16+ adds structured diagnostic lines logged under the "KOTA"
from __future__ import annotations tag ("I (812) KOTA: boot fw=1.0.16 build=4f10989e ... last_restart=none")
and prefixes every ESP_LOGE message with a stable error ID ("[E-SD-03] ").
import re Both are parsed here so the diagnostics engine reads fields directly
import time instead of matching message text.
from dataclasses import dataclass, field """
from enum import Enum
from __future__ import annotations
from .redact import redact
import re
ANSI_RE = re.compile(r"\x1b\[[0-9;]*[A-Za-z]") import time
ESP_LOG_RE = re.compile(r"^([EWIDV]) \((\d+)\) ([^:]{1,40}?): ?(.*)$") from dataclasses import dataclass, field
# ESP32-S3 ROM prints e.g. "ESP-ROM:esp32s3-20210327" then from enum import Enum
# "rst:0x1 (POWERON),boot:0x8 (SPI_FAST_FLASH_BOOT)".
BOOT_BANNER_RE = re.compile(r"^ESP-ROM:") from .redact import redact
RESET_REASON_RE = re.compile(r"^rst:0x([0-9a-fA-F]+) \(([A-Z0-9_]+)\)")
PANIC_RE = re.compile( ANSI_RE = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")
r"Guru Meditation Error|abort\(\) was called|ESP_ERROR_CHECK failed|" ESP_LOG_RE = re.compile(r"^([EWIDV]) \((\d+)\) ([^:]{1,40}?): ?(.*)$")
r"^Backtrace:|Rebooting\.\.\.$" # ESP32-S3 ROM prints e.g. "ESP-ROM:esp32s3-20210327" then
) # "rst:0x1 (POWERON),boot:0x8 (SPI_FAST_FLASH_BOOT)".
BOOT_BANNER_RE = re.compile(r"^ESP-ROM:")
RESET_REASON_RE = re.compile(r"^rst:0x([0-9a-fA-F]+) \(([A-Z0-9_]+)\)")
class LineKind(str, Enum): # "[E-SD-03] Failed to initialize the card ..." (firmware error_ids.csv).
LOG = "log" # ESP_LOGx line ERROR_ID_RE = re.compile(r"^\[(E-[A-Z0-9]+-\d{2,})\] ?")
BOOT = "boot" # ROM boot banner (start of a new boot) KOTA_TAG = "KOTA"
RESET = "reset" # ROM reset-reason line PANIC_RE = re.compile(
PANIC = "panic" # crash / abort output r"Guru Meditation Error|abort\(\) was called|ESP_ERROR_CHECK failed|"
RAW = "raw" # anything else (task list rows, line protocol, ...) r"^Backtrace:|Rebooting\.\.\.$"
HOST = "host" # event generated by this tool (connect, reset, ...) )
def host_event(text: str) -> LogLine: class LineKind(str, Enum):
return LogLine(f"--- {text} ---", LineKind.HOST) LOG = "log" # ESP_LOGx line
BOOT = "boot" # ROM boot banner (start of a new boot)
RESET = "reset" # ROM reset-reason line
@dataclass(frozen=True) PANIC = "panic" # crash / abort output
class LogLine: KOTA = "kota" # structured "KOTA: <record> key=value ..." line
text: str # cleaned + redacted RAW = "raw" # anything else (task list rows, line protocol, ...)
kind: LineKind HOST = "host" # event generated by this tool (connect, reset, ...)
host_time: float = field(default_factory=time.time)
level: str | None = None # E/W/I/D/V for LOG lines
uptime_ms: int | None = None def host_event(text: str) -> LogLine:
tag: str | None = None return LogLine(f"--- {text} ---", LineKind.HOST)
message: str | None = None
reset_reason: str | None = None
@dataclass(frozen=True)
class LogLine:
def clean(raw: str) -> str: text: str # cleaned + redacted
return ANSI_RE.sub("", raw).replace("\r", "").rstrip() kind: LineKind
host_time: float = field(default_factory=time.time)
level: str | None = None # E/W/I/D/V for LOG lines
def parse_line(raw: str, host_time: float | None = None) -> LogLine: uptime_ms: int | None = None
text = redact(clean(raw)) tag: str | None = None
t = time.time() if host_time is None else host_time message: str | None = None
if m := ESP_LOG_RE.match(text): reset_reason: str | None = None
level, ms, tag, msg = m.groups() error_id: str | None = None # "E-SD-03" when the message carries one
return LogLine(text, LineKind.LOG, t, level, int(ms), tag.strip(), msg) record: str | None = None # KOTA lines: "boot", "i2c", "health", ...
if BOOT_BANNER_RE.match(text): fields: dict[str, str] = field(default_factory=dict) # KOTA key=value pairs
return LogLine(text, LineKind.BOOT, t) words: tuple[str, ...] = () # KOTA bare words ("verify", "OK", "->", ...)
if m := RESET_REASON_RE.match(text):
return LogLine(text, LineKind.RESET, t, reset_reason=m.group(2)) @property
if PANIC_RE.search(text): def match_text(self) -> str:
return LogLine(text, LineKind.PANIC, t) """Text for message rules: the error-ID prefix removed, so rules
return LogLine(text, LineKind.RAW, t) written for older firmware keep matching."""
if self.error_id and self.message is not None and self.tag:
return self.text.replace(f"[{self.error_id}] ", "", 1)
class LineFramer: return self.text
"""Accumulates bytes and yields complete lines.
A partial line is released after `idle_flush_s` without new bytes so def parse_kota(body: str) -> tuple[str, dict[str, str], tuple[str, ...]]:
prompts / unterminated output are not held back forever. """'rtc verify running=1 delta=2s ok=1' -> ('rtc', {...}, ('verify',)).
Lines are also split where a new log line starts in the middle Values never contain spaces. The mic line has a parenthesised aside
("I (2302) chip[DL]: I (2302) chip[DL]: Posting..."): the two S3 cores ("(GPIO3=1, expected 1)"): brackets and commas are stripped from keys
interleave output, and the USB-Serial-JTAG FIFO keeps the tail of an old and values, and the aside's words are kept as bare words.
line while no host reads, releasing it glued in front of the next live """
output. After a (re)open, the fragment in front of the first such split tokens = body.split()
is stale and dropped. Timing cannot identify it, because the FIFO only if not tokens:
flushes when the board next prints, possibly seconds later. return "", {}, ()
""" fields: dict[str, str] = {}
words: list[str] = []
def __init__(self, idle_flush_s: float = 0.3, max_line: int = 4096, for tok in tokens[1:]:
drop_first_partial: bool = False): key, eq, value = tok.partition("=")
self._buf = bytearray() if eq and key.strip("(,"):
self._last_rx = 0.0 key = key.lstrip("(")
self.idle_flush_s = idle_flush_s # "0x68=DS1307(missing)" keeps its bracket; "(GPIO3=1," loses it.
self.max_line = max_line value = value.rstrip(",")
self._first_line_pending = drop_first_partial if tok.startswith("(") or value.endswith(")") and "(" not in value:
value = value.rstrip(")")
def cancel_drop(self) -> None: fields[key] = value
self._first_line_pending = False else:
words.append(tok.strip("(),"))
def feed(self, data: bytes, now: float | None = None) -> list[str]: return tokens[0], fields, tuple(w for w in words if w)
now = time.monotonic() if now is None else now
if data:
self._buf.extend(data) def clean(raw: str) -> str:
self._last_rx = now return ANSI_RE.sub("", raw).replace("\r", "").rstrip()
out: list[str] = []
while (i := self._buf.find(b"\n")) >= 0:
out += self._emit(self._buf[:i]) def parse_line(raw: str, host_time: float | None = None) -> LogLine:
del self._buf[: i + 1] text = redact(clean(raw))
if len(self._buf) >= self.max_line: t = time.time() if host_time is None else host_time
out += self._emit(self._buf) if m := ESP_LOG_RE.match(text):
self._buf.clear() level, ms, tag, msg = m.groups()
return out tag = tag.strip()
if tag == KOTA_TAG:
def poll_idle(self, now: float | None = None) -> list[str]: record, fields, words = parse_kota(msg)
now = time.monotonic() if now is None else now return LogLine(text, LineKind.KOTA, t, level, int(ms), tag, msg,
if self._buf and now - self._last_rx >= self.idle_flush_s: record=record, fields=fields, words=words)
return self.flush() eid = None
return [] if em := ERROR_ID_RE.match(msg):
eid, msg = em.group(1), msg[em.end():]
def flush(self) -> list[str]: return LogLine(text, LineKind.LOG, t, level, int(ms), tag, msg, error_id=eid)
if not self._buf: if BOOT_BANNER_RE.match(text):
return [] return LogLine(text, LineKind.BOOT, t)
out = self._emit(self._buf) if m := RESET_REASON_RE.match(text):
self._buf.clear() return LogLine(text, LineKind.RESET, t, reset_reason=m.group(2))
return out if PANIC_RE.search(text):
return LogLine(text, LineKind.PANIC, t)
def _emit(self, raw: bytes | bytearray) -> list[str]: return LogLine(text, LineKind.RAW, t)
parts = split_glued(bytes(raw).decode("utf-8", errors="replace"))
if self._first_line_pending:
self._first_line_pending = False class LineFramer:
if len(parts) > 1: """Accumulates bytes and yields complete lines.
parts = parts[1:] # stale FIFO fragment from before the open
return parts A partial line is released after `idle_flush_s` without new bytes so
prompts / unterminated output are not held back forever.
# Start of a log line (optionally ANSI-coloured) or ROM banner. Lines are also split where a new log line starts in the middle
_LINE_START = re.compile(r"(?:\x1b\[[0-9;]*m)?(?:[EWIDV] \(\d+\) \S|ESP-ROM:)") ("I (2302) chip[DL]: I (2302) chip[DL]: Posting..."): the two S3 cores
interleave output, and the USB-Serial-JTAG FIFO keeps the tail of an old
line while no host reads, releasing it glued in front of the next live
def split_glued(text: str) -> list[str]: output. After a (re)open, the fragment in front of the first such split
# Left-to-right scan so an ANSI colour prefix stays with its line. is stale and dropped. Timing cannot identify it, because the FIFO only
cuts = [m.start() for m in _LINE_START.finditer(text) if m.start() > 0] flushes when the board next prints, possibly seconds later.
if not cuts: """
return [text]
bounds = [0, *cuts, len(text)] def __init__(self, idle_flush_s: float = 0.3, max_line: int = 4096,
return [text[a:b] for a, b in zip(bounds, bounds[1:]) if a < b] drop_first_partial: bool = False):
self._buf = bytearray()
self._last_rx = 0.0
self.idle_flush_s = idle_flush_s
self.max_line = max_line
self._first_line_pending = drop_first_partial
def cancel_drop(self) -> None:
self._first_line_pending = False
def feed(self, data: bytes, now: float | None = None) -> list[str]:
now = time.monotonic() if now is None else now
if data:
self._buf.extend(data)
self._last_rx = now
out: list[str] = []
while (i := self._buf.find(b"\n")) >= 0:
out += self._emit(self._buf[:i])
del self._buf[: i + 1]
if len(self._buf) >= self.max_line:
out += self._emit(self._buf)
self._buf.clear()
return out
def poll_idle(self, now: float | None = None) -> list[str]:
now = time.monotonic() if now is None else now
if self._buf and now - self._last_rx >= self.idle_flush_s:
return self.flush()
return []
def flush(self) -> list[str]:
if not self._buf:
return []
out = self._emit(self._buf)
self._buf.clear()
return out
def _emit(self, raw: bytes | bytearray) -> list[str]:
parts = split_glued(bytes(raw).decode("utf-8", errors="replace"))
if self._first_line_pending:
self._first_line_pending = False
if len(parts) > 1:
parts = parts[1:] # stale FIFO fragment from before the open
return parts
# Start of a log line (optionally ANSI-coloured) or ROM banner.
_LINE_START = re.compile(r"(?:\x1b\[[0-9;]*m)?(?:[EWIDV] \(\d+\) \S|ESP-ROM:)")
def split_glued(text: str) -> list[str]:
# Left-to-right scan so an ANSI colour prefix stays with its line.
cuts = [m.start() for m in _LINE_START.finditer(text) if m.start() > 0]
if not cuts:
return [text]
bounds = [0, *cuts, len(text)]
return [text[a:b] for a, b in zip(bounds, bounds[1:]) if a < b]
+999 -583
View File
File diff suppressed because it is too large. Load diff
+193
View File
@@ -0,0 +1,193 @@
id,module,severity,message,action
E-SD-01,SD,error,Failed to take SPI mutex,Internal error - send the log to the firmware team
E-SD-02,SD,error,"Failed to mount filesystem. If you want the card to be formatted, set the CONFIG_EXAMPLE_FORMAT_IF_MOUNT_FAILED menuconfig option.",SD card is not FAT formatted or is corrupt; reformat it as FAT32 and restore ENV.TXT
E-SD-03,SD,error,Failed to initialize the card (%s). Make sure SD card lines have pull-up resistors in place.,Reseat the SD card; if it persists replace the card or check the SD connector
E-SD-04,SD,error,Failed to stat %s,Reseat the SD card; if it persists replace the card or check the SD connector
E-SD-05,SD,error,Failed to take SPI mutex,Internal error - send the log to the firmware team
E-ENV-01,ENV,error,Failed to take SPI mutex,Internal error - send the log to the firmware team
E-ENV-02,ENV,error,Failed to open .env file for reading,Check ENV.TXT on the SD card exists and has NAME=VALUE lines
E-ENV-03,ENV,error,Failed to take SPI mutex,Internal error - send the log to the firmware team
E-ENV-04,ENV,error,Failed to open existing .env file for reading; aborting write to avoid losing other variables,Check ENV.TXT on the SD card exists and has NAME=VALUE lines
E-ENV-05,ENV,error,Failed to open .env file for writing,Check ENV.TXT on the SD card exists and has NAME=VALUE lines
E-ENV-06,ENV,error,Failed to take SPI mutex,Internal error - send the log to the firmware team
E-ENV-07,ENV,error,Failed to open existing .env file for reading; aborting delete to avoid losing other variables,Check ENV.TXT on the SD card exists and has NAME=VALUE lines
E-ENV-08,ENV,error,Failed to open .env file for writing,Check ENV.TXT on the SD card exists and has NAME=VALUE lines
E-ENV-09,ENV,error,Failed to take SPI mutex,Internal error - send the log to the firmware team
E-INF-01,INF,error,Error %d at %s:%d,Internal error - send the log to the firmware team
E-INF-02,INF,error,Failed to initialize HTTP client,Internal error - send the log to the firmware team
E-INF-03,INF,error,"Failed to perform HTTP request: %d, %s",Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
E-INF-04,INF,error,"Bad request, check line protocol format: %s",Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
E-INF-05,INF,error,Failed to read INFLUX_URL from .env file,Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
E-INF-06,INF,error,Failed to read INFLUX_TOKEN from .env file,Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
E-INF-07,INF,error,Failed to take SPI mutex,Internal error - send the log to the firmware team
E-INF-08,INF,error,Failed to open buffer file for reading,Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
E-INF-09,INF,error,Failed to take SPI mutex,Internal error - send the log to the firmware team
E-INF-10,INF,error,Failed to open buffer file for clearing,Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
E-INF-11,INF,error,Failed to take SPI mutex,Internal error - send the log to the firmware team
E-INF-12,INF,error,Failed to create buffer file,Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
E-INF-13,INF,error,Failed to open buffer file for appending,Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
E-INF-14,INF,error,Failed to take SPI mutex,Internal error - send the log to the firmware team
E-INF-15,INF,error,Failed to open buffer file for counting,Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
E-INF-16,INF,error,Failed to read buffer for flushing: %s,Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
E-INF-17,INF,error,Failed to write chunk to Influx: %s,Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
E-INF-18,INF,error,Failed to write chunk with 5 retries to Influx: %s,Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
E-INF-19,INF,error,Failed to clear buffer after flushing: %s,Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
E-INF-20,INF,error,Failed to flush buffer before writing: %s,Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
E-INF-21,INF,error,Failed to write to Influx: %s,Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
E-INF-22,INF,error,Failed to append new entry to buffer: %s,Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
E-OTA-01,OTA,error,Error %s at %s:%d,Internal error - send the log to the firmware team
E-OTA-02,OTA,error,Failed to create OTA task,Internal error - send the log to the firmware team
E-OTA-03,OTA,error,Failed to open NVS: %s,Internal error - send the log to the firmware team
E-OTA-04,OTA,error,Failed to read OTA token from NVS: %s,Internal error - send the log to the firmware team
E-OTA-05,OTA,error,Failed to read OTA token from NVS: %s,Internal error - send the log to the firmware team
E-OTA-06,OTA,error,Failed to get running partition,Check the network connection; if it persists send the log to the firmware team
E-OTA-07,OTA,error,Failed to get OTA state,Check the network connection; if it persists send the log to the firmware team
E-OTA-08,OTA,error,Failed to read update metadata from NVS: %s,Internal error - send the log to the firmware team
E-OTA-09,OTA,error,Failed to report failed selfcheck: %s,Check the network connection; if it persists send the log to the firmware team
E-OTA-10,OTA,error,Failed to initialize HTTP client,Internal error - send the log to the firmware team
E-OTA-11,OTA,error,Device registration failed with status code: %d,Check the network connection; if it persists send the log to the firmware team
E-OTA-12,OTA,error,Device registration failed: %s,Check the network connection; if it persists send the log to the firmware team
E-OTA-13,OTA,error,Failed to check for updates: %s,Check the network connection; if it persists send the log to the firmware team
E-OTA-14,OTA,error,Free stack size decreased from %u to %u,Internal error - send the log to the firmware team
E-OTA-15,OTA,error,Failed to initialize HTTP client,Internal error - send the log to the firmware team
E-OTA-16,OTA,error,OTA Update check failed with status code: %d,Check the network connection; if it persists send the log to the firmware team
E-OTA-17,OTA,error,"Update %s has already been tried %u times and failed, not trying again",Internal error - send the log to the firmware team
E-OTA-18,OTA,error,OTA update failed: %s,Check the network connection; if it persists send the log to the firmware team
E-OTA-19,OTA,error,Failed to read update metadata from NVS: %s,Internal error - send the log to the firmware team
E-OTA-20,OTA,error,Failed to read update ID from NVS: %s,Internal error - send the log to the firmware team
E-OTA-21,OTA,error,Failed to read update ID from NVS: %s,Internal error - send the log to the firmware team
E-OTA-22,OTA,error,Failed to read update tries from NVS: %s,Internal error - send the log to the firmware team
E-OTA-23,OTA,error,Failing selfcheck: %s,Firmware update failed its self check and will roll back; check the sensors listed in the log
E-OTA-24,OTA,error,Failed to send update result: %s,Check the network connection; if it persists send the log to the firmware team
E-OTA-25,OTA,error,Failed to mark app as invalid for rollback: %s,Internal error - send the log to the firmware team
E-OTA-26,OTA,error,Failed to send update result: %s,Check the network connection; if it persists send the log to the firmware team
E-OTA-27,OTA,error,Failed to mark app as valid to commit update: %s,Internal error - send the log to the firmware team
E-OTA-28,OTA,error,Failed to initialize HTTP client,Internal error - send the log to the firmware team
E-OTA-29,OTA,error,Failed to send update result with status code: %d,Check the network connection; if it persists send the log to the firmware team
E-WIFI-01,WIFI,error,esp_netif_init() failed: %s,Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
E-WIFI-02,WIFI,error,esp_event_loop_create_default() failed: %s,Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
E-WIFI-03,WIFI,error,esp_wifi_init() failed: %s,Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
E-WIFI-04,WIFI,error,Failed to register WIFI_EVENT handler: %s,Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
E-WIFI-05,WIFI,error,Failed to register IP_EVENT handler: %s,Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
E-WIFI-06,WIFI,error,esp_wifi_set_mode() failed: %s,Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
E-WIFI-07,WIFI,error,esp_timer_create() failed: %s,Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
E-WIFI-08,WIFI,error,esp_wifi_start() failed: %s,Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
E-WIFI-09,WIFI,error,esp_wifi_set_config() failed: %s,Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
E-WIFI-10,WIFI,error,esp_wifi_connect() failed: %s,Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
E-WIFI-11,WIFI,error,esp_wifi_set_mode(APSTA) failed: %s,Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
E-WIFI-12,WIFI,error,esp_wifi_set_config(AP) failed: %s,Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
E-WIFI-13,WIFI,error,esp_wifi_connect() failed: %s,Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
E-WIFI-14,WIFI,error,esp_wifi_scan_start() failed: %s,Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
E-WIFI-15,WIFI,error,esp_wifi_scan_get_ap_num() failed: %s,Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
E-WIFI-16,WIFI,error,esp_wifi_scan_get_ap_records() failed: %s,Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
E-PROV-01,PROV,error,mdns_init() failed: %s,Retry WiFi provisioning (short button press); restart the device if it persists
E-PROV-02,PROV,error,httpd_start() failed: %s,Retry WiFi provisioning (short button press); restart the device if it persists
E-MAIN-01,MAIN,error,Error %d at %s:%d,Internal error - send the log to the firmware team
E-MAIN-02,MAIN,error,"Failed to open commissioning window, err:%",Internal error - send the log to the firmware team
E-MAIN-03,MAIN,error,"Attribute update callback: endpoint_id: %u, cluster_id: 0x%lx, attribute_id: 0x%lx",Internal error - send the log to the firmware team
E-MAIN-04,MAIN,error,Device MAC address: %02X:%02X:%02X:%02X:%02X:%02X,Internal error - send the log to the firmware team
E-MAIN-05,MAIN,error,Failed to initialize SD card: %s,Reseat the SD card; if it persists replace the card or check the SD connector
E-MAIN-06,MAIN,error,Failed to initialize EnvironmentService: %s,Check ENV.TXT on the SD card exists and has NAME=VALUE lines
E-MAIN-07,MAIN,error,Failed to initialize WifiCredentialsService: %s,Check ENV.TXT on the SD card exists and has NAME=VALUE lines
E-MAIN-08,MAIN,error,WiFi provisioning server failed to start: %s; clearing HTTP_SERVER and restarting,Retry WiFi provisioning (short button press); restart the device if it persists
E-MAIN-09,MAIN,error,Failed to create Matter node,Internal error - send the log to the firmware team
E-MAIN-10,MAIN,error,Failed to start ESP-Matter,Internal error - send the log to the firmware team
E-MAIN-11,MAIN,error,Failed to start WifiService: %s,Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
E-MAIN-12,MAIN,error,"Failed to initialized the encrypted OTA, err: %d",Internal error - send the log to the firmware team
E-MAIN-13,MAIN,error,Failed to initialize RTC: %s,Check the RTC (DS1307) and the sensor cable
E-MAIN-14,MAIN,error,Failed to initialize Influx buffer: %s,Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
E-MAIN-15,MAIN,error,Failed to initialize BME688: %s,Check the BME688 sensor and the sensor cable
E-MAIN-16,MAIN,error,Failed to initialize SEN66: %s,"Check the SEN66 sensor, its power supply and the sensor cable"
E-MAIN-17,MAIN,error,Failed to initialize AS7341: %s,Check the AS7341 light sensor and the sensor cable
E-MAIN-18,MAIN,error,Failed to initialize Microphone: %s,Check the microphone board and its cable
E-MAIN-19,MAIN,error,Failed to initialize Flicker sensor: %s,Check the flicker sensor and its cable
E-MAIN-20,MAIN,error,Failed to initialize DeviceStatus: %s,Internal error - send the log to the firmware team
E-MAIN-21,MAIN,error,BME688 self check failed: %s,Check the BME688 sensor and the sensor cable
E-MAIN-22,MAIN,error,SEN66 self check failed: %s,"Check the SEN66 sensor, its power supply and the sensor cable"
E-MAIN-23,MAIN,error,AS7341 self check failed: %s,Check the AS7341 light sensor and the sensor cable
E-MAIN-24,MAIN,error,Microphone self check failed: %s,Check the microphone board and its cable
E-MAIN-25,MAIN,error,Flicker sensor self check failed: %s,Check the flicker sensor and its cable
E-MAIN-26,MAIN,error,Failed to report passed selfcheck: %s,Internal error - send the log to the firmware team
E-MAIN-27,MAIN,error,Failed to flush Influx buffer: %s,Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
E-STAT-01,STAT,error,Failed to initialize LED strip: %s,Internal error - send the log to the firmware team
E-SPI-01,SPI,error,Failed to take SPI mutex,Internal error - send the log to the firmware team
E-RTC-01,RTC,error,Failed to take I2C mutex,Internal error - send the log to the firmware team
E-RTC-02,RTC,error,Failed to add I2C device: %s,Check the RTC (DS1307) and the sensor cable
E-RTC-03,RTC,error,Failed to initialize DS1307 control register: %s,Check the RTC (DS1307) and the sensor cable
E-RTC-04,RTC,error,Attempted to set time on uninitialized DS1307,Internal error - send the log to the firmware team
E-RTC-05,RTC,error,Failed to take I2C mutex,Internal error - send the log to the firmware team
E-RTC-06,RTC,error,Attempted to get time on uninitialized DS1307,Internal error - send the log to the firmware team
E-RTC-07,RTC,error,Failed to take I2C mutex,Internal error - send the log to the firmware team
E-RTC-08,RTC,error,Attempted to start updating time on uninitialized DS1307,Internal error - send the log to the firmware team
E-BME-01,BME,error,Failed to take I2C mutex,Internal error - send the log to the firmware team
E-BME-02,BME,error,Failed to add I2C device: %d,Check the BME688 sensor and the sensor cable
E-BME-03,BME,error,Failed to initialize BME688: %d,Check the BME688 sensor and the sensor cable
E-BME-04,BME,error,Failed to set BME688 configuration: %d,Check the BME688 sensor and the sensor cable
E-BME-05,BME,error,Failed to set BME688 heater configuration: %d,Check the BME688 sensor and the sensor cable
E-BME-06,BME,error,Failed to set BME688 operation mode: %d,Check the BME688 sensor and the sensor cable
E-BME-07,BME,error,Failed to get BME688 data: %d,Check the BME688 sensor and the sensor cable
E-BME-08,BME,error,No new data available from BME688,Check the BME688 sensor and the sensor cable
E-BME-09,BME,error,Failed to get data from BME688: %s,Check the BME688 sensor and the sensor cable
E-BME-10,BME,error,Self check failed: %s,Check the BME688 sensor and the sensor cable
E-BME-11,BME,error,Failed to take I2C mutex,Internal error - send the log to the firmware team
E-BME-12,BME,error,I2C read failed: %s,Check the BME688 sensor and the sensor cable
E-BME-13,BME,error,Failed to take I2C mutex,Internal error - send the log to the firmware team
E-BME-14,BME,error,Failed to allocate memory for I2C write buffer,Internal error - send the log to the firmware team
E-BME-15,BME,error,I2C write failed: %s,Check the BME688 sensor and the sensor cable
E-SEN-01,SEN,error,Failed to take I2C mutex,Internal error - send the log to the firmware team
E-SEN-02,SEN,error,Failed to add I2C device: %d,"Check the SEN66 sensor, its power supply and the sensor cable"
E-SEN-03,SEN,error,Attempted to wake up uninitialized SEN66,Internal error - send the log to the firmware team
E-SEN-04,SEN,error,Failed to take sensor mutex,Internal error - send the log to the firmware team
E-SEN-05,SEN,error,Failed to send start measurement command: %d,"Check the SEN66 sensor, its power supply and the sensor cable"
E-SEN-06,SEN,error,Attempted to sleep uninitialized SEN66,Internal error - send the log to the firmware team
E-SEN-07,SEN,error,Failed to take sensor mutex,Internal error - send the log to the firmware team
E-SEN-08,SEN,error,Failed to send stop measurement command: %d,"Check the SEN66 sensor, its power supply and the sensor cable"
E-SEN-09,SEN,error,Failed to take I2C mutex,Internal error - send the log to the firmware team
E-SEN-10,SEN,error,Failed to take I2C mutex,Internal error - send the log to the firmware team
E-SEN-11,SEN,error,Failed to read ready status: %d,"Check the SEN66 sensor, its power supply and the sensor cable"
E-SEN-12,SEN,error,"Sensor not ready after %d attempts, trying to wake it up","Check the SEN66 sensor, its power supply and the sensor cable"
E-SEN-13,SEN,error,Failed to read measurement: %d,"Check the SEN66 sensor, its power supply and the sensor cable"
E-SEN-14,SEN,error,Failed while awaiting sensor ready: %d,"Check the SEN66 sensor, its power supply and the sensor cable"
E-SEN-15,SEN,error,Failed to read measurement for line protocol: %d,"Check the SEN66 sensor, its power supply and the sensor cable"
E-SEN-16,SEN,error,Self-check failed: Sensor not ready: %d,"Check the SEN66 sensor, its power supply and the sensor cable"
E-SEN-17,SEN,error,Self-check failed: Failed to read measurement: %d,"Check the SEN66 sensor, its power supply and the sensor cable"
E-AS-01,AS,error,Failed to take I2C mutex,Internal error - send the log to the firmware team
E-AS-02,AS,error,Failed to initialize AS7341: %s,Check the AS7341 light sensor and the sensor cable
E-AS-03,AS,error,Attempted to wake up uninitialized AS7341,Internal error - send the log to the firmware team
E-AS-04,AS,error,Failed to take I2C mutex,Internal error - send the log to the firmware team
E-AS-05,AS,error,Failed to wake up AS7341: %s,Check the AS7341 light sensor and the sensor cable
E-AS-06,AS,error,Attempted to put uninitialized AS7341 to sleep,Internal error - send the log to the firmware team
E-AS-07,AS,error,Failed to take I2C mutex,Internal error - send the log to the firmware team
E-AS-08,AS,error,Failed to put AS7341 to sleep: %s,Check the AS7341 light sensor and the sensor cable
E-AS-09,AS,error,Attempted to get line protocol on uninitialized AS7341,Internal error - send the log to the firmware team
E-AS-10,AS,error,Failed to take I2C mutex,Internal error - send the log to the firmware team
E-AS-11,AS,error,Failed to read spectral data: %s,Check the AS7341 light sensor and the sensor cable
E-AS-12,AS,error,Failed to read basic counts data: %s,Check the AS7341 light sensor and the sensor cable
E-AS-13,AS,error,Failed to read flicker detection state: %s,Check the AS7341 light sensor and the sensor cable
E-AS-14,AS,error,Self-check failed: Failed to read spectral data: %s,Check the AS7341 light sensor and the sensor cable
E-MIC-01,MIC,error,Failed to create I2S channel: %s,Check the microphone board and its cable
E-MIC-02,MIC,error,Failed to initialize I2S channel in standard mode: %s,Check the microphone board and its cable
E-MIC-03,MIC,error,Failed to configure shutdown pin: %s,Check the microphone board and its cable
E-MIC-04,MIC,error,Failed to read samples from I2S channel: %s,Check the microphone board and its cable
E-MIC-05,MIC,error,Failed to read samples for line protocol: %s,Check the microphone board and its cable
E-FLK-01,FLK,error,Error %s at %s:%d,Internal error - send the log to the firmware team
E-FLK-02,FLK,error,Attempting to initialize sensor that is already initialized,Check the flicker sensor and its cable
E-FLK-03,FLK,error,Failed to allocate memory for FFT buffers,Internal error - send the log to the firmware team
E-FLK-04,FLK,error,Failed to initialize FFT: %s,Check the flicker sensor and its cable
E-FLK-05,FLK,error,Attempting to read from uninitialized sensor,Internal error - send the log to the firmware team
E-FLK-06,FLK,error,Failed to take I2C mutex,Internal error - send the log to the firmware team
E-FLK-07,FLK,error,Failed to get dominant frequency: %s,Check the flicker sensor and its cable
E-FLK-08,FLK,error,Attempting to read from uninitialized sensor,Internal error - send the log to the firmware team
E-FLK-09,FLK,error,Failed to read ADC value: %s,Check the flicker sensor and its cable
E-FLK-10,FLK,error,Failed to create gather task: %s,Internal error - send the log to the firmware team
E-FLK-11,FLK,error,Attempting to self check uninitialized sensor,Internal error - send the log to the firmware team
E-FLK-12,FLK,error,Self check failed to get dominant frequency: %s,Check the flicker sensor and its cable
E-DEV-01,DEV,error,Failed to initialize ADC unit: %s,Internal error - send the log to the firmware team
E-DEV-02,DEV,error,Failed to configure ADC channel: %s,Internal error - send the log to the firmware team
E-DEV-03,DEV,error,Failed to install temperature sensor: %s,Internal error - send the log to the firmware team
E-DEV-04,DEV,error,Failed to read ADC value: %s,Internal error - send the log to the firmware team
E-DEV-05,DEV,error,Failed to allocate memory for task list buffer,Internal error - send the log to the firmware team
E-GATH-01,GATH,error,Failed to take line protocol mutex,Internal error - send the log to the firmware team
E-GATH-02,GATH,error,Failed to get line protocol from sensor,Device ran out of memory; restart it and send the log to the firmware team
E-GATH-03,GATH,error,Failed to create task for sensor,Internal error - send the log to the firmware team
E-GATH-04,GATH,error,Failed to create main gather task,Internal error - send the log to the firmware team
1 id module severity message action
2 E-SD-01 SD error Failed to take SPI mutex Internal error - send the log to the firmware team
3 E-SD-02 SD error Failed to mount filesystem. If you want the card to be formatted, set the CONFIG_EXAMPLE_FORMAT_IF_MOUNT_FAILED menuconfig option. SD card is not FAT formatted or is corrupt; reformat it as FAT32 and restore ENV.TXT
4 E-SD-03 SD error Failed to initialize the card (%s). Make sure SD card lines have pull-up resistors in place. Reseat the SD card; if it persists replace the card or check the SD connector
5 E-SD-04 SD error Failed to stat %s Reseat the SD card; if it persists replace the card or check the SD connector
6 E-SD-05 SD error Failed to take SPI mutex Internal error - send the log to the firmware team
7 E-ENV-01 ENV error Failed to take SPI mutex Internal error - send the log to the firmware team
8 E-ENV-02 ENV error Failed to open .env file for reading Check ENV.TXT on the SD card exists and has NAME=VALUE lines
9 E-ENV-03 ENV error Failed to take SPI mutex Internal error - send the log to the firmware team
10 E-ENV-04 ENV error Failed to open existing .env file for reading; aborting write to avoid losing other variables Check ENV.TXT on the SD card exists and has NAME=VALUE lines
11 E-ENV-05 ENV error Failed to open .env file for writing Check ENV.TXT on the SD card exists and has NAME=VALUE lines
12 E-ENV-06 ENV error Failed to take SPI mutex Internal error - send the log to the firmware team
13 E-ENV-07 ENV error Failed to open existing .env file for reading; aborting delete to avoid losing other variables Check ENV.TXT on the SD card exists and has NAME=VALUE lines
14 E-ENV-08 ENV error Failed to open .env file for writing Check ENV.TXT on the SD card exists and has NAME=VALUE lines
15 E-ENV-09 ENV error Failed to take SPI mutex Internal error - send the log to the firmware team
16 E-INF-01 INF error Error %d at %s:%d Internal error - send the log to the firmware team
17 E-INF-02 INF error Failed to initialize HTTP client Internal error - send the log to the firmware team
18 E-INF-03 INF error Failed to perform HTTP request: %d, %s Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
19 E-INF-04 INF error Bad request, check line protocol format: %s Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
20 E-INF-05 INF error Failed to read INFLUX_URL from .env file Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
21 E-INF-06 INF error Failed to read INFLUX_TOKEN from .env file Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
22 E-INF-07 INF error Failed to take SPI mutex Internal error - send the log to the firmware team
23 E-INF-08 INF error Failed to open buffer file for reading Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
24 E-INF-09 INF error Failed to take SPI mutex Internal error - send the log to the firmware team
25 E-INF-10 INF error Failed to open buffer file for clearing Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
26 E-INF-11 INF error Failed to take SPI mutex Internal error - send the log to the firmware team
27 E-INF-12 INF error Failed to create buffer file Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
28 E-INF-13 INF error Failed to open buffer file for appending Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
29 E-INF-14 INF error Failed to take SPI mutex Internal error - send the log to the firmware team
30 E-INF-15 INF error Failed to open buffer file for counting Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
31 E-INF-16 INF error Failed to read buffer for flushing: %s Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
32 E-INF-17 INF error Failed to write chunk to Influx: %s Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
33 E-INF-18 INF error Failed to write chunk with 5 retries to Influx: %s Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
34 E-INF-19 INF error Failed to clear buffer after flushing: %s Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
35 E-INF-20 INF error Failed to flush buffer before writing: %s Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
36 E-INF-21 INF error Failed to write to Influx: %s Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
37 E-INF-22 INF error Failed to append new entry to buffer: %s Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
38 E-OTA-01 OTA error Error %s at %s:%d Internal error - send the log to the firmware team
39 E-OTA-02 OTA error Failed to create OTA task Internal error - send the log to the firmware team
40 E-OTA-03 OTA error Failed to open NVS: %s Internal error - send the log to the firmware team
41 E-OTA-04 OTA error Failed to read OTA token from NVS: %s Internal error - send the log to the firmware team
42 E-OTA-05 OTA error Failed to read OTA token from NVS: %s Internal error - send the log to the firmware team
43 E-OTA-06 OTA error Failed to get running partition Check the network connection; if it persists send the log to the firmware team
44 E-OTA-07 OTA error Failed to get OTA state Check the network connection; if it persists send the log to the firmware team
45 E-OTA-08 OTA error Failed to read update metadata from NVS: %s Internal error - send the log to the firmware team
46 E-OTA-09 OTA error Failed to report failed selfcheck: %s Check the network connection; if it persists send the log to the firmware team
47 E-OTA-10 OTA error Failed to initialize HTTP client Internal error - send the log to the firmware team
48 E-OTA-11 OTA error Device registration failed with status code: %d Check the network connection; if it persists send the log to the firmware team
49 E-OTA-12 OTA error Device registration failed: %s Check the network connection; if it persists send the log to the firmware team
50 E-OTA-13 OTA error Failed to check for updates: %s Check the network connection; if it persists send the log to the firmware team
51 E-OTA-14 OTA error Free stack size decreased from %u to %u Internal error - send the log to the firmware team
52 E-OTA-15 OTA error Failed to initialize HTTP client Internal error - send the log to the firmware team
53 E-OTA-16 OTA error OTA Update check failed with status code: %d Check the network connection; if it persists send the log to the firmware team
54 E-OTA-17 OTA error Update %s has already been tried %u times and failed, not trying again Internal error - send the log to the firmware team
55 E-OTA-18 OTA error OTA update failed: %s Check the network connection; if it persists send the log to the firmware team
56 E-OTA-19 OTA error Failed to read update metadata from NVS: %s Internal error - send the log to the firmware team
57 E-OTA-20 OTA error Failed to read update ID from NVS: %s Internal error - send the log to the firmware team
58 E-OTA-21 OTA error Failed to read update ID from NVS: %s Internal error - send the log to the firmware team
59 E-OTA-22 OTA error Failed to read update tries from NVS: %s Internal error - send the log to the firmware team
60 E-OTA-23 OTA error Failing selfcheck: %s Firmware update failed its self check and will roll back; check the sensors listed in the log
61 E-OTA-24 OTA error Failed to send update result: %s Check the network connection; if it persists send the log to the firmware team
62 E-OTA-25 OTA error Failed to mark app as invalid for rollback: %s Internal error - send the log to the firmware team
63 E-OTA-26 OTA error Failed to send update result: %s Check the network connection; if it persists send the log to the firmware team
64 E-OTA-27 OTA error Failed to mark app as valid to commit update: %s Internal error - send the log to the firmware team
65 E-OTA-28 OTA error Failed to initialize HTTP client Internal error - send the log to the firmware team
66 E-OTA-29 OTA error Failed to send update result with status code: %d Check the network connection; if it persists send the log to the firmware team
67 E-WIFI-01 WIFI error esp_netif_init() failed: %s Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
68 E-WIFI-02 WIFI error esp_event_loop_create_default() failed: %s Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
69 E-WIFI-03 WIFI error esp_wifi_init() failed: %s Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
70 E-WIFI-04 WIFI error Failed to register WIFI_EVENT handler: %s Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
71 E-WIFI-05 WIFI error Failed to register IP_EVENT handler: %s Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
72 E-WIFI-06 WIFI error esp_wifi_set_mode() failed: %s Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
73 E-WIFI-07 WIFI error esp_timer_create() failed: %s Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
74 E-WIFI-08 WIFI error esp_wifi_start() failed: %s Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
75 E-WIFI-09 WIFI error esp_wifi_set_config() failed: %s Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
76 E-WIFI-10 WIFI error esp_wifi_connect() failed: %s Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
77 E-WIFI-11 WIFI error esp_wifi_set_mode(APSTA) failed: %s Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
78 E-WIFI-12 WIFI error esp_wifi_set_config(AP) failed: %s Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
79 E-WIFI-13 WIFI error esp_wifi_connect() failed: %s Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
80 E-WIFI-14 WIFI error esp_wifi_scan_start() failed: %s Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
81 E-WIFI-15 WIFI error esp_wifi_scan_get_ap_num() failed: %s Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
82 E-WIFI-16 WIFI error esp_wifi_scan_get_ap_records() failed: %s Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
83 E-PROV-01 PROV error mdns_init() failed: %s Retry WiFi provisioning (short button press); restart the device if it persists
84 E-PROV-02 PROV error httpd_start() failed: %s Retry WiFi provisioning (short button press); restart the device if it persists
85 E-MAIN-01 MAIN error Error %d at %s:%d Internal error - send the log to the firmware team
86 E-MAIN-02 MAIN error Failed to open commissioning window, err:% Internal error - send the log to the firmware team
87 E-MAIN-03 MAIN error Attribute update callback: endpoint_id: %u, cluster_id: 0x%lx, attribute_id: 0x%lx Internal error - send the log to the firmware team
88 E-MAIN-04 MAIN error Device MAC address: %02X:%02X:%02X:%02X:%02X:%02X Internal error - send the log to the firmware team
89 E-MAIN-05 MAIN error Failed to initialize SD card: %s Reseat the SD card; if it persists replace the card or check the SD connector
90 E-MAIN-06 MAIN error Failed to initialize EnvironmentService: %s Check ENV.TXT on the SD card exists and has NAME=VALUE lines
91 E-MAIN-07 MAIN error Failed to initialize WifiCredentialsService: %s Check ENV.TXT on the SD card exists and has NAME=VALUE lines
92 E-MAIN-08 MAIN error WiFi provisioning server failed to start: %s; clearing HTTP_SERVER and restarting Retry WiFi provisioning (short button press); restart the device if it persists
93 E-MAIN-09 MAIN error Failed to create Matter node Internal error - send the log to the firmware team
94 E-MAIN-10 MAIN error Failed to start ESP-Matter Internal error - send the log to the firmware team
95 E-MAIN-11 MAIN error Failed to start WifiService: %s Check WiFi signal and credentials; re-run WiFi provisioning (short button press)
96 E-MAIN-12 MAIN error Failed to initialized the encrypted OTA, err: %d Internal error - send the log to the firmware team
97 E-MAIN-13 MAIN error Failed to initialize RTC: %s Check the RTC (DS1307) and the sensor cable
98 E-MAIN-14 MAIN error Failed to initialize Influx buffer: %s Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
99 E-MAIN-15 MAIN error Failed to initialize BME688: %s Check the BME688 sensor and the sensor cable
100 E-MAIN-16 MAIN error Failed to initialize SEN66: %s Check the SEN66 sensor, its power supply and the sensor cable
101 E-MAIN-17 MAIN error Failed to initialize AS7341: %s Check the AS7341 light sensor and the sensor cable
102 E-MAIN-18 MAIN error Failed to initialize Microphone: %s Check the microphone board and its cable
103 E-MAIN-19 MAIN error Failed to initialize Flicker sensor: %s Check the flicker sensor and its cable
104 E-MAIN-20 MAIN error Failed to initialize DeviceStatus: %s Internal error - send the log to the firmware team
105 E-MAIN-21 MAIN error BME688 self check failed: %s Check the BME688 sensor and the sensor cable
106 E-MAIN-22 MAIN error SEN66 self check failed: %s Check the SEN66 sensor, its power supply and the sensor cable
107 E-MAIN-23 MAIN error AS7341 self check failed: %s Check the AS7341 light sensor and the sensor cable
108 E-MAIN-24 MAIN error Microphone self check failed: %s Check the microphone board and its cable
109 E-MAIN-25 MAIN error Flicker sensor self check failed: %s Check the flicker sensor and its cable
110 E-MAIN-26 MAIN error Failed to report passed selfcheck: %s Internal error - send the log to the firmware team
111 E-MAIN-27 MAIN error Failed to flush Influx buffer: %s Check the network connection and INFLUX_URL / INFLUX_TOKEN in ENV.TXT
112 E-STAT-01 STAT error Failed to initialize LED strip: %s Internal error - send the log to the firmware team
113 E-SPI-01 SPI error Failed to take SPI mutex Internal error - send the log to the firmware team
114 E-RTC-01 RTC error Failed to take I2C mutex Internal error - send the log to the firmware team
115 E-RTC-02 RTC error Failed to add I2C device: %s Check the RTC (DS1307) and the sensor cable
116 E-RTC-03 RTC error Failed to initialize DS1307 control register: %s Check the RTC (DS1307) and the sensor cable
117 E-RTC-04 RTC error Attempted to set time on uninitialized DS1307 Internal error - send the log to the firmware team
118 E-RTC-05 RTC error Failed to take I2C mutex Internal error - send the log to the firmware team
119 E-RTC-06 RTC error Attempted to get time on uninitialized DS1307 Internal error - send the log to the firmware team
120 E-RTC-07 RTC error Failed to take I2C mutex Internal error - send the log to the firmware team
121 E-RTC-08 RTC error Attempted to start updating time on uninitialized DS1307 Internal error - send the log to the firmware team
122 E-BME-01 BME error Failed to take I2C mutex Internal error - send the log to the firmware team
123 E-BME-02 BME error Failed to add I2C device: %d Check the BME688 sensor and the sensor cable
124 E-BME-03 BME error Failed to initialize BME688: %d Check the BME688 sensor and the sensor cable
125 E-BME-04 BME error Failed to set BME688 configuration: %d Check the BME688 sensor and the sensor cable
126 E-BME-05 BME error Failed to set BME688 heater configuration: %d Check the BME688 sensor and the sensor cable
127 E-BME-06 BME error Failed to set BME688 operation mode: %d Check the BME688 sensor and the sensor cable
128 E-BME-07 BME error Failed to get BME688 data: %d Check the BME688 sensor and the sensor cable
129 E-BME-08 BME error No new data available from BME688 Check the BME688 sensor and the sensor cable
130 E-BME-09 BME error Failed to get data from BME688: %s Check the BME688 sensor and the sensor cable
131 E-BME-10 BME error Self check failed: %s Check the BME688 sensor and the sensor cable
132 E-BME-11 BME error Failed to take I2C mutex Internal error - send the log to the firmware team
133 E-BME-12 BME error I2C read failed: %s Check the BME688 sensor and the sensor cable
134 E-BME-13 BME error Failed to take I2C mutex Internal error - send the log to the firmware team
135 E-BME-14 BME error Failed to allocate memory for I2C write buffer Internal error - send the log to the firmware team
136 E-BME-15 BME error I2C write failed: %s Check the BME688 sensor and the sensor cable
137 E-SEN-01 SEN error Failed to take I2C mutex Internal error - send the log to the firmware team
138 E-SEN-02 SEN error Failed to add I2C device: %d Check the SEN66 sensor, its power supply and the sensor cable
139 E-SEN-03 SEN error Attempted to wake up uninitialized SEN66 Internal error - send the log to the firmware team
140 E-SEN-04 SEN error Failed to take sensor mutex Internal error - send the log to the firmware team
141 E-SEN-05 SEN error Failed to send start measurement command: %d Check the SEN66 sensor, its power supply and the sensor cable
142 E-SEN-06 SEN error Attempted to sleep uninitialized SEN66 Internal error - send the log to the firmware team
143 E-SEN-07 SEN error Failed to take sensor mutex Internal error - send the log to the firmware team
144 E-SEN-08 SEN error Failed to send stop measurement command: %d Check the SEN66 sensor, its power supply and the sensor cable
145 E-SEN-09 SEN error Failed to take I2C mutex Internal error - send the log to the firmware team
146 E-SEN-10 SEN error Failed to take I2C mutex Internal error - send the log to the firmware team
147 E-SEN-11 SEN error Failed to read ready status: %d Check the SEN66 sensor, its power supply and the sensor cable
148 E-SEN-12 SEN error Sensor not ready after %d attempts, trying to wake it up Check the SEN66 sensor, its power supply and the sensor cable
149 E-SEN-13 SEN error Failed to read measurement: %d Check the SEN66 sensor, its power supply and the sensor cable
150 E-SEN-14 SEN error Failed while awaiting sensor ready: %d Check the SEN66 sensor, its power supply and the sensor cable
151 E-SEN-15 SEN error Failed to read measurement for line protocol: %d Check the SEN66 sensor, its power supply and the sensor cable
152 E-SEN-16 SEN error Self-check failed: Sensor not ready: %d Check the SEN66 sensor, its power supply and the sensor cable
153 E-SEN-17 SEN error Self-check failed: Failed to read measurement: %d Check the SEN66 sensor, its power supply and the sensor cable
154 E-AS-01 AS error Failed to take I2C mutex Internal error - send the log to the firmware team
155 E-AS-02 AS error Failed to initialize AS7341: %s Check the AS7341 light sensor and the sensor cable
156 E-AS-03 AS error Attempted to wake up uninitialized AS7341 Internal error - send the log to the firmware team
157 E-AS-04 AS error Failed to take I2C mutex Internal error - send the log to the firmware team
158 E-AS-05 AS error Failed to wake up AS7341: %s Check the AS7341 light sensor and the sensor cable
159 E-AS-06 AS error Attempted to put uninitialized AS7341 to sleep Internal error - send the log to the firmware team
160 E-AS-07 AS error Failed to take I2C mutex Internal error - send the log to the firmware team
161 E-AS-08 AS error Failed to put AS7341 to sleep: %s Check the AS7341 light sensor and the sensor cable
162 E-AS-09 AS error Attempted to get line protocol on uninitialized AS7341 Internal error - send the log to the firmware team
163 E-AS-10 AS error Failed to take I2C mutex Internal error - send the log to the firmware team
164 E-AS-11 AS error Failed to read spectral data: %s Check the AS7341 light sensor and the sensor cable
165 E-AS-12 AS error Failed to read basic counts data: %s Check the AS7341 light sensor and the sensor cable
166 E-AS-13 AS error Failed to read flicker detection state: %s Check the AS7341 light sensor and the sensor cable
167 E-AS-14 AS error Self-check failed: Failed to read spectral data: %s Check the AS7341 light sensor and the sensor cable
168 E-MIC-01 MIC error Failed to create I2S channel: %s Check the microphone board and its cable
169 E-MIC-02 MIC error Failed to initialize I2S channel in standard mode: %s Check the microphone board and its cable
170 E-MIC-03 MIC error Failed to configure shutdown pin: %s Check the microphone board and its cable
171 E-MIC-04 MIC error Failed to read samples from I2S channel: %s Check the microphone board and its cable
172 E-MIC-05 MIC error Failed to read samples for line protocol: %s Check the microphone board and its cable
173 E-FLK-01 FLK error Error %s at %s:%d Internal error - send the log to the firmware team
174 E-FLK-02 FLK error Attempting to initialize sensor that is already initialized Check the flicker sensor and its cable
175 E-FLK-03 FLK error Failed to allocate memory for FFT buffers Internal error - send the log to the firmware team
176 E-FLK-04 FLK error Failed to initialize FFT: %s Check the flicker sensor and its cable
177 E-FLK-05 FLK error Attempting to read from uninitialized sensor Internal error - send the log to the firmware team
178 E-FLK-06 FLK error Failed to take I2C mutex Internal error - send the log to the firmware team
179 E-FLK-07 FLK error Failed to get dominant frequency: %s Check the flicker sensor and its cable
180 E-FLK-08 FLK error Attempting to read from uninitialized sensor Internal error - send the log to the firmware team
181 E-FLK-09 FLK error Failed to read ADC value: %s Check the flicker sensor and its cable
182 E-FLK-10 FLK error Failed to create gather task: %s Internal error - send the log to the firmware team
183 E-FLK-11 FLK error Attempting to self check uninitialized sensor Internal error - send the log to the firmware team
184 E-FLK-12 FLK error Self check failed to get dominant frequency: %s Check the flicker sensor and its cable
185 E-DEV-01 DEV error Failed to initialize ADC unit: %s Internal error - send the log to the firmware team
186 E-DEV-02 DEV error Failed to configure ADC channel: %s Internal error - send the log to the firmware team
187 E-DEV-03 DEV error Failed to install temperature sensor: %s Internal error - send the log to the firmware team
188 E-DEV-04 DEV error Failed to read ADC value: %s Internal error - send the log to the firmware team
189 E-DEV-05 DEV error Failed to allocate memory for task list buffer Internal error - send the log to the firmware team
190 E-GATH-01 GATH error Failed to take line protocol mutex Internal error - send the log to the firmware team
191 E-GATH-02 GATH error Failed to get line protocol from sensor Device ran out of memory; restart it and send the log to the firmware team
192 E-GATH-03 GATH error Failed to create task for sensor Internal error - send the log to the firmware team
193 E-GATH-04 GATH error Failed to create main gather task Internal error - send the log to the firmware team
+147 -97
View File
@@ -1,97 +1,147 @@
"""Firmware identification from the boot log. """Firmware identification from the boot log.
The app version string is "1.0" in every build seen so far, so builds are Up to firmware 1.0 the app version string was "1.0" in every build, so
told apart by the ELF SHA256 prefix printed by app_init. Boxes receive new builds are told apart by the ELF SHA256 prefix printed by app_init. Boxes
firmware over OTA; an unknown SHA usually means a box has already updated. receive new firmware over OTA; an unknown SHA usually means a box has already
""" updated.
from __future__ import annotations Firmware 1.0.16+ prints "KOTA: boot fw=1.0.16 build=4f10989e ..." (version
unique per build, first 8 hex digits of the ELF SHA256). Builds found in the
import re tool's firmware/ folder are registered with `register_local_build` so the
from dataclasses import dataclass, field box's build can be shown with its compile date.
"""
@dataclass(frozen=True) from __future__ import annotations
class KnownFirmware:
name: str import re
source: str from dataclasses import dataclass, field
sd_wifi: bool # reads SSID/PASSWORD from ENV.TXT
setup_portal: bool # short press -> Wi-Fi setup portal
@dataclass(frozen=True)
class KnownFirmware:
KNOWN: dict[str, KnownFirmware] = { name: str
"45fa9d5b9": KnownFirmware( source: str
name="v1.0 (built Jun 29 2026)", sd_wifi: bool # reads SSID/PASSWORD from ENV.TXT
source="factory image new_system.bin", setup_portal: bool # short press -> Wi-Fi setup portal
sd_wifi=False,
setup_portal=False,
), KNOWN: dict[str, KnownFirmware] = {
"c94ba0e9b": KnownFirmware( "45fa9d5b9": KnownFirmware(
name="v1.0 source build (Sep 26 2026)", name="v1.0 (built Jun 29 2026)",
source="developer build, built by Krzysztof Kallas", source="factory image new_system.bin",
sd_wifi=True, sd_wifi=False,
setup_portal=True, setup_portal=False,
), ),
} "c94ba0e9b": KnownFirmware(
name="v1.0 source build (Sep 26 2026)",
_ELF = re.compile(r"app_init: ELF file SHA256:\s+(?P<sha>[0-9a-f]{6,})") source="developer build, built by Krzysztof Kallas",
_VER = re.compile(r"app_init: App version:\s+(?P<v>\S+)") sd_wifi=True,
_BUILT = re.compile(r"app_init: Compile time:\s+(?P<t>.+)$") setup_portal=True,
_IDF = re.compile(r"app_init: ESP-IDF:\s+(?P<v>\S+)") ),
# Evidence of features, for builds not in KNOWN. }
_FEATURE_SD_WIFI = re.compile(r"WIFI_CREDENTIALS: ")
_FEATURE_PORTAL = re.compile(r"WIFI_PROVISIONING: |Short press: ") # elf sha (full or prefix) -> (version, compile time, file name) of builds in firmware/
# Deployed v1.0 logs the SD mount under the INFLUX_BUFFER tag. LOCAL_BUILDS: dict[str, tuple[str, str, str]] = {}
_LEGACY_SD_TAG = re.compile(r"INFLUX_BUFFER: SD card mounted")
def register_local_build(elf_sha: str, version: str, built: str, file_name: str) -> None:
@dataclass LOCAL_BUILDS[elf_sha.lower()] = (version, built, file_name)
class FirmwareInfo:
elf_sha: str | None = None
version: str | None = None def same_build(a: str | None, b: str | None) -> bool:
built: str | None = None """ELF SHA prefixes of different lengths (8 from KOTA: boot, 9+ from
idf: str | None = None app_init, 64 from an image) name the same build if they agree."""
evidence: set[str] = field(default_factory=set) if not a or not b:
return False
def observe(self, text: str) -> None: n = min(len(a), len(b))
if m := _ELF.search(text): return n >= 6 and a[:n].lower() == b[:n].lower()
self.elf_sha = m.group("sha")
elif m := _VER.search(text):
self.version = m.group("v") def local_build(elf_sha: str | None) -> tuple[str, str, str] | None:
elif m := _BUILT.search(text): return next((v for sha, v in LOCAL_BUILDS.items() if same_build(sha, elf_sha)), None)
self.built = m.group("t").strip()
elif m := _IDF.search(text):
self.idf = m.group("v") _ELF = re.compile(r"app_init: ELF file SHA256:\s+(?P<sha>[0-9a-f]{6,})")
if _FEATURE_SD_WIFI.search(text): _VER = re.compile(r"app_init: App version:\s+(?P<v>\S+)")
self.evidence.add("sd_wifi") _BUILT = re.compile(r"app_init: Compile time:\s+(?P<t>.+)$")
if _FEATURE_PORTAL.search(text): _IDF = re.compile(r"app_init: ESP-IDF:\s+(?P<v>\S+)")
self.evidence.add("setup_portal") # Evidence of features, for builds not in KNOWN.
if _LEGACY_SD_TAG.search(text): _FEATURE_SD_WIFI = re.compile(r"WIFI_CREDENTIALS: ")
self.evidence.add("legacy_v1") _FEATURE_PORTAL = re.compile(r"WIFI_PROVISIONING: |Short press: ")
# Deployed v1.0 logs the SD mount under the INFLUX_BUFFER tag.
@property _LEGACY_SD_TAG = re.compile(r"INFLUX_BUFFER: SD card mounted")
def known(self) -> KnownFirmware | None:
if not self.elf_sha:
return None @dataclass
return next((k for sha, k in KNOWN.items() if self.elf_sha.startswith(sha)), None) class FirmwareInfo:
elf_sha: str | None = None
@property version: str | None = None
def supports_sd_wifi(self) -> bool | None: built: str | None = None
"""True/False when determinable, None when unknown (no boot seen).""" idf: str | None = None
if k := self.known: hw: str | None = None
return k.sd_wifi evidence: set[str] = field(default_factory=set)
if "sd_wifi" in self.evidence:
return True def observe_kota(self, fields: dict[str, str]) -> None:
if "legacy_v1" in self.evidence: """'KOTA: boot fw=1.0.16 build=4f10989e hw=2 ...'"""
return False if fields.get("fw"):
return None self.version = fields["fw"]
build = fields.get("build", "")
def describe(self) -> str: # app_init's longer prefix is kept if it agrees.
if k := self.known: if build and not same_build(self.elf_sha, build):
return f"{k.name} - {k.source}" self.elf_sha = build.lower()
if self.elf_sha: if fields.get("hw"):
built = f", built {self.built}" if self.built else "" self.hw = fields["hw"]
return f"Unknown build {self.elf_sha[:9]}{built} (probably updated over OTA)" self.evidence.add("kota") # 1.0.16+: SD Wi-Fi and setup portal exist
if "legacy_v1" in self.evidence:
return "Probably v1.0 factory image (press Reset & capture to confirm)" def observe(self, text: str) -> None:
return "Not identified yet - press Reset & capture" if m := _ELF.search(text):
self.elf_sha = m.group("sha")
elif m := _VER.search(text):
self.version = m.group("v")
elif m := _BUILT.search(text):
self.built = m.group("t").strip()
elif m := _IDF.search(text):
self.idf = m.group("v")
if _FEATURE_SD_WIFI.search(text):
self.evidence.add("sd_wifi")
if _FEATURE_PORTAL.search(text):
self.evidence.add("setup_portal")
if _LEGACY_SD_TAG.search(text):
self.evidence.add("legacy_v1")
@property
def known(self) -> KnownFirmware | None:
if not self.elf_sha:
return None
return next((k for sha, k in KNOWN.items() if same_build(self.elf_sha, sha)), None)
@property
def supports_sd_wifi(self) -> bool | None:
"""True/False when determinable, None when unknown (no boot seen)."""
if k := self.known:
return k.sd_wifi
if "sd_wifi" in self.evidence or "kota" in self.evidence:
return True
if "legacy_v1" in self.evidence:
return False
return None
def describe(self) -> str:
if k := self.known:
return f"{k.name} - {k.source}"
if self.elf_sha and (self.version not in (None, "1.0") or local_build(self.elf_sha)):
local = local_build(self.elf_sha)
built = self.built or (local[1] if local else None)
text = f"v{self.version or (local[0] if local else '?')} (build {self.elf_sha[:8]}"
text += f", compiled {built})" if built else ")"
if self.hw:
text += f", hardware {self.hw}"
if local:
text += f" - same as firmware/{local[2]}"
return text
if self.elf_sha:
built = f", built {self.built}" if self.built else ""
return f"Unknown build {self.elf_sha[:9]}{built} (probably updated over OTA)"
if "legacy_v1" in self.evidence:
return "Probably v1.0 factory image (press Reset & capture to confirm)"
return "Not identified yet - press Reset & capture"
+1 -1
View File
@@ -21,7 +21,7 @@ from .engine import LED, DiagnosticsEngine, Severity
GUIDES_PATH = Path(__file__).with_name("guides.toml") GUIDES_PATH = Path(__file__).with_name("guides.toml")
# LED answers a technician can give (engine colours + a reboot-loop pattern). # LED answers a technician can give (engine colours + a reboot-loop pattern).
LED_ANSWERS = ["GREEN", "PURPLE", "RED", "BLUE", "WHITE", "YELLOW", "ORANGE", "OFF", "CYCLING"] LED_ANSWERS = ["GREEN", "PURPLE", "RED", "BLUE", "WHITE", "YELLOW", "ORANGE", "CYAN", "OFF", "CYCLING"]
LED_ANSWER_LABELS = {**{k: v[0] for k, v in LED.items()}, LED_ANSWER_LABELS = {**{k: v[0] for k, v in LED.items()},
"CYCLING": "Keeps changing / goes dark every few seconds"} "CYCLING": "Keeps changing / goes dark every few seconds"}
STEP_TYPES = {"led", "question", "info", "wait", "route"} STEP_TYPES = {"led", "question", "info", "wait", "route"}
+740 -735
View File
File diff suppressed because it is too large. Load diff
+263
View File
@@ -0,0 +1,263 @@
"""Knowledge about the structured "KOTA:" lines of firmware 1.0.16+.
Firmware source of truth (kota-sensorboard/main):
boot_info.cpp "boot fw=.. build=.. hw=.. mac=.. reset=.. mode=.. commissioned=.. last_restart=.."
"restart reason=.." (W, printed just before a self-restart)
status.cpp "status A -> B [code=N] reason=x", "led color=.. pattern=.. [n=..|period=..ms]",
"led previous_boot status=.. code=..", "led restart_flash color=.."
i2c.cpp "i2c SDA=1 SCL=1 0x39=AS7341 0x68=DS1307(missing) .. [bus=stuck]"
ds1307.cpp "rtc running=1 time=..", "rtc read_failed err=..", "rtc verify running=1 delta=2s ok=1"
sd_card.cpp "sd type=.. size=.. fs=.. free=.. env_keys=A,B buffer_lines=N", "sd mounted=0 [err=..]"
main.cpp "matter fabrics=N window=open|closed qr=MT:.. manual=.."
microphone.cpp "mic enabled=0 (GPIO3=1, expected 0)"
health.cpp "health up=60s status=OK wifi=connected rssi=-61 time_valid=1 sd=ok buffer=0
heap=123456 psram=7.8M last_upload=12s|never ota=registered|unregistered|selfcheck"
Error IDs ("[E-SD-03] ...") come from error_ids.csv, a copy of the
firmware's docs/error_ids.csv (the firmware build generates its IDs from it).
"""
from __future__ import annotations
import csv
from dataclasses import dataclass
from pathlib import Path
ERROR_IDS_PATH = Path(__file__).with_name("error_ids.csv")
# Firmware colour names (status.cpp colors[]) -> engine LED keys.
LED_COLOURS = {
"green": "GREEN", "cyan": "CYAN", "white": "WHITE", "red": "RED",
"blue": "BLUE", "purple": "PURPLE", "yellow": "YELLOW", "orange": "ORANGE",
}
RED_CODES = {1: "BME688", 2: "SEN66", 3: "AS7341", 4: "Microphone", 5: "Flicker sensor", 6: "Self-check"}
I2C_DEVICES = {"0x39": "AS7341", "0x68": "DS1307", "0x6B": "SEN66", "0x76": "BME688"}
# last_restart values written by kota_restart() that are part of normal
# operation (button presses, a finished setup, an installed update).
INTENTIONAL_RESTARTS = {
"ota_update", "button_provisioning_abort", "button_wifi_cleared",
"button_provisioning_toggle", "provisioning_saved",
}
MODULES = {
"SD": "SD card", "ENV": "ENV.TXT", "INF": "InfluxDB upload", "OTA": "Firmware update",
"WIFI": "Wi-Fi", "PROV": "Wi-Fi setup", "MAIN": "Start-up", "STAT": "Status LED", "SPI": "SPI bus",
"RTC": "Clock (RTC)", "BME": "BME688", "SEN": "SEN66", "AS": "AS7341", "MIC": "Microphone",
"FLK": "Flicker sensor", "DEV": "Device", "GATH": "Sensor readings",
}
@dataclass(frozen=True)
class ErrorId:
id: str
module: str
severity: str # error | warning | retired
message: str
action: str
@property
def module_name(self) -> str:
return MODULES.get(self.module, self.module)
def load_error_ids(path: Path = ERROR_IDS_PATH) -> dict[str, ErrorId]:
if not path.exists():
return {}
with path.open(encoding="utf-8", newline="") as fh:
return {r["id"]: ErrorId(r["id"], r["module"], r["severity"], r["message"], r["action"])
for r in csv.DictReader(fh)}
def led_for_status(status: str, code: int) -> tuple[str, str]:
"""(LED key, pattern text) for a status - mirrors Status::pattern_for().
Used when the box's own "led" line was not captured (connected mid-run)."""
if status == "OK":
return "GREEN", "solid"
if status == "ERROR":
return ("RED", f"{code} pulses") if 1 <= code <= 6 else ("RED", "solid")
if status == "OUT_OF_RESOURCES":
return "RED", "solid"
if status == "UPDATING":
return "YELLOW", "blinking"
if status == "SELF_CHECK":
return "ORANGE", "solid"
if status == "CONNECTION_ERROR":
return ("PURPLE", "blinking") if code == 1 else ("PURPLE", "solid")
if status == "RTC_ERROR":
return "BLUE", "2 pulses" if code == 2 else "1 pulse"
if status == "SD_ERROR":
return "WHITE", "fast blinking"
if status == "RESETING":
return "WHITE", "solid"
if status == "HTTP_SERVER":
return "WHITE", "breathing"
return "UNKNOWN", ""
def pattern_text(fields: dict[str, str]) -> str:
"""'led color=red pattern=pulses n=2' -> '2 pulses'."""
p = fields.get("pattern", "")
if p == "pulses":
n = fields.get("n", "?")
return f"{n} pulse" if n == "1" else f"{n} pulses"
if p == "blink":
period = fields.get("period", "").removesuffix("ms")
fast = period.isdigit() and int(period) <= 500
return ("fast blinking" if fast else "blinking") + (f" ({period} ms)" if period else "")
if p == "breathe":
return "breathing"
return p # solid / off
def led_meaning(colour: str, pattern: str) -> str:
"""Technician meaning of a colour + pattern (firmware diagnostics doc)."""
if colour == "GREEN":
return "OK"
if colour == "CYAN":
return "phone connected for pairing" if "fast" in pattern else "waiting to be paired in Matter"
if colour == "WHITE":
if "fast" in pattern:
return "SD card or ENV.TXT error"
if "breath" in pattern:
return "Wi-Fi setup portal"
return "factory reset"
if colour == "RED":
if "pulse" in pattern:
n = int(pattern.split()[0]) if pattern.split()[0].isdigit() else 0
return f"{RED_CODES.get(n, 'sensor')} failed"
return "internal error / out of memory"
if colour == "BLUE":
return "I2C bus stuck (sensor cable)" if pattern.startswith("2") else "clock (RTC) not responding"
if colour == "PURPLE":
return "server rejected the box (check ENV.TXT credentials)" if "blink" in pattern else "no network"
if colour == "YELLOW":
return "downloading a firmware update"
if colour == "ORANGE":
return "self-check after an update"
return ""
# Finding for the current firmware status (Status::set_status). key suffix ->
# (severity, title, meaning, actions, explained_by). The status finding is
# grouped under a more specific finding when one explains it.
_SENSOR_ROOTS = ("sensor.init_failed", "sensor.selfcheck_failed", "kota.i2c_stuck", "kota.sensor_missing",
"sen66.not_ready", "bme688.read_fail", "as7341.read_fail", "mic.read_fail",
"ota.selfcheck_failed")
_NET_ROOTS = ("matter.not_commissioned", "wifi.disconnected", "wifi.setup_portal", "kota.wifi_down",
"net.dns_fail", "net.tls_fail")
def status_finding(status: str, code: int) -> tuple[str, str, str, str, tuple[str, ...], tuple[str, ...]] | None:
"""(key, severity, title, meaning, actions, explained_by) or None for healthy states."""
if status == "ERROR":
if 1 <= code <= 5:
s = RED_CODES[code]
return (f"status.error.{code}", "critical", f"{s} fault (LED red, {code} pulses)",
f"The firmware reports the {s} as failed.",
(f"Open the case and check the {s} connector/cable.",
"If several sensors fail: check the shared I2C cable.",
"The box restarts itself after 150 s in this state."), _SENSOR_ROOTS)
if code == 6:
return ("status.error.6", "error", "Post-update self-check failed (LED red, 6 pulses)",
"The new firmware failed its self-check and rolls back.",
("Check the sensor named in the log (inside the case), then power-cycle.",), _SENSOR_ROOTS)
return ("status.error", "error", "Internal error (LED red)",
"The firmware is in its general error state.",
("Save the session log and send it to the firmware team.",
"The box restarts itself after 150 s in this state."), _SENSOR_ROOTS)
if status == "OUT_OF_RESOURCES":
return ("status.oom", "error", "Firmware ran out of memory (LED red)",
"The firmware could not allocate memory; it restarts itself after 30 s.",
("Power-cycle. If it repeats, save the session log for the firmware team.",),
("sys.out_of_resources",))
if status == "CONNECTION_ERROR":
if code == 1:
return ("status.conn.1", "critical", "Server rejected the box (LED purple, blinking)",
"The network works but the server refused the box (HTTP 401/403/404): "
"INFLUX_URL / INFLUX_TOKEN in ENV.TXT are wrong or revoked.",
("Re-provision the SD card with the current ENV.TXT (SD card is inside the case).",),
("influx.auth", "influx.not_found"))
return ("status.conn", "error", "No connection to the servers (LED purple)",
"Uploads or the update check fail: no Wi-Fi, no Internet or the server is unreachable.",
("Check the box is paired/connected to Wi-Fi and the network has Internet.",),
_NET_ROOTS + ("influx.buffer_fail", "ota.check_failed", "influx.server_error"))
if status == "RTC_ERROR":
if code == 2:
return ("status.rtc.2", "critical", "I2C bus stuck (LED blue, 2 pulses)",
"SDA or SCL is held low: a shorted or broken sensor cable, or a faulty sensor.",
("Open the case and check the I2C cable between the boards.",
"Unplug sensors one by one to find the one holding the bus."), ("kota.i2c_stuck",))
return ("status.rtc.1", "critical", "Clock chip (RTC) not responding (LED blue, 1 pulse)",
"The DS1307 clock does not answer on the I2C bus.",
("Open the case and check the I2C cable/connector between the boards.",
"If the cable is fine: the RTC module is faulty."),
("rtc.init_failed", "kota.rtc_read_failed", "kota.sensor_missing"))
if status == "SD_ERROR":
return ("status.sd", "critical", "SD card or ENV.TXT error (LED white, fast blinking)",
"The SD card cannot be read or ENV.TXT is missing settings.",
("Open the case, re-seat the SD card or re-provision it with the tool.",),
("kota.sd_unmounted", "influx.env_missing", "sd.card_fail", "sd.mount_fail",
"sd.env_open_fail", "influx.init_fail"))
if status == "RESETING":
return ("status.reset", "warning", "Factory reset in progress (LED white, solid)",
"The Matter button was held: the box forgets its Matter network.",
("Pair the box again in the Matter app afterwards.",), ("sys.factory_reset",))
if status == "HTTP_SERVER":
return ("status.portal", "warning", "Box is in Wi-Fi setup mode (LED white, breathing)",
"The box hosts its own Wi-Fi network for configuration.",
("Connect a phone to the box's network and open http://sensorbox.local/,",
"or short-press the Matter button to leave setup mode."), ("wifi.setup_portal",))
return None # OK, UPDATING, SELF_CHECK: covered by milestones / OTA rules
# last_restart -> (severity, title, meaning, actions); None = not a fault.
def restart_finding(reason: str) -> tuple[str, str, str, tuple[str, ...]] | None:
if reason in INTENTIONAL_RESTARTS or reason in ("none", "", "-"):
return None
if reason == "status_watchdog":
return ("warning", "Box restarted itself after 150 s in the red error state",
"By design the firmware restarts when it stays in the error state (red) for 150 s.",
("Fix the grouped cause; the restarts stop by themselves.",))
if reason == "status_oom_watchdog":
return ("error", "Box restarted itself because it ran out of memory",
"The firmware was out of memory for 30 s and restarted.",
("Save the session log for the firmware team.",))
if reason == "provisioning_failed":
return ("warning", "Wi-Fi setup portal failed to start",
"The setup portal could not start; the box cleared setup mode and restarted.",
("Retry Wi-Fi setup (short button press); restart the device if it persists.",))
if reason == "panic":
return ("critical", "Firmware crashed (panic) and restarted",
"The firmware hit a fatal error.",
("Press Reset & capture to record the crash; save the session log for the firmware team.",))
if reason in ("task_wdt", "int_wdt", "wdt"):
return ("error", "Firmware froze and was restarted by the watchdog",
f"The firmware stopped responding ({reason}); the watchdog restarted it.",
("Save the session log for the firmware team.",))
if reason == "brownout":
return ("error", "Power supply voltage dropped (brown-out)",
"The supply voltage fell too low and the chip reset itself.",
("Check the power supply, cable and connectors.",))
if reason == "unknown_sw":
return ("warning", "Unexpected software restart",
"The firmware restarted without recording a reason.",
("Watch whether it repeats; save the session log for the firmware team.",))
return ("warning", f"Box restarted itself ({reason})",
f"The firmware recorded the restart reason '{reason}'.",
("Save the session log for the firmware team if it repeats.",))
def parse_size_gb(value: str) -> float | None:
"""'7.3GB' -> 7.3 (sd_card.cpp format_gb)."""
v = value.upper().removesuffix("GB")
try:
return float(v)
except ValueError:
return None
def parse_seconds(value: str) -> int | None:
v = value.removesuffix("s")
return int(v) if v.lstrip("-").isdigit() else None
+724 -572
View File
File diff suppressed because it is too large. Load diff
+260 -303
View File
@@ -1,303 +1,260 @@
"""Firmware images: validation, integrity and layout. """Firmware images: validation, integrity, layout and the firmware folder.
Two origins: The tool flashes ONLY the .bin files in its own firmware/ folder (next to
* factory - bundled with the tool (firmware/firmware.toml), SHA-256 locked; kota_tech/). There is no import and no per-user library: to offer a build,
* developer - a newer build the firmware team sends to technicians, the firmware team puts the file into that folder. Images are listed by the
imported into a per-user library (~/KotaTechnicianTool/firmware). compile date stored in the firmware itself (ESP-IDF app descriptor), newest
Two kinds: first, so the file name does not matter.
* merged - bootloader at 0x0 + partition table + app (like new_system.bin);
App-only or Full flashing; Two kinds:
* app - the application binary only (build/kota-sensorboard.bin); * merged - bootloader at 0x0 + partition table + app (merged-binary.bin);
App-only flashing, laid out like the factory image. App-only or Full flashing;
* app - the application binary only (build/kota-sensorboard.bin);
Every image is checked structurally (ESP32-S3, kota-sensorboard app App-only flashing, laid out like a merged image in the folder.
descriptor, segment checksum and the appended SHA-256) so a truncated or
corrupted file is refused before anything is written. Every image is checked structurally (ESP32-S3, kota-sensorboard app
""" descriptor, segment checksum and the appended SHA-256) so a truncated or
corrupted file is refused before anything is written.
from __future__ import annotations """
import datetime as dt from __future__ import annotations
import hashlib
import json import datetime as dt
import shutil import hashlib
import struct import struct
import tomllib from dataclasses import dataclass
from dataclasses import dataclass from pathlib import Path
from pathlib import Path
FIRMWARE_DIR = Path(__file__).resolve().parents[2] / "firmware"
FIRMWARE_DIR = Path(__file__).resolve().parents[2] / "firmware"
MANIFEST = FIRMWARE_DIR / "firmware.toml" PT_OFFSET = 0x8000
LIBRARY_DIR = Path.home() / "KotaTechnicianTool" / "firmware" PT_SIZE = 0xC00
LIBRARY_INDEX = "library.json" ESP32S3_CHIP_ID = 9
IMAGE_MAGIC = 0xE9
PT_OFFSET = 0x8000 APP_DESC_MAGIC = 0xABCD5432
PT_SIZE = 0xC00 FLASH_SIZES = {0: "1MB", 1: "2MB", 2: "4MB", 3: "8MB", 4: "16MB", 5: "32MB"}
ESP32S3_CHIP_ID = 9 _MONTHS = {m: i for i, m in enumerate(
IMAGE_MAGIC = 0xE9 ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], 1)}
APP_DESC_MAGIC = 0xABCD5432
FLASH_SIZES = {0: "1MB", 1: "2MB", 2: "4MB", 3: "8MB", 4: "16MB", 5: "32MB"}
_MONTHS = {m: i for i, m in enumerate( class ImageError(ValueError):
["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], 1)} pass
class ImageError(ValueError): @dataclass(frozen=True)
pass class Partition:
label: str
type: int
@dataclass(frozen=True) subtype: int
class Partition: offset: int
label: str size: int
type: int
subtype: int
offset: int @dataclass(frozen=True)
size: int class AppInfo:
project: str
version: str
@dataclass(frozen=True) built: str # "Sep 28 2026 15:07:57" as in the app descriptor
class AppInfo: idf: str
project: str elf_sha: str # hex
version: str
built: str # "Jun 29 2026 11:03:32" as in the app descriptor @property
idf: str def built_at(self) -> dt.datetime | None:
elf_sha: str # hex try:
mon, day, year, hms = self.built.split()
@property h, m, s = (int(x) for x in hms.split(":"))
def built_at(self) -> dt.datetime | None: return dt.datetime(int(year), _MONTHS[mon], int(day), h, m, s)
try: except (ValueError, KeyError):
mon, day, year, hms = self.built.split() return None
h, m, s = (int(x) for x in hms.split(":"))
return dt.datetime(int(year), _MONTHS[mon], int(day), h, m, s) @property
except (ValueError, KeyError): def compiled(self) -> str:
return None """'2026-09-28 15:07' (ISO-like, sortable) or the raw descriptor text."""
t = self.built_at
return t.strftime("%Y-%m-%d %H:%M") if t else self.built
@dataclass(frozen=True)
class FirmwareImage:
path: Path @dataclass(frozen=True)
name: str class FirmwareImage:
notes: str path: Path
origin: str # "factory" | "developer" kind: str # "merged" | "app"
kind: str # "merged" | "app" sha256: str
sha256: str flash_size: str
flash_size: str partitions: tuple[Partition, ...]
partitions: tuple[Partition, ...] partition_table: bytes # expected table on the box
partition_table: bytes # expected table on the box app_offset: int # where the app starts inside the file
app_offset: int # where the app starts inside the file app_length: int # exact app image length (from its structure)
app_length: int # exact app image length (from its structure) app: AppInfo
app: AppInfo
built_by: str = "" # who compiled a developer build (shown in the UI) @property
def name(self) -> str:
@property return self.path.name
def data(self) -> bytes:
return self.path.read_bytes() @property
def data(self) -> bytes:
@property return self.path.read_bytes()
def is_developer(self) -> bool:
return self.origin == "developer" def partition(self, label: str) -> Partition:
for p in self.partitions:
def partition(self, label: str) -> Partition: if p.label == label:
for p in self.partitions: return p
if p.label == label: raise ImageError(f"partition {label!r} not in image")
return p
raise ImageError(f"partition {label!r} not in image") def app_bytes(self) -> bytes:
return self.data[self.app_offset:self.app_offset + self.app_length]
def app_bytes(self) -> bytes:
return self.data[self.app_offset:self.app_offset + self.app_length] def blank_otadata(self) -> bytes:
"""Erased otadata: the bootloader then boots ota_0."""
def blank_otadata(self) -> bytes: return b"\xff" * self.partition("otadata").size
"""Erased otadata: the bootloader then boots ota_0."""
return b"\xff" * self.partition("otadata").size def label(self) -> str:
"""Choice text: compile date first (that is what the technician picks by)."""
def label(self) -> str: kind = "" if self.kind == "merged" else ", app only"
if self.origin == "factory": return f"Compiled {self.app.compiled} - v{self.app.version} [{self.app.elf_sha[:8]}]{kind} ({self.name})"
tag = "factory"
else:
tag = "developer build" + (f" - built by {self.built_by}" if self.built_by else "") # ---------------------------------------------------------------- parsing
return f"{self.app.version} built {self.app.built} [{self.app.elf_sha[:9]}] - {tag}"
def parse_partition_table(raw: bytes) -> tuple[Partition, ...]:
parts = []
# ---------------------------------------------------------------- parsing for i in range(0, len(raw) - 31, 32):
entry = raw[i:i + 32]
def parse_partition_table(raw: bytes) -> tuple[Partition, ...]: magic = entry[:2]
parts = [] if magic == b"\xaa\x50":
for i in range(0, len(raw) - 31, 32): _, ptype, sub, off, size = struct.unpack_from("<HBBII", entry)
entry = raw[i:i + 32] label = entry[12:28].split(b"\0")[0].decode("ascii", "replace")
magic = entry[:2] parts.append(Partition(label, ptype, sub, off, size))
if magic == b"\xaa\x50": elif magic in (b"\xeb\xeb", b"\xff\xff"): # MD5 entry / end
_, ptype, sub, off, size = struct.unpack_from("<HBBII", entry) break
label = entry[12:28].split(b"\0")[0].decode("ascii", "replace") else:
parts.append(Partition(label, ptype, sub, off, size)) raise ImageError(f"corrupt partition table entry at 0x{PT_OFFSET + i:x}")
elif magic in (b"\xeb\xeb", b"\xff\xff"): # MD5 entry / end return tuple(parts)
break
else:
raise ImageError(f"corrupt partition table entry at 0x{PT_OFFSET + i:x}") def app_image_length(data: bytes, offset: int = 0) -> int:
return tuple(parts) """Validate an ESP app image at `offset`; return its exact length.
Checks the segment checksum and, when the header says so, the appended
def app_image_length(data: bytes, offset: int = 0) -> int: SHA-256 - the same checks the bootloader performs before booting it.
"""Validate an ESP app image at `offset`; return its exact length. """
if len(data) < offset + 24 or data[offset] != IMAGE_MAGIC:
Checks the segment checksum and, when the header says so, the appended raise ImageError(f"no firmware image at 0x{offset:x}")
SHA-256 - the same checks the bootloader performs before booting it. segments = data[offset + 1]
""" chip_id = struct.unpack_from("<H", data, offset + 12)[0]
if len(data) < offset + 24 or data[offset] != IMAGE_MAGIC: if chip_id != ESP32S3_CHIP_ID:
raise ImageError(f"no firmware image at 0x{offset:x}") raise ImageError(f"image is for chip id {chip_id}, not ESP32-S3")
segments = data[offset + 1] hash_appended = data[offset + 23] == 1
chip_id = struct.unpack_from("<H", data, offset + 12)[0] pos, checksum = offset + 24, 0xEF
if chip_id != ESP32S3_CHIP_ID: for _ in range(segments):
raise ImageError(f"image is for chip id {chip_id}, not ESP32-S3") if pos + 8 > len(data):
hash_appended = data[offset + 23] == 1 raise ImageError("image is truncated (segment header missing)")
pos, checksum = offset + 24, 0xEF _, seg_len = struct.unpack_from("<II", data, pos)
for _ in range(segments): pos += 8
if pos + 8 > len(data): if pos + seg_len > len(data):
raise ImageError("image is truncated (segment header missing)") raise ImageError("image is truncated (segment data missing)")
_, seg_len = struct.unpack_from("<II", data, pos) for b in data[pos:pos + seg_len]:
pos += 8 checksum ^= b
if pos + seg_len > len(data): pos += seg_len
raise ImageError("image is truncated (segment data missing)") pos += 15 - ((pos - offset) % 16) # pad so the checksum ends a 16-byte block
for b in data[pos:pos + seg_len]: if pos >= len(data) or data[pos] != checksum:
checksum ^= b raise ImageError("image checksum is wrong - the file is corrupted")
pos += seg_len pos += 1
pos += 15 - ((pos - offset) % 16) # pad so the checksum ends a 16-byte block if hash_appended:
if pos >= len(data) or data[pos] != checksum: if pos + 32 > len(data):
raise ImageError("image checksum is wrong - the file is corrupted") raise ImageError("image is truncated (SHA-256 missing)")
pos += 1 if hashlib.sha256(data[offset:pos]).digest() != data[pos:pos + 32]:
if hash_appended: raise ImageError("image SHA-256 does not match its content - the file is corrupted")
if pos + 32 > len(data): pos += 32
raise ImageError("image is truncated (SHA-256 missing)") return pos - offset
if hashlib.sha256(data[offset:pos]).digest() != data[pos:pos + 32]:
raise ImageError("image SHA-256 does not match its content - the file is corrupted")
pos += 32 def _app_info(data: bytes, offset: int) -> AppInfo:
return pos - offset d = data[offset + 0x20:offset + 0x20 + 256]
if len(d) < 256 or struct.unpack_from("<I", d)[0] != APP_DESC_MAGIC:
raise ImageError("firmware has no ESP-IDF app descriptor")
def _app_info(data: bytes, offset: int) -> AppInfo: s = lambda o, n: d[o:o + n].split(b"\0")[0].decode("ascii", "replace")
d = data[offset + 0x20:offset + 0x20 + 256] info = AppInfo(project=s(48, 32), version=s(16, 32), built=f"{s(96, 16)} {s(80, 16)}",
if len(d) < 256 or struct.unpack_from("<I", d)[0] != APP_DESC_MAGIC: idf=s(112, 32), elf_sha=d[144:176].hex())
raise ImageError("firmware has no ESP-IDF app descriptor") if info.project != "kota-sensorboard":
s = lambda o, n: d[o:o + n].split(b"\0")[0].decode("ascii", "replace") raise ImageError(f"firmware is {info.project!r}, not kota-sensorboard")
info = AppInfo(project=s(48, 32), version=s(16, 32), built=f"{s(96, 16)} {s(80, 16)}", return info
idf=s(112, 32), elf_sha=d[144:176].hex())
if info.project != "kota-sensorboard":
raise ImageError(f"firmware is {info.project!r}, not kota-sensorboard")
return info def inspect_image(path: Path, reference: FirmwareImage | None = None) -> FirmwareImage:
"""Validate a merged or app-only image. App-only images need a `reference`
(a merged image) that provides the flash layout."""
def inspect_image(path: Path, name: str = "", notes: str = "", origin: str = "factory", data = path.read_bytes()
reference: FirmwareImage | None = None, built_by: str = "") -> FirmwareImage: if len(data) >= PT_OFFSET + PT_SIZE and data[0] == IMAGE_MAGIC and data[PT_OFFSET:PT_OFFSET + 2] == b"\xaa\x50":
"""Validate a merged or app-only image. App-only images need a `reference` app_image_length(data, 0) # bootloader must be intact
(the factory image) that provides the flash layout.""" table = data[PT_OFFSET:PT_OFFSET + PT_SIZE]
data = path.read_bytes() parts = parse_partition_table(table)
if len(data) >= PT_OFFSET + PT_SIZE and data[0] == IMAGE_MAGIC and data[PT_OFFSET:PT_OFFSET + 2] == b"\xaa\x50": labels = {p.label for p in parts}
app_image_length(data, 0) # bootloader must be intact for need in ("nvs", "otadata", "ota_0"):
table = data[PT_OFFSET:PT_OFFSET + PT_SIZE] if need not in labels:
parts = parse_partition_table(table) raise ImageError(f"partition table has no {need!r} partition")
labels = {p.label for p in parts} ota0 = next(p for p in parts if p.label == "ota_0")
for need in ("nvs", "otadata", "ota_0"): kind, app_off, flash_size = "merged", ota0.offset, FLASH_SIZES.get(data[3] >> 4, "?")
if need not in labels: elif data[:1] == bytes([IMAGE_MAGIC]):
raise ImageError(f"partition table has no {need!r} partition") if reference is None:
ota0 = next(p for p in parts if p.label == "ota_0") raise ImageError("app-only file, but there is no complete (merged) image in the folder "
kind, app_off, flash_size = "merged", ota0.offset, FLASH_SIZES.get(data[3] >> 4, "?") "to take the flash layout from")
elif data[:1] == bytes([IMAGE_MAGIC]): kind, app_off = "app", 0
if reference is None: parts, table, flash_size = reference.partitions, reference.partition_table, reference.flash_size
raise ImageError("app-only image needs the factory image as layout reference") ota0 = next(p for p in parts if p.label == "ota_0")
kind, app_off = "app", 0 else:
parts, table, flash_size = reference.partitions, reference.partition_table, reference.flash_size raise ImageError("not an ESP32 firmware file")
ota0 = next(p for p in parts if p.label == "ota_0") length = app_image_length(data, app_off)
else: if length > ota0.size:
raise ImageError("not an ESP32 firmware file") raise ImageError(f"firmware ({length} bytes) does not fit the ota_0 partition ({ota0.size} bytes)")
length = app_image_length(data, app_off) app = _app_info(data, app_off)
if length > ota0.size: return FirmwareImage(path, kind, hashlib.sha256(data).hexdigest(),
raise ImageError(f"firmware ({length} bytes) does not fit the ota_0 partition ({ota0.size} bytes)") flash_size, parts, table, app_off, length, app)
app = _app_info(data, app_off)
return FirmwareImage(path, name or path.name, notes, origin, kind, hashlib.sha256(data).hexdigest(),
flash_size, parts, table, app_off, length, app, built_by) # ------------------------------------------------------------- catalogue
def folder_images(folder: Path = FIRMWARE_DIR) -> tuple[list[FirmwareImage], list[str]]:
# ------------------------------------------------------------- catalogue """(valid images newest-compiled first, problems) for the .bin files in `folder`.
def bundled_images(manifest: Path = MANIFEST) -> list[FirmwareImage]: A broken or foreign file is reported, never offered. The same build
"""Images shipped with the tool whose file exists and matches its SHA-256. under two file names is offered once.
Factory images first; bundled developer builds keep their origin/built_by.""" """
if not manifest.exists(): if not folder.is_dir():
return [] return [], [f"firmware folder not found: {folder}"]
out = [] files = sorted(p for p in folder.iterdir() if p.is_file() and p.suffix.lower() == ".bin")
for e in tomllib.loads(manifest.read_text(encoding="utf-8")).get("image", []): merged: list[FirmwareImage] = []
path = manifest.parent / e["file"] app_only: list[Path] = []
if not path.exists(): problems: list[str] = []
continue for f in files:
origin = e.get("origin", "factory") try:
if origin not in ("factory", "developer"): merged.append(inspect_image(f))
raise ImageError(f"{path.name}: unknown origin {origin!r} in the manifest") except ImageError as exc:
img = inspect_image(path, e.get("name", ""), e.get("notes", ""), origin, built_by=e.get("built_by", "")) if "app-only" in str(exc):
if img.sha256 != e["sha256"].lower(): app_only.append(f)
raise ImageError(f"{path.name}: SHA-256 does not match the manifest - file changed or corrupt") else:
out.append(img) problems.append(f"{f.name}: {exc}")
return sorted(out, key=lambda i: i.origin != "factory") except OSError as exc:
problems.append(f"{f.name}: cannot read ({exc})")
merged.sort(key=_newest_first)
def factory_images(manifest: Path = MANIFEST) -> list[FirmwareImage]: reference = merged[0] if merged else None
"""Only the official factory image(s).""" images = list(merged)
return [i for i in bundled_images(manifest) if i.origin == "factory"] for f in app_only:
try:
images.append(inspect_image(f, reference))
class FirmwareLibrary: except (ImageError, OSError) as exc:
"""Developer builds imported by the technician (persist across tool versions).""" problems.append(f"{f.name}: {exc}")
images.sort(key=_newest_first)
def __init__(self, root: Path = LIBRARY_DIR): unique: dict[str, FirmwareImage] = {}
self.root = root for img in images:
if img.sha256 in unique:
def _index(self) -> list[dict]: problems.append(f"{img.name}: same file as {unique[img.sha256].name} (listed once)")
f = self.root / LIBRARY_INDEX else:
return json.loads(f.read_text(encoding="utf-8")) if f.exists() else [] unique[img.sha256] = img
return list(unique.values()), problems
def _save(self, entries: list[dict]) -> None:
self.root.mkdir(parents=True, exist_ok=True)
(self.root / LIBRARY_INDEX).write_text(json.dumps(entries, indent=2), encoding="utf-8") def _newest_first(img: FirmwareImage) -> tuple:
# Unknown compile dates last; merged before app-only for the same date.
def images(self, reference: FirmwareImage | None) -> tuple[list[FirmwareImage], list[str]]: t = img.app.built_at
"""(valid images, problems) - a changed or broken file is reported, not offered.""" return (t is None, -t.timestamp() if t else 0.0, img.kind != "merged", img.name)
imgs, problems = [], []
for e in self._index():
path = self.root / e["file"]
try:
img = inspect_image(path, e.get("name", ""), e.get("notes", ""), "developer", reference,
e.get("built_by", ""))
if img.sha256 != e["sha256"]:
raise ImageError("file changed since it was imported")
imgs.append(img)
except (OSError, ImageError) as exc:
problems.append(f"{e.get('original', e['file'])}: {exc}")
return imgs, problems
def import_file(self, src: Path, reference: FirmwareImage | None, notes: str = "",
built_by: str = "") -> FirmwareImage:
img = inspect_image(src, origin="developer", reference=reference) # validate before copying
entries = self._index()
existing = next((e for e in entries if e["sha256"] == img.sha256), None)
if existing:
return inspect_image(self.root / existing["file"], existing["name"], existing["notes"],
"developer", reference, existing.get("built_by", ""))
self.root.mkdir(parents=True, exist_ok=True)
fname = f"{img.app.elf_sha[:9]}_{img.sha256[:8]}.bin"
shutil.copyfile(src, self.root / fname)
built_by = built_by.strip()
name = f"Developer build {img.app.version} ({img.app.built})" + (f", built by {built_by}" if built_by else "")
entries.append({"file": fname, "sha256": img.sha256, "name": name, "original": src.name,
"imported": dt.datetime.now().isoformat(timespec="seconds"), "notes": notes,
"built_by": built_by})
self._save(entries)
return inspect_image(self.root / fname, name, notes, "developer", reference, built_by)
def remove(self, sha256: str) -> None:
entries = self._index()
keep = [e for e in entries if e["sha256"] != sha256]
for e in entries:
if e["sha256"] == sha256:
(self.root / e["file"]).unlink(missing_ok=True)
self._save(keep)
# Backwards-compatible name used by earlier callers/tests.
official_images = factory_images
+113 -96
View File
@@ -1,96 +1,113 @@
"""Matter onboarding payloads: the "MT:..." QR string and the 11-digit manual code. """Matter onboarding payloads: the "MT:..." QR string and the 11-digit manual code.
Implements the Matter spec (5.1.3 QR payload, 5.1.4 manual pairing code): Implements the Matter spec (5.1.3 QR payload, 5.1.4 manual pairing code):
bit fields packed LSB-first, Base38 in 3-byte chunks, Verhoeff check digit. bit fields packed LSB-first, Base38 in 3-byte chunks, Verhoeff check digit.
The sensorbox firmware uses the Matter SDK example commissionable data The sensorbox firmware uses the Matter SDK example commissionable data
(CONFIG_EXAMPLE_COMMISSIONABLE_DATA_PROVIDER): every v1.0 box advertises (CONFIG_EXAMPLE_COMMISSIONABLE_DATA_PROVIDER): every v1.0 box advertises
VID 0xFFF1 / PID 0x8000 / discriminator 3840 with passcode 20202021, which is VID 0xFFF1 / PID 0x8000 / discriminator 3840 with passcode 20202021, which is
exactly the sticker (QR "MT:Y.K9042C00KA0648G00", manual 3497-011-2332). exactly the sticker (QR "MT:Y.K9042C00KA0648G00", manual 3497-011-2332).
VID/PID/discriminator are taken from the box's own log when available; the VID/PID/discriminator are taken from the box's own log when available; the
passcode is never logged, so the known default is used. passcode is never logged, so the known default is used.
""" """
from __future__ import annotations from __future__ import annotations
import re import re
from dataclasses import dataclass from dataclasses import dataclass
BASE38 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-." BASE38 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-."
RENDEZVOUS_BLE = 1 << 1 RENDEZVOUS_BLE = 1 << 1
DEFAULT_PASSCODE = 20202021 # Matter SDK test passcode used by the v1.0 firmware DEFAULT_PASSCODE = 20202021 # Matter SDK test passcode used by the v1.0 firmware
DEFAULT = dict(vendor_id=0xFFF1, product_id=0x8000, discriminator=3840) DEFAULT = dict(vendor_id=0xFFF1, product_id=0x8000, discriminator=3840)
# chip[DIS]: Advertise commission parameter vendorID=65521 productID=32768 discriminator=3840/15 cm=1 cp=0 # chip[DIS]: Advertise commission parameter vendorID=65521 productID=32768 discriminator=3840/15 cm=1 cp=0
_ADVERTISE = re.compile(r"vendorID=(\d+) productID=(\d+) discriminator=(\d+)") _ADVERTISE = re.compile(r"vendorID=(\d+) productID=(\d+) discriminator=(\d+)")
@dataclass(frozen=True) @dataclass(frozen=True)
class SetupPayload: class SetupPayload:
vendor_id: int = DEFAULT["vendor_id"] vendor_id: int = DEFAULT["vendor_id"]
product_id: int = DEFAULT["product_id"] product_id: int = DEFAULT["product_id"]
discriminator: int = DEFAULT["discriminator"] discriminator: int = DEFAULT["discriminator"]
passcode: int = DEFAULT_PASSCODE passcode: int = DEFAULT_PASSCODE
rendezvous: int = RENDEZVOUS_BLE rendezvous: int = RENDEZVOUS_BLE
flow: int = 0 # standard commissioning flow flow: int = 0 # standard commissioning flow
version: int = 0 version: int = 0
from_log: bool = False # VID/PID/discriminator read from this box's log from_log: bool = False # VID/PID/discriminator read from this box's log
qr: str | None = None # exact payload reported by the box ("KOTA: matter qr=MT:...")
def qr_text(self) -> str: manual: str | None = None # exact 11-digit manual code reported by the box
fields = [(self.version, 3), (self.vendor_id, 16), (self.product_id, 16), (self.flow, 2),
(self.rendezvous, 8), (self.discriminator, 12), (self.passcode, 27), (0, 4)] @property
value, shift = 0, 0 def from_box(self) -> bool:
for v, bits in fields: return self.qr is not None
if not 0 <= v < (1 << bits):
raise ValueError(f"field value {v} does not fit in {bits} bits") def qr_text(self) -> str:
value |= v << shift if self.qr:
shift += bits return self.qr
return "MT:" + _base38(value.to_bytes(shift // 8, "little")) fields = [(self.version, 3), (self.vendor_id, 16), (self.product_id, 16), (self.flow, 2),
(self.rendezvous, 8), (self.discriminator, 12), (self.passcode, 27), (0, 4)]
def manual_code(self) -> str: value, shift = 0, 0
short = self.discriminator >> 8 # upper 4 bits for v, bits in fields:
chunk1 = short >> 2 # vid_pid_present = 0 if not 0 <= v < (1 << bits):
chunk2 = ((short & 0x3) << 14) | (self.passcode & 0x3FFF) raise ValueError(f"field value {v} does not fit in {bits} bits")
chunk3 = self.passcode >> 14 value |= v << shift
digits = f"{chunk1}{chunk2:05d}{chunk3:04d}" shift += bits
return digits + str(verhoeff_check(digits)) return "MT:" + _base38(value.to_bytes(shift // 8, "little"))
def manual_code_pretty(self) -> str: def manual_code(self) -> str:
c = self.manual_code() if self.manual:
return f"{c[:4]}-{c[4:7]}-{c[7:]}" return self.manual
short = self.discriminator >> 8 # upper 4 bits
chunk1 = short >> 2 # vid_pid_present = 0
def _base38(data: bytes) -> str: chunk2 = ((short & 0x3) << 14) | (self.passcode & 0x3FFF)
out = [] chunk3 = self.passcode >> 14
for i in range(0, len(data), 3): digits = f"{chunk1}{chunk2:05d}{chunk3:04d}"
chunk = data[i:i + 3] return digits + str(verhoeff_check(digits))
value = int.from_bytes(chunk, "little")
for _ in range({3: 5, 2: 4, 1: 2}[len(chunk)]): def manual_code_pretty(self) -> str:
value, rem = divmod(value, 38) c = self.manual_code()
out.append(BASE38[rem]) return f"{c[:4]}-{c[4:7]}-{c[7:]}"
return "".join(out)
def _base38(data: bytes) -> str:
_D = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 0, 6, 7, 8, 9, 5], [2, 3, 4, 0, 1, 7, 8, 9, 5, 6], out = []
[3, 4, 0, 1, 2, 8, 9, 5, 6, 7], [4, 0, 1, 2, 3, 9, 5, 6, 7, 8], [5, 9, 8, 7, 6, 0, 4, 3, 2, 1], for i in range(0, len(data), 3):
[6, 5, 9, 8, 7, 1, 0, 4, 3, 2], [7, 6, 5, 9, 8, 2, 1, 0, 4, 3], [8, 7, 6, 5, 9, 3, 2, 1, 0, 4], chunk = data[i:i + 3]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]] value = int.from_bytes(chunk, "little")
_P = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 5, 7, 6, 2, 8, 3, 0, 9, 4], [5, 8, 0, 3, 7, 9, 6, 1, 4, 2], for _ in range({3: 5, 2: 4, 1: 2}[len(chunk)]):
[8, 9, 1, 6, 0, 4, 3, 5, 2, 7], [9, 4, 5, 3, 1, 2, 6, 8, 7, 0], [4, 2, 8, 6, 5, 7, 3, 9, 0, 1], value, rem = divmod(value, 38)
[2, 7, 9, 3, 8, 0, 6, 4, 1, 5], [7, 0, 4, 6, 9, 1, 3, 2, 5, 8]] out.append(BASE38[rem])
_INV = [0, 4, 3, 2, 1, 5, 6, 7, 8, 9] return "".join(out)
def verhoeff_check(digits: str) -> int: _D = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 0, 6, 7, 8, 9, 5], [2, 3, 4, 0, 1, 7, 8, 9, 5, 6],
c = 0 [3, 4, 0, 1, 2, 8, 9, 5, 6, 7], [4, 0, 1, 2, 3, 9, 5, 6, 7, 8], [5, 9, 8, 7, 6, 0, 4, 3, 2, 1],
for i, d in enumerate(reversed(digits)): [6, 5, 9, 8, 7, 1, 0, 4, 3, 2], [7, 6, 5, 9, 8, 2, 1, 0, 4, 3], [8, 7, 6, 5, 9, 3, 2, 1, 0, 4],
c = _D[c][_P[(i + 1) % 8][int(d)]] [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]]
return _INV[c] _P = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 5, 7, 6, 2, 8, 3, 0, 9, 4], [5, 8, 0, 3, 7, 9, 6, 1, 4, 2],
[8, 9, 1, 6, 0, 4, 3, 5, 2, 7], [9, 4, 5, 3, 1, 2, 6, 8, 7, 0], [4, 2, 8, 6, 5, 7, 3, 9, 0, 1],
[2, 7, 9, 3, 8, 0, 6, 4, 1, 5], [7, 0, 4, 6, 9, 1, 3, 2, 5, 8]]
def payload_from_log(lines: list[str]) -> SetupPayload: _INV = [0, 4, 3, 2, 1, 5, 6, 7, 8, 9]
"""Use the box's advertised VID/PID/discriminator if seen; defaults otherwise."""
for text in reversed(lines):
if m := _ADVERTISE.search(text): def verhoeff_check(digits: str) -> int:
return SetupPayload(int(m.group(1)), int(m.group(2)), int(m.group(3)), from_log=True) c = 0
return SetupPayload() for i, d in enumerate(reversed(digits)):
c = _D[c][_P[(i + 1) % 8][int(d)]]
return _INV[c]
def payload_from_log(lines: list[str], qr: str | None = None, manual: str | None = None) -> SetupPayload:
"""Firmware 1.0.16+ reports its exact QR payload and manual code
("KOTA: matter ... qr=MT:... manual=..."); older firmware: use the
advertised VID/PID/discriminator if seen; defaults otherwise."""
base = SetupPayload()
for text in reversed(lines):
if m := _ADVERTISE.search(text):
base = SetupPayload(int(m.group(1)), int(m.group(2)), int(m.group(3)), from_log=True)
break
if qr:
return SetupPayload(base.vendor_id, base.product_id, base.discriminator, from_log=True,
qr=qr, manual=manual if manual and manual.isdigit() else None)
return base
+155 -101
View File
@@ -1,101 +1,155 @@
"""Hand-off of a diagnosis to the KOTA service system (Google Apps Script). """Hand-off of a diagnosis to the KOTA service system (Google Apps Script).
The tool opens the box's service page in the technician's browser: The tool opens the box's service page in the technician's browser:
<base><MAC>#kota-report=<base64url(JSON)> <base><MAC>#kota-report=<base64url(JSON)>
The service page (v1.1.0+) reads the fragment and pre-fills status and note; The service page (v1.1.0+) reads the fragment and pre-fills status and note;
the technician checks it, adds the location and saves - so the report is the technician checks it, adds the location and saves - so the report is
authored by their own Google login and the tool holds no credentials. authored by their own Google login and the tool holds no credentials.
The fragment is never sent to any server (redirect host or Apps Script). The fragment is never sent to any server (redirect host or Apps Script).
""" """
from __future__ import annotations from __future__ import annotations
import base64 import base64
import json import json
import re import re
from .. import __version__ from .. import __version__
from ..diag.engine import Report, Severity from ..diag.engine import Report, Severity
DEFAULT_BASE = "https://service.kota-app.com/" DEFAULT_BASE = "https://service.kota-app.com/"
NOTE_LIMIT = 4000 # the service form accepts 5000; leave room for the technician NOTE_LIMIT = 4800 # the service form and Code.gs accept 5000; leave room for the technician
# Status names exactly as in the service system (Code.gs STATUSES). # Status names exactly as in the service system (Code.gs STATUSES).
OK = "Działa poprawnie" OK = "Działa poprawnie"
CHECK = "Do sprawdzenia" CHECK = "Do sprawdzenia"
IN_SERVICE = "W trakcie serwisu" IN_SERVICE = "W trakcie serwisu"
HARDWARE = "Błąd hardware" HARDWARE = "Błąd hardware"
SOFTWARE = "Błąd software" SOFTWARE = "Błąd software"
POWER = "Problem z zasilaniem" POWER = "Problem z zasilaniem"
CONNECTIVITY = "Problem z łącznością" CONNECTIVITY = "Problem z łącznością"
# Root-finding rule id prefix -> service status (first match wins). # Root-finding rule id prefix -> service status (first match wins).
_STATUS_BY_RULE = [ _STATUS_BY_RULE = [
("reboot.brownout", POWER), ("reboot.power", POWER), ("tech.power.", POWER), ("reboot.brownout", POWER), ("reboot.power", POWER), ("tech.power.", POWER),
("sys.crash", SOFTWARE), ("reboot.watchdog", SOFTWARE), ("sys.out_of_resources", SOFTWARE), ("sys.crash", SOFTWARE), ("reboot.watchdog", SOFTWARE), ("sys.out_of_resources", SOFTWARE),
("influx.bad_request", SOFTWARE), ("ota.selfcheck_failed", SOFTWARE), ("tech.quick.hung", SOFTWARE), ("influx.bad_request", SOFTWARE), ("ota.selfcheck_failed", SOFTWARE), ("tech.quick.hung", SOFTWARE),
("rtc.init_failed", HARDWARE), ("rtc.lost_after_sync", HARDWARE), ("i2c.", HARDWARE), ("sensor.", HARDWARE), ("rtc.init_failed", HARDWARE), ("rtc.lost_after_sync", HARDWARE), ("i2c.", HARDWARE), ("sensor.", HARDWARE),
("sd.", HARDWARE), ("sen66.", HARDWARE), ("bme688.", HARDWARE), ("as7341.", HARDWARE), ("sd.", HARDWARE), ("sen66.", HARDWARE), ("bme688.", HARDWARE), ("as7341.", HARDWARE),
("mic.read_fail", HARDWARE), ("mic.silent", HARDWARE), ("tech.rtc_i2c.", HARDWARE), ("tech.sensors.", HARDWARE), ("mic.read_fail", HARDWARE), ("mic.silent", HARDWARE), ("tech.rtc_i2c.", HARDWARE), ("tech.sensors.", HARDWARE),
("tech.mic.mic_faulty", HARDWARE), ("tech.mic.mic_switch_faulty", HARDWARE), ("tech.white.sd_", HARDWARE), ("tech.mic.mic_faulty", HARDWARE), ("tech.mic.mic_switch_faulty", HARDWARE), ("tech.white.sd_", HARDWARE),
("matter.", CONNECTIVITY), ("net.", CONNECTIVITY), ("wifi.", CONNECTIVITY), ("influx.", CONNECTIVITY), ("matter.", CONNECTIVITY), ("net.", CONNECTIVITY), ("wifi.", CONNECTIVITY), ("influx.", CONNECTIVITY),
("ota.", CONNECTIVITY), ("tech.network.", CONNECTIVITY), ("ota.", CONNECTIVITY), ("tech.network.", CONNECTIVITY),
("rtc.clock_not_running", CHECK), ("reboot.", CHECK), # firmware 1.0.16+ (KOTA: lines, status, error IDs)
] ("reboot.crash", SOFTWARE), ("reboot.status_oom_watchdog", SOFTWARE), ("status.oom", SOFTWARE),
_MAC = re.compile(r"^[0-9A-F]{12}$") ("kota.low_heap", SOFTWARE),
("kota.i2c_stuck", HARDWARE), ("kota.sensor_missing", HARDWARE), ("kota.rtc_", HARDWARE),
("kota.sd_", HARDWARE), ("status.error", HARDWARE), ("status.rtc", HARDWARE), ("status.sd", HARDWARE),
def normalize_mac(mac: str) -> str: ("kota.wifi_down", CONNECTIVITY), ("kota.weak_wifi", CONNECTIVITY), ("kota.no_upload", CONNECTIVITY),
return re.sub(r"[^0-9A-Fa-f]", "", mac or "").upper() ("kota.ota_unregistered", CONNECTIVITY), ("kota.buffer_backlog", CONNECTIVITY), ("status.conn", CONNECTIVITY),
("kota.time_invalid", CHECK),
*((f"eid.{m}", HARDWARE) for m in ("SD", "ENV", "RTC", "BME", "SEN", "AS", "MIC", "FLK", "SPI")),
def service_status(report: Report) -> str: *((f"eid.{m}", CONNECTIVITY) for m in ("INF", "WIFI", "OTA", "PROV")),
"""Suggested status; the technician can change it in the form.""" ("eid.", SOFTWARE),
problems = [rc for rc in report.roots if rc.severity >= Severity.WARNING] ("rtc.clock_not_running", CHECK), ("reboot.", CHECK),
if not problems: ]
return OK if any(m == "data_uploaded" and t is not None for m, _, t in report.milestones) else CHECK _MAC = re.compile(r"^[0-9A-F]{12}$")
rid = problems[0].finding.rule_id
for prefix, status in _STATUS_BY_RULE:
if rid.startswith(prefix): def normalize_mac(mac: str) -> str:
return status return re.sub(r"[^0-9A-Fa-f]", "", mac or "").upper()
return CHECK
def service_status(report: Report) -> str:
def service_note(report: Report, limit: int = NOTE_LIMIT) -> str: """Suggested status; the technician can change it in the form."""
lines = [f"[KOTA Technician Tool {__version__}] {report.verdict}", problems = [rc for rc in report.roots if rc.severity >= Severity.WARNING]
f"Firmware: {report.firmware.describe()}", if not problems:
f"Expected LED: {report.led.capitalize()}"] return OK if any(m == "data_uploaded" and t is not None for m, _, t in report.milestones) else CHECK
reached = [label for _, label, t in report.milestones if t is not None] rid = problems[0].finding.rule_id
missing = [label for _, label, t in report.milestones if t is None] for prefix, status in _STATUS_BY_RULE:
if reached: if rid.startswith(prefix):
lines.append("OK: " + ", ".join(reached)) return status
if missing: return CHECK
lines.append("Not reached: " + ", ".join(missing))
for rc in report.roots:
f = rc.finding BOX_MARK = {"ok": "✔", "warn": "!", "bad": "✖", "info": "i"} # same marks as the Diagnosis panel
lines.append(f"- [{f.severity.label}] {f.title}") SD_WIFI = {True: "reads Wi-Fi settings from the SD card",
for c in rc.consequences: False: "does not read Wi-Fi settings from the SD card",
lines.append(f" -> {c.title}") None: "Wi-Fi-from-SD support unknown"}
if report.technician:
lines.append("Technician checks:")
lines += [f" * {t}" for t in report.technician[-12:]] def service_note(report: Report, limit: int = NOTE_LIMIT) -> str:
text = "\n".join(lines) """The Diagnosis panel as text: verdict, LED, firmware, box self-report,
return text if len(text) <= limit else text[:limit - 20].rstrip() + "\n...(shortened)" start-up progress with times, findings with details and when they were seen.
Falls back to shorter finding details when the full text does not fit the
def report_url(mac: str, report: Report, base: str = DEFAULT_BASE) -> str: service form (consequences' explanations first, then all), then truncates.
mac = normalize_mac(mac) """
if not _MAC.match(mac): for detail in ("all", "roots", "none"):
raise ValueError(f"not a box MAC address: {mac!r}") text = _note(report, detail)
payload = {"v": 1, "mac": mac, "status": service_status(report), "note": service_note(report), if len(text) <= limit:
"tool": f"v{__version__}"} return text
raw = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8") return text[:limit - 20].rstrip() + "\n...(shortened)"
frag = base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
base = base if base.endswith("/") else base + "/"
return f"{base}{mac}#kota-report={frag}" def _note(report: Report, detail: str) -> str:
fw = report.firmware
source = " (reported by the box)" if report.led_exact else ""
def decode_fragment(url: str) -> dict: lines = [f"[KOTA Technician Tool {__version__}] {report.verdict}", "",
"""Inverse of report_url (used by tests and for troubleshooting).""" f"Status LED should be: {report.led_text()}{source}"]
frag = url.split("#kota-report=", 1)[1] if report.led_reason:
return json.loads(base64.urlsafe_b64decode(frag + "=" * (-len(frag) % 4)).decode("utf-8")) lines.append(f" from: {report.led_reason}")
lines += ["", f"Firmware: {fw.describe()}", f" {SD_WIFI[fw.supports_sd_wifi]}"]
if report.box:
lines += ["", "Box self-report (KOTA lines):"]
lines += [f" {BOX_MARK.get(st, '-')} {topic}: {text}" for topic, text, st in report.box]
lines += ["", "Start-up progress (current boot):"]
lines += [f" ✔ {label} ({t / 1000:.1f} s)" if t is not None else f" ○ {label}"
for _, label, t in report.milestones]
lines += ["", "Findings - root causes first:" if report.roots else "Findings: no problems detected in the log"]
for rc in report.roots:
lines += _finding(rc.finding, "", detail in ("all", "roots"))
for c in rc.consequences:
lines += _finding(c, " ↳ ", detail == "all")
for title, items in (("Seen in earlier boots only", report.earlier),
("Resolved during this session", report.resolved)):
if items:
lines += ["", f"{title} ({len(items)}):"]
lines += [f" - [{f.severity.label}] {f.title} - {f.seen_text()}" for f in items]
if report.technician:
lines += ["", "Technician checks:"]
lines += [f" * {t}" for t in report.technician[-12:]]
return "\n".join(lines)
def _finding(f, prefix: str, detailed: bool) -> list[str]:
ind = " " * len(prefix) + " "
out = [f"{prefix}[{f.severity.label}] {f.title}"]
if detailed:
out.append(f"{ind}What it means: {f.meaning}")
if f.actions:
out.append(f"{ind}What to do:")
out += [f"{ind} {i}. {a}" for i, a in enumerate(f.actions, 1)]
out += [f"{ind}Error {eid}" + (f": {a}" if a else "") for eid, a in f.error_ids.items()]
out.append(f"{ind}{f.seen_text()}")
if f.evidence:
out.append(f"{ind}Log: {f.evidence[-1]}")
return out
def report_url(mac: str, report: Report, base: str = DEFAULT_BASE) -> str:
mac = normalize_mac(mac)
if not _MAC.match(mac):
raise ValueError(f"not a box MAC address: {mac!r}")
payload = {"v": 1, "mac": mac, "status": service_status(report), "note": service_note(report),
"tool": f"v{__version__}"}
raw = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
frag = base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
base = base if base.endswith("/") else base + "/"
return f"{base}{mac}#kota-report={frag}"
def decode_fragment(url: str) -> dict:
"""Inverse of report_url (used by tests and for troubleshooting)."""
frag = url.split("#kota-report=", 1)[1]
return json.loads(base64.urlsafe_b64decode(frag + "=" * (-len(frag) % 4)).decode("utf-8"))
+87 -85
View File
@@ -1,85 +1,87 @@
"""Quick-start cheat sheet shown on launch. """Quick-start cheat sheet shown on launch.
Targets the DEPLOYED firmware: new_system.bin, app "kota-sensorboard" LED table for firmware 1.0.16+ (firmware-diagnostics-what-changed.md,
1.0, built Jun 29 2026 11:03:32, ELF SHA256 45fa9d5b9... (verified on a status.cpp Status::pattern_for): colour AND pattern name the fault. Older
live board). That build has no Wi-Fi setup portal / SSID-on-SD support; boxes (v1.0, built Jun 29 2026) show the same colours, always solid.
those exist only in the newer, unbuilt source. The status LED is always """
SOLID; the separate small LED toggles every second while alive.
""" # (swatch colour, LED name, pattern -> meaning, first action)
LED_TABLE = [
# (swatch colour, LED name, meaning, first action) ("#2e9e44", "Green", "solid: everything OK.", "Nothing to do."),
LED_TABLE = [ ("#1fc8d8", "Cyan",
("#2e9e44", "Green", "Everything OK.", "Nothing to do."), "breathing: not paired in Matter yet<br>fast blink: a phone is connected for pairing.",
("#8e44ad", "Purple", "Pair the box in the Matter app (QR sticker or the QR code in the tool)."),
"No Internet / InfluxDB or OTA server unreachable.", ("#f4f4f4", "White",
"Check the box is commissioned in the Matter app (sticker QR code) and the " "fast blink: SD card or ENV.TXT error<br>solid: factory reset (Matter button held 5 s)<br>"
"site Wi-Fi has Internet. Board reboots itself after ~2.5 min of purple."), "breathing: Wi-Fi setup portal.",
("#d64541", "Red", "SD card is inside the case: re-seat or re-provision it. Setup portal: short-press the button to leave."),
"Sensor or hardware fault (BME688, SEN66, AS7341, microphone, flicker) " ("#d64541", "Red",
"or failed self-check after update.", "1-6 pulses: 1 BME688, 2 SEN66, 3 AS7341, 4 microphone, 5 flicker, 6 self-check failed<br>"
"Connect serial - the log names the failing sensor. Check sensor cables."), "solid: other internal error / out of memory.",
("#2f6fd6", "Blue", "Count the pulses, then check that sensor's cable. The box restarts itself after 150 s."),
"Clock (RTC DS1307) failed to start. The RTC is the first I2C device, " ("#2f6fd6", "Blue",
"so a broken I2C cable also shows blue.", "1 pulse: clock (RTC) not responding<br>2 pulses: I2C bus stuck (shorted / broken sensor cable).",
"Check the I2C harness first, then the RTC module / coin cell."), "Check the I2C cable between the boards first, then the RTC module."),
("#e6c229", "Yellow", "Firmware update downloading.", "Do not switch off. Wait."), ("#8e44ad", "Purple",
("#f08c1a", "Orange", "Self-check after an update (~2.5 min).", "solid: no network<br>blinking: server rejected the box (wrong ENV.TXT credentials).",
"Wait; should turn green (or red on failure)."), "Solid: check Wi-Fi / Internet. Blinking: re-provision the SD card with the current ENV.TXT."),
("#f4f4f4", "White", ("#e6c229", "Yellow", "blinking, faster over time: downloading an update.", "Do not switch off. Wait."),
"SD card missing/unreadable or ENV.TXT incomplete - or a factory reset is " ("#f08c1a", "Orange", "solid: self-check after an update (~2.5 min).",
"in progress (Matter button held 5 s).", "Wait; should turn green (or red on failure)."),
"If nobody pressed the Matter button: the SD card is inside the case - " ("#444444", "Off", "Firmware did not start (or crashed very early).",
"unscrew, re-seat or re-provision it."), "Check power switch & USB cable. If the small LED is also dark: re-flash."),
("#444444", "Off", "Firmware did not start (or crashed very early).", ]
"Check power switch & USB cable. If the small LED is also dark: re-flash."),
] HINTS = [
"<b>Before a self-restart</b> the LED flashes the error colour 3 times; <b>after the restart</b> it "
HINTS = [ "shows the previous error for 3 s. So a reboot loop shows its cause. Connect serial and press "
"<b>Colour keeps changing / LED goes dark every few seconds</b> = reboot loop. " "<i>Reset &amp; capture</i>: the tool reads the restart reason from the box.",
"Connect serial and press <i>Reset &amp; capture</i>: the last lines before the " "<b>Small LED next to the RGB LED</b> (heartbeat): blinks once per second while online, "
"reboot name the cause.", "double-blinks while offline. Dark or steady = firmware hung or not running.",
"<b>Small LED next to the RGB LED</b> blinks once per second while the " "<b>Serial monitor</b>: lines starting with <b>KOTA:</b> are the box's own diagnosis (boot, I2C, SD, "
"firmware runs. Not blinking = firmware hung or not running.", "clock, Matter, microphone, status, LED, and a health line every 60 s). The Diagnosis panel reads them "
"<b>Outside the case</b> (back): power switch, the <b>microphone switch</b> just above it " "directly; filter the view with <i>KOTA diagnostics + errors</i>. Error lines carry a code like "
"(off = no noise measurements), and the Matter button. Holding the " "<b>[E-SD-03]</b> - the tool shows the recommended action for it.",
"Matter button <b>5 s</b> factory-resets the box (it forgets its Matter " "<b>Outside the case</b> (back): power switch, the <b>microphone switch</b> just above it "
"network and must be commissioned again with the sticker QR code).", "(off = no noise measurements), and the Matter button. Holding the "
"<b>Inside the case</b> (unscrew): RESET and BOOT buttons and the SD card. " "Matter button <b>5 s</b> factory-resets the box (it forgets its Matter "
"Normally not needed - the tool resets the board over USB.", "network and must be commissioned again with the sticker QR code).",
"<b>Gathering messages for the first ~2 minutes</b> are normal " "<b>Inside the case</b> (unscrew): RESET and BOOT buttons and the SD card. "
"(the air-quality sensor warms up for 120 s).", "Normally not needed - the tool resets the board over USB.",
] "<b>Flashing</b> uses only the firmware files in the tool's <b>firmware</b> folder; choose the build "
"by its compile date.",
STEPS = [ ]
"Switch the sensorbox <b>power switch ON</b>.",
"Connect the laptop to the box's <b>native USB</b> port with a data-capable cable.", STEPS = [
"Open the <b>Serial monitor</b> tab, choose the sensorbox port, press " "Switch the sensorbox <b>power switch ON</b>.",
"<b>Connect</b>.", "Connect the laptop to the box's <b>native USB</b> port with a data-capable cable.",
"Press <b>Reset &amp; capture</b> to record a full boot log from the first line.", "Open the <b>Serial monitor</b> tab, choose the sensorbox port, press "
"Read the <b>Diagnosis</b> panel on the right, then open <b>Guided troubleshooting</b> " "<b>Connect</b>.",
"and start <b>Quick check</b>: the tool asks what you see and checks the log live.", "Press <b>Reset &amp; capture</b> to record a full boot log from the first line.",
] "Read the <b>Diagnosis</b> panel on the right, then open <b>Guided troubleshooting</b> "
"and start <b>Quick check</b>: the tool asks what you see and checks the log live.",
]
def cheatsheet_html() -> str:
rows = "".join(
f"<tr><td style='padding:6px'><span style='background:{c};" def cheatsheet_html() -> str:
f"border:1px solid #888'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>&nbsp;<b>{name}</b></td>" rows = "".join(
f"<td style='padding:6px'>{meaning}</td><td style='padding:6px'>{action}</td></tr>" f"<tr><td style='padding:6px'><span style='background:{c};"
for c, name, meaning, action in LED_TABLE f"border:1px solid #888'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>&nbsp;<b>{name}</b></td>"
) f"<td style='padding:6px'>{meaning}</td><td style='padding:6px'>{action}</td></tr>"
steps = "".join(f"<li>{s}</li>" for s in STEPS) for c, name, meaning, action in LED_TABLE
hints = "".join(f"<li>{h}</li>" for h in HINTS) )
return f""" steps = "".join(f"<li>{s}</li>" for s in STEPS)
<h2>Sensorbox quick start</h2> hints = "".join(f"<li>{h}</li>" for h in HINTS)
<ol>{steps}</ol> return f"""
<h3>RGB status LED (always solid colour)</h3> <h2>Sensorbox quick start</h2>
<table border='1' cellspacing='0' cellpadding='0' width='100%'> <ol>{steps}</ol>
<tr><th align='left' style='padding:6px'>LED</th> <h3>RGB status LED - colour and pattern</h3>
<th align='left' style='padding:6px'>Most likely meaning</th> <table border='1' cellspacing='0' cellpadding='0' width='100%'>
<th align='left' style='padding:6px'>First action</th></tr> <tr><th align='left' style='padding:6px'>LED</th>
{rows} <th align='left' style='padding:6px'>Pattern: meaning</th>
</table> <th align='left' style='padding:6px'>First action</th></tr>
<h3>Good to know</h3> {rows}
<ul>{hints}</ul> </table>
""" <h3>Good to know</h3>
<ul>{hints}</ul>
"""
+252 -234
View File
@@ -1,234 +1,252 @@
"""Diagnostics side panel: renders a diag.engine.Report. """Diagnostics side panel: renders a diag.engine.Report.
Layout: verdict banner, expected LED, firmware, start-up milestones, a Layout: verdict banner, expected LED (colour + pattern + meaning when the
findings tree (root causes; their consequences as children; titles only) box reports it), firmware, the box's own self-report (KOTA lines), start-up
and a wrapped detail pane for the selected finding. milestones, a findings tree (root causes; their consequences as children;
""" titles only) and a wrapped detail pane for the selected finding.
"""
from __future__ import annotations
from __future__ import annotations
from PySide6.QtCore import Qt
from PySide6.QtGui import QBrush, QColor from PySide6.QtCore import Qt
from PySide6.QtWidgets import ( from PySide6.QtGui import QBrush, QColor
QFrame, from PySide6.QtWidgets import (
QHBoxLayout, QFrame,
QLabel, QHBoxLayout,
QListWidget, QLabel,
QListWidgetItem, QListWidget,
QPushButton, QListWidgetItem,
QSizePolicy, QPushButton,
QSplitter, QSizePolicy,
QTextBrowser, QSplitter,
QTreeWidget, QTextBrowser,
QTreeWidgetItem, QTreeWidget,
QVBoxLayout, QTreeWidgetItem,
QWidget, QVBoxLayout,
) QWidget,
)
from ..diag.engine import LED, Finding, Report, Severity
from ..diag.engine import LED, Finding, Report, Severity
SEV_COLOR = {
Severity.CRITICAL: "#b03a2e", SEV_COLOR = {
Severity.ERROR: "#d9534f", Severity.CRITICAL: "#b03a2e",
Severity.WARNING: "#c77c02", Severity.ERROR: "#d9534f",
Severity.INFO: "#2e6da4", Severity.WARNING: "#c77c02",
} Severity.INFO: "#2e6da4",
# verdict banner (background, text) by verdict severity; None = healthy }
BANNER = { # verdict banner (background, text) by verdict severity; None = healthy
Severity.CRITICAL: ("#f6d5d1", "#7b1e14"), BANNER = {
Severity.ERROR: ("#f9dedc", "#8a2019"), Severity.CRITICAL: ("#f6d5d1", "#7b1e14"),
Severity.WARNING: ("#fdebc8", "#6b4400"), Severity.ERROR: ("#f9dedc", "#8a2019"),
None: ("#d8f0dd", "#1b5e2a"), Severity.WARNING: ("#fdebc8", "#6b4400"),
} None: ("#d8f0dd", "#1b5e2a"),
_KEY = Qt.ItemDataRole.UserRole }
_KEY = Qt.ItemDataRole.UserRole
BOX_STATE = {"ok": ("#1b7a33", "✔"), "warn": ("#c77c02", "!"), "bad": ("#b03a2e", "✖"), "info": ("#2e6da4", "i")}
def _heading(text: str) -> QLabel:
lbl = QLabel(text)
f = lbl.font() def _heading(text: str) -> QLabel:
f.setBold(True) lbl = QLabel(text)
lbl.setFont(f) f = lbl.font()
return lbl f.setBold(True)
lbl.setFont(f)
return lbl
def _esc(s: str) -> str:
return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
def _esc(s: str) -> str:
return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
class DiagnosticsPanel(QWidget):
def __init__(self, parent: QWidget | None = None):
super().__init__(parent) class DiagnosticsPanel(QWidget):
self.setMinimumWidth(380) def __init__(self, parent: QWidget | None = None):
super().__init__(parent)
self.verdict = QLabel(wordWrap=True) self.setMinimumWidth(380)
self.verdict.setMargin(10)
vf = self.verdict.font() self.verdict = QLabel(wordWrap=True)
vf.setPointSize(vf.pointSize() + 2) self.verdict.setMargin(10)
vf.setBold(True) vf = self.verdict.font()
self.verdict.setFont(vf) vf.setPointSize(vf.pointSize() + 2)
vf.setBold(True)
self.led_swatch = QLabel() self.verdict.setFont(vf)
self.led_swatch.setFixedSize(22, 22)
self.led_text = QLabel(wordWrap=True) self.led_swatch = QLabel()
led_row = QHBoxLayout() self.led_swatch.setFixedSize(22, 22)
led_row.addWidget(self.led_swatch, 0, Qt.AlignmentFlag.AlignTop) self.led_text = QLabel(wordWrap=True)
led_row.addWidget(self.led_text, 1) led_row = QHBoxLayout()
led_row.addWidget(self.led_swatch, 0, Qt.AlignmentFlag.AlignTop)
self.firmware = QLabel(wordWrap=True) led_row.addWidget(self.led_text, 1)
self.firmware.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
self.firmware = QLabel(wordWrap=True)
self.milestones = QListWidget() self.firmware.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
self.milestones.setFrameShape(QFrame.Shape.NoFrame)
self.milestones.setSelectionMode(QListWidget.SelectionMode.NoSelection) self.box_title = _heading("Box self-report (KOTA lines)")
self.milestones.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Maximum) self.box = QLabel(wordWrap=True)
self.box.setTextFormat(Qt.TextFormat.RichText)
self.tree = QTreeWidget() self.box.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
self.tree.setHeaderHidden(True)
self.tree.setIndentation(16) self.milestones = QListWidget()
self.tree.setTextElideMode(Qt.TextElideMode.ElideRight) self.milestones.setFrameShape(QFrame.Shape.NoFrame)
self.detail = QTextBrowser() self.milestones.setSelectionMode(QListWidget.SelectionMode.NoSelection)
self.detail.setOpenExternalLinks(False) self.milestones.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Maximum)
findings = QSplitter(Qt.Orientation.Vertical)
findings.addWidget(self.tree) self.tree = QTreeWidget()
findings.addWidget(self.detail) self.tree.setHeaderHidden(True)
findings.setSizes([220, 260]) self.tree.setIndentation(16)
self.tree.setTextElideMode(Qt.TextElideMode.ElideRight)
lay = QVBoxLayout(self) self.detail = QTextBrowser()
lay.setContentsMargins(4, 0, 0, 0) self.detail.setOpenExternalLinks(False)
lay.addWidget(self.verdict) findings = QSplitter(Qt.Orientation.Vertical)
lay.addWidget(_heading("Status LED should be")) findings.addWidget(self.tree)
lay.addLayout(led_row) findings.addWidget(self.detail)
lay.addWidget(_heading("Firmware")) findings.setSizes([220, 260])
lay.addWidget(self.firmware)
self.qr_btn = QPushButton("Matter pairing QR code...") lay = QVBoxLayout(self)
self.qr_btn.setToolTip("Show the box's Matter QR code on screen to scan with the phone") lay.setContentsMargins(4, 0, 0, 0)
lay.addWidget(self.qr_btn, 0, Qt.AlignmentFlag.AlignLeft) lay.addWidget(self.verdict)
lay.addWidget(_heading("Start-up progress (current boot)")) lay.addWidget(_heading("Status LED should be"))
lay.addWidget(self.milestones) lay.addLayout(led_row)
lay.addWidget(_heading("Findings - root causes first; click one for details")) lay.addWidget(_heading("Firmware"))
lay.addWidget(findings, 1) lay.addWidget(self.firmware)
self.qr_btn = QPushButton("Matter pairing QR code...")
self._findings: dict[str, Finding] = {} self.qr_btn.setToolTip("Show the box's Matter QR code on screen to scan with the phone")
self._selected: str | None = None lay.addWidget(self.qr_btn, 0, Qt.AlignmentFlag.AlignLeft)
# key -> expanded, chosen by the user; survives the rebuild on refresh. lay.addWidget(self.box_title)
self._expanded: dict[str, bool] = {} lay.addWidget(self.box)
self.tree.currentItemChanged.connect(self._on_select) lay.addWidget(_heading("Start-up progress (current boot)"))
self.tree.itemCollapsed.connect(lambda it: self._remember(it, False)) lay.addWidget(self.milestones)
self.tree.itemExpanded.connect(lambda it: self._remember(it, True)) lay.addWidget(_heading("Findings - root causes first; click one for details"))
lay.addWidget(findings, 1)
# ------------------------------------------------------------------
def show_report(self, r: Report) -> None: self._findings: dict[str, Finding] = {}
bg, fg = BANNER.get(r.verdict_severity, BANNER[Severity.WARNING]) self._selected: str | None = None
if r.lines == 0: # key -> expanded, chosen by the user; survives the rebuild on refresh.
bg, fg = "#e6e6e6", "#333333" self._expanded: dict[str, bool] = {}
self.verdict.setText(r.verdict) self.tree.currentItemChanged.connect(self._on_select)
self.verdict.setStyleSheet(f"QLabel {{ background:{bg}; color:{fg}; border-radius:6px; }}") self.tree.itemCollapsed.connect(lambda it: self._remember(it, False))
self.tree.itemExpanded.connect(lambda it: self._remember(it, True))
name, colour = LED[r.led]
self.led_swatch.setStyleSheet( # ------------------------------------------------------------------
f"QLabel {{ background:{colour}; border:1px solid #777; border-radius:11px; }}") def show_report(self, r: Report) -> None:
ask = "" if r.led == "UNKNOWN" else " - <i>check it matches the box</i>" bg, fg = BANNER.get(r.verdict_severity, BANNER[Severity.WARNING])
reason = f"<br><small style='color:#666'>from: {_esc(r.led_reason)}</small>" if r.led_reason else "" if r.lines == 0:
self.led_text.setText(f"<b>{name}</b>{ask}{reason}") bg, fg = "#e6e6e6", "#333333"
self.verdict.setText(r.verdict)
fw = r.firmware self.verdict.setStyleSheet(f"QLabel {{ background:{bg}; color:{fg}; border-radius:6px; }}")
sd = {True: "reads Wi-Fi settings from the SD card",
False: "does not read Wi-Fi settings from the SD card", name, colour = LED[r.led]
None: "Wi-Fi-from-SD support unknown"} self.led_swatch.setStyleSheet(
self.firmware.setText(f"{_esc(fw.describe())}<br><small>{sd[fw.supports_sd_wifi]}</small>") f"QLabel {{ background:{colour}; border:1px solid #777; border-radius:11px; }}")
ask = "" if r.led == "UNKNOWN" else " - <i>check it matches the box</i>"
self.milestones.clear() pattern = f", {_esc(r.led_pattern)}" if r.led_pattern else ""
for _, label, t in r.milestones: meaning = f" = {_esc(r.led_meaning)}" if r.led_meaning else ""
done = t is not None source = " <small style='color:#1b7a33'>(reported by the box)</small>" if r.led_exact else ""
it = QListWidgetItem(("✔ " if done else "○ ") + label reason = f"<br><small style='color:#666'>from: {_esc(r.led_reason)}</small>" if r.led_reason else ""
+ (f" ({t / 1000:.1f} s)" if done else "")) self.led_text.setText(f"<b>{name}{pattern}</b>{meaning}{source}{ask}{reason}")
it.setForeground(QBrush(QColor("#1b7a33" if done else "#8a8a8a")))
self.milestones.addItem(it) fw = r.firmware
rows = min(max(self.milestones.count(), 1), 15) sd = {True: "reads Wi-Fi settings from the SD card",
self.milestones.setFixedHeight(rows * max(self.milestones.sizeHintForRow(0), 16) + 6) False: "does not read Wi-Fi settings from the SD card",
None: "Wi-Fi-from-SD support unknown"}
self._fill_tree(r) self.firmware.setText(f"{_esc(fw.describe())}<br><small>{sd[fw.supports_sd_wifi]}</small>")
def _fill_tree(self, r: Report) -> None: self.box_title.setVisible(bool(r.box))
self.tree.blockSignals(True) self.box.setVisible(bool(r.box))
self.tree.clear() self.box.setText("<table cellspacing='0' cellpadding='1'>" + "".join(
self._findings = {} f"<tr><td style='color:{BOX_STATE[st][0]}'><b>{BOX_STATE[st][1]}</b>&nbsp;</td>"
if not r.roots: f"<td><b>{_esc(topic)}</b>&nbsp;</td><td>{_esc(text)}</td></tr>"
it = QTreeWidgetItem(["No problems detected in the log so far."]) for topic, text, st in r.box) + "</table>")
it.setForeground(0, QBrush(QColor("#1b7a33")))
self.tree.addTopLevelItem(it) self.milestones.clear()
for rc in r.roots: for _, label, t in r.milestones:
top = self._item(rc.finding, bold=True) done = t is not None
self.tree.addTopLevelItem(top) it = QListWidgetItem(("✔ " if done else "○ ") + label
for c in rc.consequences: + (f" ({t / 1000:.1f} s)" if done else ""))
top.addChild(self._item(c, prefix="↳ ")) it.setForeground(QBrush(QColor("#1b7a33" if done else "#8a8a8a")))
top.setExpanded(self._expanded.get(rc.finding.key, True)) self.milestones.addItem(it)
for title, key, items in (("Seen in earlier boots only", "grp:earlier", r.earlier), rows = min(max(self.milestones.count(), 1), 15)
("Resolved during this session", "grp:resolved", r.resolved)): self.milestones.setFixedHeight(rows * max(self.milestones.sizeHintForRow(0), 16) + 6)
if not items:
continue self._fill_tree(r)
grp = QTreeWidgetItem([f"{title} ({len(items)})"])
grp.setData(0, _KEY, key) def _fill_tree(self, r: Report) -> None:
grp.setForeground(0, QBrush(QColor("#666666"))) self.tree.blockSignals(True)
self.tree.addTopLevelItem(grp) self.tree.clear()
for f in items: self._findings = {}
grp.addChild(self._item(f, prefix="✔ " if key == "grp:resolved" else "")) if not r.roots:
grp.setExpanded(self._expanded.get(key, False)) it = QTreeWidgetItem(["No problems detected in the log so far."])
# Keep the selection across refreshes; default to the top root cause. it.setForeground(0, QBrush(QColor("#1b7a33")))
target = self._selected if self._selected in self._findings else ( self.tree.addTopLevelItem(it)
r.roots[0].finding.key if r.roots else None) for rc in r.roots:
self.tree.blockSignals(False) top = self._item(rc.finding, bold=True)
self._select(target) self.tree.addTopLevelItem(top)
for c in rc.consequences:
def _remember(self, item: QTreeWidgetItem, expanded: bool) -> None: top.addChild(self._item(c, prefix="↳ "))
if key := item.data(0, _KEY): top.setExpanded(self._expanded.get(rc.finding.key, True))
self._expanded[key] = expanded for title, key, items in (("Seen in earlier boots only", "grp:earlier", r.earlier),
("Resolved during this session", "grp:resolved", r.resolved)):
def _item(self, f: Finding, prefix: str = "", bold: bool = False) -> QTreeWidgetItem: if not items:
it = QTreeWidgetItem([f"{prefix}[{f.severity.label}] {f.title}"]) continue
it.setData(0, _KEY, f.key) grp = QTreeWidgetItem([f"{title} ({len(items)})"])
it.setForeground(0, QBrush(QColor(SEV_COLOR.get(f.severity, "#333333")))) grp.setData(0, _KEY, key)
it.setToolTip(0, f.title) grp.setForeground(0, QBrush(QColor("#666666")))
if bold: self.tree.addTopLevelItem(grp)
font = it.font(0) for f in items:
font.setBold(True) grp.addChild(self._item(f, prefix="✔ " if key == "grp:resolved" else ""))
it.setFont(0, font) grp.setExpanded(self._expanded.get(key, False))
self._findings[f.key] = f # Keep the selection across refreshes; default to the top root cause.
return it target = self._selected if self._selected in self._findings else (
r.roots[0].finding.key if r.roots else None)
def _select(self, key: str | None) -> None: self.tree.blockSignals(False)
if key is None: self._select(target)
self.detail.setHtml("<p style='color:#666'>Nothing to show yet.</p>")
return def _remember(self, item: QTreeWidgetItem, expanded: bool) -> None:
match = self.tree.findItems("*", Qt.MatchFlag.MatchWildcard | Qt.MatchFlag.MatchRecursive) if key := item.data(0, _KEY):
for it in match: self._expanded[key] = expanded
if it.data(0, _KEY) == key:
self.tree.setCurrentItem(it) def _item(self, f: Finding, prefix: str = "", bold: bool = False) -> QTreeWidgetItem:
return it = QTreeWidgetItem([f"{prefix}[{f.severity.label}] {f.title}"])
it.setData(0, _KEY, f.key)
def _on_select(self, cur: QTreeWidgetItem | None, _prev) -> None: it.setForeground(0, QBrush(QColor(SEV_COLOR.get(f.severity, "#333333"))))
key = cur.data(0, _KEY) if cur else None it.setToolTip(0, f.title)
f = self._findings.get(key or "") if bold:
if f is None: font = it.font(0)
return font.setBold(True)
self._selected = key it.setFont(0, font)
self.detail.setHtml(_detail_html(f)) self._findings[f.key] = f
return it
def _detail_html(f: Finding) -> str: def _select(self, key: str | None) -> None:
colour = SEV_COLOR.get(f.severity, "#333") if key is None:
actions = "".join(f"<li>{_esc(a)}</li>" for a in f.actions) self.detail.setHtml("<p style='color:#666'>Nothing to show yet.</p>")
seen = f"Seen {f.count}x" return
if f.first_uptime_ms is not None: match = self.tree.findItems("*", Qt.MatchFlag.MatchWildcard | Qt.MatchFlag.MatchRecursive)
seen += f", first at {f.first_uptime_ms / 1000:.1f} s after start" for it in match:
if f.resolved and f.resolved_by: if it.data(0, _KEY) == key:
seen += f" - resolved ({_esc(f.resolved_by)})" self.tree.setCurrentItem(it)
evidence = "<br>".join(_esc(e) for e in f.evidence) return
return (
f"<h3 style='color:{colour}; margin:0'>{_esc(f.title)}</h3>" def _on_select(self, cur: QTreeWidgetItem | None, _prev) -> None:
f"<p><b>What it means:</b> {_esc(f.meaning)}</p>" key = cur.data(0, _KEY) if cur else None
+ (f"<p><b>What to do:</b></p><ol>{actions}</ol>" if actions else "") f = self._findings.get(key or "")
+ f"<p style='color:#666'>{seen}</p>" if f is None:
+ (f"<p style='color:#555; font-family:Consolas,Menlo,monospace; font-size:9pt'>{evidence}</p>" return
if evidence else "") self._selected = key
) self.detail.setHtml(_detail_html(f))
def _detail_html(f: Finding) -> str:
colour = SEV_COLOR.get(f.severity, "#333")
actions = "".join(f"<li>{_esc(a)}</li>" for a in f.actions)
seen = _esc(f.seen_text())
evidence = "<br>".join(_esc(e) for e in f.evidence)
codes = "".join(f"<li><b>{_esc(eid)}</b>" + (f" - {_esc(a)}" if a else "") + "</li>"
for eid, a in f.error_ids.items())
return (
f"<h3 style='color:{colour}; margin:0'>{_esc(f.title)}</h3>"
f"<p><b>What it means:</b> {_esc(f.meaning)}</p>"
+ (f"<p><b>What to do:</b></p><ol>{actions}</ol>" if actions else "")
+ (f"<p><b>Firmware error codes</b> (error_ids.csv):</p><ul>{codes}</ul>" if codes else "")
+ f"<p style='color:#666'>{seen}</p>"
+ (f"<p style='color:#555; font-family:Consolas,Menlo,monospace; font-size:9pt'>{evidence}</p>"
if evidence else "")
)
+364 -398
View File
@@ -1,398 +1,364 @@
"""Flash firmware tab: factory image or imported developer builds; App-only by default.""" """Flash firmware tab: only the .bin files in the tool's firmware/ folder,
chosen by their compile date; App-only by default."""
from __future__ import annotations
from __future__ import annotations
import datetime as dt
import tempfile import datetime as dt
from pathlib import Path import tempfile
from pathlib import Path
from PySide6.QtCore import QObject, Qt, QTimer, Signal
from PySide6.QtWidgets import ( from PySide6.QtCore import QObject, Qt, QTimer, QUrl, Signal
QButtonGroup, from PySide6.QtGui import QDesktopServices
QCheckBox, from PySide6.QtWidgets import (
QFileDialog, QButtonGroup,
QInputDialog, QCheckBox,
QComboBox, QComboBox,
QGroupBox, QGroupBox,
QHBoxLayout, QHBoxLayout,
QLabel, QLabel,
QMessageBox, QMessageBox,
QPlainTextEdit, QPlainTextEdit,
QProgressBar, QProgressBar,
QPushButton, QPushButton,
QRadioButton, QRadioButton,
QVBoxLayout, QVBoxLayout,
QWidget, QWidget,
) )
from ..core.session import SESSIONS_DIR from ..core.session import SESSIONS_DIR
from ..flash.image import FirmwareImage, FirmwareLibrary, ImageError, bundled_images from ..diag.firmware import local_build, register_local_build, same_build
from ..flash.plan import Mode, build_plan from ..flash.image import FIRMWARE_DIR, FirmwareImage, folder_images
from ..flash.runner import FlashRunner, Result from ..flash.plan import Mode, build_plan
from ..serialio.ports import PortInfo, list_serial_ports from ..flash.runner import FlashRunner, Result
from ..serialio.ports import PortInfo, list_serial_ports
BACKUP_DIR = SESSIONS_DIR.parent / "backups"
VERIFY_TIMEOUT_MS = 45_000 BACKUP_DIR = SESSIONS_DIR.parent / "backups"
VERIFY_TIMEOUT_MS = 45_000
HELP = (
"<b>If flashing cannot connect:</b> use a data-capable USB cable directly on the laptop, close " HELP = (
"other programs using the port, then retry. Last resort (case must be opened): hold <b>BOOT</b>, " "<b>If flashing cannot connect:</b> use a data-capable USB cable directly on the laptop, close "
"press and release <b>RESET</b>, release <b>BOOT</b>, and press Start again." "other programs using the port, then retry. Last resort (case must be opened): hold <b>BOOT</b>, "
) "press and release <b>RESET</b>, release <b>BOOT</b>, and press Start again."
)
class _Bridge(QObject):
step = Signal(int, str) class _Bridge(QObject):
progress = Signal(int) step = Signal(int, str)
output = Signal(str) progress = Signal(int)
done = Signal(object) output = Signal(str)
done = Signal(object)
class FlashTab(QWidget):
def __init__(self, serial_tab, parent: QWidget | None = None): class FlashTab(QWidget):
super().__init__(parent) def __init__(self, serial_tab, parent: QWidget | None = None):
self.serial_tab = serial_tab super().__init__(parent)
self._images: list[FirmwareImage] = [] self.serial_tab = serial_tab
self._ports: list[PortInfo] = [] # before any signal can call _update() self._images: list[FirmwareImage] = []
self._runner: FlashRunner | None = None self._ports: list[PortInfo] = [] # before any signal can call _update()
self._port: PortInfo | None = None self._runner: FlashRunner | None = None
self._image: FirmwareImage | None = None self._port: PortInfo | None = None
self._image: FirmwareImage | None = None
# 1. box
box = QGroupBox("1. Sensorbox") # 1. box
self.port_combo = QComboBox(minimumWidth=360) box = QGroupBox("1. Sensorbox")
refresh = QPushButton("Refresh") self.port_combo = QComboBox(minimumWidth=360)
refresh.clicked.connect(self.refresh_ports) refresh = QPushButton("Refresh")
self.box_fw = QLabel(wordWrap=True) refresh.clicked.connect(self.refresh_ports)
bl = QVBoxLayout(box) self.box_fw = QLabel(wordWrap=True)
row = QHBoxLayout() bl = QVBoxLayout(box)
row.addWidget(self.port_combo) row = QHBoxLayout()
row.addWidget(refresh) row.addWidget(self.port_combo)
row.addStretch(1) row.addWidget(refresh)
bl.addLayout(row) row.addStretch(1)
bl.addWidget(self.box_fw) bl.addLayout(row)
bl.addWidget(self.box_fw)
# 2. firmware
fwbox = QGroupBox("2. Firmware") # 2. firmware - only files in the tool's firmware/ folder
self.image_combo = QComboBox(minimumWidth=360) fwbox = QGroupBox("2. Firmware (by compile date)")
self.import_btn = QPushButton("Import firmware file...") self.image_combo = QComboBox(minimumWidth=360)
self.import_btn.setToolTip("Add a newer build the firmware team sent you (.bin)") self.image_combo.setToolTip(f"Firmware files in {FIRMWARE_DIR}")
self.import_btn.clicked.connect(self._import) self.reload_btn = QPushButton("Refresh list")
self.remove_btn = QPushButton("Remove from list") self.reload_btn.setToolTip("Read the firmware folder again (after the firmware team added a file)")
self.remove_btn.clicked.connect(self._remove) self.reload_btn.clicked.connect(lambda: self._load_images(self._selected_sha()))
self.image_info = QLabel(wordWrap=True) self.folder_btn = QPushButton("Open firmware folder")
self.image_info.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) self.folder_btn.clicked.connect(
fl = QVBoxLayout(fwbox) lambda: QDesktopServices.openUrl(QUrl.fromLocalFile(str(FIRMWARE_DIR))))
fl.addWidget(self.image_combo) self.image_info = QLabel(wordWrap=True)
brow = QHBoxLayout() self.image_info.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
brow.addWidget(self.import_btn) fl = QVBoxLayout(fwbox)
brow.addWidget(self.remove_btn) fl.addWidget(self.image_combo)
brow.addStretch(1) brow = QHBoxLayout()
fl.addLayout(brow) brow.addWidget(self.reload_btn)
fl.addWidget(self.image_info) brow.addWidget(self.folder_btn)
self._library = FirmwareLibrary() brow.addStretch(1)
self._reference: FirmwareImage | None = None fl.addLayout(brow)
self._problems: list[str] = [] fl.addWidget(self.image_info)
self._problems: list[str] = []
# 3. mode
modebox = QGroupBox("3. What to write") # 3. mode
self.rb_app = QRadioButton("App only (recommended for repairs)") modebox = QGroupBox("3. What to write")
self.rb_full = QRadioButton("Full factory image (new or completely wiped boards)") self.rb_app = QRadioButton("App only (recommended for repairs)")
self.mode_group = QButtonGroup(self) self.rb_full = QRadioButton("Full image (new or completely wiped boards)")
self.mode_group.addButton(self.rb_app) self.mode_group = QButtonGroup(self)
self.mode_group.addButton(self.rb_full) self.mode_group.addButton(self.rb_app)
self.rb_app.setChecked(True) self.mode_group.addButton(self.rb_full)
app_note = QLabel("Replaces the firmware only. Keeps the Matter pairing, the OTA registration and the " self.rb_app.setChecked(True)
"settings stored on the box.", wordWrap=True) app_note = QLabel("Replaces the firmware only. Keeps the Matter pairing, the OTA registration and the "
full_note = QLabel("Writes everything like the factory. <b>Erases the Matter pairing and the OTA " "settings stored on the box.", wordWrap=True)
"registration</b> - the box must be paired again afterwards.", wordWrap=True) full_note = QLabel("Writes everything like the factory. <b>Erases the Matter pairing and the OTA "
for n in (app_note, full_note): "registration</b> - the box must be paired again afterwards.", wordWrap=True)
n.setContentsMargins(24, 0, 0, 6) for n in (app_note, full_note):
n.setStyleSheet("color:#555") n.setContentsMargins(24, 0, 0, 6)
self.confirm_full = QCheckBox("I understand the pairing and OTA registration will be erased") n.setStyleSheet("color:#555")
self.backup = QCheckBox("Back up the box's complete flash first (8 MB, about 3 minutes)") self.confirm_full = QCheckBox("I understand the pairing and OTA registration will be erased")
ml = QVBoxLayout(modebox) self.backup = QCheckBox("Back up the box's complete flash first (8 MB, about 3 minutes)")
for w in (self.rb_app, app_note, self.rb_full, full_note, self.confirm_full, self.backup): ml = QVBoxLayout(modebox)
ml.addWidget(w) for w in (self.rb_app, app_note, self.rb_full, full_note, self.confirm_full, self.backup):
ml.addWidget(w)
# 4. run
runbox = QGroupBox("4. Flash") # 4. run
self.plan_label = QLabel(wordWrap=True) runbox = QGroupBox("4. Flash")
self.start_btn = QPushButton("Start flashing") self.plan_label = QLabel(wordWrap=True)
self.start_btn.setMinimumHeight(36) self.start_btn = QPushButton("Start flashing")
self.start_btn.clicked.connect(self._start) self.start_btn.setMinimumHeight(36)
self.step_label = QLabel() self.start_btn.clicked.connect(self._start)
self.bar = QProgressBar() self.step_label = QLabel()
self.result = QLabel(wordWrap=True) self.bar = QProgressBar()
self.result.setMargin(8) self.result = QLabel(wordWrap=True)
self.result.setTextFormat(Qt.TextFormat.RichText) self.result.setMargin(8)
self.details_btn = QPushButton("Show esptool output") self.result.setTextFormat(Qt.TextFormat.RichText)
self.details_btn.setCheckable(True) self.details_btn = QPushButton("Show esptool output")
self.output = QPlainTextEdit(readOnly=True) self.details_btn.setCheckable(True)
self.output.setVisible(False) self.output = QPlainTextEdit(readOnly=True)
self.details_btn.toggled.connect(self.output.setVisible) self.output.setVisible(False)
rl = QVBoxLayout(runbox) self.details_btn.toggled.connect(self.output.setVisible)
for w in (self.plan_label, self.start_btn, self.step_label, self.bar, self.result, self.details_btn, self.output): rl = QVBoxLayout(runbox)
rl.addWidget(w) for w in (self.plan_label, self.start_btn, self.step_label, self.bar, self.result, self.details_btn, self.output):
help_lbl = QLabel(HELP, wordWrap=True) rl.addWidget(w)
help_lbl.setStyleSheet("color:#555") help_lbl = QLabel(HELP, wordWrap=True)
rl.addWidget(help_lbl) help_lbl.setStyleSheet("color:#555")
rl.addStretch(1) # keep the run column packed at the top rl.addWidget(help_lbl)
rl.addStretch(1) # keep the run column packed at the top
left = QVBoxLayout()
for w in (box, fwbox, modebox): left = QVBoxLayout()
left.addWidget(w) for w in (box, fwbox, modebox):
left.addStretch(1) left.addWidget(w)
lay = QHBoxLayout(self) left.addStretch(1)
lay.addLayout(left, 1) lay = QHBoxLayout(self)
lay.addWidget(runbox, 1) lay.addLayout(left, 1)
lay.addWidget(runbox, 1)
self._bridge = _Bridge()
self._bridge.step.connect(self._on_step) self._bridge = _Bridge()
self._bridge.progress.connect(self.bar.setValue) self._bridge.step.connect(self._on_step)
self._bridge.output.connect(self.output.appendPlainText) self._bridge.progress.connect(self.bar.setValue)
self._bridge.done.connect(self._on_done) self._bridge.output.connect(self.output.appendPlainText)
self._verify_timer = QTimer(self, interval=500) self._bridge.done.connect(self._on_done)
self._verify_timer.timeout.connect(self._check_verify) self._verify_timer = QTimer(self, interval=500)
self._verify_timer.timeout.connect(self._check_verify)
for sig in (self.rb_app.toggled, self.confirm_full.toggled, self.backup.toggled):
sig.connect(self._update) for sig in (self.rb_app.toggled, self.confirm_full.toggled, self.backup.toggled):
self.rb_full.toggled.connect(lambda on: self.backup.setChecked(on)) # backup default on for Full sig.connect(self._update)
self.image_combo.currentIndexChanged.connect(self._update) self.rb_full.toggled.connect(lambda on: self.backup.setChecked(on)) # backup default on for Full
self.port_combo.currentIndexChanged.connect(self._update) self.image_combo.currentIndexChanged.connect(self._update)
self.port_combo.currentIndexChanged.connect(self._update)
self._load_images()
self.refresh_ports() self._load_images()
self._show_result("", None) self.refresh_ports()
self._show_result("", None)
# ------------------------------------------------------------ setup
def _load_images(self, select_sha: str | None = None) -> None: # ------------------------------------------------------------ setup
self._problems = [] def _load_images(self, select_sha: str | None = None) -> None:
try: self._images, self._problems = folder_images()
bundled = bundled_images() for img in self._images: # lets the Serial monitor show a box build's compile date
except ImageError as exc: register_local_build(img.app.elf_sha, img.app.version, img.app.built, img.name)
bundled = [] self.image_combo.blockSignals(True)
self._problems.append(f"bundled image: {exc}") self.image_combo.clear()
factory = [i for i in bundled if not i.is_developer] for img in self._images:
self._reference = factory[0] if factory else None self.image_combo.addItem(img.label())
dev, problems = self._library.images(self._reference) if not self._images:
dev += [i for i in bundled if i.is_developer] self.image_combo.addItem("No firmware file in the firmware folder")
self._problems += problems idx = next((i for i, im in enumerate(self._images) if im.sha256 == select_sha), 0)
# Newest developer builds first, then the factory image. self.image_combo.setCurrentIndex(idx) # default: newest compile date
dev.sort(key=lambda i: i.app.built_at or dt.datetime.min, reverse=True) self.image_combo.blockSignals(False)
self._images = dev + factory self._update()
self.image_combo.blockSignals(True)
self.image_combo.clear() def _selected_sha(self) -> str | None:
for img in self._images: img = self._selected_image()
self.image_combo.addItem(img.label()) return img.sha256 if img else None
if not self._images:
self.image_combo.addItem("No firmware image available - import one") def refresh_ports(self) -> None:
idx = next((i for i, im in enumerate(self._images) if im.sha256 == select_sha), None) current = self.port_combo.currentData()
if idx is None: self._ports = list_serial_ports()
idx = len(dev) if factory else 0 # default: the factory image self.port_combo.clear()
self.image_combo.setCurrentIndex(idx) for p in self._ports:
self.image_combo.blockSignals(False) self.port_combo.addItem(p.label, p.device)
self._update() if not self._ports:
self.port_combo.addItem("No sensorbox found - check USB cable and power switch", None)
def _import(self) -> None: self.port_combo.setCurrentIndex(max(self.port_combo.findData(current), 0))
path, _ = QFileDialog.getOpenFileName(self, "Import firmware from the firmware team", str(Path.home()), self._update()
"Firmware (*.bin);;All files (*)")
if not path: def showEvent(self, event): # noqa: N802 - refresh when the tab is opened
return self.refresh_ports()
built_by, ok = QInputDialog.getText(self, "Who built this firmware?", super().showEvent(event)
"Name of the developer who built this image (shown next to it):")
if not ok: # ------------------------------------------------------------ state
return def _selected_image(self) -> FirmwareImage | None:
try: i = self.image_combo.currentIndex()
img = self._library.import_file(Path(path), self._reference, built_by=built_by) return self._images[i] if 0 <= i < len(self._images) else None
except (ImageError, OSError) as exc:
QMessageBox.warning(self, "Cannot use this file", f"This file cannot be flashed:\n\n{exc}") def _selected_port(self) -> PortInfo | None:
return dev = self.port_combo.currentData()
self._load_images(select_sha=img.sha256) return next((p for p in self._ports if p.device == dev), None)
kind = "complete image" if img.kind == "merged" else "app only"
QMessageBox.information( def _update(self) -> None:
self, "Firmware imported", img = self._selected_image()
f"{img.name}\nbuild {img.app.elf_sha[:9]}, {kind}\n\nFile fingerprint (SHA-256):\n{img.sha256}\n\n" info = ""
"Compare it with the fingerprint the firmware team sent you before flashing.") if img:
a = img.app
def _remove(self) -> None: kind = "complete image (bootloader + layout + app)" if img.kind == "merged" else "app only"
img = self._selected_image() info = (f"<b>Compiled {a.built}</b> &middot; {a.project} v{a.version}, ESP-IDF {a.idf}, {kind}<br>"
if img and img.is_developer and QMessageBox.question( f"<small>file firmware/{img.name} &middot; build {a.elf_sha[:8]} &middot; "
self, "Remove firmware", f"Remove {img.name} from this computer?") == QMessageBox.StandardButton.Yes: f"SHA-256 {img.sha256[:16]}... &middot; checksum OK</small>")
self._library.remove(img.sha256) else:
self._load_images() info = (f"Put the firmware .bin file from the firmware team into<br><code>{FIRMWARE_DIR}</code><br>"
"and press <b>Refresh list</b>. Only files in this folder can be flashed.")
def refresh_ports(self) -> None: if self._problems:
current = self.port_combo.currentData() info += ("<br><span style='color:#b03a2e'><b>Not offered:</b> "
self._ports = list_serial_ports() + "; ".join(self._problems) + "</span>")
self.port_combo.clear() self.image_info.setText(info)
for p in self._ports: # An app-only file has no bootloader/layout: Full mode is impossible.
self.port_combo.addItem(p.label, p.device) full_ok = bool(img and img.kind == "merged")
if not self._ports: self.rb_full.setEnabled(full_ok and self._runner is None)
self.port_combo.addItem("No sensorbox found - check USB cable and power switch", None) if not full_ok and self.rb_full.isChecked():
self.port_combo.setCurrentIndex(max(self.port_combo.findData(current), 0)) self.rb_app.setChecked(True)
self._update() self.box_fw.setText(self._box_text(img))
def showEvent(self, event): # noqa: N802 - refresh when the tab is opened self.confirm_full.setVisible(self.rb_full.isChecked())
self.refresh_ports() ok = bool(img and self._selected_port() and self._runner is None
super().showEvent(event) and (self.rb_app.isChecked() or self.confirm_full.isChecked()))
self.start_btn.setEnabled(ok)
# ------------------------------------------------------------ state if img and self._selected_port():
def _selected_image(self) -> FirmwareImage | None: mode = Mode.APP_ONLY if self.rb_app.isChecked() else Mode.FULL
i = self.image_combo.currentIndex() steps = ["Back up the complete flash (~3 min)"] if self.backup.isChecked() else []
return self._images[i] if 0 <= i < len(self._images) else None if mode == Mode.APP_ONLY:
steps += ["Check the box has the same partition layout", "Write the firmware app (~20 s)"]
def _selected_port(self) -> PortInfo | None: else:
dev = self.port_combo.currentData() steps += ["Write the complete image (~25 s)"]
return next((p for p in self._ports if p.device == dev), None) steps += ["Restart the box and verify the new firmware boots"]
self.plan_label.setText("<b>Plan:</b><ol>" + "".join(f"<li>{s}</li>" for s in steps) + "</ol>")
def _update(self) -> None: else:
img = self._selected_image() self.plan_label.setText("Select a sensorbox and a firmware image.")
info = ""
if img: def _box_text(self, img: FirmwareImage | None) -> str:
a = img.app fw = self.serial_tab.engine.firmware
origin = ("<b>Factory image</b> (bundled with the tool)" if not img.is_developer else if not fw.elf_sha:
"<b style='color:#c77c02'>Developer build</b> - only flash builds you received " return "Firmware on the box: unknown - connect in the Serial monitor and press Reset & capture to see it."
"from the firmware team") msg = f"Box currently runs: {fw.describe()}"
kind = "complete image (bootloader + layout + app)" if img.kind == "merged" else "app only" if not img:
info = (f"{origin}<br>{a.project} {a.version}, built {a.built}, ESP-IDF {a.idf}, {kind}<br>" return msg
f"<small>build {a.elf_sha[:9]} &middot; file SHA-256 {img.sha256[:16]}... " if same_build(fw.elf_sha, img.app.elf_sha):
f"&middot; checksum OK</small>" + (f"<br><small>{img.notes}</small>" if img.notes else "")) return msg + "<br><i>It already has this firmware. Re-flash only if you suspect the firmware is damaged.</i>"
if self._problems: local = local_build(fw.elf_sha)
info += ("<br><span style='color:#b03a2e'><b>Not offered:</b> " box_built, img_built = _parse_built(fw.built or (local[1] if local else None)), img.app.built_at
+ "; ".join(self._problems) + "</span>") if box_built and img_built and img_built > box_built:
self.image_info.setText(info) return msg + f"<br><b style='color:#2e6da4'>The selected firmware is newer (built {img.app.built}).</b>"
self.remove_btn.setEnabled(bool(img and img.is_developer) and self._runner is None) if box_built and img_built and img_built < box_built:
# An app-only file has no bootloader/layout: Full mode is impossible. return msg + ("<br><b style='color:#c77c02'>The selected firmware is OLDER than the box's (the box was "
full_ok = bool(img and img.kind == "merged") "probably updated over OTA). The box updates itself again once online.</b>")
self.rb_full.setEnabled(full_ok and self._runner is None) return msg + "<br><b style='color:#c77c02'>The box runs a different build.</b>"
if not full_ok and self.rb_full.isChecked():
self.rb_app.setChecked(True) # ------------------------------------------------------------ flash
self.box_fw.setText(self._box_text(img)) def _start(self) -> None:
img, port = self._selected_image(), self._selected_port()
self.confirm_full.setVisible(self.rb_full.isChecked()) if not img or not port:
ok = bool(img and self._selected_port() and self._runner is None return
and (self.rb_app.isChecked() or self.confirm_full.isChecked())) mode = Mode.APP_ONLY if self.rb_app.isChecked() else Mode.FULL
self.start_btn.setEnabled(ok) what = ("the firmware app (pairing and settings are kept)" if mode == Mode.APP_ONLY
if img and self._selected_port(): else "the COMPLETE image (pairing and OTA registration are erased)")
mode = Mode.APP_ONLY if self.rb_app.isChecked() else Mode.FULL if QMessageBox.question(self, "Flash firmware",
steps = ["Back up the complete flash (~3 min)"] if self.backup.isChecked() else [] f"Write {what}\n\nFirmware: v{img.app.version}, compiled {img.app.built}\n"
if mode == Mode.APP_ONLY: f"File: firmware/{img.name}\nBox: {port.label}\n\n"
steps += ["Check the box has the same partition layout", "Write the firmware app (~20 s)"] "Keep the box powered and the USB cable connected until it finishes.",
else: QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Cancel
steps += ["Write the complete factory image (~25 s)"] ) != QMessageBox.StandardButton.Ok:
steps += ["Restart the box and verify the new firmware boots"] return
self.plan_label.setText("<b>Plan:</b><ol>" + "".join(f"<li>{s}</li>" for s in steps) + "</ol>") backup_to = None
else: if self.backup.isChecked():
self.plan_label.setText("Select a sensorbox and a firmware image.") BACKUP_DIR.mkdir(parents=True, exist_ok=True)
stamp = dt.datetime.now().strftime("%Y%m%d_%H%M%S")
def _box_text(self, img: FirmwareImage | None) -> str: backup_to = BACKUP_DIR / f"{(port.mac or port.device).replace(':', '')}_{stamp}.bin"
fw = self.serial_tab.engine.firmware plan = build_plan(img, mode, port.device, Path(tempfile.mkdtemp(prefix="kota_flash_")), backup_to)
if not fw.elf_sha:
return "Firmware on the box: unknown - connect in the Serial monitor and press Reset & capture to see it." self._port, self._image = port, img
msg = f"Box currently runs: {fw.describe()}" + (f", built {fw.built}" if fw.built else "") self.serial_tab.release_port() # esptool needs the port exclusively
if not img: self.output.clear()
return msg self.output.appendPlainText("\n".join(plan.summary()))
if fw.elf_sha.startswith(img.app.elf_sha[:9]) or img.app.elf_sha.startswith(fw.elf_sha): self._show_result("", None)
return msg + "<br><i>It already has this firmware. Re-flash only if you suspect the firmware is damaged.</i>" self._runner = FlashRunner(plan, self._bridge.step.emit, self._bridge.progress.emit,
box_built, img_built = _parse_built(fw.built), img.app.built_at self._bridge.output.emit, self._bridge.done.emit)
if box_built and img_built and img_built > box_built: self._set_busy(True)
return msg + f"<br><b style='color:#2e6da4'>The selected firmware is newer (built {img.app.built}).</b>" self._runner.start()
if box_built and img_built and img_built < box_built:
return msg + ("<br><b style='color:#c77c02'>The selected firmware is OLDER than the box's (the box was " def _set_busy(self, busy: bool) -> None:
"probably updated over OTA). The box updates itself again once online.</b>") for w in (self.port_combo, self.image_combo, self.rb_app, self.backup, self.confirm_full,
return msg + "<br><b style='color:#c77c02'>The box runs a different build.</b>" self.reload_btn):
w.setEnabled(not busy)
# ------------------------------------------------------------ flash self._update()
def _start(self) -> None:
img, port = self._selected_image(), self._selected_port() def _on_step(self, i: int, title: str) -> None:
if not img or not port: n = len(self._runner.plan.steps) if self._runner else 0
return self.step_label.setText(f"Step {i + 1} of {n + 1}: {title}")
mode = Mode.APP_ONLY if self.rb_app.isChecked() else Mode.FULL
what = ("the firmware app (pairing and settings are kept)" if mode == Mode.APP_ONLY def _on_done(self, res: Result) -> None:
else "the COMPLETE factory image (pairing and OTA registration are erased)") self._runner = None
if QMessageBox.question(self, "Flash firmware", if not res.ok:
f"Write {what}\n\nImage: {img.name}\nBox: {port.label}\n\n" self._set_busy(False)
"Keep the box powered and the USB cable connected until it finishes.", self.step_label.setText("Stopped.")
QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Cancel hint = f"<p>{res.hint}</p>" if res.hint else ""
) != QMessageBox.StandardButton.Ok: self._show_result(f"<b>Flashing failed.</b> {res.message}{hint}", "error")
return self.details_btn.setChecked(True)
backup_to = None return
if self.backup.isChecked(): self.step_label.setText("Final step: restarting the box and checking which firmware it boots...")
BACKUP_DIR.mkdir(parents=True, exist_ok=True) self.bar.setValue(0)
stamp = dt.datetime.now().strftime("%Y%m%d_%H%M%S") self._show_result("Firmware written. Waiting for the box to start...", "info")
backup_to = BACKUP_DIR / f"{(port.mac or port.device).replace(':', '')}_{stamp}.bin" self.serial_tab.connect_port(self._port, capture=True)
plan = build_plan(img, mode, port.device, Path(tempfile.mkdtemp(prefix="kota_flash_")), backup_to) self._verify_ms = 0
self._verify_timer.start()
self._port, self._image = port, img
self.serial_tab.release_port() # esptool needs the port exclusively def _check_verify(self) -> None:
self.output.clear() self._verify_ms += self._verify_timer.interval()
self.output.appendPlainText("\n".join(plan.summary())) self.bar.setValue(min(100, int(100 * self._verify_ms / VERIFY_TIMEOUT_MS)))
self._show_result("", None) fw = self.serial_tab.engine.firmware
self._runner = FlashRunner(plan, self._bridge.step.emit, self._bridge.progress.emit, want = self._image.app.elf_sha[:8]
self._bridge.output.emit, self._bridge.done.emit) done = same_build(fw.elf_sha, self._image.app.elf_sha)
self._set_busy(True) if done or self._verify_ms >= VERIFY_TIMEOUT_MS:
self._runner.start() self._verify_timer.stop()
self._set_busy(False)
def _set_busy(self, busy: bool) -> None: self.bar.setValue(100)
for w in (self.port_combo, self.image_combo, self.rb_app, self.backup, self.confirm_full, self.import_btn): if done:
w.setEnabled(not busy) self.step_label.setText("Done.")
self._update() self._show_result(f"<b>Success.</b> The box boots the new firmware (build {want}). "
"Check the Diagnosis panel in the Serial monitor.", "ok")
def _on_step(self, i: int, title: str) -> None: else:
n = len(self._runner.plan.steps) if self._runner else 0 seen = fw.elf_sha[:8] if fw.elf_sha else "no boot seen"
self.step_label.setText(f"Step {i + 1} of {n + 1}: {title}") self._show_result(f"<b>Written, but not verified.</b> Expected build {want}, saw: {seen}. "
"Open the Serial monitor and press Reset & capture.", "warning")
def _on_done(self, res: Result) -> None:
self._runner = None def _show_result(self, html: str, kind: str | None) -> None:
if not res.ok: colours = {"ok": ("#2e9e44", "#e3f4e7"), "info": ("#2e6da4", "#e3edf7"),
self._set_busy(False) "warning": ("#c77c02", "#fdf0d6"), "error": ("#d9534f", "#f9e0df")}
self.step_label.setText("Stopped.") self.result.setVisible(bool(html))
hint = f"<p>{res.hint}</p>" if res.hint else "" if html:
self._show_result(f"<b>Flashing failed.</b> {res.message}{hint}", "error") border, bg = colours[kind or "info"]
self.details_btn.setChecked(True) self.result.setStyleSheet(f"QLabel {{ border:2px solid {border}; background:{bg}; border-radius:6px; }}")
return self.result.setText(html)
self.step_label.setText("Final step: restarting the box and checking which firmware it boots...")
self.bar.setValue(0)
self._show_result("Firmware written. Waiting for the box to start...", "info") def _parse_built(s: str | None) -> dt.datetime | None:
self.serial_tab.connect_port(self._port, capture=True) """'Jun 29 2026 11:03:32' (app_init "Compile time") -> datetime."""
self._verify_ms = 0 if not s:
self._verify_timer.start() return None
try:
def _check_verify(self) -> None: return dt.datetime.strptime(" ".join(s.split()), "%b %d %Y %H:%M:%S")
self._verify_ms += self._verify_timer.interval() except ValueError:
self.bar.setValue(min(100, int(100 * self._verify_ms / VERIFY_TIMEOUT_MS))) return None
fw = self.serial_tab.engine.firmware
want = self._image.app.elf_sha[:9]
done = fw.elf_sha is not None and fw.elf_sha.startswith(want)
if done or self._verify_ms >= VERIFY_TIMEOUT_MS:
self._verify_timer.stop()
self._set_busy(False)
self.bar.setValue(100)
if done:
self.step_label.setText("Done.")
self._show_result(f"<b>Success.</b> The box boots the new firmware (build {want}). "
"Check the Diagnosis panel in the Serial monitor.", "ok")
else:
seen = fw.elf_sha[:9] if fw.elf_sha else "no boot seen"
self._show_result(f"<b>Written, but not verified.</b> Expected build {want}, saw: {seen}. "
"Open the Serial monitor and press Reset & capture.", "warning")
def _show_result(self, html: str, kind: str | None) -> None:
colours = {"ok": ("#2e9e44", "#e3f4e7"), "info": ("#2e6da4", "#e3edf7"),
"warning": ("#c77c02", "#fdf0d6"), "error": ("#d9534f", "#f9e0df")}
self.result.setVisible(bool(html))
if html:
border, bg = colours[kind or "info"]
self.result.setStyleSheet(f"QLabel {{ border:2px solid {border}; background:{bg}; border-radius:6px; }}")
self.result.setText(html)
def _parse_built(s: str | None) -> dt.datetime | None:
"""'Jun 29 2026 11:03:32' (app_init "Compile time") -> datetime."""
if not s:
return None
try:
return dt.datetime.strptime(" ".join(s.split()), "%b %d %Y %H:%M:%S")
except ValueError:
return None
+424 -415
View File
@@ -1,415 +1,424 @@
from __future__ import annotations from __future__ import annotations
from pathlib import Path from pathlib import Path
from PySide6.QtCore import QCoreApplication, QObject, QSettings, Qt, QTimer, QUrl, Signal from PySide6.QtCore import QCoreApplication, QObject, QSettings, Qt, QTimer, QUrl, Signal
from PySide6.QtGui import QColor, QDesktopServices, QFont, QGuiApplication, QTextCharFormat, QTextCursor from PySide6.QtGui import QColor, QDesktopServices, QFont, QGuiApplication, QTextCharFormat, QTextCursor
from PySide6.QtWidgets import ( from PySide6.QtWidgets import (
QCheckBox, QCheckBox,
QComboBox, QComboBox,
QFileDialog, QFileDialog,
QHBoxLayout, QHBoxLayout,
QInputDialog, QInputDialog,
QLabel, QLabel,
QMainWindow, QMainWindow,
QMessageBox, QMessageBox,
QPlainTextEdit, QPlainTextEdit,
QPushButton, QPushButton,
QSplitter, QSplitter,
QTabWidget, QTabWidget,
QTextBrowser, QTextBrowser,
QVBoxLayout, QVBoxLayout,
QWidget, QWidget,
) )
from .. import __version__ from .. import __version__
from ..core.logfile import read_log_file from ..core.logfile import read_log_file
from ..core.logline import LineKind, LogLine, host_event from ..core.logline import LineKind, LogLine, host_event
from ..core.session import SessionLog from ..core.session import SessionLog
from ..diag.engine import DiagnosticsEngine from ..diag.engine import DiagnosticsEngine
from ..diag.guides import GuideRunner from ..diag.guides import GuideRunner
from ..serialio.manager import SerialManager, State from ..serialio.manager import SerialManager, State
from ..serialio.ports import PortInfo, list_serial_ports from ..serialio.ports import PortInfo, list_serial_ports
from ..matter.payload import SetupPayload, payload_from_log from ..matter.payload import SetupPayload, payload_from_log
from ..service.report import DEFAULT_BASE, normalize_mac, report_url from ..service.report import DEFAULT_BASE, normalize_mac, report_url
from .cheatsheet import cheatsheet_html from .cheatsheet import cheatsheet_html
from .diag_panel import DiagnosticsPanel from .diag_panel import DiagnosticsPanel
from .flash_tab import FlashTab from .flash_tab import FlashTab
from .matter_qr import MatterQrDialog from .matter_qr import MatterQrDialog
from .guide_panel import GuidePanel from .guide_panel import GuidePanel
from .sd_tab import SdTab from .sd_tab import SdTab
MAX_LINES = 20000 MAX_LINES = 20000
LEVEL_FILTERS = {"All lines": None, "Warnings + errors": {"W", "E"}, "Errors only": {"E"}} # "KOTA" = the firmware's structured diagnostic lines (1.0.16+) plus errors.
COLORS = { LEVEL_FILTERS = {"All lines": None, "KOTA diagnostics + errors": "KOTA",
"E": "#ff6b6b", "Warnings + errors": {"W", "E"}, "Errors only": {"E"}}
"W": "#f5c451", COLORS = {
"I": "#d4d4d4", "E": "#ff6b6b",
LineKind.BOOT: "#6fc3ff", "W": "#f5c451",
LineKind.RESET: "#6fc3ff", "I": "#d4d4d4",
LineKind.PANIC: "#ff4dd2", LineKind.BOOT: "#6fc3ff",
LineKind.HOST: "#7ee07e", LineKind.RESET: "#6fc3ff",
LineKind.RAW: "#a8a8a8", LineKind.PANIC: "#ff4dd2",
} LineKind.HOST: "#7ee07e",
LineKind.KOTA: "#5fd7e8",
LineKind.RAW: "#a8a8a8",
class _Bridge(QObject): }
"""Marshals SerialManager callbacks (reader thread) onto the UI thread."""
line = Signal(object) class _Bridge(QObject):
state = Signal(object, str) """Marshals SerialManager callbacks (reader thread) onto the UI thread."""
line = Signal(object)
class SerialTab(QWidget): state = Signal(object, str)
def __init__(self, parent: QWidget | None = None):
super().__init__(parent)
self._bridge = _Bridge() class SerialTab(QWidget):
self._bridge.line.connect(self._on_line) def __init__(self, parent: QWidget | None = None):
self._bridge.state.connect(self._on_state) super().__init__(parent)
self._manager = SerialManager(self._bridge.line.emit, self._bridge.state.emit) self._bridge = _Bridge()
self._session = SessionLog() self._bridge.line.connect(self._on_line)
self._ports: list[PortInfo] = [] self._bridge.state.connect(self._on_state)
self._counts = {"E": 0, "W": 0, "boots": 0} self._manager = SerialManager(self._bridge.line.emit, self._bridge.state.emit)
self._engine = DiagnosticsEngine() self._session = SessionLog()
self._diag_dirty = True self._ports: list[PortInfo] = []
self._runner = GuideRunner(self._engine, on_action=self._guide_action, on_log=self._guide_log) self._counts = {"E": 0, "W": 0, "boots": 0}
self._engine = DiagnosticsEngine()
# --- controls self._diag_dirty = True
self.port_combo = QComboBox(minimumWidth=320) self._runner = GuideRunner(self._engine, on_action=self._guide_action, on_log=self._guide_log)
self.all_ports = QCheckBox("Show all ports")
self.refresh_btn = QPushButton("Refresh") # --- controls
self.connect_btn = QPushButton("Connect") self.port_combo = QComboBox(minimumWidth=320)
self.reset_btn = QPushButton("Reset && capture") self.all_ports = QCheckBox("Show all ports")
self.reset_btn.setToolTip("Reboot the sensorbox and record the log from the first boot line") self.refresh_btn = QPushButton("Refresh")
self.filter_combo = QComboBox() self.connect_btn = QPushButton("Connect")
self.filter_combo.addItems(LEVEL_FILTERS) self.reset_btn = QPushButton("Reset && capture")
self.clear_btn = QPushButton("Clear view") self.reset_btn.setToolTip("Reboot the sensorbox and record the log from the first boot line")
self.save_btn = QPushButton("Save view as...") self.filter_combo = QComboBox()
self.folder_btn = QPushButton("Open logs folder") self.filter_combo.addItems(LEVEL_FILTERS)
self.analyze_btn = QPushButton("Analyze log file...") self.clear_btn = QPushButton("Clear view")
self.analyze_btn.setToolTip("Load a saved session log or serial capture and diagnose it") self.save_btn = QPushButton("Save view as...")
self.copy_btn = QPushButton("Copy report") self.folder_btn = QPushButton("Open logs folder")
self.copy_btn.setToolTip("Copy the diagnosis as text (e.g. to send to the firmware team)") self.analyze_btn = QPushButton("Analyze log file...")
self.service_btn = QPushButton("Service report...") self.analyze_btn.setToolTip("Load a saved session log or serial capture and diagnose it")
self.service_btn.setToolTip("Open this box's page in the KOTA service system with the diagnosis " self.copy_btn = QPushButton("Copy report")
"filled in; check it and press Save there") self.copy_btn.setToolTip("Copy the diagnosis as text (e.g. to send to the firmware team)")
self._settings = QSettings("KOTA", "TechnicianTool") self.service_btn = QPushButton("Service report...")
self.auto_service = QCheckBox("Open service report on disconnect") self.service_btn.setToolTip("Open this box's page in the KOTA service system with the diagnosis "
self.auto_service.setChecked(self._settings.value("service/auto", False, type=bool)) "filled in; check it and press Save there")
self.auto_service.toggled.connect(lambda on: self._settings.setValue("service/auto", on)) self._settings = QSettings("KOTA", "TechnicianTool")
self._active_port: PortInfo | None = None self.auto_service = QCheckBox("Open service report on disconnect")
self.auto_service.setChecked(self._settings.value("service/auto", False, type=bool))
row1 = QHBoxLayout() self.auto_service.toggled.connect(lambda on: self._settings.setValue("service/auto", on))
for w in (QLabel("Port:"), self.port_combo, self.all_ports, self.refresh_btn, self._active_port: PortInfo | None = None
self.connect_btn, self.reset_btn):
row1.addWidget(w) row1 = QHBoxLayout()
row1.addStretch(1) for w in (QLabel("Port:"), self.port_combo, self.all_ports, self.refresh_btn,
row2 = QHBoxLayout() self.connect_btn, self.reset_btn):
for w in (QLabel("Show:"), self.filter_combo, self.clear_btn, self.save_btn, self.folder_btn, row1.addWidget(w)
self.analyze_btn, self.copy_btn, self.service_btn, self.auto_service): row1.addStretch(1)
row2.addWidget(w) row2 = QHBoxLayout()
row2.addStretch(1) for w in (QLabel("Show:"), self.filter_combo, self.clear_btn, self.save_btn, self.folder_btn,
self.analyze_btn, self.copy_btn, self.service_btn, self.auto_service):
self.view = QPlainTextEdit(readOnly=True) row2.addWidget(w)
self.view.setMaximumBlockCount(MAX_LINES) row2.addStretch(1)
self.view.setLineWrapMode(QPlainTextEdit.LineWrapMode.NoWrap)
mono = QFont("Menlo" if QFont("Menlo").exactMatch() else "Consolas") self.view = QPlainTextEdit(readOnly=True)
mono.setStyleHint(QFont.StyleHint.Monospace) self.view.setMaximumBlockCount(MAX_LINES)
mono.setPointSize(10) self.view.setLineWrapMode(QPlainTextEdit.LineWrapMode.NoWrap)
self.view.setFont(mono) mono = QFont("Menlo" if QFont("Menlo").exactMatch() else "Consolas")
self.view.setStyleSheet("QPlainTextEdit { background:#1e1e1e; color:#d4d4d4; }") mono.setStyleHint(QFont.StyleHint.Monospace)
mono.setPointSize(10)
self.diag = DiagnosticsPanel() self.view.setFont(mono)
self.guide = GuidePanel(self._runner, self._engine, matter_payload=self.matter_payload) self.view.setStyleSheet("QPlainTextEdit { background:#1e1e1e; color:#d4d4d4; }")
self.side_tabs = QTabWidget()
self.side_tabs.addTab(self.diag, "Diagnosis") self.diag = DiagnosticsPanel()
self.side_tabs.addTab(self.guide, "Guided troubleshooting") self.guide = GuidePanel(self._runner, self._engine, matter_payload=self.matter_payload)
split = QSplitter(Qt.Orientation.Horizontal) self.side_tabs = QTabWidget()
split.addWidget(self.view) self.side_tabs.addTab(self.diag, "Diagnosis")
split.addWidget(self.side_tabs) self.side_tabs.addTab(self.guide, "Guided troubleshooting")
split.setStretchFactor(0, 3) split = QSplitter(Qt.Orientation.Horizontal)
split.setStretchFactor(1, 2) split.addWidget(self.view)
split.setSizes([700, 480]) split.addWidget(self.side_tabs)
split.setStretchFactor(0, 3)
self.status = QLabel() split.setStretchFactor(1, 2)
layout = QVBoxLayout(self) split.setSizes([700, 480])
layout.addLayout(row1)
layout.addLayout(row2) self.status = QLabel()
layout.addWidget(split, 1) layout = QVBoxLayout(self)
layout.addWidget(self.status) layout.addLayout(row1)
layout.addLayout(row2)
# --- wiring layout.addWidget(split, 1)
self.refresh_btn.clicked.connect(self.refresh_ports) layout.addWidget(self.status)
self.all_ports.toggled.connect(self.refresh_ports)
self.connect_btn.clicked.connect(self._toggle_connect) # --- wiring
self.reset_btn.clicked.connect(self._manager.reset_board) self.refresh_btn.clicked.connect(self.refresh_ports)
self.clear_btn.clicked.connect(self.view.clear) self.all_ports.toggled.connect(self.refresh_ports)
self.save_btn.clicked.connect(self._save_view) self.connect_btn.clicked.connect(self._toggle_connect)
self.folder_btn.clicked.connect(self._open_folder) self.reset_btn.clicked.connect(self._manager.reset_board)
self.analyze_btn.clicked.connect(self._analyze_file) self.clear_btn.clicked.connect(self.view.clear)
self.copy_btn.clicked.connect(self._copy_report) self.save_btn.clicked.connect(self._save_view)
self.service_btn.clicked.connect(lambda: self._open_service_report(auto=False)) self.folder_btn.clicked.connect(self._open_folder)
self.diag.qr_btn.clicked.connect(lambda: MatterQrDialog(self.matter_payload(), self).exec()) self.analyze_btn.clicked.connect(self._analyze_file)
self.copy_btn.clicked.connect(self._copy_report)
# Report refresh is throttled; lines can arrive at >100/s. self.service_btn.clicked.connect(lambda: self._open_service_report(auto=False))
self._diag_timer = QTimer(self, interval=400) self.diag.qr_btn.clicked.connect(lambda: MatterQrDialog(self.matter_payload(), self).exec())
self._diag_timer.timeout.connect(self._refresh_diag)
self._diag_timer.start() # Report refresh is throttled; lines can arrive at >100/s.
self._diag_timer = QTimer(self, interval=400)
# Auto-detect a box being plugged in while idle. self._diag_timer.timeout.connect(self._refresh_diag)
self._poll = QTimer(self, interval=2000) self._diag_timer.start()
self._poll.timeout.connect(self._auto_refresh)
self._poll.start() # Auto-detect a box being plugged in while idle.
self._poll = QTimer(self, interval=2000)
self.refresh_ports() self._poll.timeout.connect(self._auto_refresh)
self._on_state(State.DISCONNECTED, "") self._poll.start()
# ---- ports ------------------------------------------------------- self.refresh_ports()
def refresh_ports(self) -> None: self._on_state(State.DISCONNECTED, "")
current = self.port_combo.currentData()
self._ports = list_serial_ports(include_all=self.all_ports.isChecked()) # ---- ports -------------------------------------------------------
self.port_combo.clear() def refresh_ports(self) -> None:
for p in self._ports: current = self.port_combo.currentData()
self.port_combo.addItem(p.label, p.device) self._ports = list_serial_ports(include_all=self.all_ports.isChecked())
if not self._ports: self.port_combo.clear()
self.port_combo.addItem("No sensorbox found - check USB cable and power switch", None) for p in self._ports:
idx = self.port_combo.findData(current) self.port_combo.addItem(p.label, p.device)
self.port_combo.setCurrentIndex(max(idx, 0)) if not self._ports:
self.port_combo.addItem("No sensorbox found - check USB cable and power switch", None)
def _auto_refresh(self) -> None: idx = self.port_combo.findData(current)
if self._manager.is_running: self.port_combo.setCurrentIndex(max(idx, 0))
return
devices = [p.device for p in list_serial_ports(self.all_ports.isChecked())] def _auto_refresh(self) -> None:
if devices != [p.device for p in self._ports]: if self._manager.is_running:
self.refresh_ports() return
devices = [p.device for p in list_serial_ports(self.all_ports.isChecked())]
def _selected_port(self) -> PortInfo | None: if devices != [p.device for p in self._ports]:
dev = self.port_combo.currentData() self.refresh_ports()
return next((p for p in self._ports if p.device == dev), None)
def _selected_port(self) -> PortInfo | None:
# ---- connection -------------------------------------------------- dev = self.port_combo.currentData()
def _toggle_connect(self) -> None: return next((p for p in self._ports if p.device == dev), None)
if self._manager.is_running:
# Session file is closed in _on_state(DISCONNECTED), after the # ---- connection --------------------------------------------------
# reader thread's final queued lines have been written. def _toggle_connect(self) -> None:
self._manager.disconnect() if self._manager.is_running:
return # Session file is closed in _on_state(DISCONNECTED), after the
port = self._selected_port() # reader thread's final queued lines have been written.
if port is None: self._manager.disconnect()
return return
self._connect(port) port = self._selected_port()
if port is None:
def _connect(self, port: PortInfo) -> None: return
self._counts = {"E": 0, "W": 0, "boots": 0} self._connect(port)
self._engine.reset()
self._runner.cancel() def _connect(self, port: PortInfo) -> None:
self._diag_dirty = True self._counts = {"E": 0, "W": 0, "boots": 0}
self._session.start(port.mac or port.device) self._engine.reset()
self._active_port = port self._runner.cancel()
self._manager.connect(port) self._diag_dirty = True
self._session.start(port.mac or port.device)
def matter_payload(self) -> SetupPayload: self._active_port = port
"""Pairing payload from this box's log (VID/PID/discriminator), defaults otherwise.""" self._manager.connect(port)
return payload_from_log([self._engine.matter_advert] if self._engine.matter_advert else [])
def matter_payload(self) -> SetupPayload:
# ---- service system ------------------------------------------------- """Pairing payload reported by this box (KOTA: matter), from its log, or the defaults."""
def _service_base(self) -> str: return payload_from_log([self._engine.matter_advert] if self._engine.matter_advert else [],
return str(self._settings.value("service/base", DEFAULT_BASE)) self._engine.matter_qr, self._engine.matter_manual)
def _open_service_report(self, auto: bool) -> None: # ---- service system -------------------------------------------------
mac = normalize_mac(self._engine.mac or (self._active_port.mac if self._active_port else "") or "") def _service_base(self) -> str:
if len(mac) != 12: return str(self._settings.value("service/base", DEFAULT_BASE))
if not auto:
QMessageBox.information(self, "Service report", "The box's MAC address is not known yet. " def _open_service_report(self, auto: bool) -> None:
"Connect to the box and press Reset & capture first.") mac = normalize_mac(self._engine.mac or (self._active_port.mac if self._active_port else "") or "")
return if len(mac) != 12:
url = report_url(mac, self._engine.report(), self._service_base()) if not auto:
QDesktopServices.openUrl(QUrl(url)) QMessageBox.information(self, "Service report", "The box's MAC address is not known yet. "
# Log that it happened, not the report itself (it is already in the session log). "Connect to the box and press Reset & capture first.")
self._guide_log(f"service report for {mac} opened in the browser - check it and press Save there") return
url = report_url(mac, self._engine.report(), self._service_base())
# ---- hand-off with the flash tab ------------------------------------ QDesktopServices.openUrl(QUrl(url))
@property # Log that it happened, not the report itself (it is already in the session log).
def engine(self) -> DiagnosticsEngine: self._guide_log(f"service report for {mac} opened in the browser - check it and press Save there")
return self._engine
# ---- hand-off with the flash tab ------------------------------------
def release_port(self) -> None: @property
"""Stop monitoring so esptool can open the port exclusively.""" def engine(self) -> DiagnosticsEngine:
if self._manager.is_running: return self._engine
self._no_auto_service = True # a flash hand-off is not the end of a session
self._manager.disconnect() # joins the reader thread def release_port(self) -> None:
QCoreApplication.processEvents() # deliver its queued final lines/state now """Stop monitoring so esptool can open the port exclusively."""
self._no_auto_service = False if self._manager.is_running:
self._no_auto_service = True # a flash hand-off is not the end of a session
def connect_port(self, port: PortInfo, capture: bool = True) -> None: self._manager.disconnect() # joins the reader thread
"""Monitor `port`; with capture, restart the box once connected to record its boot.""" QCoreApplication.processEvents() # deliver its queued final lines/state now
self.release_port() self._no_auto_service = False
idx = self.port_combo.findData(port.device)
if idx < 0: def connect_port(self, port: PortInfo, capture: bool = True) -> None:
self.port_combo.addItem(port.label, port.device) """Monitor `port`; with capture, restart the box once connected to record its boot."""
self._ports.append(port) self.release_port()
idx = self.port_combo.count() - 1 idx = self.port_combo.findData(port.device)
self.port_combo.setCurrentIndex(idx) if idx < 0:
self._reset_on_connect = capture self.port_combo.addItem(port.label, port.device)
self._connect(port) self._ports.append(port)
idx = self.port_combo.count() - 1
def _on_state(self, state: State, detail: str) -> None: self.port_combo.setCurrentIndex(idx)
running = state != State.DISCONNECTED self._reset_on_connect = capture
if not running and self._manager.is_running: self._connect(port)
return # stale event from a session that was already replaced
if state == State.CONNECTED and getattr(self, "_reset_on_connect", False): def _on_state(self, state: State, detail: str) -> None:
self._reset_on_connect = False running = state != State.DISCONNECTED
QTimer.singleShot(300, self._manager.reset_board) if not running and self._manager.is_running:
if not running and self._session.path is not None: return # stale event from a session that was already replaced
self._session.write_report(self._engine.report().to_text()) if state == State.CONNECTED and getattr(self, "_reset_on_connect", False):
if (self.auto_service.isChecked() and self._engine.lines self._reset_on_connect = False
and not getattr(self, "_no_auto_service", False)): QTimer.singleShot(300, self._manager.reset_board)
self._open_service_report(auto=True) if not running and self._session.path is not None:
self._session.stop() self._session.write_report(self._engine.report().to_text())
self.connect_btn.setText("Disconnect" if running else "Connect") if (self.auto_service.isChecked() and self._engine.lines
self.reset_btn.setEnabled(state == State.CONNECTED) and not getattr(self, "_no_auto_service", False)):
self.port_combo.setEnabled(not running) self._open_service_report(auto=True)
self.all_ports.setEnabled(not running) self._session.stop()
self.refresh_btn.setEnabled(not running) self.connect_btn.setText("Disconnect" if running else "Connect")
# Offline analysis would mix with the live session; disconnect first. self.reset_btn.setEnabled(state == State.CONNECTED)
self.analyze_btn.setEnabled(not running) self.port_combo.setEnabled(not running)
self._state_text = f"{state.value}" + (f" ({detail})" if detail else "") self.all_ports.setEnabled(not running)
self._update_status() self.refresh_btn.setEnabled(not running)
# Offline analysis would mix with the live session; disconnect first.
def _update_status(self) -> None: self.analyze_btn.setEnabled(not running)
sess = f" | Session log: {self._session.path}" if self._session.path else "" self._state_text = f"{state.value}" + (f" ({detail})" if detail else "")
c = self._counts self._update_status()
self.status.setText(
f"{getattr(self, '_state_text', '')} | boots seen: {c['boots']} " def _update_status(self) -> None:
f"errors: {c['E']} warnings: {c['W']}{sess}" sess = f" | Session log: {self._session.path}" if self._session.path else ""
) c = self._counts
self.status.setText(
# ---- lines ------------------------------------------------------- f"{getattr(self, '_state_text', '')} | boots seen: {c['boots']} "
def _on_line(self, line: LogLine) -> None: f"errors: {c['E']} warnings: {c['W']}{sess}"
self._session.write(line) )
self._engine.feed(line)
self._runner.feed(line) # ---- lines -------------------------------------------------------
self._diag_dirty = True def _on_line(self, line: LogLine) -> None:
if line.kind == LineKind.BOOT: self._session.write(line)
self._counts["boots"] += 1 self._engine.feed(line)
if line.level in ("E", "W"): self._runner.feed(line)
self._counts[line.level] += 1 self._diag_dirty = True
self._update_status() if line.kind == LineKind.BOOT:
self._counts["boots"] += 1
allowed = LEVEL_FILTERS[self.filter_combo.currentText()] if line.level in ("E", "W"):
if allowed is not None and line.kind != LineKind.HOST and not ( self._counts[line.level] += 1
line.level in allowed or line.kind in (LineKind.PANIC, LineKind.BOOT, LineKind.RESET) self._update_status()
):
return if self._visible(line):
self._append(line) self._append(line)
def _append(self, line: LogLine) -> None: def _visible(self, line: LogLine) -> bool:
sb = self.view.verticalScrollBar() allowed = LEVEL_FILTERS[self.filter_combo.currentText()]
at_bottom = sb.value() >= sb.maximum() - 4 if allowed is None or line.kind in (LineKind.HOST, LineKind.PANIC, LineKind.BOOT, LineKind.RESET):
fmt = QTextCharFormat() return True
fmt.setForeground(QColor(COLORS.get(line.level) or COLORS.get(line.kind, "#d4d4d4"))) if allowed == "KOTA":
if line.kind in (LineKind.PANIC, LineKind.BOOT, LineKind.HOST): return line.kind == LineKind.KOTA or line.level == "E"
fmt.setFontWeight(QFont.Weight.Bold) return line.level in allowed
cur = QTextCursor(self.view.document())
cur.movePosition(QTextCursor.MoveOperation.End) def _append(self, line: LogLine) -> None:
if not self.view.document().isEmpty(): sb = self.view.verticalScrollBar()
cur.insertBlock() at_bottom = sb.value() >= sb.maximum() - 4
cur.insertText(line.text, fmt) fmt = QTextCharFormat()
if at_bottom: colour = COLORS.get(line.kind) if line.kind == LineKind.KOTA and line.level == "I" else None
sb.setValue(sb.maximum()) fmt.setForeground(QColor(colour or COLORS.get(line.level) or COLORS.get(line.kind, "#d4d4d4")))
if line.kind in (LineKind.PANIC, LineKind.BOOT, LineKind.HOST) or line.record in ("boot", "status"):
# ---- diagnostics ------------------------------------------------- fmt.setFontWeight(QFont.Weight.Bold)
def _refresh_diag(self) -> None: cur = QTextCursor(self.view.document())
if self._diag_dirty: cur.movePosition(QTextCursor.MoveOperation.End)
self._diag_dirty = False if not self.view.document().isEmpty():
self.diag.show_report(self._engine.report()) cur.insertBlock()
self.guide.refresh() # countdowns and timeouts need a steady tick cur.insertText(line.text, fmt)
if at_bottom:
# ---- guided troubleshooting hooks ------------------------------------ sb.setValue(sb.maximum())
def _guide_action(self, action: str) -> bool:
if action == "reset" and self._manager.state == State.CONNECTED: # ---- diagnostics -------------------------------------------------
self._manager.reset_board() def _refresh_diag(self) -> None:
return True if self._diag_dirty:
return False self._diag_dirty = False
self.diag.show_report(self._engine.report())
def _guide_log(self, text: str) -> None: self.guide.refresh() # countdowns and timeouts need a steady tick
# Technician answers go into the session log and the log view.
line = host_event(text) # ---- guided troubleshooting hooks ------------------------------------
self._session.write(line) def _guide_action(self, action: str) -> bool:
self._append(line) if action == "reset" and self._manager.state == State.CONNECTED:
self._diag_dirty = True self._manager.reset_board()
return True
def _copy_report(self) -> None: return False
QGuiApplication.clipboard().setText(self._engine.report().to_text())
def _guide_log(self, text: str) -> None:
def _analyze_file(self) -> None: # Technician answers go into the session log and the log view.
path, _ = QFileDialog.getOpenFileName( line = host_event(text)
self, "Analyze log file", str(self._session.root), "Logs (*.log *.txt);;All files (*)") self._session.write(line)
if not path: self._append(line)
return self._diag_dirty = True
lines = read_log_file(Path(path))
self.view.clear() def _copy_report(self) -> None:
self._engine.reset() QGuiApplication.clipboard().setText(self._engine.report().to_text())
self._runner.cancel()
self._counts = {"E": 0, "W": 0, "boots": 0} def _analyze_file(self) -> None:
for line in lines: path, _ = QFileDialog.getOpenFileName(
self._engine.feed(line) self, "Analyze log file", str(self._session.root), "Logs (*.log *.txt);;All files (*)")
if line.kind == LineKind.BOOT: if not path:
self._counts["boots"] += 1 return
if line.level in ("E", "W"): lines = read_log_file(Path(path))
self._counts[line.level] += 1 self.view.clear()
self._append(line) self._engine.reset()
self._state_text = f"Analyzed file: {Path(path).name} ({len(lines)} lines)" self._runner.cancel()
self._update_status() self._counts = {"E": 0, "W": 0, "boots": 0}
self._diag_dirty = True for line in lines:
self._refresh_diag() self._engine.feed(line)
if line.kind == LineKind.BOOT:
# ---- misc -------------------------------------------------------- self._counts["boots"] += 1
def _save_view(self) -> None: if line.level in ("E", "W"):
path, _ = QFileDialog.getSaveFileName(self, "Save log view", "sensorbox_log.txt", "Text (*.txt)") self._counts[line.level] += 1
if path: self._append(line)
with open(path, "w", encoding="utf-8") as fh: self._state_text = f"Analyzed file: {Path(path).name} ({len(lines)} lines)"
fh.write(self.view.toPlainText()) self._update_status()
self._diag_dirty = True
def _open_folder(self) -> None: self._refresh_diag()
self._session.root.mkdir(parents=True, exist_ok=True)
QDesktopServices.openUrl(QUrl.fromLocalFile(str(self._session.root))) # ---- misc --------------------------------------------------------
def _save_view(self) -> None:
def shutdown(self) -> None: path, _ = QFileDialog.getSaveFileName(self, "Save log view", "sensorbox_log.txt", "Text (*.txt)")
self._manager.disconnect() if path:
self._session.stop() with open(path, "w", encoding="utf-8") as fh:
fh.write(self.view.toPlainText())
class MainWindow(QMainWindow): def _open_folder(self) -> None:
def __init__(self): self._session.root.mkdir(parents=True, exist_ok=True)
super().__init__() QDesktopServices.openUrl(QUrl.fromLocalFile(str(self._session.root)))
self.setWindowTitle(f"KOTA Sensorbox Technician Tool v{__version__}")
self.resize(1200, 800) def shutdown(self) -> None:
tabs = QTabWidget() self._manager.disconnect()
guide = QTextBrowser(openExternalLinks=True) self._session.stop()
guide.setHtml(cheatsheet_html())
self.serial_tab = SerialTab()
self.flash_tab = FlashTab(self.serial_tab) class MainWindow(QMainWindow):
tabs.addTab(guide, "Quick start") def __init__(self):
tabs.addTab(self.serial_tab, "Serial monitor") super().__init__()
tabs.addTab(self.flash_tab, "Flash firmware") self.setWindowTitle(f"KOTA Sensorbox Technician Tool v{__version__}")
self.sd_tab = SdTab(self.serial_tab) self.resize(1200, 800)
tabs.addTab(self.sd_tab, "SD card") tabs = QTabWidget()
self.setCentralWidget(tabs) guide = QTextBrowser(openExternalLinks=True)
settings_menu = self.menuBar().addMenu("Settings") guide.setHtml(cheatsheet_html())
settings_menu.addAction("Service system address...", self._edit_service_base) self.serial_tab = SerialTab()
self.flash_tab = FlashTab(self.serial_tab)
def _edit_service_base(self) -> None: tabs.addTab(guide, "Quick start")
st = self.serial_tab tabs.addTab(self.serial_tab, "Serial monitor")
text, ok = QInputDialog.getText( tabs.addTab(self.flash_tab, "Flash firmware")
self, "Service system address", self.sd_tab = SdTab(self.serial_tab)
"Address of the KOTA service system (the box MAC is added at the end):", tabs.addTab(self.sd_tab, "SD card")
text=st._service_base()) self.setCentralWidget(tabs)
if ok and text.strip().startswith(("https://", "http://")): settings_menu = self.menuBar().addMenu("Settings")
st._settings.setValue("service/base", text.strip()) settings_menu.addAction("Service system address...", self._edit_service_base)
elif ok:
QMessageBox.warning(self, "Service system address", "The address must start with https://") def _edit_service_base(self) -> None:
st = self.serial_tab
def closeEvent(self, event): # noqa: N802 (Qt naming) text, ok = QInputDialog.getText(
self.serial_tab.shutdown() self, "Service system address",
super().closeEvent(event) "Address of the KOTA service system (the box MAC is added at the end):",
text=st._service_base())
if ok and text.strip().startswith(("https://", "http://")):
st._settings.setValue("service/base", text.strip())
elif ok:
QMessageBox.warning(self, "Service system address", "The address must start with https://")
def closeEvent(self, event): # noqa: N802 (Qt naming)
self.serial_tab.shutdown()
super().closeEvent(event)
+76 -72
View File
@@ -1,72 +1,76 @@
"""Matter pairing QR code on screen, so the technician can scan it from the laptop.""" """Matter pairing QR code on screen, so the technician can scan it from the laptop."""
from __future__ import annotations from __future__ import annotations
import segno import segno
from PySide6.QtCore import Qt from PySide6.QtCore import Qt
from PySide6.QtGui import QColor, QImage, QPainter, QPixmap from PySide6.QtGui import QColor, QImage, QPainter, QPixmap
from PySide6.QtWidgets import QDialog, QDialogButtonBox, QLabel, QVBoxLayout, QWidget from PySide6.QtWidgets import QDialog, QDialogButtonBox, QLabel, QVBoxLayout, QWidget
from ..matter.payload import SetupPayload from ..matter.payload import SetupPayload
def qr_pixmap(text: str, size: int = 260) -> QPixmap: def qr_pixmap(text: str, size: int = 260) -> QPixmap:
"""Black-on-white QR with the quiet zone phones need (4 modules).""" """Black-on-white QR with the quiet zone phones need (4 modules)."""
qr = segno.make(text, error="m") qr = segno.make(text, error="m")
matrix = [list(row) for row in qr.matrix_iter(scale=1, border=4)] matrix = [list(row) for row in qr.matrix_iter(scale=1, border=4)]
n = len(matrix) n = len(matrix)
module = max(1, size // n) module = max(1, size // n)
img = QImage(n * module, n * module, QImage.Format.Format_RGB32) img = QImage(n * module, n * module, QImage.Format.Format_RGB32)
img.fill(QColor("white")) img.fill(QColor("white"))
p = QPainter(img) p = QPainter(img)
p.setPen(Qt.PenStyle.NoPen) p.setPen(Qt.PenStyle.NoPen)
p.setBrush(QColor("black")) p.setBrush(QColor("black"))
for y, row in enumerate(matrix): for y, row in enumerate(matrix):
for x, dark in enumerate(row): for x, dark in enumerate(row):
if dark: if dark:
p.drawRect(x * module, y * module, module, module) p.drawRect(x * module, y * module, module, module)
p.end() p.end()
return QPixmap.fromImage(img) return QPixmap.fromImage(img)
class MatterQrWidget(QWidget): class MatterQrWidget(QWidget):
def __init__(self, payload: SetupPayload, size: int = 260, parent: QWidget | None = None): def __init__(self, payload: SetupPayload, size: int = 260, parent: QWidget | None = None):
super().__init__(parent) super().__init__(parent)
self.image = QLabel() self.image = QLabel()
self.image.setAlignment(Qt.AlignmentFlag.AlignCenter) self.image.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.code = QLabel() self.code = QLabel()
self.code.setAlignment(Qt.AlignmentFlag.AlignCenter) self.code.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.code.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) self.code.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
f = self.code.font() f = self.code.font()
f.setPointSize(f.pointSize() + 4) f.setPointSize(f.pointSize() + 4)
f.setBold(True) f.setBold(True)
self.code.setFont(f) self.code.setFont(f)
self.note = QLabel(wordWrap=True) self.note = QLabel(wordWrap=True)
self.note.setAlignment(Qt.AlignmentFlag.AlignCenter) self.note.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.note.setStyleSheet("color:#555") self.note.setStyleSheet("color:#555")
lay = QVBoxLayout(self) lay = QVBoxLayout(self)
lay.addWidget(self.image) lay.addWidget(self.image)
lay.addWidget(self.code) lay.addWidget(self.code)
lay.addWidget(self.note) lay.addWidget(self.note)
self._size = size self._size = size
self.set_payload(payload) self.set_payload(payload)
def set_payload(self, payload: SetupPayload) -> None: def set_payload(self, payload: SetupPayload) -> None:
self.payload = payload self.payload = payload
self.image.setPixmap(qr_pixmap(payload.qr_text(), self._size)) self.image.setPixmap(qr_pixmap(payload.qr_text(), self._size))
self.code.setText(f"Manual code: {payload.manual_code_pretty()}") self.code.setText(f"Manual code: {payload.manual_code_pretty()}")
src = ("from this box's log" if payload.from_log else if payload.from_box:
"standard code of the v1.0 firmware - connect the box to confirm") src = "QR and manual code exactly as reported by the box (KOTA: matter line)"
self.note.setText(f"Scan with the Matter app (Apple Home, Google Home, ...), or type the manual code. " else:
f"Discriminator {payload.discriminator} ({src}). Same as the sticker on the box.") src = f"Discriminator {payload.discriminator} " + (
"(from this box's log)" if payload.from_log else
"(standard code of the v1.0 firmware - connect the box to confirm)")
class MatterQrDialog(QDialog): self.note.setText(f"Scan with the Matter app (Apple Home, Google Home, ...), or type the manual code. "
def __init__(self, payload: SetupPayload, parent: QWidget | None = None): f"{src}. Same as the sticker on the box.")
super().__init__(parent)
self.setWindowTitle("Matter pairing code")
lay = QVBoxLayout(self) class MatterQrDialog(QDialog):
lay.addWidget(MatterQrWidget(payload, 320)) def __init__(self, payload: SetupPayload, parent: QWidget | None = None):
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) super().__init__(parent)
buttons.rejected.connect(self.reject) self.setWindowTitle("Matter pairing code")
lay.addWidget(buttons) lay = QVBoxLayout(self)
lay.addWidget(MatterQrWidget(payload, 320))
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Close)
buttons.rejected.connect(self.reject)
lay.addWidget(buttons)
+1 -1
View File
@@ -1,6 +1,6 @@
[project] [project]
name = "kota-technician-tool" name = "kota-technician-tool"
version = "0.6.0" version = "0.7.0"
description = "KOTA sensorbox technician diagnostic tool (demo)" description = "KOTA sensorbox technician diagnostic tool (demo)"
requires-python = ">=3.11,<3.14" requires-python = ">=3.11,<3.14"
dependencies = [ dependencies = [
+1 -1
View File
@@ -3,7 +3,7 @@
cd "$(dirname "$0")" || exit 1 cd "$(dirname "$0")" || exit 1
# Keep the virtual environment out of the (Google Drive) tool folder. # Keep the virtual environment out of the (Google Drive) tool folder.
export UV_PROJECT_ENVIRONMENT="$HOME/Library/Caches/KotaTechnicianTool/venv-0.6" export UV_PROJECT_ENVIRONMENT="$HOME/Library/Caches/KotaTechnicianTool/venv-0.7"
export PATH="$HOME/.local/bin:$PATH" export PATH="$HOME/.local/bin:$PATH"
if ! command -v uv >/dev/null 2>&1; then if ! command -v uv >/dev/null 2>&1; then
+1 -1
View File
@@ -3,7 +3,7 @@ setlocal
cd /d "%~dp0" cd /d "%~dp0"
rem Keep the virtual environment out of the (Google Drive) tool folder. rem Keep the virtual environment out of the (Google Drive) tool folder.
set "UV_PROJECT_ENVIRONMENT=%LOCALAPPDATA%\KotaTechnicianTool\venv-0.6" set "UV_PROJECT_ENVIRONMENT=%LOCALAPPDATA%\KotaTechnicianTool\venv-0.7"
set "PATH=%USERPROFILE%\.local\bin;%PATH%" set "PATH=%USERPROFILE%\.local\bin;%PATH%"
where uv >nul 2>nul where uv >nul 2>nul
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+22
View File
@@ -0,0 +1,22 @@
ESP-ROM:esp32s3-20210327
rst:0x15 (USB_UART_CHIP_RESET),boot:0x8 (SPI_FAST_FLASH_BOOT)
I (1299) app_init: Project name: kota-sensorboard
I (1303) app_init: App version: 1.0.16
I (1307) app_init: Compile time: Sep 28 2026 15:07:57
I (1317) app_init: ELF file SHA256: 4f10989e2...
E (1402) ID: [E-MAIN-04] Device MAC address: A4:CB:8F:C9:46:F8
I (1480) KOTA: led previous_boot status=CONNECTION_ERROR code=1
I (1481) KOTA: led color=purple pattern=blink period=1000ms
I (1790) KOTA: i2c SDA=1 SCL=1 0x39=AS7341 0x68=DS1307 0x6B=SEN66 0x76=BME688
I (1795) KOTA: rtc running=1 time=2026-09-28T15:20:01
I (1850) SD_CARD: SD card mounted successfully
I (1990) KOTA: sd type=SDHC size=7.4GB fs=FAT32 free=7.3GB env_keys=INFLUX_URL,INFLUX_TOKEN buffer_lines=0
I (2300) MAIN: ESP-Matter started successfully
I (2310) KOTA: boot fw=1.0.16 build=4f10989e hw=2 mac=A4CB8FC946F8 reset=USB_UART_CHIP_RESET mode=matter commissioned=1 last_restart=none
I (2315) KOTA: matter fabrics=1 window=closed qr=MT:Y.K9042C00KA0648G00 manual=34970112332
I (2400) KOTA: mic enabled=1 (GPIO3=0, expected 0)
I (4481) KOTA: led color=green pattern=solid
I (5200) WIFI_SERVICE: Got IP address
I (6100) SNTP: Time synchronized: Mon Sep 28 15:20:06 2026
I (8100) KOTA: rtc verify running=1 delta=2s ok=1
I (60010) KOTA: health up=60s status=OK wifi=connected rssi=-58 time_valid=1 sd=ok buffer=0 heap=143220 psram=7.6M last_upload=14s ota=registered
+20 -6
View File
@@ -43,16 +43,20 @@ APP = ["I (1299) app_init: Project name: kota-sensorboard",
# ------------------------------------------------------------------ rules # ------------------------------------------------------------------ rules
def test_rules_load_and_have_no_cycles(): def test_rules_load_and_have_no_cycles():
rules = load_rules() from kota_tech.diag import kota
by_id = {r.id: r for r in rules} graph = {r.id: r.explained_by for r in load_rules()}
for r in rules: for st in ("ERROR", "OUT_OF_RESOURCES", "CONNECTION_ERROR", "RTC_ERROR", "SD_ERROR", "RESETING", "HTTP_SERVER"):
seen, todo = set(), list(r.explained_by) for code in range(7):
if sf := kota.status_finding(st, code):
graph[sf[0]] = sf[5]
for start, explained_by in graph.items():
seen, todo = set(), list(explained_by)
while todo: while todo:
rid = todo.pop() rid = todo.pop()
assert rid != r.id, f"explained_by cycle through {r.id}" assert rid != start, f"explained_by cycle through {start}"
if rid not in seen: if rid not in seen:
seen.add(rid) seen.add(rid)
todo += by_id[rid].explained_by todo += graph.get(rid, ())
# --------------------------------------------------------- real captures # --------------------------------------------------------- real captures
@@ -233,3 +237,13 @@ def test_session_log_format(tmp_path):
for ln in lines: for ln in lines:
e.feed(ln) e.feed(ln)
assert e.boot.tool_reset assert e.boot.tool_reset
def test_live_brownout_loop_is_a_power_problem():
# Real capture (2026-09-28): "E BOD: Brownout detector was triggered" has no
# timestamp and the ROM reports RTC_SW_SYS_RST, not a brown-out reset.
r = replay("live_brownout_loop_A4CB8FC946F8_fw1.0.txt")
top = r.roots[0]
assert top.finding.rule_id == "reboot.brownout" and top.finding.count >= 5
assert "reboot.loop" in {c.rule_id for c in top.consequences}
assert r.verdict.startswith("Problem: Power supply")
+104 -131
View File
@@ -1,5 +1,6 @@
"""Flashing: image validation on the real official image, plan building, """Flashing: image validation on the real image in firmware/, the folder
and the runner against a fake esptool (no hardware).""" catalogue (compile-date order), plan building, and the runner against a fake
esptool (no hardware)."""
import hashlib import hashlib
import sys import sys
@@ -8,31 +9,39 @@ from pathlib import Path
import pytest import pytest
from kota_tech.flash.image import ImageError, inspect_image, official_images from kota_tech.flash.image import ImageError, app_image_length, folder_images, inspect_image
from kota_tech.flash.plan import Mode, build_plan, check_partition_table from kota_tech.flash.plan import Mode, build_plan, check_partition_table
from kota_tech.flash.runner import FlashRunner from kota_tech.flash.runner import FlashRunner
FW = Path(__file__).resolve().parents[1] / "firmware" / "new_system.bin" FW_DIR = Path(__file__).resolve().parents[1] / "firmware"
FW = sorted(FW_DIR.glob("*.bin"))[0]
@pytest.fixture(scope="module") @pytest.fixture(scope="module")
def image(): def image():
imgs = official_images() imgs, problems = folder_images()
assert len(imgs) == 1 assert imgs and problems == []
return imgs[0] return imgs[0]
# ------------------------------------------------------------------ image # ------------------------------------------------------------------ image
def test_official_image_is_the_deployed_v1_build(image): def test_folder_image_is_a_kota_build(image):
assert image.app.project == "kota-sensorboard" assert image.app.project == "kota-sensorboard"
assert image.app.elf_sha.startswith("45fa9d5b9") # same as the live board assert image.kind == "merged"
assert image.app.built_at is not None # compile date is readable
assert image.flash_size == "8MB" assert image.flash_size == "8MB"
assert image.partition("ota_0").offset == 0x40000 assert image.partition("ota_0").offset == 0x40000
assert image.partition("otadata").offset == 0x31000 assert image.partition("otadata").offset == 0x31000
assert image.partition("nvs").offset == 0x10000 assert image.partition("nvs").offset == 0x10000
def test_label_starts_with_compile_date(image):
label = image.label()
assert label.startswith(f"Compiled {image.app.built_at:%Y-%m-%d %H:%M}")
assert image.app.version in label and image.name in label
def test_app_bytes_are_a_complete_app_image(image): def test_app_bytes_are_a_complete_app_image(image):
app = image.app_bytes() app = image.app_bytes()
assert app[0] == 0xE9 assert app[0] == 0xE9
@@ -40,17 +49,6 @@ def test_app_bytes_are_a_complete_app_image(image):
assert len(image.blank_otadata()) == 0x2000 and set(image.blank_otadata()) == {0xFF} assert len(image.blank_otadata()) == 0x2000 and set(image.blank_otadata()) == {0xFF}
def test_modified_image_is_refused(tmp_path):
data = bytearray(FW.read_bytes())
data[-1] ^= 0xFF
bad = tmp_path / "new_system.bin"
bad.write_bytes(data)
manifest = tmp_path / "firmware.toml"
manifest.write_text(f'[[image]]\nfile = "new_system.bin"\nsha256 = "{hashlib.sha256(FW.read_bytes()).hexdigest()}"\n')
with pytest.raises(ImageError, match="SHA-256"):
official_images(manifest)
@pytest.mark.parametrize("patch,msg", [ @pytest.mark.parametrize("patch,msg", [
((0, 0x00), "not an ESP32 firmware"), ((0, 0x00), "not an ESP32 firmware"),
((12, 0x05), "not ESP32-S3"), ((12, 0x05), "not ESP32-S3"),
@@ -64,6 +62,93 @@ def test_wrong_images_are_rejected(tmp_path, patch, msg):
inspect_image(p) inspect_image(p)
def test_integrity_check_on_folder_image(image):
d = image.data
assert app_image_length(d, 0) > 0 # bootloader
assert app_image_length(d, 0x40000) == len(d) - 0x40000 # app ends exactly at file end
@pytest.mark.parametrize("damage,msg", [
(lambda b: b[:len(b) // 2], "truncated"),
(lambda b: b[:0x40000 + 5000] + bytes([b[0x40000 + 5000] ^ 1]) + b[0x40000 + 5001:], "corrupted"),
])
def test_corrupted_or_truncated_images_refused(tmp_path, damage, msg):
p = tmp_path / "broken.bin"
p.write_bytes(damage(FW.read_bytes()))
with pytest.raises(ImageError, match=msg):
inspect_image(p)
# ------------------------------------------------------- firmware folder
def _with_compile_date(data: bytes, date: str, time: str, off: int = 0x40000) -> bytes:
"""Copy of a merged image whose app claims another compile date, with the
segment checksum and appended SHA-256 recomputed (a valid, different build)."""
d = bytearray(data)
desc = off + 0x20
old = bytes(d[desc + 80:desc + 112])
new = time.encode().ljust(16, b"\0") + date.encode().ljust(16, b"\0")
d[desc + 80:desc + 112] = new
end = off + app_image_length(data, off) - 32 # SHA-256 follows the checksum byte
xor = 0
for a, b in zip(old, new):
xor ^= a ^ b
d[end - 1] ^= xor
d[end:end + 32] = hashlib.sha256(bytes(d[off:end])).digest()
return bytes(d)
def test_folder_lists_builds_newest_compile_date_first(tmp_path):
data = FW.read_bytes()
(tmp_path / "a_old.bin").write_bytes(_with_compile_date(data, "Jan 5 2026", "08:00:00"))
(tmp_path / "z_new.bin").write_bytes(_with_compile_date(data, "Dec 24 2026", "18:30:00"))
(tmp_path / "m_mid.bin").write_bytes(_with_compile_date(data, "Jun 15 2026", "12:00:00"))
imgs, problems = folder_images(tmp_path)
assert problems == []
assert [i.name for i in imgs] == ["z_new.bin", "m_mid.bin", "a_old.bin"]
assert imgs[0].label().startswith("Compiled 2026-12-24 18:30")
assert imgs[2].label().startswith("Compiled 2026-01-05 08:00")
def test_folder_reports_bad_files_and_duplicates(tmp_path):
data = FW.read_bytes()
(tmp_path / "good.bin").write_bytes(data)
(tmp_path / "copy.bin").write_bytes(data)
(tmp_path / "notes.bin").write_bytes(b"hello firmware team")
(tmp_path / "readme.txt").write_text("ignored: not a .bin")
imgs, problems = folder_images(tmp_path)
assert len(imgs) == 1
assert any("notes.bin" in p and "not an ESP32 firmware" in p for p in problems)
assert any("same file as" in p for p in problems)
assert not any("readme" in p for p in problems)
def test_app_only_file_uses_the_merged_layout(tmp_path, image):
(tmp_path / "merged.bin").write_bytes(image.data)
(tmp_path / "kota-sensorboard.bin").write_bytes(
_with_compile_date(image.data, "Dec 1 2026", "10:00:00")[0x40000:])
imgs, problems = folder_images(tmp_path)
assert problems == []
app = next(i for i in imgs if i.kind == "app")
assert imgs[0] is app # newer compile date first
assert app.partition("ota_0").offset == 0x40000 and "app only" in app.label()
assert [s.kind for s in build_plan(app, Mode.APP_ONLY, "COM5", tmp_path / "w").steps] == ["read_pt", "write"]
with pytest.raises(ValueError, match="app only"):
build_plan(app, Mode.FULL, "COM5", tmp_path / "w")
def test_app_only_file_without_merged_image_is_not_offered(tmp_path, image):
(tmp_path / "kota-sensorboard.bin").write_bytes(image.app_bytes())
imgs, problems = folder_images(tmp_path)
assert imgs == [] and "no complete (merged) image" in problems[0]
def test_empty_or_missing_folder(tmp_path):
assert folder_images(tmp_path) == ([], [])
imgs, problems = folder_images(tmp_path / "nope")
assert imgs == [] and "not found" in problems[0]
# ------------------------------------------------------------------- plan # ------------------------------------------------------------------- plan
def test_app_only_plan_keeps_nvs(image, tmp_path): def test_app_only_plan_keeps_nvs(image, tmp_path):
@@ -160,115 +245,3 @@ def test_runner_reports_connect_failure_with_hint(image, tmp_path):
res, *_ = _run(plan, cmd) res, *_ = _run(plan, cmd)
assert not res.ok and res.failed_step == 0 assert not res.ok and res.failed_step == 0
assert "BOOT" in res.hint assert "BOOT" in res.hint
# ------------------------------------------------- developer builds (v0.5)
from kota_tech.flash.image import FirmwareLibrary, app_image_length # noqa: E402
def _app_only_file(image, tmp_path, name="kota-sensorboard.bin"):
p = tmp_path / name
p.write_bytes(image.app_bytes()) # what a developer build/ folder contains
return p
def test_integrity_check_on_factory_image(image):
d = image.data
assert app_image_length(d, 0) > 0 # bootloader
assert app_image_length(d, 0x40000) == len(d) - 0x40000 # app ends exactly at file end
@pytest.mark.parametrize("damage,msg", [
(lambda b: b[:len(b) // 2], "truncated"),
(lambda b: b[:0x40000 + 5000] + bytes([b[0x40000 + 5000] ^ 1]) + b[0x40000 + 5001:], "corrupted"),
])
def test_corrupted_or_truncated_images_refused(tmp_path, damage, msg):
p = tmp_path / "broken.bin"
p.write_bytes(damage(FW.read_bytes()))
with pytest.raises(ImageError, match=msg):
inspect_image(p, origin="developer")
def test_import_app_only_developer_build(image, tmp_path):
lib = FirmwareLibrary(tmp_path / "lib")
src = _app_only_file(image, tmp_path)
img = lib.import_file(src, reference=image)
assert img.is_developer and img.kind == "app"
assert img.partition("ota_0").offset == 0x40000 # layout from the factory image
assert img.app_bytes() == image.app_bytes()
listed, problems = lib.images(image)
assert [i.sha256 for i in listed] == [img.sha256] and problems == []
assert lib.import_file(src, reference=image).sha256 == img.sha256 # re-import: no duplicate
assert len(lib.images(image)[0]) == 1
def test_app_only_build_cannot_be_flashed_full(image, tmp_path):
lib = FirmwareLibrary(tmp_path / "lib")
img = lib.import_file(_app_only_file(image, tmp_path), reference=image)
plan = build_plan(img, Mode.APP_ONLY, "COM5", tmp_path / "w")
assert [s.kind for s in plan.steps] == ["read_pt", "write"]
with pytest.raises(ValueError, match="app only"):
build_plan(img, Mode.FULL, "COM5", tmp_path / "w")
def test_import_merged_developer_build(image, tmp_path):
lib = FirmwareLibrary(tmp_path / "lib")
src = tmp_path / "dev_full.bin"
src.write_bytes(image.data)
img = lib.import_file(src, reference=image)
assert img.kind == "merged" and img.is_developer
assert [s.kind for s in build_plan(img, Mode.FULL, "COM5", tmp_path / "w").steps] == ["write"]
def test_library_detects_file_changed_after_import(image, tmp_path):
lib = FirmwareLibrary(tmp_path / "lib")
img = lib.import_file(_app_only_file(image, tmp_path), reference=image)
stored = tmp_path / "lib" / img.path.name
data = bytearray(stored.read_bytes())
data[-40] ^= 1
stored.write_bytes(data)
listed, problems = lib.images(image)
assert listed == [] and problems
def test_library_remove(image, tmp_path):
lib = FirmwareLibrary(tmp_path / "lib")
img = lib.import_file(_app_only_file(image, tmp_path), reference=image)
lib.remove(img.sha256)
assert lib.images(image) == ([], []) and not img.path.exists()
def test_non_firmware_file_refused(tmp_path, image):
p = tmp_path / "notes.bin"
p.write_bytes(b"hello firmware team")
with pytest.raises(ImageError, match="not an ESP32 firmware"):
FirmwareLibrary(tmp_path / "lib").import_file(p, reference=image)
# ------------------------------------------- bundled developer build (v0.6)
from kota_tech.flash.image import bundled_images # noqa: E402
def test_bundled_developer_build_is_labelled_and_not_default():
imgs = bundled_images()
assert [i.origin for i in imgs] == ["factory", "developer"] # factory first
dev = imgs[1]
assert dev.built_by == "Krzysztof Kallas" and "built by Krzysztof Kallas" in dev.label()
assert dev.kind == "merged" and dev.app.elf_sha.startswith("c94ba0e9b")
assert dev.partition_table == imgs[0].partition_table # App-only safe on v1.0 boxes
assert [i.origin for i in factory_images_only()] == ["factory"]
def factory_images_only():
from kota_tech.flash.image import factory_images
return factory_images()
def test_import_records_who_built_it(image, tmp_path):
lib = FirmwareLibrary(tmp_path / "lib")
img = lib.import_file(_app_only_file(image, tmp_path), reference=image, built_by=" Anna Nowak ")
assert img.built_by == "Anna Nowak" and "built by Anna Nowak" in img.label()
again, _ = lib.images(image)
assert again[0].built_by == "Anna Nowak"
+238
View File
@@ -0,0 +1,238 @@
"""Firmware 1.0.16+ structured "KOTA:" lines and error IDs.
The lines below are built from the exact format strings in the firmware
source (boot_info.cpp, status.cpp, i2c.cpp, ds1307.cpp, sd_card.cpp,
main.cpp, microphone.cpp, health.cpp); no hardware capture exists yet.
"""
from pathlib import Path
from kota_tech.core.logfile import read_log_file
from kota_tech.core.logline import LineKind, parse_line
from kota_tech.diag.engine import DiagnosticsEngine, Severity
from kota_tech.diag.firmware import same_build
from kota_tech.matter.payload import payload_from_log
from kota_tech.service.report import CONNECTIVITY, HARDWARE, service_status
FIX = Path(__file__).parent / "fixtures"
BANNER = ["ESP-ROM:esp32s3-20210327", "rst:0x15 (USB_UART_CHIP_RESET),boot:0x8 (SPI_FAST_FLASH_BOOT)"]
I2C_OK = "I (1790) KOTA: i2c SDA=1 SCL=1 0x39=AS7341 0x68=DS1307 0x6B=SEN66 0x76=BME688"
SD_OK = ("I (1990) KOTA: sd type=SDHC size=7.4GB fs=FAT32 free=7.3GB "
"env_keys=INFLUX_URL,INFLUX_TOKEN buffer_lines=0")
BOOT = ("I (2310) KOTA: boot fw=1.0.16 build=4f10989e hw=2 mac=A4CB8FC946F8 reset=USB_UART_CHIP_RESET "
"mode=matter commissioned=1 last_restart={last}")
def run(lines):
e = DiagnosticsEngine()
for i, text in enumerate(lines):
e.feed(parse_line(text, host_time=i * 0.01))
return e, e.report()
def roots(report):
return {rc.finding.rule_id: rc for rc in report.roots}
# ------------------------------------------------------------- parsing
def test_kota_lines_are_parsed_into_fields():
ln = parse_line(BOOT.format(last="status_watchdog"))
assert ln.kind == LineKind.KOTA and ln.record == "boot" and ln.level == "I"
assert ln.fields["fw"] == "1.0.16" and ln.fields["last_restart"] == "status_watchdog"
st = parse_line("I (5) KOTA: status OK -> CONNECTION_ERROR code=1 reason=influx_rejected")
assert st.words == ("OK", "->", "CONNECTION_ERROR") and st.fields == {"code": "1", "reason": "influx_rejected"}
mic = parse_line("I (6) KOTA: mic enabled=0 (GPIO3=1, expected 0)")
assert mic.fields["enabled"] == "0" and mic.fields["GPIO3"] == "1"
i2c = parse_line("I (7) KOTA: i2c SDA=1 SCL=1 0x39=AS7341 0x68=DS1307(missing) 0x50=?")
assert i2c.fields["0x68"] == "DS1307(missing)" and i2c.fields["0x50"] == "?"
verify = parse_line("I (8) KOTA: rtc verify running=1 delta=2s ok=1")
assert verify.record == "rtc" and "verify" in verify.words and verify.fields["ok"] == "1"
def test_error_id_is_split_off_but_kept_in_text():
ln = parse_line("E (1200) SD_CARD: [E-SD-03] Failed to initialize the card (ESP_ERR_TIMEOUT).")
assert ln.kind == LineKind.LOG and ln.error_id == "E-SD-03"
assert ln.message.startswith("Failed to initialize") and "[E-SD-03]" in ln.text
assert ln.match_text == "E (1200) SD_CARD: Failed to initialize the card (ESP_ERR_TIMEOUT)."
def test_sd_line_with_secret_key_names_is_not_redacted():
ln = parse_line("I (9) KOTA: sd type=SDHC size=7.4GB fs=FAT32 free=7.3GB "
"env_keys=INFLUX_URL,INFLUX_TOKEN,SSID,PASSWORD buffer_lines=0")
assert ln.fields["env_keys"] == "INFLUX_URL,INFLUX_TOKEN,SSID,PASSWORD"
# -------------------------------------------------------------- engine
def test_healthy_box_from_kota_lines():
e = DiagnosticsEngine()
for ln in read_log_file(FIX / "synthetic_fw1.0.16_healthy.txt"):
e.feed(ln)
r = e.report()
assert r.verdict.startswith("Healthy")
assert (r.led, r.led_pattern, r.led_exact, r.led_meaning) == ("GREEN", "solid", True, "OK")
assert "v1.0.16" in r.firmware.describe() and "4f10989e" in r.firmware.describe()
assert e.mac == "A4:CB:8F:C9:46:F8"
reached = {m for m, _, t in r.milestones if t is not None}
assert {"i2c_ok", "sd_mounted", "env_loaded", "matter_commissioned", "wifi_connected",
"time_synced", "clock_verified", "data_uploaded", "ota_registered"} <= reached
topics = {t: st for t, _, st in r.box}
assert topics["I2C"] == topics["SD card"] == topics["Health"] == "ok"
# The purple state before the tool's reset is shown, but only as information now.
prev = [f for f in r.earlier + [rc.finding for rc in r.roots] if f.rule_id == "boot.previous_status"]
assert not prev or prev[0].severity == Severity.INFO
assert "E-MAIN-04" not in r.to_text() # MAC line is a benign ESP_LOGE
def test_i2c_bus_stuck_is_root_of_blue_led():
_, r = run(BANNER + [
"I (1480) KOTA: led color=blue pattern=pulses n=2",
"I (1790) KOTA: i2c SDA=0 SCL=1 bus=stuck",
"I (1791) KOTA: status OK -> RTC_ERROR code=2 reason=i2c_bus_stuck",
])
rs = roots(r)
assert "kota.i2c_stuck" in rs and rs["kota.i2c_stuck"].finding.severity == Severity.CRITICAL
assert "status.rtc.2" in {c.rule_id for c in rs["kota.i2c_stuck"].consequences}
assert (r.led, r.led_pattern) == ("BLUE", "2 pulses") and "I2C bus stuck" in r.led_meaning
assert service_status(r) == HARDWARE
def test_missing_sensor_named_by_i2c_scan_and_red_pulses():
_, r = run(BANNER + [
"I (1790) KOTA: i2c SDA=1 SCL=1 0x39=AS7341 0x68=DS1307 0x6B=SEN66(missing) 0x76=BME688",
SD_OK,
"E (2100) MAIN: [E-MAIN-16] Failed to initialize SEN66: ESP_ERR_TIMEOUT",
"I (2101) KOTA: status OK -> ERROR code=2 reason=sen66_init_failed",
"I (2102) KOTA: led color=red pattern=pulses n=2",
])
rs = roots(r)
root = rs["kota.sensor_missing"]
assert root.finding.title == "SEN66 does not answer on the I2C bus"
grouped = {c.rule_id for c in root.consequences}
assert {"status.error.2", "sensor.init_failed"} <= grouped
init = next(c for c in root.consequences if c.rule_id == "sensor.init_failed")
assert "E-MAIN-16" in init.error_ids and "SEN66" in init.error_ids["E-MAIN-16"]
assert r.led_meaning == "SEN66 failed"
assert "missing: SEN66" in dict((t, x) for t, x, _ in r.box)["I2C"]
def test_server_rejected_box_is_purple_blinking():
_, r = run(BANNER + [I2C_OK, SD_OK, BOOT.format(last="none"),
"I (70000) KOTA: status OK -> CONNECTION_ERROR code=1 reason=influx_rejected",
"I (70001) KOTA: led color=purple pattern=blink period=1000ms"])
assert r.roots[0].finding.rule_id == "status.conn.1"
assert r.roots[0].finding.severity == Severity.CRITICAL
assert (r.led, r.led_pattern) == ("PURPLE", "blinking (1000 ms)")
assert "server rejected" in r.led_meaning
assert "influx_rejected" in r.led_reason
assert service_status(r) == CONNECTIVITY
def test_status_back_to_ok_resolves_the_status_finding():
_, r = run(BANNER + [I2C_OK, "I (5000) KOTA: status OK -> CONNECTION_ERROR reason=influx_failed",
"I (9000) KOTA: status CONNECTION_ERROR -> OK reason=influx_ok"])
assert "status.conn" not in roots(r)
assert any(f.rule_id == "status.conn" and f.resolved_by == "status -> OK" for f in r.resolved)
def test_restart_reason_from_the_next_boot_line():
_, r = run(BANNER + [I2C_OK, BOOT.format(last="none"),
"I (5000) KOTA: status OK -> ERROR code=3 reason=as7341_failed",
"W (155000) KOTA: restart reason=status_watchdog",
"I (155001) KOTA: led restart_flash color=red",
"ESP-ROM:esp32s3-20210327", "rst:0xc (RTC_SW_CPU_RESET),boot:0x8 (SPI_FAST_FLASH_BOOT)",
"I (1480) KOTA: led previous_boot status=ERROR code=3",
I2C_OK, BOOT.format(last="status_watchdog")])
ids = {f.rule_id: f for rc in r.roots for f in [rc.finding, *rc.consequences]}
f = ids["reboot.status_watchdog"]
assert "150 s" in f.title and "state ERROR code=3" in f.meaning
def test_brownout_restart_recorded_by_firmware():
_, r = run(BANNER + [I2C_OK, BOOT.format(last="none"), "I (90000) KOTA: health up=90s status=OK "
"wifi=connected rssi=-60 time_valid=1 sd=ok buffer=0 heap=150000 psram=7.6M "
"last_upload=10s ota=registered",
"ESP-ROM:esp32s3-20210327", "rst:0xf (RTCWDT_BROWN_OUT_RESET),boot:0x8",
I2C_OK, BOOT.format(last="brownout")])
assert r.roots[0].finding.rule_id == "reboot.brownout"
def test_uncaptured_error_id_uses_the_csv_action():
_, r = run(BANNER + [I2C_OK, "E (3000) INFLUX_BUFFER: [E-INF-13] Failed to open buffer file for appending"])
f = next(f for rc in r.roots for f in [rc.finding, *rc.consequences] if "E-INF-13" in f.error_ids)
# A rule already knows this message, so the rule finding carries the code.
assert f.rule_id == "sd.write_fail"
_, r = run(BANNER + [I2C_OK, "E (3000) SPI: [E-SPI-01] Failed to take SPI mutex"])
f = roots(r)["eid.SPI"].finding
assert f.title == "SPI bus: Failed to take SPI mutex"
assert "firmware team" in f.actions[0] and f.error_ids == {"E-SPI-01": f.actions[0]}
def test_legacy_rules_still_match_lines_with_error_ids():
_, r = run(BANNER + ["E (1200) MAIN: [E-MAIN-13] Failed to initialize RTC: ESP_ERR_TIMEOUT"])
assert "rtc.init_failed" in roots(r)
def test_health_line_gives_status_when_connected_mid_run():
e, r = run(["I (600000) KOTA: health up=600s status=CONNECTION_ERROR wifi=disconnected rssi=0 "
"time_valid=1 sd=ok buffer=120 heap=150000 psram=7.6M last_upload=never ota=registered",
"I (660000) KOTA: health up=660s status=CONNECTION_ERROR wifi=disconnected rssi=0 "
"time_valid=1 sd=ok buffer=130 heap=150000 psram=7.6M last_upload=never ota=registered"])
assert (r.led, r.led_pattern) == ("PURPLE", "solid") and not r.led_exact
rs = roots(r)
assert "kota.wifi_down" in rs
assert "status.conn" in {c.rule_id for c in rs["kota.wifi_down"].consequences}
assert r.mid_run
def test_sd_and_rtc_self_report():
_, r = run(BANNER + [
"I (1795) KOTA: rtc running=0 time=2000-01-01T00:00:00",
"I (1990) KOTA: sd type=SDHC size=7.4GB fs=FAT32 free=7.3GB env_keys=INFLUX_URL buffer_lines=0",
"I (8100) KOTA: rtc verify running=0 delta=0s ok=0",
])
ids = {f.key for rc in r.roots for f in [rc.finding, *rc.consequences]}
assert {"influx.env_missing:INFLUX_TOKEN", "kota.rtc_stopped", "kota.rtc_not_ticking"} <= ids
_, r = run(BANNER + ["I (1990) KOTA: sd mounted=0 err=ESP_ERR_TIMEOUT",
"I (1991) KOTA: status OK -> SD_ERROR reason=sd_mount_failed"])
rs = roots(r)
assert "kota.sd_unmounted" in rs and "ESP_ERR_TIMEOUT" in rs["kota.sd_unmounted"].finding.title
assert "status.sd" in {c.rule_id for c in rs["kota.sd_unmounted"].consequences}
def test_matter_and_mic_lines():
e, r = run(BANNER + ["I (2315) KOTA: matter fabrics=0 window=open qr=MT:Y.K9042C00KA0648G00 manual=34970112332",
"I (2400) KOTA: mic enabled=0 (GPIO3=1, expected 0)",
"I (4481) KOTA: led color=cyan pattern=breathe period=3000ms"])
rs = roots(r)
assert "matter.not_commissioned" in rs and "mic.disabled" in rs
assert (r.led, r.led_meaning) == ("CYAN", "waiting to be paired in Matter")
p = payload_from_log([], e.matter_qr, e.matter_manual)
assert p.qr_text() == "MT:Y.K9042C00KA0648G00" and p.manual_code_pretty() == "3497-011-2332"
_, r = run(BANNER + ["I (2315) KOTA: matter fabrics=0 window=open qr=MT:Y.K9042C00KA0648G00 manual=34970112332",
"I (90000) KOTA: matter fabrics=1 window=closed qr=MT:Y.K9042C00KA0648G00 manual=34970112332"])
assert "matter.not_commissioned" not in roots(r)
def test_build_prefixes_of_different_length_match():
full = "4f10989e2b40c1d29fb3e8f8faaa50e5555997909c6d6b1db9d4e1e4d04555dc"
assert same_build("4f10989e", full) and same_build(full, "4f10989e2")
assert not same_build("4f10989f", full) and not same_build(None, full)
def test_live_fw1016_uncommissioned_box():
# Real capture (2026-09-28) after flashing 1.0.16 App-only: not paired in Matter.
e = DiagnosticsEngine()
for ln in read_log_file(FIX / "live_boot_A4CB8FC946F8_fw1.0.16_uncommissioned.txt"):
e.feed(ln)
r = e.report()
assert r.firmware.version == "1.0.16" and same_build(r.firmware.elf_sha, "4f10989e")
assert (r.led, r.led_pattern, r.led_exact) == ("CYAN", "breathing", True)
rs = roots(r)
assert r.roots[0].finding.rule_id == "matter.not_commissioned"
grouped = {c.rule_id for c in rs["matter.not_commissioned"].consequences}
assert {"kota.wifi_down", "net.dns_fail", "status.conn", "kota.buffer_backlog"} <= grouped
assert "rtc.clock_not_running" in {c.rule_id for c in rs["kota.rtc_stopped"].consequences}
assert e.matter_qr == "MT:Y.K9042C00KA0648G00"
assert not any(f.rule_id.startswith("other.") for f in e.findings.values())
+17 -1
View File
@@ -33,7 +33,7 @@ def test_bench_box_is_a_connectivity_problem():
assert service_status(e.report()) == CONNECTIVITY assert service_status(e.report()) == CONNECTIVITY
note = service_note(e.report()) note = service_note(e.report())
assert note.startswith("[KOTA Technician Tool") assert note.startswith("[KOTA Technician Tool")
assert "not commissioned in Matter" in note and "-> No Internet" in note assert "not commissioned in Matter" in note and "↳ [Error] No Internet" in note
assert "Firmware: v1.0" in note assert "Firmware: v1.0" in note
@@ -89,3 +89,19 @@ def test_invalid_mac_rejected(bad):
def test_normalize_mac(): def test_normalize_mac():
assert normalize_mac("a4:cb:8f:c9:46:f8") == "A4CB8FC946F8" assert normalize_mac("a4:cb:8f:c9:46:f8") == "A4CB8FC946F8"
def test_note_mirrors_the_diagnosis_panel():
from pathlib import Path
from kota_tech.core.logfile import read_log_file
e = DiagnosticsEngine()
for ln in read_log_file(Path(__file__).parent / "fixtures" / "live_boot_A4CB8FC946F8_fw1.0.16_uncommissioned.txt"):
e.feed(ln)
note = service_note(e.report())
assert len(note) <= 5000
for part in ("Status LED should be: Cyan, breathing", "Box self-report (KOTA lines):",
"✔ I2C: found: AS7341, DS1307, SEN66, BME688", "Start-up progress (current boot):",
"✔ SD card mounted (1.7 s)", "○ Connected to Wi-Fi", "What to do:",
"Seen 12x, first at 21.6 s after start, last at 126.8 s",
"↳ [Error] No Internet: server names cannot be resolved"):
assert part in note, part
Generated
+1 -1
View File
@@ -250,7 +250,7 @@ wheels = [
[[package]] [[package]]
name = "kota-technician-tool" name = "kota-technician-tool"
version = "0.6.0" version = "0.7.0"
source = { virtual = "." } source = { virtual = "." }
dependencies = [ dependencies = [
{ name = "esptool" }, { name = "esptool" },