Files
bellsystems-cp/backend/devices/firestore_v1.py
T
bonaminandClaude Opus 5.5 2e3d7ba062 refactor(devices): store hardware identity as hw_family / hw_revision
The firmware moved its NVS identity keys from hw_type / hw_version to
hw_family / hw_revision (NvsMigration.cpp), and the NVS generator, cloudflash
and the device models already used the new names. Firestore device docs and
the manufacturing code still wrote and read hw_type / hw_version, so the
device API's hw_family / hw_revision were always "" (0 of 14 docs had them)
and the console used two names for one value.

Device docs now use the firmware's names (schema v1.1.0, decision D2 in the
bellsystems-schema repo). The apps don't read these fields, so no app change.

- Manufacturing batch-create writes hw_family / hw_revision; the inventory
  API exposes hw_family / hw_revision (filters: ?hw_family= / ?hw_families=).
  Reads fall back to hw_type / hw_version so docs not yet migrated still work.
- devices/firestore_v1.py renames hw_type / hw_version on read and write and
  rejects a hw_family that isn't a code (e.g. "Bell Plus"): when the console
  generates NVS from it, the firmware builds its OTA URL from that value.
- Inventory, provisioning, onboarding and overview pages use the new names.

Unchanged on purpose: the firmware catalog and flash assets
(/api/firmware/{hw_type}/..., hw_type_override) — a separate store and the
URL devices call; same values, only the variable name differs. The public
cloudflash response keeps its hw_type field (public contract).

Data migration (rename + fix 3 display-label values) runs from the
bellsystems-schema repo AFTER this is deployed: the currently deployed
console still reads hw_type.

Verified: 118 backend tests pass; frontend builds; ESLint errors in
ProvisioningWizard.jsx (7) are pre-existing and unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 21:02:20 +02:00

242 lines
9.5 KiB
Python

