feat(bms): discover JK batteries and integrate read-only telemetry scenes
This commit is contained in:
@@ -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()
|
||||
Reference in New Issue
Block a user