Debian Codegraph @

test.py

raw
1 """Capture / validation harness for PR #15 on a 2021+ (new-style) Acaia scale.
2
3 PR #15 ("Decode button payloads by walking the record chain") was only tested on
4 an original Pearl (old-style, service 1820 / char 2a80). Its author flagged that
5 tag ``0x0b`` widths in particular need a second opinion on 2021+ firmware.
6
7 This script drives a *new-style* scale through the ``aioacaia`` connection stack
8 (so auth + heartbeats keep it streaming), feeds every notification through the
9 *new* record-chain parser, and logs, for each frame:
10
11 * the raw notification bytes,
12 * the decoded message object, and
13 * a per-record ``[tag][body]`` breakdown that stops and flags anything the walk
14 can't explain (unknown tag, truncated body, unknown button key).
15
16 Everything is written verbatim to a ``capture-*.log`` file so real frames can be
17 turned into new fixtures afterwards. The console shows the interesting frames
18 (button presses and anomalies) so decoding can be validated live.
19
20 Usage
21 -----
22 .venv/bin/python test.py [MAC_ADDRESS] [--old-style]
23
24 The address is taken from, in order: the CLI argument, a ``mac.txt`` file next to
25 this script (git-ignored, same convention as run.py), or a BLE scan.
26
27 While it runs, physically operate the scale and type short notes + Enter to drop
28 timestamped markers into the log (e.g. ``put 55g``, ``pressed stop``). Prefix a
29 line with ``!`` to send a command instead: ``!tare``, ``!timer`` (start/stop
30 toggle), ``!reset``. Type ``q`` + Enter (or Ctrl+C) to stop and print a summary.
31 """
32
33 from __future__ import annotations
34
35 import asyncio
36 import logging
37 import sys
38 import time
39 from dataclasses import dataclass, field
40 from datetime import datetime
41 from pathlib import Path
42
43 from bleak.backends.characteristic import BleakGATTCharacteristic
44
45 from aioacaia.const import HEADER1, HEADER2
46 from aioacaia.discovery import find_acaia_devices
47 from aioacaia.exceptions import (
48 AcaiaMessageError,
49 AcaiaMessageTooLong,
50 AcaiaMessageTooShort,
51 )
52 from aioacaia.messages import (
53 ButtonMessage,
54 ButtonType,
55 Settings,
56 TimerMessage,
57 WeightMessage,
58 )
59
60 # NOTE: the underscore-prefixed names below are internal to aioacaia. They are
61 # imported on purpose so this harness stays byte-for-byte in sync with the exact
62 # record widths and button map the PR #15 parser uses.
63 from aioacaia.parser import ( # noqa: PLC2701
64 _BATTERY_TAG,
65 _BUTTON_TYPES,
66 _RECORD_WIDTHS,
67 _UNKNOWN_TAG_0B,
68 MessageType,
69 decode,
70 decode_time,
71 decode_weight,
72 )
73 from aioacaia.scale import AcaiaScale
74
75 _HEADER = bytes((HEADER1, HEADER2))
76
77 # Command bytes (frame[2]) that carry a decodable body.
78 _EVENT_COMMAND = 0x0C
79 _SETTINGS_COMMAND = 0x08
80
81 # Human-readable names for the record tags used in the breakdown.
82 _TAG_NAMES: dict[int, str] = {
83 int(MessageType.WEIGHT): "weight",
84 int(MessageType.TIMER): "timer",
85 int(MessageType.BUTTON): "button/key",
86 _BATTERY_TAG: "battery",
87 _UNKNOWN_TAG_0B: "0x0b (unexplained)",
88 }
89 _BUTTON_NAMES: dict[int, str] = {
90 code: bt.value for code, (bt, _tr) in _BUTTON_TYPES.items()
91 }
92
93
94 def _msg_type_name(value: int) -> str:
95 try:
96 return MessageType(value).name
97 except ValueError:
98 return f"0x{value:02x}"
99
100
101 def _summarize(msg: object) -> str:
102 """One-line human summary of a decoded message."""
103 if isinstance(msg, ButtonMessage):
104 parts = [f"button={msg.button.value}"]
105 if msg.timer_running is not None:
106 parts.append(f"timer_running={msg.timer_running}")
107 if msg.time is not None:
108 parts.append(f"time={msg.time:g}s")
109 if msg.weight is not None:
110 parts.append(f"weight={msg.weight:g}g")
111 return " ".join(parts)
112 if isinstance(msg, WeightMessage):
113 return f"weight={msg.weight:g}g"
114 if isinstance(msg, TimerMessage):
115 return f"time={msg.time:g}s"
116 if isinstance(msg, Settings):
117 return (
118 f"battery={msg.battery}% units={msg.units} "
119 f"auto_off={msg.auto_off} beep={msg.beep_on}"
120 )
121 return repr(msg)
122
123
124 @dataclass
125 class ChainReport:
126 """Result of walking one ``[tag][body]`` record chain."""
127
128 lines: list[str] = field(default_factory=list)
129 flags: list[str] = field(default_factory=list)
130
131 @property
132 def ok(self) -> bool:
133 return not self.flags
134
135
136 def annotate_chain(chain: bytes) -> ChainReport:
137 """Describe every record in a chain, flagging anything the walk can't parse.
138
139 Mirrors ``aioacaia.parser._walk_records`` but keeps going verbosely and, on
140 the first thing it can't explain, prints the leftover bytes so a wrong width
141 (e.g. tag ``0x0b`` on 2021+ firmware) is obvious.
142 """
143 report = ChainReport()
144 index = 0
145 total = len(chain)
146 while index < total:
147 tag = chain[index]
148 if tag == MessageType.BUTTON:
149 if index + 2 > total:
150 flag = f"[{index}] tag 0x08 button/key truncated: {chain[index:].hex()}"
151 report.lines.append(flag + " <-- CHECK")
152 report.flags.append(flag)
153 break
154 key = chain[index + 1]
155 name = _BUTTON_NAMES.get(key, f"UNKNOWN key {key}")
156 report.lines.append(f"[{index}] tag 0x08 button/key: key={key} ({name})")
157 if key not in _BUTTON_NAMES:
158 report.flags.append(f"[{index}] unknown button key {key}")
159 index += 2
160 continue
161 width = _RECORD_WIDTHS.get(tag)
162 name = _TAG_NAMES.get(tag, f"0x{tag:02x}")
163 if width is None:
164 flag = f"[{index}] tag 0x{tag:02x} UNKNOWN -> walk stops; leftover: {chain[index:].hex()}"
165 report.lines.append(flag + " <-- CHECK")
166 report.flags.append(flag)
167 break
168 body = bytearray(chain[index + 1 : index + 1 + width])
169 if len(body) < width:
170 flag = (
171 f"[{index}] tag 0x{tag:02x} {name} needs {width} bytes, "
172 f"got {len(body)}: {body.hex()}"
173 )
174 report.lines.append(flag + " <-- CHECK")
175 report.flags.append(flag)
176 break
177 detail = f"body={body.hex()}"
178 if tag == MessageType.WEIGHT:
179 try:
180 detail += f" -> {decode_weight(body):g} g"
181 except AcaiaMessageError as ex:
182 detail += f" -> WEIGHT DECODE ERROR: {ex.message}"
183 report.flags.append(f"[{index}] weight decode error: {ex.message}")
184 elif tag == MessageType.TIMER:
185 try:
186 detail += f" -> {decode_time(body):g} s"
187 except AcaiaMessageError as ex:
188 detail += f" -> TIME DECODE ERROR: {ex.message}"
189 report.flags.append(f"[{index}] time decode error: {ex.message}")
190 report.lines.append(f"[{index}] tag 0x{tag:02x} {name} {detail}")
191 index += 1 + width
192 return report
193
194
195 @dataclass
196 class FixtureCandidate:
197 """A distinct button/heartbeat payload worth pasting into the fixtures."""
198
199 msg_type: int
200 payload_hex: str
201 summary: str
202 first_at: float
203 clean: bool
204
205
206 class CaptureSession:
207 """Reassembles notifications into frames and logs raw + decoded + records."""
208
209 def __init__(self, log: logging.Logger) -> None:
210 self.log = log
211 self.log_path: Path | None = None
212 self._buffer = bytearray()
213 self._start_mono = time.monotonic()
214 self._notif_count = 0
215 self._frame_count = 0
216 self._counts: dict[str, int] = {}
217 self._fixtures: dict[str, FixtureCandidate] = {}
218 self._attention: list[str] = []
219 self._last_start_mono: float | None = None
220 self._last_weight: float | None = None
221
222 # --- clock helpers -----------------------------------------------------
223 def _elapsed(self) -> float:
224 return time.monotonic() - self._start_mono
225
226 # --- notification entry point -----------------------------------------
227 def handle_notification(
228 self, _char: BleakGATTCharacteristic, data: bytearray
229 ) -> None:
230 """Bleak notify callback: log the raw bytes and decode any full frames."""
231 self._notif_count += 1
232 self.log.debug(
233 "NOTIFY #%d %s (+%.3fs) raw=%s",
234 self._notif_count,
235 datetime.now().strftime("%H:%M:%S.%f")[:-3],
236 self._elapsed(),
237 bytes(data).hex(),
238 )
239 self._buffer += data
240 try:
241 self._drain()
242 except Exception: # never let a parsing bug kill the capture
243 self.log.exception("Unexpected error while decoding buffer")
244
245 def marker(self, text: str) -> None:
246 """Record a user note, timestamped, so presses map to frames."""
247 self.log.info(">> MARKER (+%.1fs): %s", self._elapsed(), text)
248
249 def tick(self) -> None:
250 """Periodic liveness line so the console shows it is still capturing."""
251 weight = "n/a" if self._last_weight is None else f"{self._last_weight:g}g"
252 self.log.info(
253 "... capturing (+%.0fs) notifications=%d frames=%d last_weight=%s",
254 self._elapsed(),
255 self._notif_count,
256 self._frame_count,
257 weight,
258 )
259
260 # --- framing (mirrors AcaiaScale._extract_messages) --------------------
261 def _drain(self) -> None:
262 while self._buffer:
263 start = self._buffer.find(_HEADER)
264 if start < 0:
265 # No header: keep a trailing lone HEADER1, drop the rest.
266 if self._buffer[-1] == HEADER1:
267 self._buffer = bytearray((HEADER1,))
268 else:
269 self.log.debug("Ignoring non-header bytes: %s", self._buffer.hex())
270 self._buffer.clear()
271 return
272 if start > 0:
273 self.log.debug(
274 "Dropping %d bytes before header: %s",
275 start,
276 self._buffer[:start].hex(),
277 )
278 del self._buffer[:start]
279
280 pre = bytes(self._buffer)
281 try:
282 msg, remaining = decode(self._buffer)
283 except AcaiaMessageTooShort:
284 return # partial frame, wait for the next notification
285 except AcaiaMessageTooLong:
286 if self._skip_to_next_frame() is None:
287 return
288 continue
289 except AcaiaMessageError as ex:
290 hexb = bytes(ex.bytes_recvd).hex()
291 self.log.warning("DECODE ERROR: %s bytes=%s", ex.message, hexb)
292 self._attention.append(f"decode error '{ex.message}': {hexb}")
293 del self._buffer[:2]
294 continue
295
296 consumed = pre[: len(pre) - len(remaining)]
297 self._buffer = bytearray(remaining)
298 self._on_frame(consumed, msg)
299
300 def _skip_to_next_frame(self) -> int | None:
301 nxt = self._buffer.find(_HEADER, 2)
302 while nxt >= 0:
303 try:
304 decode(self._buffer[nxt:])
305 except AcaiaMessageError:
306 nxt = self._buffer.find(_HEADER, nxt + 2)
307 else:
308 break
309 if nxt < 0:
310 return None
311 self.log.debug("Resyncing: discarding %d bytes before next header", nxt)
312 del self._buffer[:nxt]
313 return nxt
314
315 # --- per-frame handling ------------------------------------------------
316 def _on_frame(self, consumed: bytes, msg: object) -> None:
317 self._frame_count += 1
318 command = consumed[2]
319 length = consumed[3]
320
321 # Decide up front whether this frame is worth showing on the console.
322 interesting = False
323 if command == _EVENT_COMMAND:
324 mt = consumed[4]
325 payload = consumed[5:-2]
326 interesting = mt == MessageType.BUTTON or (
327 mt == MessageType.HEARTBEAT
328 and payload[2:3] == bytes([MessageType.BUTTON])
329 )
330 level = logging.INFO if interesting else logging.DEBUG
331
332 self.log.log(
333 level,
334 "FRAME #%d cmd=0x%02x len=%d raw=%s",
335 self._frame_count,
336 command,
337 length,
338 consumed.hex(),
339 )
340 if msg is not None:
341 name = type(msg).__name__
342 self._counts[name] = self._counts.get(name, 0) + 1
343 self.log.log(level, " DECODED %s -> %s", name, _summarize(msg))
344 if isinstance(msg, WeightMessage):
345 self._last_weight = msg.weight
346 else:
347 self.log.log(level, " DECODED (no message for command 0x%02x)", command)
348
349 if command != _EVENT_COMMAND:
350 return
351
352 msg_type = consumed[4]
353 payload = consumed[5:-2]
354 self.log.log(
355 level,
356 " event msg_type=%d (%s) payload=%s",
357 msg_type,
358 _msg_type_name(msg_type),
359 payload.hex(),
360 )
361
362 if msg_type == MessageType.BUTTON:
363 report = annotate_chain(bytes([MessageType.BUTTON]) + payload)
364 self._emit_records(report, level, consumed)
365 self._record_fixture(msg_type, payload, msg, report)
366 self._timer_crosscheck(msg)
367 elif msg_type == MessageType.HEARTBEAT:
368 wrapper, wrapped = payload[:2], payload[2:]
369 self.log.log(
370 level,
371 " heartbeat wrapper=%s wrapped=%s",
372 wrapper.hex(),
373 wrapped.hex(),
374 )
375 report = annotate_chain(bytes(wrapped))
376 self._emit_records(report, level, consumed)
377 if wrapped[:1] == bytes([MessageType.BUTTON]):
378 self._record_fixture(msg_type, payload, msg, report)
379 self._timer_crosscheck(msg)
380
381 def _emit_records(self, report: ChainReport, level: int, consumed: bytes) -> None:
382 self.log.log(level, " records:")
383 for line in report.lines:
384 self.log.log(level, " %s", line)
385 if not report.ok:
386 for flag in report.flags:
387 self.log.warning(" ANOMALY in %s -> %s", consumed.hex(), flag)
388 self._attention.append(f"frame {consumed.hex()} -> {report.flags[0]}")
389
390 def _record_fixture(
391 self, msg_type: int, payload: bytes, msg: object, report: ChainReport
392 ) -> None:
393 key = f"{msg_type}:{payload.hex()}"
394 if key in self._fixtures:
395 return
396 self._fixtures[key] = FixtureCandidate(
397 msg_type=int(msg_type),
398 payload_hex=payload.hex(),
399 summary=_summarize(msg),
400 first_at=self._elapsed(),
401 clean=report.ok,
402 )
403
404 def _timer_crosscheck(self, msg: object) -> None:
405 """Compare a decoded stop/reset time against wall-clock since START."""
406 if not isinstance(msg, ButtonMessage):
407 return
408 if msg.button is ButtonType.START:
409 self._last_start_mono = time.monotonic()
410 self.log.info(" [timer] START captured; timing the next stop/reset")
411 elif msg.button in (ButtonType.STOP, ButtonType.RESET) and msg.time is not None:
412 if self._last_start_mono is not None:
413 wall = time.monotonic() - self._last_start_mono
414 verdict = "OK" if abs(msg.time - wall) < 2.0 else "MISMATCH <-- CHECK"
415 self.log.info(
416 " [timer] decoded=%.1fs vs wall-clock=%.1fs -> %s",
417 msg.time,
418 wall,
419 verdict,
420 )
421 self._last_start_mono = None
422 else:
423 self.log.info(
424 " [timer] decoded=%.1fs (no START captured to compare)", msg.time
425 )
426
427 # --- end of session ----------------------------------------------------
428 def summary(self) -> None:
429 log = self.log
430 log.info("")
431 log.info("=" * 72)
432 log.info("CAPTURE SUMMARY")
433 log.info(
434 "notifications=%d frames=%d duration=%.1fs",
435 self._notif_count,
436 self._frame_count,
437 self._elapsed(),
438 )
439 if self._counts:
440 log.info("message types:")
441 for name, count in sorted(self._counts.items()):
442 log.info(" %-16s %d", name, count)
443
444 log.info("")
445 if self._fixtures:
446 log.info("FIXTURE CANDIDATES (paste into tests/fixtures/messages.py):")
447 for fc in self._fixtures.values():
448 flag = (
449 ""
450 if fc.clean
451 else " # <-- record walk incomplete; CHECK widths (e.g. tag 0x0b)"
452 )
453 log.info(
454 ' frame(%d, bytes.fromhex("%s")) # %s%s',
455 fc.msg_type,
456 fc.payload_hex,
457 fc.summary,
458 flag,
459 )
460 else:
461 log.info(
462 "No button/heartbeat frames captured -- press the scale's "
463 "buttons (tare/start/stop/reset) during the next run."
464 )
465
466 log.info("")
467 if self._attention:
468 log.info("NEEDS ATTENTION (%d):", len(self._attention))
469 for item in self._attention:
470 log.info(" %s", item)
471 else:
472 log.info(
473 "No anomalies flagged: the PR #15 parser explained every captured "
474 "record chain on this scale."
475 )
476 log.info("")
477 if self.log_path is not None:
478 log.info("Full raw + debug log: %s", self.log_path)
479 log.info("=" * 72)
480
481
482 def _setup_logging() -> tuple[logging.Logger, Path]:
483 ts = datetime.now().strftime("%Y%m%d-%H%M%S")
484 log_path = Path(__file__).with_name(f"capture-{ts}.log")
485
486 file_handler = logging.FileHandler(log_path, encoding="utf-8")
487 file_handler.setLevel(logging.DEBUG)
488 file_handler.setFormatter(
489 logging.Formatter("%(asctime)s %(levelname)-7s %(name)s: %(message)s")
490 )
491
492 console = logging.StreamHandler(sys.stdout)
493 console.setLevel(logging.INFO)
494 console.setFormatter(logging.Formatter("%(message)s"))
495
496 log = logging.getLogger("capture")
497 log.setLevel(logging.DEBUG)
498 log.addHandler(file_handler)
499 log.addHandler(console)
500 log.propagate = False
501
502 # Send aioacaia's own debug logs to the same file for cross-reference.
503 lib = logging.getLogger("aioacaia")
504 lib.setLevel(logging.DEBUG)
505 lib.addHandler(file_handler)
506 lib.propagate = False
507
508 return log, log_path
509
510
511 def _parse_args() -> tuple[str | None, bool]:
512 address: str | None = None
513 old_style = False
514 for arg in sys.argv[1:]:
515 if arg in ("--old-style", "--old"):
516 old_style = True
517 elif arg in ("--new-style", "--new"):
518 old_style = False
519 elif not arg.startswith("-"):
520 address = arg
521 return address, old_style
522
523
524 async def _resolve_address(address: str | None, log: logging.Logger) -> str:
525 if address:
526 return address
527 mac_file = Path(__file__).with_name("mac.txt")
528 if mac_file.exists():
529 address = mac_file.read_text(encoding="utf-8").strip()
530 log.info("Using MAC from mac.txt: %s", address)
531 return address
532 log.info("No address given and no mac.txt found; scanning for Acaia devices...")
533 found = await find_acaia_devices()
534 if not found:
535 raise SystemExit(
536 "No Acaia scale found. Pass a MAC address, or write one to mac.txt."
537 )
538 log.info("Discovered %d device(s); using the first: %s", len(found), found[0])
539 return found[0]
540
541
542 _INSTRUCTIONS = """
543 Suggested validation sequence (narrate each step with a typed marker):
544 1. Put a known weight on the scale (e.g. 55 g) -> type: put 55g
545 2. Press TARE on the scale -> type: tare
546 3. Press START, wait ~10 s, press STOP -> type: start / stop
547 (the decoded stop time is cross-checked against the wall clock)
548 4. Press RESET -> type: reset
549 5. Repeat 3-4 with weight still on the scale (captures weight+time chains)
550 Watch the START frames for tag 0x0b -- that is the width PR #15 is unsure about.
551 Type a note + Enter for a marker, '!tare/!timer/!reset' to send a command,
552 or 'q' to stop.
553 """
554
555
556 async def _run_command(scale: AcaiaScale, log: logging.Logger, cmd: str) -> None:
557 try:
558 if cmd == "tare":
559 await scale.tare()
560 elif cmd in ("timer", "start", "stop", "toggle"):
561 await scale.start_stop_timer()
562 elif cmd == "reset":
563 await scale.reset_timer()
564 else:
565 log.info("Unknown command '!%s' (try !tare, !timer, !reset)", cmd)
566 return
567 log.info(">> sent command: !%s", cmd)
568 except Exception as ex: # noqa: BLE001 - diagnostic tool, surface anything
569 log.warning("command !%s failed: %s", cmd, ex)
570
571
572 def _install_stdin(
573 loop: asyncio.AbstractEventLoop,
574 session: CaptureSession,
575 scale: AcaiaScale,
576 stop_event: asyncio.Event,
577 ) -> bool:
578 try:
579 fd = sys.stdin.fileno()
580 except (ValueError, OSError):
581 return False
582
583 def _on_readable() -> None:
584 line = sys.stdin.readline()
585 if line == "": # EOF
586 loop.remove_reader(fd)
587 stop_event.set()
588 return
589 text = line.strip()
590 if not text:
591 return
592 if text.lower() in ("q", "quit", "exit"):
593 stop_event.set()
594 return
595 if text.startswith("!"):
596 session.marker(f"command {text}")
597 loop.create_task(_run_command(scale, session.log, text[1:].lower()))
598 else:
599 session.marker(text)
600
601 try:
602 loop.add_reader(fd, _on_readable)
603 except (NotImplementedError, ValueError, OSError):
604 return False
605 return True
606
607
608 async def _ticker(session: CaptureSession, stop_event: asyncio.Event) -> None:
609 while not stop_event.is_set():
610 try:
611 await asyncio.wait_for(stop_event.wait(), timeout=10.0)
612 except TimeoutError:
613 session.tick()
614
615
616 async def main() -> None:
617 log, log_path = _setup_logging()
618 session = CaptureSession(log)
619 session.log_path = log_path
620
621 address_arg, old_style = _parse_args()
622 address = await _resolve_address(address_arg, log)
623
624 scale = AcaiaScale(address, is_new_style_scale=not old_style)
625 log.info(
626 "Connecting to %s as %s-style scale (notify=%s, write=%s)...",
627 address,
628 "old" if old_style else "new",
629 scale._notify_char_id, # noqa: SLF001 - diagnostic visibility
630 scale._default_char_id, # noqa: SLF001
631 )
632
633 await scale.connect(callback=session.handle_notification)
634 log.info("Connected. Logging to %s", log_path)
635 log.info(_INSTRUCTIONS)
636
637 stop_event = asyncio.Event()
638 loop = asyncio.get_running_loop()
639 if not _install_stdin(loop, session, scale, stop_event):
640 log.info("(stdin markers unavailable; run interactively for markers)")
641 ticker = asyncio.create_task(_ticker(session, stop_event))
642
643 try:
644 await stop_event.wait()
645 except (KeyboardInterrupt, asyncio.CancelledError):
646 pass
647 finally:
648 ticker.cancel()
649 try:
650 await scale.disconnect()
651 except Exception as ex: # noqa: BLE001
652 log.debug("Error during disconnect: %s", ex)
653 session.summary()
654
655
656 if __name__ == "__main__":
657 try:
658 asyncio.run(main())
659 except KeyboardInterrupt:
660 pass