"""Event identity. An `event_id` is `::`. The key alone is not enough: both series reuse keys (a MiniMate restarts at 01110000 after an erase; every Micromate's counter starts at the same value). The timestamp turns a stale id into a loud StaleEvent instead of a download of whatever now sits at that key. "-" stands in for an unknown timestamp. """ from __future__ import annotations import datetime from typing import Optional, Tuple from .errors import BadRequest from .series import normalise_serial _NO_STAMP = "-" _STAMP_FMT = "%Y%m%d%H%M%S" def stamp_of(dt: Optional[datetime.datetime]) -> Optional[str]: return dt.strftime(_STAMP_FMT) if dt is not None else None def iso_of(dt: Optional[datetime.datetime]) -> Optional[str]: return dt.isoformat() if dt is not None else None def make_event_id(serial: str, key: bytes, stamp: Optional[str]) -> str: return f"{normalise_serial(serial)}:{key.hex()}:{stamp or _NO_STAMP}" def parse_event_id(event_id: str, serial: str) -> Tuple[bytes, Optional[str]]: """(key, stamp) for an id that belongs to `serial`; BadRequest otherwise.""" parts = (event_id or "").strip().split(":") if len(parts) != 3: raise BadRequest(f"not an event_id: {event_id!r} -- take it from GET /device/events") id_serial, key_hex, stamp = parts if normalise_serial(id_serial) != normalise_serial(serial): raise BadRequest(f"event_id {event_id!r} belongs to {id_serial}, not {serial}") try: key = bytes.fromhex(key_hex) except ValueError: key = b"" if len(key) != 4: raise BadRequest(f"event_id {event_id!r}: the key must be 8 hex digits") if stamp != _NO_STAMP: try: datetime.datetime.strptime(stamp, _STAMP_FMT) except ValueError: raise BadRequest(f"event_id {event_id!r}: bad timestamp {stamp!r}") from None return key, (None if stamp == _NO_STAMP else stamp)