145 lines
4.7 KiB
Python
145 lines
4.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Host probe v3 — socket-transport command ids (stdlib only).
|
|
|
|
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.
|
|
|
|
Run on the SoftAP-joined host:
|
|
python3 host_probe3.py --sn A03X2516013210060005 --ports 9000
|
|
"""
|
|
|
|
import argparse
|
|
import json
|
|
import socket
|
|
import time
|
|
import zlib
|
|
|
|
# Wire cmdType per CommunicationCmd::cmd (socket mode).
|
|
APOWER, QUERY_INFO, BMS, EMS = 0x51B, 0x44D, 0x6A9, 0x6AB
|
|
SNNO = [0]
|
|
|
|
|
|
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
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("--sn", required=True)
|
|
ap.add_argument("--host", default="10.100.1.1")
|
|
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),
|
|
]
|
|
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
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|