"""Device documents <-> Firestore schema v1.
The contract lives in the bellsystems-schema repo (v1/firestore.schema.json). v1 is
the shape the shipped tablet and phone apps read. FlutterFlow parses each document
inside safeGet: ONE field of the wrong type makes the app silently drop the whole
device from the user's list. So every console write to a device goes through
`to_firestore`, and every read goes through `to_api`.
Rules enforced here (README "rules every writer must follow"):
- Timestamps are Firestore Timestamps (datetime). Unset = None, never "".
- IP addresses are dotted strings ("10.0.0.5"), never octet arrays.
- Exact v1 key spelling: bellguardSafetyOn, usesStaticIP. The misspellings
bellGuardSafetyOn / useStaticIP / users_list are converted or dropped.
- device_id and serial_number are equal (decision D1); serial_number is canonical.
- device_melodies_all items use the MelodyMainItem shape (mainInformation, ...).
"""
from __future__ import annotations
import re
from datetime import datetime, timezone
from typing import Any
from google.cloud.firestore_v1 import DocumentReference, GeoPoint
from shared.exceptions import ValidationError
# Keys inside device_attributes (and its nested maps) that hold Timestamps.
TIMESTAMP_KEYS = {
"towerClockTime",
"daySilenceFrom", "daySilenceTo",
"nightSilenceFrom", "nightSilenceTo",
"backlightTurnOnTime", "backlightTurnOffTime",
"subscrStart",
"warrantyStart", "maintainedOn",
}
IP_KEYS = {"ipAddress", "gateway", "subnet", "dns1", "dns2"}
# Misspelled key -> v1 key, per nested map. A value of None means "drop".
LEGACY_KEYS: dict[str, dict[str, str | None]] = {
# hw_type / hw_version: pre-2026-11-08 names; the firmware NVS uses hw_family / hw_revision.
"": {"users_list": None, "hw_type": "hw_family", "hw_version": "hw_revision"},
"device_attributes": {"bellGuardSafetyOn": "bellguardSafetyOn"},
"device_attributes.networkSettings": {"useStaticIP": "usesStaticIP"},
}
# Shape of a melody stored inside a device (MelodyMainItem) vs. a melodies/{id} doc.
_MELODY_ITEM_FORBIDDEN = {"information", "default_settings", "url"}
# Format the console API used to serve before ISO 8601 ("15 January 2026 at 22:01:00 UTC+0000").
# Still accepted on write so a browser tab opened before the deploy can't corrupt data.
_LEGACY_DISPLAY_FMT = "%d %B %Y at %H:%M:%S UTC%z"
# Board family code: a BoardType value ("vesper_plus") or a bespoke UID. Never a display
# label like "Bell Plus" — the firmware builds its OTA URL from this value.
_HW_FAMILY = re.compile(r"^[a-z0-9][a-z0-9_-]*$")
_IPV4 = re.compile(r"^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$")
# ---------------------------------------------------------------- write side
def to_timestamp(value: Any, field: str) -> datetime | None:
"""Coerce an API value into a Firestore Timestamp (tz-aware datetime) or None."""
if value is None or value == "":
return None
if isinstance(value, datetime):
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
if isinstance(value, str):
s = value.strip()
try:
dt = datetime.fromisoformat(s.replace("Z", "+00:00"))
return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
except ValueError:
pass
try:
return datetime.strptime(s, _LEGACY_DISPLAY_FMT)
except ValueError:
pass
raise ValidationError(f"{field}: expected an ISO 8601 timestamp or null, got {value!r}")
def to_ipv4(value: Any, field: str) -> str:
"""Coerce an API value into a dotted IPv4 string. "" means not set."""
if value is None:
return ""
if isinstance(value, (list, tuple)):
parts = [str(p).strip() for p in value if str(p).strip() != ""]
if not parts:
return ""
value = ".".join(parts)
if isinstance(value, str):
s = value.strip()
if s == "" or _IPV4.match(s):
return s
raise ValidationError(f"{field}: expected a dotted IPv4 address like \"10.0.0.5\", got {value!r}")
def _normalize_map(data: dict, path: str) -> dict:
"""Recursively apply key renames, timestamp and IP coercion to one map."""
renames = LEGACY_KEYS.get(path, {})
out: dict = {}
# v1 keys first, so a legacy duplicate never overwrites a correct value
# that is also present in the same map.
for key in sorted(data, key=lambda k: k in renames):
value = data[key]
if key in renames:
target = renames[key]
if target is None or target in out or target in data:
continue # drop the legacy key (v1 key present, or field is retired)
key = target
child = f"{path}.{key}" if path else key
if isinstance(value, dict):
value = _normalize_map(value, child)
elif key in TIMESTAMP_KEYS and path:
value = to_timestamp(value, child)
elif key in IP_KEYS and path.endswith("networkSettings"):
value = to_ipv4(value, child)
out[key] = value
return out
def _user_ref(db, entry) -> DocumentReference:
if isinstance(entry, DocumentReference):
return entry
uid = str(entry).strip().split("/")[-1]
if not uid:
raise ValidationError(f"user_list: empty entry {entry!r}")
return db.collection("users").document(uid)
def _check_melodies(items: Any, db) -> list:
if items is None:
return []
if not isinstance(items, list):
raise ValidationError("device_melodies_all: expected a list")
out = []
for i, item in enumerate(items):
if not isinstance(item, dict):
raise ValidationError(f"device_melodies_all[{i}]: expected an object")
bad = _MELODY_ITEM_FORBIDDEN & item.keys()
if bad:
raise ValidationError(
f"device_melodies_all[{i}]: uses melodies-collection keys {sorted(bad)}; "
"device melodies must use mainInformation / defaultSettings / settings / binaryUrl"
)
ref = item.get("melodyReference")
if isinstance(ref, str) and db is not None:
item = {**item, "melodyReference": db.collection("melodies").document(ref.split("/")[-1]) if ref else None}
out.append(item)
return out
def to_firestore(data: dict, db=None) -> dict:
"""Normalize a (partial) device document for writing to Firestore under v1.
Raises ValidationError (422) for values that cannot be represented in v1, instead
of writing something the apps would choke on.
"""
out = _normalize_map(data, "")
# D1: device_id mirrors serial_number. Whichever one is being written, write both.
sn, did = out.get("serial_number"), out.get("device_id")
if sn and did and sn != did:
raise ValidationError(f"device_id ({did}) must equal serial_number ({sn})")
if sn or did:
out["serial_number"] = out["device_id"] = sn or did
fam = out.get("hw_family")
if fam not in (None, "") and not (isinstance(fam, str) and _HW_FAMILY.match(fam)):
raise ValidationError(f"hw_family: expected a board family code like \"vesper_plus\", got {fam!r}")
if "user_list" in out and db is not None:
refs, seen = [], set()
for e in out["user_list"] or []:
ref = _user_ref(db, e)
if ref.id not in seen:
seen.add(ref.id)
refs.append(ref)
out["user_list"] = refs
if "device_melodies_all" in out:
out["device_melodies_all"] = _check_melodies(out["device_melodies_all"], db)
coords = out.get("device_location_coordinates")
if isinstance(coords, dict) and "lat" in coords and "lng" in coords:
out["device_location_coordinates"] = GeoPoint(coords["lat"], coords["lng"])
return out
# ----------------------------------------------------------------- read side
def _api_value(v):
if isinstance(v, datetime):
dt = v if v.tzinfo else v.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
if isinstance(v, GeoPoint):
return {"lat": v.latitude, "lng": v.longitude}
if isinstance(v, DocumentReference):
return v.path
if isinstance(v, dict):
return {k: _api_value(x) for k, x in v.items()}
if isinstance(v, list):
return [_api_value(x) for x in v]
return v
def to_api(raw: dict) -> dict:
"""Firestore device doc -> JSON for the console frontend.
Timestamps become ISO 8601 UTC strings (round-trip safe with to_timestamp),
references become paths, GeoPoints become {lat, lng}. Legacy misspelled keys
are folded into their v1 names so the frontend only ever sees v1 names.
"""
return _api_value(_normalize_read(raw, ""))
def _normalize_read(data: dict, path: str) -> dict:
renames = LEGACY_KEYS.get(path, {})
out = {}
for key in sorted(data, key=lambda k: k in renames):
value = data[key]
if key in renames:
target = renames[key]
if target is None or target in data:
continue
key = target
child = f"{path}.{key}" if path else key
if isinstance(value, dict):
value = _normalize_read(value, child)
elif key in TIMESTAMP_KEYS and path and value == "":
value = None # stored "" (pre-v1 bug) reads as unset
elif key in IP_KEYS and path.endswith("networkSettings") and isinstance(value, list):
parts = [str(p) for p in value if str(p) != ""]
value = ".".join(parts) if parts else ""
out[key] = value
return out