feat(bms): discover JK batteries and integrate read-only telemetry scenes
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
"""Read-only JK BLE equipment plugin. No settings or power-control operations."""
|
||||
|
||||
MODEL = "jk.bms"
|
||||
VERSION = "0.1.0"
|
||||
PLUGIN = "missioncore.jk-bms"
|
||||
@@ -0,0 +1,252 @@
|
||||
"""One BLE owner, bounded scans and retries; no pairing, resets or settings.
|
||||
|
||||
BlueZ discovery leases are per D-Bus client. Stop only this client's leases;
|
||||
never disconnect an already connected peer or cancel another client's scan.
|
||||
"""
|
||||
|
||||
import contextlib
|
||||
import time
|
||||
|
||||
import dbus
|
||||
from dbus.mainloop.glib import DBusGMainLoop
|
||||
|
||||
from .protocol import (
|
||||
CHARACTERISTIC,
|
||||
SERVICE,
|
||||
Frames,
|
||||
candidate,
|
||||
identity,
|
||||
query,
|
||||
supported,
|
||||
telemetry,
|
||||
)
|
||||
|
||||
DEVICE = "org.bluez.Device1"
|
||||
ADAPTER = "org.bluez.Adapter1"
|
||||
GATT = "org.bluez.GattCharacteristic1"
|
||||
|
||||
|
||||
class Observer:
|
||||
def __init__(self, service):
|
||||
DBusGMainLoop(set_as_default=True)
|
||||
self.service = service
|
||||
self.bus = dbus.SystemBus()
|
||||
self.scanning = set()
|
||||
self.seen = {}
|
||||
self.retry = {}
|
||||
self.active = None
|
||||
self.next_scan = 0
|
||||
self.scan_end = 0
|
||||
self.closed = False
|
||||
self.bus.add_signal_receiver(
|
||||
self.changed,
|
||||
dbus_interface="org.freedesktop.DBus.Properties",
|
||||
signal_name="PropertiesChanged",
|
||||
path_keyword="path",
|
||||
)
|
||||
self.bus.add_signal_receiver(
|
||||
self.added,
|
||||
dbus_interface="org.freedesktop.DBus.ObjectManager",
|
||||
signal_name="InterfacesAdded",
|
||||
)
|
||||
|
||||
def interface(self, path, interface):
|
||||
return dbus.Interface(self.bus.get_object("org.bluez", path, introspect=False), interface)
|
||||
|
||||
def objects(self):
|
||||
return self.interface("/", "org.freedesktop.DBus.ObjectManager").GetManagedObjects(
|
||||
timeout=3
|
||||
)
|
||||
|
||||
def added(self, path, interfaces):
|
||||
if DEVICE in interfaces:
|
||||
self.observe(str(path), interfaces[DEVICE])
|
||||
|
||||
def observe(self, path, properties):
|
||||
if not candidate(properties):
|
||||
return
|
||||
address = str(properties["Address"]).upper()
|
||||
adapter = str(properties.get("Adapter", ""))
|
||||
rssi = int(properties.get("RSSI", -127))
|
||||
if self.service.observe(address, adapter.rsplit("/", 1)[-1], rssi):
|
||||
self.seen[path] = (time.monotonic(), address, adapter, rssi)
|
||||
|
||||
def changed(self, interface, changed, invalidated, path=None):
|
||||
try:
|
||||
if str(interface) == DEVICE and any(k in changed for k in ("RSSI", "ManufacturerData")):
|
||||
properties = self.interface(path, "org.freedesktop.DBus.Properties").GetAll(
|
||||
DEVICE, timeout=3
|
||||
)
|
||||
self.observe(str(path), properties)
|
||||
a = self.active
|
||||
if a and str(path) == a.get("characteristic") and "Value" in changed:
|
||||
for frame in a["frames"].feed(bytes(changed["Value"])):
|
||||
if frame[4] == 3:
|
||||
info = identity(frame)
|
||||
if not info["model"].startswith("JK_"):
|
||||
self.finish("identity_mismatch")
|
||||
return
|
||||
self.service.identify(a["address"], info)
|
||||
if not supported(info):
|
||||
self.finish("unsupported_firmware", delay=300)
|
||||
return
|
||||
a["verified"] = True
|
||||
elif frame[4] == 2 and a.get("verified"):
|
||||
self.service.sample(a["address"], telemetry(frame))
|
||||
a["last_sample"] = time.monotonic()
|
||||
except (dbus.DBusException, ValueError, OSError, KeyError):
|
||||
self.finish("invalid_response")
|
||||
|
||||
def stop_scan(self):
|
||||
for path in list(self.scanning):
|
||||
with contextlib.suppress(dbus.DBusException):
|
||||
self.interface(path, ADAPTER).StopDiscovery(timeout=3)
|
||||
self.scanning.discard(path)
|
||||
|
||||
def finish(self, reason, delay=None):
|
||||
a, self.active = self.active, None
|
||||
if not a:
|
||||
return
|
||||
self.service.state(a["address"], reason)
|
||||
failures = (
|
||||
0 if a.get("last_sample") else min(self.retry.get(a["address"], (0, 0))[1] + 1, 6)
|
||||
)
|
||||
self.retry[a["address"]] = (
|
||||
time.monotonic() + (delay if delay is not None else max(5, 2**failures)),
|
||||
failures,
|
||||
)
|
||||
try:
|
||||
if a.get("notifying"):
|
||||
self.interface(a["characteristic"], GATT).StopNotify(timeout=3)
|
||||
except dbus.DBusException:
|
||||
pass
|
||||
with contextlib.suppress(dbus.DBusException):
|
||||
self.interface(a["path"], DEVICE).Disconnect(timeout=3)
|
||||
self.next_scan = 0
|
||||
|
||||
def write_read(self, command):
|
||||
a = self.active
|
||||
self.interface(a["characteristic"], GATT).WriteValue(
|
||||
dbus.Array(query(command), signature="y"),
|
||||
dbus.Dictionary({"type": dbus.String("command")}, signature="sv"),
|
||||
timeout=3,
|
||||
)
|
||||
a["last_query"] = time.monotonic()
|
||||
|
||||
def tick(self):
|
||||
if self.closed:
|
||||
return False
|
||||
self.service.expire()
|
||||
try:
|
||||
objects, now = self.objects(), time.monotonic()
|
||||
a = self.active
|
||||
if a:
|
||||
properties = objects.get(a["path"], {}).get(DEVICE, {})
|
||||
if properties.get("Connected"):
|
||||
a["connected"] = True
|
||||
elif a.get("connected"):
|
||||
self.finish("disconnected")
|
||||
return True
|
||||
if properties.get("ServicesResolved") and not a.get("characteristic"):
|
||||
services = {
|
||||
str(p)
|
||||
for p, v in objects.items()
|
||||
if str(p).startswith(a["path"] + "/")
|
||||
and v.get("org.bluez.GattService1", {}).get("UUID") == SERVICE
|
||||
}
|
||||
chars = [
|
||||
str(p)
|
||||
for p, v in objects.items()
|
||||
if str(v.get(GATT, {}).get("Service")) in services
|
||||
and v[GATT].get("UUID") == CHARACTERISTIC
|
||||
and {"notify", "write-without-response"}.issubset(
|
||||
set(v[GATT].get("Flags", []))
|
||||
)
|
||||
]
|
||||
if len(chars) != 1:
|
||||
self.finish("unsupported_gatt", delay=300)
|
||||
return True
|
||||
a["characteristic"] = chars[0]
|
||||
self.interface(chars[0], GATT).StartNotify(timeout=3)
|
||||
a["notifying"] = True
|
||||
self.service.state(a["address"], "identifying")
|
||||
self.write_read(0x97)
|
||||
if a.get("verified") and not a.get("requested"):
|
||||
self.write_read(0x96)
|
||||
a["requested"] = True
|
||||
if a.get("last_query") and now - a.get("last_sample", a["last_query"]) > 12:
|
||||
self.finish("read_timeout")
|
||||
elif not a.get("last_sample") and now - a["started"] > 45:
|
||||
self.finish("connect_timeout")
|
||||
elif now - a["started"] > 120:
|
||||
# Fairness: refresh discovery so a second BMS can be admitted.
|
||||
self.finish("reconnecting", delay=5)
|
||||
return True
|
||||
if now >= self.next_scan and not self.scanning:
|
||||
for path, interfaces in objects.items():
|
||||
properties = interfaces.get(ADAPTER)
|
||||
if properties is None:
|
||||
continue
|
||||
try:
|
||||
if not properties.get("Powered"):
|
||||
self.interface(path, "org.freedesktop.DBus.Properties").Set(
|
||||
ADAPTER, "Powered", dbus.Boolean(True), timeout=3
|
||||
)
|
||||
self.interface(path, ADAPTER).SetDiscoveryFilter(
|
||||
dbus.Dictionary(
|
||||
{
|
||||
"Transport": dbus.String("le"),
|
||||
"DuplicateData": dbus.Boolean(True),
|
||||
},
|
||||
signature="sv",
|
||||
),
|
||||
timeout=3,
|
||||
)
|
||||
self.interface(path, ADAPTER).StartDiscovery(timeout=3)
|
||||
self.scanning.add(str(path))
|
||||
except dbus.DBusException:
|
||||
continue
|
||||
self.scan_end, self.next_scan = now + 12, now + 20
|
||||
if self.scanning and now >= self.scan_end:
|
||||
self.stop_scan()
|
||||
choices = [
|
||||
(path, value)
|
||||
for path, value in self.seen.items()
|
||||
if now - value[0] < 20 and self.retry.get(value[1], (0, 0))[0] <= now
|
||||
]
|
||||
# Never seize a peer already used by another Bluetooth client.
|
||||
busy = {
|
||||
str(v.get(DEVICE, {}).get("Address", "")).upper()
|
||||
for v in objects.values()
|
||||
if v.get(DEVICE, {}).get("Connected")
|
||||
}
|
||||
choices = [(p, v) for p, v in choices if v[1] not in busy]
|
||||
if choices:
|
||||
# Least recently attempted battery first, strongest adapter for it.
|
||||
path, (_, address, adapter, rssi) = min(
|
||||
choices, key=lambda row: (self.retry.get(row[1][1], (0, 0))[0], -row[1][3])
|
||||
)
|
||||
self.service.observe(address, adapter.rsplit("/", 1)[-1], rssi)
|
||||
self.service.state(address, "connecting")
|
||||
a = dict(path=path, address=address, started=now, frames=Frames())
|
||||
self.active = a
|
||||
|
||||
def failed(error):
|
||||
if self.active is a:
|
||||
self.finish("connect_failed")
|
||||
|
||||
self.interface(path, DEVICE).Connect(
|
||||
reply_handler=lambda: None, error_handler=failed, timeout=40
|
||||
)
|
||||
self.seen = {p: v for p, v in self.seen.items() if now - v[0] < 30}
|
||||
except (dbus.DBusException, ValueError, OSError, KeyError):
|
||||
self.finish("bluetooth_unavailable")
|
||||
self.stop_scan()
|
||||
self.next_scan = time.monotonic() + 15
|
||||
return True
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
self.finish("stopped")
|
||||
self.stop_scan()
|
||||
self.bus.close()
|
||||
@@ -0,0 +1,139 @@
|
||||
"""JK02_32S profile qualified against BD6A17S6P / 11.47.
|
||||
|
||||
Only 0x97 (identity) and 0x96 (telemetry subscription) can be constructed.
|
||||
Never expose the raw identity frame: it contains unrelated credential fields.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
|
||||
SERVICE = "0000ffe0-0000-1000-8000-00805f9b34fb"
|
||||
CHARACTERISTIC = "0000ffe1-0000-1000-8000-00805f9b34fb"
|
||||
HEADER = bytes.fromhex("55aaeb90")
|
||||
|
||||
|
||||
def query(command):
|
||||
if type(command) is not int or command not in (0x97, 0x96):
|
||||
raise ValueError("Only the two reviewed read requests are supported")
|
||||
data = bytes.fromhex("aa5590eb") + bytes([command, 0]) + bytes(13)
|
||||
return data + bytes([sum(data) & 255])
|
||||
|
||||
|
||||
def device_id(address):
|
||||
if not re.fullmatch(r"(?:[0-9A-F]{2}:){5}[0-9A-F]{2}", address):
|
||||
raise ValueError("Invalid public Bluetooth identity")
|
||||
return "jkbms_" + hashlib.sha256(("public:" + address).encode()).hexdigest()[:32]
|
||||
|
||||
|
||||
def candidate(properties):
|
||||
"""Advertisement is a candidate, never a verified model or ownership claim."""
|
||||
address = str(properties.get("Address", "")).upper()
|
||||
if properties.get("AddressType") != "public" or not re.fullmatch(
|
||||
r"(?:[0-9A-F]{2}:){5}[0-9A-F]{2}", address
|
||||
):
|
||||
return False
|
||||
manufacturer = properties.get("ManufacturerData", {})
|
||||
data = bytes(manufacturer.get(0x0B65, b""))
|
||||
return (
|
||||
str(properties.get("Name", "")).startswith("JK_")
|
||||
and len(data) == 8
|
||||
and data[:2] == b"\x88\xa0"
|
||||
and data[2:] == bytes.fromhex(address.replace(":", ""))
|
||||
)
|
||||
|
||||
|
||||
class Frames:
|
||||
def __init__(self):
|
||||
self.buffer = bytearray()
|
||||
self.rejected = 0
|
||||
|
||||
def feed(self, data):
|
||||
if len(data) > 512:
|
||||
self.buffer.clear()
|
||||
self.rejected += 1
|
||||
return []
|
||||
self.buffer.extend(data)
|
||||
result = []
|
||||
while len(self.buffer) >= 4:
|
||||
offset = self.buffer.find(HEADER)
|
||||
if offset < 0:
|
||||
del self.buffer[:-3]
|
||||
break
|
||||
del self.buffer[:offset]
|
||||
if len(self.buffer) < 300:
|
||||
break
|
||||
frame = bytes(self.buffer[:300])
|
||||
if sum(frame[:-1]) & 255 != frame[-1]:
|
||||
del self.buffer[0]
|
||||
self.rejected += 1
|
||||
continue
|
||||
del self.buffer[:300]
|
||||
result.append(frame)
|
||||
return result
|
||||
|
||||
|
||||
def identity(frame):
|
||||
if len(frame) != 300 or frame[:5] != HEADER + b"\x03":
|
||||
raise ValueError("Not a JK identity frame")
|
||||
|
||||
def field(start, end):
|
||||
return frame[start:end].split(b"\0", 1)[0].decode("ascii", "replace")
|
||||
|
||||
return {
|
||||
"model": field(6, 22),
|
||||
"hardware": field(22, 30),
|
||||
"firmware": field(30, 38),
|
||||
"name": field(46, 62),
|
||||
"manufactured_raw": field(78, 84),
|
||||
}
|
||||
|
||||
|
||||
def supported(info):
|
||||
return info.get("model") == "JK_BD6A17S6P" and info.get("firmware") == "11.47"
|
||||
|
||||
|
||||
def telemetry(frame):
|
||||
if len(frame) != 300 or frame[:5] != HEADER + b"\x02":
|
||||
raise ValueError("Not a JK telemetry frame")
|
||||
|
||||
def u(offset, size=4, signed=False):
|
||||
return int.from_bytes(frame[offset : offset + size], "little", signed=signed)
|
||||
|
||||
mask = u(70)
|
||||
count = mask.bit_count()
|
||||
# Non-contiguous channel maps are not qualified by this profile.
|
||||
if not 1 <= count <= 32 or mask != (1 << count) - 1:
|
||||
raise ValueError("Unsupported cell map")
|
||||
cells = [u(6 + i * 2, 2) / 1000 for i in range(count)]
|
||||
voltage, soc = u(150) / 1000, u(173, 1)
|
||||
if soc > 100 or any(not 0.5 < v < 5 for v in cells) or abs(sum(cells) - voltage) > 0.1:
|
||||
raise ValueError("Inconsistent battery measurements")
|
||||
|
||||
def temperature(offset, bit):
|
||||
value = u(offset, 2, True)
|
||||
return value / 10 if u(214, 1) & (1 << bit) and value != -2000 else None
|
||||
|
||||
current = u(158, signed=True) / 1000
|
||||
return {
|
||||
"voltage_v": voltage,
|
||||
"current_a": current,
|
||||
"soc_percent": soc,
|
||||
"power_w": round(voltage * current, 3),
|
||||
"power_source": "voltage_times_current",
|
||||
"remaining_ah": u(174) / 1000,
|
||||
"configured_capacity_ah": u(178) / 1000,
|
||||
"cycle_count": u(182),
|
||||
"cycle_capacity_ah": u(186) / 1000,
|
||||
"cell_count": count,
|
||||
"cell_voltages_v": cells,
|
||||
"cell_delta_v": u(76, 2) / 1000,
|
||||
"charge_mos_on": bool(u(198, 1)),
|
||||
"discharge_mos_on": bool(u(199, 1)),
|
||||
"runtime_s": u(194),
|
||||
"balance_current_a": u(170, 2, True) / 1000,
|
||||
"balance_action_raw": u(172, 1),
|
||||
"protection_flags_raw": frame[166:170].hex(),
|
||||
"temperature_mos_c": temperature(144, 0),
|
||||
"temperature_1_c": temperature(162, 1),
|
||||
"temperature_2_c": temperature(164, 2),
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
"""Local read-only inventory endpoint; no public port or arbitrary GATT API."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import pwd
|
||||
import re
|
||||
import signal
|
||||
import socket
|
||||
import socketserver
|
||||
import struct
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
from pathlib import Path
|
||||
|
||||
from .service import Service
|
||||
|
||||
|
||||
class Server(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
|
||||
daemon_threads = True
|
||||
slots = threading.BoundedSemaphore(8)
|
||||
|
||||
def process_request(self, request, address):
|
||||
if not self.slots.acquire(blocking=False):
|
||||
request.close()
|
||||
return
|
||||
super().process_request(request, address)
|
||||
|
||||
def process_request_thread(self, request, address):
|
||||
try:
|
||||
request.settimeout(5)
|
||||
super().process_request_thread(request, address)
|
||||
finally:
|
||||
self.slots.release()
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
_, uid, _ = struct.unpack(
|
||||
"3i", self.connection.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12)
|
||||
)
|
||||
node = self.headers.get("X-Node-Id", "")
|
||||
if uid != self.server.node_uid or not re.fullmatch(r"[a-zA-Z0-9_.:-]{1,128}", node):
|
||||
self.send_error(403)
|
||||
return
|
||||
if self.path != "/inventory":
|
||||
self.send_error(404)
|
||||
return
|
||||
payload = json.dumps(self.server.service.inventory(node), allow_nan=False).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(payload)))
|
||||
self.end_headers()
|
||||
self.wfile.write(payload)
|
||||
|
||||
|
||||
def main():
|
||||
if os.geteuid() == 0:
|
||||
raise SystemExit("BMS runtime must use its service account")
|
||||
from gi.repository import GLib
|
||||
|
||||
from .bluez import Observer
|
||||
|
||||
service = Service()
|
||||
observer = Observer(service)
|
||||
path = Path("/run/mission-core-jk-bms/driver.sock")
|
||||
path.unlink(missing_ok=True)
|
||||
server = Server(str(path), Handler)
|
||||
server.node_uid = pwd.getpwnam("mission-core-node").pw_uid
|
||||
server.service = service
|
||||
os.chmod(path, 0o660)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
loop = GLib.MainLoop()
|
||||
|
||||
def stop():
|
||||
loop.quit()
|
||||
return False
|
||||
|
||||
for signum in (signal.SIGTERM, signal.SIGINT):
|
||||
GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signum, stop)
|
||||
GLib.timeout_add(1000, observer.tick)
|
||||
try:
|
||||
loop.run()
|
||||
finally:
|
||||
observer.close()
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join(timeout=6)
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -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