cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.400: full source

This commit is contained in:
Setti Solutions S.R.L committed 2026-10-30 08:26:45 +02:00
1 parent 343331d234
commit d5fbcacaa4
176 files changed
+32511 -19

No files matched your search

+183
View File
@@ -0,0 +1,183 @@
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
"""The grid operator's limit from the EEBUS bridge (gridorder.py): Ed25519 against RFC 8032's vectors, the bridge's key pinned on first
use, orders checked, the controller's limits and the optimiser's
constraint."""
import asyncio
import base64
import hashlib
import json
import pytest
from cantabile_edge import gridorder
from cantabile_edge.gridorder import GridOrders, verify
# RFC 8032, 7.1, tests 1 and 2
VECTORS = [
("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
"d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", "",
"e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"),
("4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb",
"3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c", "72",
"92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00"),
]
def test_rfc8032_vectors():
for _sk, pk, msg, sig in VECTORS:
pk, msg, sig = bytes.fromhex(pk), bytes.fromhex(msg), bytes.fromhex(sig)
assert verify(pk, msg, sig)
assert not verify(pk, msg + b"x", sig)
assert not verify(pk, msg, sig[:-1] + bytes([sig[-1] ^ 1]))
assert not verify(b"\x00" * 31, b"", b"\x00" * 64)
def _sign(seed: bytes, msg: bytes) -> tuple[bytes, bytes]:
"""Ed25519 signing (RFC 8032, 5.1.6), for the tests only (the bridge
signs in Go)."""
h = hashlib.sha512(seed).digest()
a = int.from_bytes(h[:32], "little")
a &= (1 << 254) - 8
a |= 1 << 254
def enc(p):
x, y, z, _ = p
zi = pow(z, gridorder._P - 2, gridorder._P)
x, y = x * zi % gridorder._P, y * zi % gridorder._P
return (y | ((x & 1) << 255)).to_bytes(32, "little")
pub = enc(gridorder._mul(a, gridorder._G))
r = int.from_bytes(hashlib.sha512(h[32:] + msg).digest(), "little") % gridorder._L
R = enc(gridorder._mul(r, gridorder._G))
k = int.from_bytes(hashlib.sha512(R + pub + msg).digest(), "little") % gridorder._L
return pub, R + ((r + k * a) % gridorder._L).to_bytes(32, "little")
def test_signing_helper_matches_rfc():
sk, pk, _msg, sig = VECTORS[0]
pub, s = _sign(bytes.fromhex(sk), b"")
assert pub.hex() == pk and s.hex() == sig
SEED = bytes(range(32))
NOW = 1_800_000_000
def message(seed=SEED, **o):
order = {"v": 1, "kind": "eebus-lpc", "id": "cb01-1", "state": "limited", "active": True, "limit_w": 4200.0,
"from": NOW, "until": NOW + 900, "failsafe_w": 4200.0, "failsafe_s": 7200.0, "scope": "controllable",
"control_box": {"ski": "cb01", "device": "control_box_cb01"}, "issued": NOW}
order.update(o)
text = json.dumps(order)
pub, sig = _sign(seed, text.encode())
return json.dumps({"order": text, "sig": base64.b64encode(sig).decode(), "key": base64.b64encode(pub).decode()})
def test_orders_pinned_and_checked(tmp_path):
g = GridOrders(str(tmp_path), clock=lambda: NOW + 10)
assert g.take(message()) == (True, "taken")
assert (tmp_path / "eebus-bridge.key").exists()
assert g.proof() == "verified:eebus-lpc:cb01:cb01-1"
# another key: refused, the order stays
assert g.take(message(seed=bytes(32), limit_w=99999.0))[1].startswith("signed by another key")
assert g.active()["limit_w"] == 4200.0
# a forged order with the right key but a changed text
m = json.loads(message())
m["order"] = m["order"].replace("4200.0", "42000.0", 1)
assert g.take(json.dumps(m)) == (False, "bad signature")
# active without a control box
assert "control box" in g.take(message(control_box={}))[1]
# the same order again: no change; its end
assert g.take(message()) == (False, "taken")
assert g.take(message(active=False, state="normal", limit_w=0.0)) == (True, "taken")
assert g.active() is None and g.proof() == ""
def test_stale_and_ended(tmp_path):
t = [NOW]
g = GridOrders(str(tmp_path), clock=lambda: t[0])
g.take(message(until=0))
assert g.active()
t[0] += gridorder.STALE_S + 1
assert g.active() is None # the bridge went quiet: its own failsafe holds
t[0] = NOW
g.take(message(until=NOW + 60))
t[0] = NOW + 61
assert g.active() is None
def test_model_constraint_and_limits(tmp_path):
g = GridOrders(str(tmp_path), clock=lambda: NOW)
g.take(message())
m = g.for_model(NOW - 900, 900, 192)
assert m["limit_w"] == 4200.0 and m["from_step"] == 1 and m["to_step"] == 2 and m["proof"].startswith("verified:")
class C:
def __init__(self, id, kind, params):
self.id, self.kind, self.params = id, kind, params
lim = g.limits([C("ev", "ev", {"phases": 3, "voltage": 230}), C("bat", "battery", {}), C("room", "heating", {})])
assert lim == {"ev": {"current_a": (None, 6.1)}, "bat": {"power_w": (None, 4200.0)}}
highspy = pytest.importorskip("highspy")
def test_optimizer_keeps_the_controllable_draw_under_the_limit():
from cantabile_edge import optimizer
from test_optimizer import START, house
ev = {"id": "ev", "kind": "ev", "channels": ["switch", "current"],
"params": {"need_wh": 30000, "departure": "07:00", "min_current_a": 6, "max_current_a": 16,
"phases": 3, "voltage": 230},
"state": {"connected": True}, "bounds": {"current_a": [0, 16, "device", "device"]}}
free = optimizer.plan(house([ev]), 20)
s = house([ev])
s["grid_order"] = {"limit_w": 4200.0, "from_step": 0, "to_step": 192, "penalty": 500.0}
limited = optimizer.plan(s, 20)
def top(p):
return max((e["set"] for e in p["devices"]["ev"] if e["set"] != "off"), default=0)
assert top(free) > 6.1 # 30 kWh by 07:00 wants more than 4.2 kW
assert 0 < top(limited) <= 6.1 + 1e-6, limited["devices"]["ev"] # 6 A x 3 x 230 V = 4.14 kW
def test_controller_takes_an_order(tmp_path):
"""The bridge's order through the controller: the guard's grid limits
at once, merged with the console's, the owner told, gone again when it ends."""
import os
import yaml
from cantabile_edge.config import Config
from cantabile_edge.consent import Consent
from cantabile_edge.controller import Controller
from cantabile_edge.mapping import Mapping
m = tmp_path / "mapping.yaml"
m.write_text(yaml.safe_dump({"version": 3, "assets": [], "controls": [
{"id": "car", "kind": "ev", "consent": True, "entities": {"switch": "switch.wb", "current": "number.wb_amps"},
"params": {"phases": 3, "voltage": 230, "min_current_a": 6, "max_current_a": 16}}]}))
t = [NOW]
ctl = Controller(Config(site_id="ab" * 16, mapping=str(m), state_dir=str(tmp_path)), Mapping.load(str(m)),
Consent(str(tmp_path)), sink=None, clock=lambda: t[0])
ctl.saved_limits = {"car": {"current_a": {"cloud": (None, 10.0)}}}
ctl._merge_limits()
got = []
ctl.on_received.append(lambda ev: _append(got, ev))
assert asyncio.run(ctl.grid_order(message().encode()))
assert ctl.guard.extra_limits["car"]["current_a"] == {"cloud": (None, 10.0), "grid": (None, 6.1)}
assert got and got[0]["by"] == "grid" and got[0]["args"]["level"] == "emergency" and "proof" not in got[0]["args"]
st = ctl.gridorders.for_model(NOW, 900, 192)
assert st["limit_w"] == 4200.0
# ended
assert asyncio.run(ctl.grid_order(message(active=False, state="normal", limit_w=0.0, id="cb01-2").encode()))
assert ctl.guard.extra_limits["car"]["current_a"] == {"cloud": (None, 10.0)}
assert not os.path.exists(tmp_path / "limits.json") # the order's limits are never saved as the console's
async def _append(lst, ev):
lst.append(ev)
def test_inventory_carries_the_eebus_ski():
from cantabile_edge.inventory import _eebus
ski = "C0B05C0A1B0C0DE000000000000000000000C0B0"
assert _eebus({"identifiers": [["mqtt", "cantabile_eebus_cb_c0b05c"]], "serial_number": ski}) == {"eebus_ski": ski.lower()}
# anything but a SKI is left out (the platform would refuse the inventory)
assert _eebus({"identifiers": [["mqtt", "cantabile_eebus_cb_c0b05c"]], "serial_number": "c0b05c0a"}) == {}
assert _eebus({"identifiers": [["mqtt", "cantabile_modbus_x"]], "serial_number": "1"}) == {}