309 lines
15 KiB
Python
309 lines
15 KiB
Python
# 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", {})])
|
|
# the one limit shared: the charger 6 A x 690 V = 4140 W, the battery's charging the 60 W left
|
|
assert lim == {"ev": {"current_a": (None, 6.0)}, "bat": {"power_w": (None, 60.0)}}
|
|
|
|
|
|
class _C:
|
|
def __init__(self, id, kind, params, entities=None):
|
|
self.id, self.kind, self.params, self.entities = id, kind, params, entities or {}
|
|
|
|
|
|
def test_chargers_share_the_one_limit(tmp_path):
|
|
# a building's three garage chargers (Sim Durlach, feeder 6, 2026-11-08): before, each got the whole 4.2 kW
|
|
g = GridOrders(str(tmp_path), clock=lambda: NOW)
|
|
g.take(message())
|
|
evs = [_C(f"garage_{n}", "ev", {"phases": 3, "voltage": 230, "min_current_a": 6, "max_current_a": 16}) for n in (1, 2, 3)]
|
|
lim = g.limits(evs + [_C("bat", "battery", {})])
|
|
amps = [lim[f"garage_{n}"]["current_a"][1] for n in (1, 2, 3)]
|
|
assert amps == [6.0, 0.0, 0.0] # one at its minimum, the others paused: within the order
|
|
assert sum(a * 690 for a in amps) + lim["bat"]["power_w"][1] <= 4200.0
|
|
# the first has no car: the second takes the share
|
|
lim = g.limits(evs, connected={"garage_1": False, "garage_2": True, "garage_3": None})
|
|
assert [lim[f"garage_{n}"]["current_a"][1] for n in (1, 2, 3)] == [0.0, 6.0, 0.0]
|
|
# a larger order: each its share in turn, never above the order
|
|
g.take(message(limit_w=16000.0, id="cb01-2"))
|
|
lim = g.limits(evs)
|
|
amps = [lim[f"garage_{n}"]["current_a"][1] for n in (1, 2, 3)]
|
|
# the first's bound is above its 16 A (it draws at most 16 A = 11 040 W), the second gets the 4 960 W left
|
|
assert amps == [23.1, 7.1, 0.0] and sum(min(a, 16) * 690 for a in amps) <= 16000.0
|
|
|
|
|
|
def test_renewed_order_holds(tmp_path):
|
|
# the bridge renews the order (the same id, a later end): it holds past the first end
|
|
t = [NOW]
|
|
g = GridOrders(str(tmp_path), clock=lambda: t[0])
|
|
assert g.take(message()) == (True, "taken")
|
|
t[0] = NOW + 290
|
|
assert g.take(message(until=NOW + 1500)) == (False, "taken") # the same order: no new decision
|
|
t[0] = NOW + 880
|
|
g.take(message(until=NOW + 1500)) # the bridge repeats it (every 15 s)
|
|
t[0] = NOW + 1000
|
|
assert g.active() and g.active()["until"] == NOW + 1500
|
|
t[0] = NOW + 1501
|
|
assert g.active() is None
|
|
|
|
|
|
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.0)}
|
|
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"}) == {}
|
|
|
|
|
|
def test_the_order_reaches_the_cloud_once_per_quarter_hour(tmp_path):
|
|
"""An action per ledger slot while the order holds (and on a change),
|
|
one when it ends: fleet's market ledger exempts those slots."""
|
|
t = [NOW]
|
|
g = GridOrders(str(tmp_path), clock=lambda: t[0])
|
|
assert g.action() is None # no order: nothing
|
|
g.take(message(until=NOW + 1800))
|
|
a = g.action()
|
|
assert (a["entity"], a["service"], a["value"], a["result"]) == ("grid:eebus-lpc", "grid.load_limit", "4200.0", "done")
|
|
assert "grid operator's order" in a["why"] and "cb01" in a["why"] and len(a["why"]) <= 500
|
|
assert g.action() is None # the same slot: told already
|
|
t[0] = (NOW // gridorder.SLOT_S + 1) * gridorder.SLOT_S + 5 # the next quarter-hour
|
|
assert g.action()["at"] == t[0]
|
|
g.take(message(until=NOW + 1800, limit_w=3000.0)) # a new limit in the same slot
|
|
assert g.action()["value"] == "3000.0"
|
|
t[0] = NOW + 1801 # over
|
|
end = g.action()
|
|
assert end["value"] == "" and "ended" in end["why"]
|
|
assert g.action() is None
|
|
|
|
|
|
def test_controller_publishes_the_order_as_an_action(tmp_path):
|
|
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": []}))
|
|
|
|
class Sink:
|
|
def __init__(self):
|
|
self.sent = []
|
|
|
|
async def publish(self, kind, data):
|
|
self.sent.append((kind, data))
|
|
sink = Sink()
|
|
ctl = Controller(Config(site_id="ab" * 16, mapping=str(m), state_dir=str(tmp_path)), Mapping.load(str(m)),
|
|
Consent(str(tmp_path)), sink=sink, clock=lambda: NOW)
|
|
assert asyncio.run(ctl.grid_order(message().encode()))
|
|
assert [k for k, _ in sink.sent].count("action") == 1
|
|
assert [d for k, d in sink.sent if k == "action"][0]["service"] == "grid.load_limit"
|
|
|
|
|
|
def test_executor_holds_every_charger_to_its_share(tmp_path):
|
|
"""Under an order the executor sets each charger to its share whatever the plan says: a charger the plan
|
|
leaves alone (no session to plan), one planned above its share, one whose share is 0 (paused)."""
|
|
import yaml
|
|
from cantabile_edge.config import Config
|
|
from cantabile_edge.consent import Consent
|
|
from cantabile_edge.controller import Controller
|
|
from cantabile_edge.executor import RELEASE
|
|
from cantabile_edge.mapping import Mapping
|
|
m = tmp_path / "mapping.yaml"
|
|
m.write_text(yaml.safe_dump({"version": 3, "assets": [], "controls": [
|
|
{"id": f"garage_{n}", "kind": "ev", "consent": True,
|
|
"entities": {"switch": f"switch.ev{n}", "current": f"number.ev{n}_amps", "connected": f"binary_sensor.ev{n}"},
|
|
"params": {"phases": 3, "voltage": 230, "min_current_a": 6, "max_current_a": 16}} for n in (1, 2, 3)]}))
|
|
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.col.on_entities({"a": {f"binary_sensor.ev{n}": {"s": "on", "a": {}} for n in (1, 2, 3)}})
|
|
assert asyncio.run(ctl.grid_order(message().encode()))
|
|
ex = ctl.executor
|
|
cs = {c.id: c for c in ctl.controls}
|
|
ex.commands.clear()
|
|
ex.plan = None # no plan: each control's safe value (release)
|
|
want = {cid: ex.wanted(cs[cid], t[0]) for cid in cs}
|
|
assert want["garage_1"][0] == 6.0 and want["garage_1"][1] == "emergency" and "grid operator" in want["garage_1"][2]
|
|
assert want["garage_2"][0] == "off" and want["garage_3"][0] == "off"
|
|
# a plan above the share is capped; a plan below it stays the plan's
|
|
assert ex._grid_bound(cs["garage_1"], 16.0, "plan", "")[0] == 6.0
|
|
assert ex._grid_bound(cs["garage_1"], "off", "plan", "x") == ("off", "plan", "x")
|
|
assert ex._grid_bound(cs["garage_1"], RELEASE, "plan", "")[0] == 6.0
|
|
# the car on charger 1 leaves: the next round gives charger 2 the share
|
|
ctl.col.on_entities({"a": {"binary_sensor.ev1": {"s": "off", "a": {}}}})
|
|
ctl.grid_tick()
|
|
assert ctl.guard.extra_limits["garage_2"]["current_a"]["grid"] == (None, 6.0)
|
|
assert ctl.guard.extra_limits["garage_1"]["current_a"]["grid"] == (None, 0.0)
|
|
# the order ends: no bound, the plan's want again
|
|
assert asyncio.run(ctl.grid_order(message(active=False, state="normal", limit_w=0.0, id="cb01-9").encode()))
|
|
assert ex._grid_bound(cs["garage_1"], 16.0, "plan", "")[0] == 16.0
|