EnvelopeCodec message layer; scripts are thin business-API wrappers

This commit is contained in:
kfj001 committed 2026-10-16 04:44:45 +00:00
1 parent f15ae42db7
commit 363c7cc6a2
14 files changed
+551 -900

No files matched your search

+34 -131
View File
@@ -1,136 +1,43 @@
#!/usr/bin/env python3
"""Host probe v7 — per-pack BMS reads (stdlib only).
"""Host probe v7 — per-pack BMS reads via the library business API.
The app's ``queryBmsInfoBySocket`` passes ``arguments={"id": pack}``; the
id-less query answers the all-zero ``id: 0`` slot. Pack ids 1..2 select
the two batteries (``BMS_SN …B1/…B2``); ``batSoc`` is the pack charge.
Run on the SoftAP-joined host:
python3 host_probe7.py --sn A03X2516013210060005 --ports 9000
Run from the repo root on the SoftAP-joined host:
python3 scripts/host_probe7.py --sn A03X2516013210060005 --ports 9000
"""
import argparse
import json
import os
import socket
import time
import zlib
import sys
APOWER, QUERY_INFO, BMS, EMS = 0x51B, 0x44D, 0x6A9, 0x6AB
SNNO = [0]
SOC_KEYS = ("currentBatterySoc", "soc", "batSoc", "batterySoc", "vppSoc")
sys.path.insert(0, os.path.dirname(os.path.dirname(
os.path.abspath(__file__))))
from franklinwh_agate_client.battery import extract_soc # noqa: E402
from franklinwh_agate_client.device_local import ( # noqa: E402
LocalDeviceClient,
)
from franklinwh_agate_client.protocol import ( # noqa: E402
CommunicationCmd,
generate_secret_key,
)
def secret_key(sn):
return format(sum(sn.encode()) & 0xFF, "x")
def build_envelope(sn, cmd, args=None, snno=None, ts=None, equip=None):
if snno is None:
SNNO[0] = (SNNO[0] % 9999) + 1
snno = SNNO[0]
data = {"opt": 0}
if args:
data.update(args)
compact = json.dumps(data, separators=(",", ":"))
env = {"cmdType": cmd, "equipNo": equip if equip is not None else sn,
"type": 0,
"timeStamp": ts if ts is not None else int(time.time()),
"snno": snno,
"len": len(compact.encode()),
"crc": format(zlib.crc32(compact.encode()), "X"),
"dataArea": data}
return json.dumps(env, separators=(",", ":"))
def encrypt(json_str, key):
parts = json_str.split(",")
a = (parts[0] + "," + parts[1] + ",").encode()
b = ",".join(parts[2:]).encode()
n = int(key, 16)
return a + bytes((b[i] + i + len(a) + n) & 0xFF
for i in range(len(b)))
def decrypt_wire(wire):
first = wire.find(b",")
second = wire.find(b",", first + 1)
if first < 0 or second < 0:
return ""
a, b = wire[:second + 1], wire[second + 1:]
def run(label, client, call):
try:
probe = json.loads(a[:-1].decode() + "}")
except Exception:
return ""
if not isinstance(probe, dict):
return ""
n = int(secret_key(str(probe.get("equipNo", ""))), 16)
try:
return (a + bytes((t - i - len(a) - n) & 0xFF
for i, t in enumerate(b))).decode()
except Exception:
return ""
def recv_all(sock, idle=8.0):
out = bytearray()
sock.settimeout(idle)
while True:
try:
chunk = sock.recv(65536)
except (socket.timeout, TimeoutError):
break
if not chunk:
break
out.extend(chunk)
return bytes(out)
def walk(obj, key, found):
if isinstance(obj, dict):
for k, v in obj.items():
if k == key:
found.append(v)
walk(v, key, found)
elif isinstance(obj, list):
for item in obj:
walk(item, key, found)
return found
def extract_soc(reply):
for key in SOC_KEYS:
for hit in walk(reply, key, []):
if isinstance(hit, bool):
continue
try:
return float(hit), key
except (TypeError, ValueError):
continue
return None, None
def run(label, host, port, tx, timeout):
rx, err, reply = b"", None, None
try:
with socket.create_connection((host, port),
timeout=timeout) as sock:
sock.sendall(tx)
rx = recv_all(sock)
if rx:
dec = decrypt_wire(rx)
reply = json.loads(dec) if dec else {"_raw": rx.hex()}
reply = call()
except (ConnectionError, socket.error, TimeoutError) as exc:
err = "%s: %s" % (type(exc).__name__, exc)
print("--- %s -> %s:%d" % (label, host, port))
print(" rx (%d B)" % len(rx))
if reply is not None:
da = reply.get("dataArea", reply) if isinstance(reply, dict) else {}
print(" reply: " + json.dumps(reply, default=str)[:1500])
if isinstance(reply, dict):
val, src = extract_soc(reply)
print(" ==> soc: %s (source=%s)" % (val, src))
if err:
print(" error: %s" % err)
print("--- %s: error: %s: %s" % (label, type(exc).__name__, exc))
return None
print("--- %s (%d B reply)" % (label, len(json.dumps(reply))))
print(" reply: " + json.dumps(reply, default=str)[:1500])
result = extract_soc(reply)
print(" ==> soc: %s (source=%s)" % (result["value"], result["source"]))
return reply
@@ -141,21 +48,17 @@ def main():
ap.add_argument("--ports", default="9000")
ap.add_argument("--timeout", type=float, default=5.0)
args = ap.parse_args()
key = secret_key(args.sn)
print("secret key for %s: %s (radix 16)" % (args.sn, key))
variants = [
("bms/id1", BMS, {"id": 1}, None),
("bms/id2", BMS, {"id": 2}, None),
("apower/update2", APOWER, {"update": 2}, None),
("ems", EMS, None, None),
]
print("secret key for %s: %s (radix 16)"
% (args.sn, generate_secret_key(args.sn)))
for port in [int(p) for p in args.ports.split(",") if p.strip()]:
for label, cmd, data, equip in variants:
tx = encrypt(build_envelope(
args.sn, cmd, data,
equip=args.sn if equip is None else equip or "00000000",
), key)
run(label, args.host, port, tx, args.timeout)
print("=== port %d" % port)
client = LocalDeviceClient(args.sn, host=args.host,
socket_port=port, timeout=args.timeout)
run("bms/id1", client, lambda: client.query_bms_info(1))
run("bms/id2", client, lambda: client.query_bms_info(2))
run("apower/update2", client, lambda: client.send_rpc(
CommunicationCmd.DEVICE_APOWER_INFO, data={"update": 2}))
run("ems", client, client.query_ems_info)
if __name__ == "__main__":