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

+50 -122
View File
@@ -1,117 +1,43 @@
#!/usr/bin/env python3
"""Host probe v4 — socket ids + ``opt``-seeded payloads (stdlib only).
"""Host probe v4 — ``opt``-seeded payloads via the library business API.
Two corrections vs v3, both from disassembly + live capture:
* wire ``cmdType`` is the socket id (1101/1307/1705/1707);
* the ``communicate`` factory seeds every socket payload with
``"opt": 0`` first (operation type), then merges arguments, e.g.
apower → ``{"opt": 0, "update": 2}``; queryDeviceInfo →
``{"opt": 0, "minProtocolVer": "V1.00.00"}``.
Historical sweep from the ``communicate``-factory finding (socket payloads
always start with ``"opt": 0``). Now built into
``direct_connect_request``; kept as a variant-list driver over
``LocalDeviceClient.send_probe``.
Run on the SoftAP-joined host:
python3 host_probe4.py --sn A03X2516013210060005 --ports 9000
Run from the repo root on the SoftAP-joined host:
python3 scripts/host_probe4.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]
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):
SNNO[0] = (SNNO[0] % 9999) + 1
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 if snno is not None else SNNO[0],
"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, 32)
return a + bytes((b[i] + i + len(a) + n) & 0xFF
for i in range(len(b)))
def decrypt_data(wire, radix=32):
try:
i = wire.find(b"\x58")
if i < 0:
return ""
j = wire.find(b"\x58", i + 1)
if j < 0:
return ""
s = wire[:j].decode()
probe = json.loads(s + "}")
if not isinstance(probe, dict):
return ""
n = int(secret_key(str(probe.get("equipNo", ""))), radix)
prefix = s + ","
tail = wire[j + 1:]
pl = len(prefix.encode())
return prefix + bytes((t - k - pl - n) & 0xFF
for k, t in enumerate(tail)).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 run(label, host, port, tx, timeout, pre_read=0.0):
rx_pre, rx, err, reply = b"", b"", None, None
try:
with socket.create_connection((host, port),
timeout=timeout) as sock:
if pre_read:
rx_pre = recv_all(sock, idle=pre_read)
if tx:
sock.sendall(tx)
rx = recv_all(sock)
if rx:
dec = decrypt_data(rx)
reply = json.loads(dec) if dec else {"_raw": rx.hex()}
except (ConnectionError, socket.error, TimeoutError) as exc:
err = "%s: %s" % (type(exc).__name__, exc)
print("--- %s -> %s:%d" % (label, host, port))
print(" tx (%d B): %s" % (len(tx), tx.hex() or "(none)"))
if rx_pre:
print(" rx_pre (%d B): %s" % (len(rx_pre), rx_pre.hex()))
print(" rx (%d B): %s" % (len(rx), rx.hex() or "(empty)"))
if reply is not None:
print(" reply: " + json.dumps(reply, default=str)[:3000])
if err:
print(" error: %s" % err)
return rx
VARIANTS = (
("queryInfo+minProto+SN", CommunicationCmd.QUERY_DEVICE_INFO,
{"minProtocolVer": "V1.00.00"}, None),
("queryInfo+minProto+empty", CommunicationCmd.QUERY_DEVICE_INFO,
{"minProtocolVer": "V1.00.00"}, ""),
("apower+opt+update2", CommunicationCmd.DEVICE_APOWER_INFO,
{"update": 2}, None),
("bms+opt", CommunicationCmd.BMS, None, None),
("ems+opt", CommunicationCmd.EMS, None, None),
)
def main():
@@ -121,26 +47,28 @@ 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 32)" % (args.sn, key))
variants = [
("queryInfo+minProto+SN", QUERY_INFO, {"minProtocolVer": "V1.00.00"},
None),
("queryInfo+minProto+empty", QUERY_INFO, {"minProtocolVer": "V1.00.00"},
""),
("apower+opt+update2", APOWER, {"update": 2}, None),
("bms+opt", BMS, None, None),
("ems+opt", 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)
if run(label, args.host, port, tx, args.timeout,
pre_read=4.0 if "empty" not in label else 0.0):
return
client = LocalDeviceClient(args.sn, host=args.host,
socket_port=port, timeout=args.timeout)
for label, cmd, data, equip in VARIANTS:
try:
out = client.send_probe(cmd, data=data, timeout=args.timeout,
equip_no=equip)
except (ConnectionError, socket.error, TimeoutError) as exc:
print("--- %s: error: %s: %s"
% (label, type(exc).__name__, exc))
continue
rx = out.get("reply_raw") or b""
print("--- %s tx=%dB rx=%dB"
% (label, len(out["tx"]), len(rx)))
if out.get("reply") is not None:
print(" reply: "
+ json.dumps(out["reply"], default=str)[:1500])
soc = extract_soc(out["reply"])
print(" soc: %s (source=%s)" % (soc["value"],
soc["source"]))
if __name__ == "__main__":