feat(bms): discover JK batteries and integrate read-only telemetry scenes
This commit is contained in:
@@ -0,0 +1,171 @@
|
||||
"""Bounded latest telemetry in RAM; only confirmed identity survives restart."""
|
||||
|
||||
import copy
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
from . import MODEL, PLUGIN, VERSION
|
||||
from .protocol import device_id, supported
|
||||
|
||||
|
||||
def utc():
|
||||
return datetime.now(UTC).isoformat()
|
||||
|
||||
|
||||
class Service:
|
||||
def __init__(self, root="/var/lib/mission-core-jk-bms", clock=time.monotonic):
|
||||
self.root, self.clock = Path(root), clock
|
||||
self.lock = threading.RLock()
|
||||
self.instance = "jkbms_" + uuid.uuid4().hex
|
||||
self.devices = {}
|
||||
self.revision = 0
|
||||
self.day = datetime.now(UTC).date()
|
||||
for path in sorted(self.root.glob("jkbms_*.json"))[:8]:
|
||||
try:
|
||||
data = json.loads(path.read_text())
|
||||
if path.name != device_id(data["address"]) + ".json":
|
||||
continue
|
||||
self.observe(data["address"], None, None)
|
||||
self.devices[data["address"]]["identity"] = data["identity"]
|
||||
except (ValueError, KeyError, OSError):
|
||||
continue
|
||||
|
||||
def observe(self, address, adapter, rssi):
|
||||
with self.lock:
|
||||
if address not in self.devices:
|
||||
if len(self.devices) >= 8:
|
||||
return False
|
||||
self.devices[address] = dict(
|
||||
id=device_id(address),
|
||||
session="jkbms_" + uuid.uuid4().hex,
|
||||
opened=utc(),
|
||||
identity=None,
|
||||
sample=None,
|
||||
sample_at=None,
|
||||
sampled=0,
|
||||
state="discovered",
|
||||
adapter=None,
|
||||
rssi_dbm=None,
|
||||
link_generation=0,
|
||||
)
|
||||
d = self.devices[address]
|
||||
d.update(adapter=adapter, rssi_dbm=rssi)
|
||||
self.revision += 1
|
||||
return True
|
||||
|
||||
def state(self, address, state):
|
||||
with self.lock:
|
||||
self.devices[address]["state"] = state
|
||||
if state == "connecting":
|
||||
self.devices[address]["link_generation"] += 1
|
||||
self.revision += 1
|
||||
|
||||
def identify(self, address, info):
|
||||
with self.lock:
|
||||
d = self.devices[address]
|
||||
d["identity"] = copy.deepcopy(info)
|
||||
self.root.mkdir(parents=True, exist_ok=True)
|
||||
destination = self.root / (d["id"] + ".json")
|
||||
temporary = destination.with_suffix(".tmp")
|
||||
# Only allowlisted metadata, never frames, credentials or measurements.
|
||||
temporary.write_text(json.dumps({"address": address, "identity": info}))
|
||||
os.chmod(temporary, 0o600)
|
||||
os.replace(temporary, destination)
|
||||
self.revision += 1
|
||||
|
||||
def sample(self, address, sample):
|
||||
with self.lock:
|
||||
self.expire()
|
||||
self.devices[address].update(
|
||||
sample=copy.deepcopy(sample),
|
||||
sample_at=utc(),
|
||||
sampled=self.clock(),
|
||||
state="streaming",
|
||||
)
|
||||
self.revision += 1
|
||||
|
||||
def expire(self):
|
||||
with self.lock:
|
||||
self._expire()
|
||||
|
||||
def _expire(self):
|
||||
today = datetime.now(UTC).date()
|
||||
for d in self.devices.values():
|
||||
if today != self.day or self.clock() - d["sampled"] >= 300:
|
||||
d.update(sample=None, sample_at=None)
|
||||
self.day = today
|
||||
|
||||
def inventory(self, node):
|
||||
with self.lock:
|
||||
self.expire()
|
||||
items = []
|
||||
for address, d in self.devices.items():
|
||||
info = d["identity"] or {}
|
||||
fresh = d["sample"] is not None and self.clock() - d["sampled"] < 12
|
||||
online = d["state"] == "streaming" and fresh
|
||||
status = {
|
||||
k: copy.deepcopy(d[k])
|
||||
for k in (
|
||||
"state",
|
||||
"identity",
|
||||
"sample",
|
||||
"sample_at",
|
||||
"adapter",
|
||||
"rssi_dbm",
|
||||
"link_generation",
|
||||
)
|
||||
}
|
||||
status.update(
|
||||
schema="missioncore.jk-bms/v1",
|
||||
address=address,
|
||||
fresh=online,
|
||||
compatible=supported(info),
|
||||
sample_ttl_s=300,
|
||||
)
|
||||
items.append(
|
||||
dict(
|
||||
id=d["id"],
|
||||
kind=MODEL,
|
||||
name=info.get("name") or "JK BMS",
|
||||
model=info.get("model") or "JK BMS · обнаружена",
|
||||
firmware=info.get("firmware"),
|
||||
initializable=False,
|
||||
prepared=True,
|
||||
configured=bool(info),
|
||||
verified=supported(info),
|
||||
online=online,
|
||||
usb="",
|
||||
connection_mode="bluetooth",
|
||||
connection_label="Bluetooth LE",
|
||||
layers=[],
|
||||
bms_status=status,
|
||||
snapshot=dict(
|
||||
context=dict(
|
||||
session_id=d["session"],
|
||||
device=dict(
|
||||
device_id=d["id"],
|
||||
model=dict(
|
||||
plugin_id=PLUGIN, plugin_version=VERSION, model_id=MODEL
|
||||
),
|
||||
stability="stable",
|
||||
basis="hardware-identifier",
|
||||
),
|
||||
execution=dict(
|
||||
node_id=node, agent_instance_id=self.instance, platform="linux"
|
||||
),
|
||||
opened_at=d["opened"],
|
||||
),
|
||||
revision=self.revision,
|
||||
observed_at=utc(),
|
||||
enrollment="enrolled" if info else "empty",
|
||||
acquisition="idle",
|
||||
connectivity="connected" if online else "degraded",
|
||||
),
|
||||
)
|
||||
)
|
||||
return {"items": items}
|
||||
Reference in New Issue
Block a user