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
+90
-97
@@ -1,105 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Standalone host probe — no package install, no git needed (stdlib only).
|
||||
"""Host probe v2 — transport framing variants via the library.
|
||||
|
||||
Drop this file on the machine joined to the aGate SoftAP and run:
|
||||
python3 host_probe2.py --sn A03X2516013210060005
|
||||
Envelope bytes come from ``EnvelopeCodec``; only the on-the-wire framing
|
||||
varies (raw, length prefixes, split send, MQTT poke, greeting-first read).
|
||||
Raw payloads go through ``LocalDeviceClient.send_raw``.
|
||||
|
||||
Replicates ``battery --probe2``: the canonical queryAPowerData envelope
|
||||
(verified byte-for-byte against the Dart AOT disassembly) sent with
|
||||
transport-level variants. Prints exact TX/RX hex for each.
|
||||
Run from the repo root on the SoftAP-joined host:
|
||||
python3 scripts/host_probe2.py --sn A03X2516013210060005 --ports 9000
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
import zlib
|
||||
|
||||
SNNO = [0] # 1-based increaseSN counter (wraps at 9999)
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(
|
||||
os.path.abspath(__file__))))
|
||||
|
||||
from franklinwh_agate_client.device_local import ( # noqa: E402
|
||||
LocalDeviceClient,
|
||||
)
|
||||
from franklinwh_agate_client.protocol import ( # noqa: E402
|
||||
CommunicationCmd,
|
||||
direct_connect_request,
|
||||
generate_secret_key,
|
||||
)
|
||||
from franklinwh_agate_client.protocol.envelope import ( # noqa: E402
|
||||
SequenceNumber,
|
||||
)
|
||||
from franklinwh_agate_client.protocol.messages import ( # noqa: E402
|
||||
EnvelopeCodec,
|
||||
)
|
||||
|
||||
#: Minimal MQTT v3.1.1 CONNECT (client id ``probe01``).
|
||||
_MQTT_CONNECT = bytes.fromhex("101200044d5154540402003c000670726f62653031")
|
||||
|
||||
_seq = SequenceNumber()
|
||||
|
||||
|
||||
def secret_key(sn):
|
||||
return format(sum(sn.encode()) & 0xFF, "x")
|
||||
def canonical_tx(sn: str, codec: EnvelopeCodec) -> bytes:
|
||||
"""App-shaped apower query bytes (fresh snno/timeStamp)."""
|
||||
env = direct_connect_request(
|
||||
CommunicationCmd.DEVICE_APOWER_INFO, sn,
|
||||
data={"update": 2}, snno=_seq.next())
|
||||
return codec.encode(env)
|
||||
|
||||
|
||||
def build_envelope(sn, cmd=25, data=None, snno=None, ts=None):
|
||||
SNNO[0] = (SNNO[0] % 9999) + 1
|
||||
env = {
|
||||
"cmdType": cmd,
|
||||
"equipNo": 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 recv_all(sock, idle=4.0):
|
||||
def recv_all_verbose(sock: socket.socket, idle: float = 4.0):
|
||||
out = bytearray()
|
||||
sock.settimeout(idle)
|
||||
while True:
|
||||
try:
|
||||
chunk = sock.recv(65536)
|
||||
except (socket.timeout, TimeoutError):
|
||||
break
|
||||
return bytes(out), "idle-timeout"
|
||||
if not chunk:
|
||||
break
|
||||
return bytes(out), "closed-by-peer"
|
||||
out.extend(chunk)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
MQTT_CONNECT = bytes.fromhex("101200044d5154540402003c000670726f62653031")
|
||||
|
||||
|
||||
def run(label, host, port, tx, timeout, pre_read=0.0, post_idle=4.0,
|
||||
split_send=False):
|
||||
entry = (label, tx, b"", b"", None)
|
||||
rx_pre, rx = b"", b""
|
||||
err = 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:
|
||||
if split_send:
|
||||
half = len(tx) // 2
|
||||
sock.sendall(tx[:half])
|
||||
try:
|
||||
sock.settimeout(0.5)
|
||||
rx_pre += sock.recv(65536)
|
||||
except (socket.timeout, TimeoutError):
|
||||
pass
|
||||
sock.sendall(tx[half:])
|
||||
else:
|
||||
sock.sendall(tx)
|
||||
rx = recv_all(sock, idle=post_idle)
|
||||
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 err:
|
||||
print(" error: %s" % err)
|
||||
return rx
|
||||
|
||||
|
||||
def main():
|
||||
@@ -109,24 +68,58 @@ 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))
|
||||
tx = encrypt(build_envelope(args.sn, data={"update": 2}), key)
|
||||
codec = EnvelopeCodec.for_serial(args.sn)
|
||||
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()]:
|
||||
run("greet-first/read-then-raw", args.host, port, tx,
|
||||
args.timeout, pre_read=4.0)
|
||||
run("raw/long-read", args.host, port, tx, args.timeout,
|
||||
post_idle=8.0)
|
||||
run("raw/split-send", args.host, port, tx, args.timeout,
|
||||
split_send=True)
|
||||
run("le16-prefix", args.host, port,
|
||||
len(tx).to_bytes(2, "little") + tx, args.timeout)
|
||||
run("be16-prefix", args.host, port,
|
||||
len(tx).to_bytes(2, "big") + tx, args.timeout)
|
||||
run("le32-prefix", args.host, port,
|
||||
len(tx).to_bytes(4, "little") + tx, args.timeout)
|
||||
run("mqtt-connect", args.host, port, MQTT_CONNECT, args.timeout)
|
||||
client = LocalDeviceClient(args.sn, host=args.host,
|
||||
socket_port=port, timeout=args.timeout)
|
||||
tx = canonical_tx(args.sn, codec)
|
||||
|
||||
def show(label, tx_bytes, rx, how=""):
|
||||
print("--- %s tx=%dB rx=%dB %s"
|
||||
% (label, len(tx_bytes), len(rx), how))
|
||||
if rx:
|
||||
print(" rx: %s" % rx.hex()[:400])
|
||||
|
||||
# greeting-first: connect, read before sending, then send
|
||||
try:
|
||||
with socket.create_connection(
|
||||
(args.host, port), timeout=args.timeout) as sock:
|
||||
pre, _ = recv_all_verbose(sock, idle=4.0)
|
||||
sock.sendall(tx)
|
||||
rx, how = recv_all_verbose(sock, idle=8.0)
|
||||
show("greet-first/read-then-raw", tx, rx,
|
||||
"pre=%dB %s" % (len(pre), how))
|
||||
except (ConnectionError, socket.error, TimeoutError) as exc:
|
||||
print("--- greet-first: error: %s" % exc)
|
||||
|
||||
for label, payload in (
|
||||
("raw/long-read", tx),
|
||||
("le16-prefix", len(tx).to_bytes(2, "little") + tx),
|
||||
("be16-prefix", len(tx).to_bytes(2, "big") + tx),
|
||||
("le32-prefix", len(tx).to_bytes(4, "little") + tx),
|
||||
("mqtt-connect", _MQTT_CONNECT),
|
||||
):
|
||||
try:
|
||||
t0 = time.time()
|
||||
rx = client.send_raw(payload, timeout=args.timeout)
|
||||
show(label, payload, rx, "%.1fs" % (time.time() - t0))
|
||||
except (ConnectionError, socket.error, TimeoutError) as exc:
|
||||
print("--- %s: error: %s" % (label, exc))
|
||||
|
||||
# split send over one connection
|
||||
try:
|
||||
with socket.create_connection(
|
||||
(args.host, port), timeout=args.timeout) as sock:
|
||||
half = len(tx) // 2
|
||||
sock.sendall(tx[:half])
|
||||
time.sleep(0.5)
|
||||
sock.sendall(tx[half:])
|
||||
rx, how = recv_all_verbose(sock)
|
||||
show("raw/split-send", tx, rx, how)
|
||||
except (ConnectionError, socket.error, TimeoutError) as exc:
|
||||
print("--- split-send: error: %s" % exc)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in new issue
Block a user