EnvelopeCodec message layer; scripts are thin business-API wrappers
This commit is contained in:
1 parent
f15ae42db7
commit
363c7cc6a2
14 files changed
+551
-900
No files matched your search
+52
-119
@@ -1,114 +1,45 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Host probe v3 — socket-transport command ids (stdlib only).
|
||||
"""Host probe v3 — socket-id variants via the library business API.
|
||||
|
||||
A PCAPdroid capture of the working app showed ``{"cmdType":1101, ...}`` on
|
||||
the wire: ``CommunicationCmd::cmd`` returns the *second* id field for
|
||||
socket mode (QUERY_DEVICE_INFO 1101, APOWER 1307, BMS 1705, EMS 1707).
|
||||
Earlier probes used the small ids (25/0/29/30) and were dropped silently.
|
||||
Historical sweep that established the socket-transport command space
|
||||
(``1101/1307/1705/1707`` instead of the ``off_8`` ids). Superseded by
|
||||
``host_probe6.py`` for routine use; kept as a variant-list driver over
|
||||
``LocalDeviceClient.send_probe``.
|
||||
|
||||
Run on the SoftAP-joined host:
|
||||
python3 host_probe3.py --sn A03X2516013210060005 --ports 9000
|
||||
Run from the repo root on the SoftAP-joined host:
|
||||
python3 scripts/host_probe3.py --sn A03X2516013210060005 --ports 9000
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import time
|
||||
import zlib
|
||||
import sys
|
||||
|
||||
# Wire cmdType per CommunicationCmd::cmd (socket mode).
|
||||
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, data=None, snno=None, ts=None, equip=None):
|
||||
SNNO[0] = (SNNO[0] % 9999) + 1
|
||||
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": 0, "crc": ""}
|
||||
if data:
|
||||
compact = json.dumps(data, separators=(",", ":"))
|
||||
env["len"] = len(compact.encode())
|
||||
env["crc"] = format(zlib.crc32(compact.encode()), "X")
|
||||
env["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())
|
||||
plain = bytes((t - k - pl - n) & 0xFF for k, t in enumerate(tail))
|
||||
return prefix + plain.decode()
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def recv_all(sock, idle=6.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)[:2000])
|
||||
if err:
|
||||
print(" error: %s" % err)
|
||||
return rx
|
||||
VARIANTS = (
|
||||
# (label, cmd, data, equip_no override or None for the client SN)
|
||||
("queryInfo/1101+SN", CommunicationCmd.QUERY_DEVICE_INFO,
|
||||
{"minProtocolVer": "V1.00.00"}, None),
|
||||
("queryInfo/1101+empty", CommunicationCmd.QUERY_DEVICE_INFO,
|
||||
{"minProtocolVer": "V1.00.00"}, ""),
|
||||
("apower/1307+update2", CommunicationCmd.DEVICE_APOWER_INFO,
|
||||
{"update": 2}, None),
|
||||
("apower/1307+none", CommunicationCmd.DEVICE_APOWER_INFO, None, None),
|
||||
("bms/1705", CommunicationCmd.BMS, None, None),
|
||||
("ems/1707", CommunicationCmd.EMS, None, None),
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
@@ -118,26 +49,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/1101+SN", QUERY_INFO, None, None),
|
||||
("queryInfo/1101+empty-SN", QUERY_INFO, None, ""),
|
||||
("apower/1307+update2", APOWER, {"update": 2}, None),
|
||||
("apower/1307+none", APOWER, None, None),
|
||||
("bms/1705", BMS, None, None),
|
||||
("ems/1707", 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 label.startswith("queryInfo/1101+SN")
|
||||
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__":
|
||||
|
||||
Reference in new issue
Block a user