Correct wire format to disassembly: raw S1||crypt(S2), radix 32, int snno/seconds, decryptData response parser, --probe
- envelope: 7 fixed keys + conditional dataArea, no data key; int
type/snno, seconds timestamp, data setter auto len/crc (CRC32 upper);
SequenceNumber 1..9999 (increaseSN)
- crypto: encrypt is plaintext-header-first a||transform(b), key radix 32
at both tryParse sites; decrypt_data ports decryptData (dual-0x58
markers, s+'}' equipNo probe, s+','+T return); decrypt_request kept
for the device-side known-header split
- socket: raw send (no length prefix), accumulate-and-try receive
- battery: queryAPowerData shape (data={'update':2}), radix default 32,
--probe prints exact TX/RX bytes per variant; device_local.send_probe
- docs: RE_DART_FINDINGS ss3/5/8 + open items, BATTERY_POC host recipe
- tests: 19 new protocol tests, suite 44/44 green
This commit is contained in:
1 parent
2438a04ed5
commit
9e69f07636
10 files changed
+744
-182
No files matched your search
@@ -125,15 +125,16 @@ def get_battery(
|
||||
sn: str,
|
||||
host: str = "10.100.1.1",
|
||||
ports: Tuple[int, ...] = SOCKET_PORT_CANDIDATES,
|
||||
key_radix: int = 16,
|
||||
key_radix: int = 32,
|
||||
timeout: float = 5.0,
|
||||
) -> Dict[str, Any]:
|
||||
"""Query the aggregate charge percentage over the local TCP socket.
|
||||
|
||||
Tries ``DEVICE_APOWER_INFO`` (0x19) first, then ``BMS`` (0x1D) and
|
||||
``EMS`` (0x1E) as fallbacks, probing each candidate port. Returns the
|
||||
``extract_soc`` dict plus ``cmd``/``port``/``reply`` context. Raises the
|
||||
last socket error if no port answers.
|
||||
Mirrors the app's ``queryAPowerData`` first (``DEVICE_APOWER_INFO`` with
|
||||
``data={"update": 2}``), then ``BMS`` and ``EMS`` as fallbacks, probing
|
||||
each candidate port. Returns the ``extract_soc`` dict plus
|
||||
``cmd``/``port``/``reply`` context. Raises the last socket error if no
|
||||
port answers.
|
||||
"""
|
||||
last_err: Optional[Exception] = None
|
||||
for port in ports:
|
||||
@@ -141,13 +142,13 @@ def get_battery(
|
||||
sn=sn, host=host, socket_port=port,
|
||||
key_radix=key_radix, timeout=timeout,
|
||||
)
|
||||
for cmd in (
|
||||
CommunicationCmd.DEVICE_APOWER_INFO,
|
||||
CommunicationCmd.BMS,
|
||||
CommunicationCmd.EMS,
|
||||
for cmd, data in (
|
||||
(CommunicationCmd.DEVICE_APOWER_INFO, {"update": 2}),
|
||||
(CommunicationCmd.BMS, None),
|
||||
(CommunicationCmd.EMS, None),
|
||||
):
|
||||
try:
|
||||
reply = client.send_rpc(cmd)
|
||||
reply = client.send_rpc(cmd, data=data)
|
||||
except (ConnectionError, socket.error, TimeoutError) as exc:
|
||||
last_err = exc
|
||||
log.debug("port %d cmd %s failed: %s", port, cmd, exc)
|
||||
@@ -164,6 +165,47 @@ def get_battery(
|
||||
raise ConnectionError(f"no battery reply via {host}:{list(ports)}") from last_err
|
||||
|
||||
|
||||
#: ``--probe`` request variants: (label, cmd, data). The first mirrors the
|
||||
#: app's ``queryAPowerData`` exactly; the rest isolate single envelope
|
||||
#: decisions (payload present/empty/absent, fallback commands).
|
||||
PROBE_VARIANTS: Tuple[Tuple[str, CommunicationCmd, Any], ...] = (
|
||||
("apower/update2", CommunicationCmd.DEVICE_APOWER_INFO, {"update": 2}),
|
||||
("apower/none", CommunicationCmd.DEVICE_APOWER_INFO, None),
|
||||
("apower/empty", CommunicationCmd.DEVICE_APOWER_INFO, {}),
|
||||
("queryDeviceInfo/none", CommunicationCmd.QUERY_DEVICE_INFO, None),
|
||||
("bms/none", CommunicationCmd.BMS, None),
|
||||
("ems/none", CommunicationCmd.EMS, None),
|
||||
)
|
||||
|
||||
|
||||
def probe_device(
|
||||
sn: str,
|
||||
host: str = "10.100.1.1",
|
||||
ports: Tuple[int, ...] = SOCKET_PORT_CANDIDATES,
|
||||
key_radix: int = 32,
|
||||
timeout: float = 5.0,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""Send every :data:`PROBE_VARIANTS` envelope; return exact TX/RX bytes."""
|
||||
results: List[Dict[str, Any]] = []
|
||||
for port in ports:
|
||||
client = LocalDeviceClient(
|
||||
sn=sn, host=host, socket_port=port,
|
||||
key_radix=key_radix, timeout=timeout,
|
||||
)
|
||||
for label, cmd, data in PROBE_VARIANTS:
|
||||
try:
|
||||
out = client.send_probe(cmd, data=data, timeout=timeout)
|
||||
except (ConnectionError, socket.error, TimeoutError) as exc:
|
||||
out = {"cmd": str(cmd), "error": f"{type(exc).__name__}: {exc}",
|
||||
"tx": b"", "reply_raw": b"", "reply": None,
|
||||
"envelope": None}
|
||||
out.update({"variant": label, "port": port})
|
||||
results.append(out)
|
||||
if out.get("reply_raw"):
|
||||
break # device answered — deeper variants can wait
|
||||
return results
|
||||
|
||||
|
||||
def main(argv: Optional[List[str]] = None) -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Read aGate battery percentage over the device SoftAP socket."
|
||||
@@ -174,11 +216,13 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
"--ports", default=",".join(map(str, SOCKET_PORT_CANDIDATES)),
|
||||
help="comma-separated socket ports to probe",
|
||||
)
|
||||
parser.add_argument("--key-radix", type=int, default=16, choices=(16, 32))
|
||||
parser.add_argument("--key-radix", type=int, default=32, choices=(16, 32))
|
||||
parser.add_argument("--timeout", type=float, default=5.0)
|
||||
parser.add_argument("--show-hotspot", action="store_true",
|
||||
help="print derived AP SSID/password and exit")
|
||||
parser.add_argument("--raw", action="store_true", help="print full reply JSON")
|
||||
parser.add_argument("--probe", action="store_true",
|
||||
help="send probe variants and print exact TX/RX bytes")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
if args.show_hotspot:
|
||||
@@ -189,6 +233,27 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
return 0
|
||||
|
||||
ports = tuple(int(p) for p in args.ports.split(",") if p.strip())
|
||||
if args.probe:
|
||||
from .protocol import generate_secret_key
|
||||
print(f"secret key for {args.sn}: {generate_secret_key(args.sn)} "
|
||||
f"(radix {args.key_radix})")
|
||||
for out in probe_device(args.sn, host=args.host, ports=ports,
|
||||
key_radix=args.key_radix, timeout=args.timeout):
|
||||
print(f"--- {out['variant']} -> {args.host}:{out['port']}"
|
||||
f" cmd={out['cmd']}")
|
||||
if out.get("envelope") is not None:
|
||||
print(" envelope: " + json.dumps(out["envelope"], default=str))
|
||||
tx = out.get("tx") or b""
|
||||
print(f" tx ({len(tx)} B): {tx.hex()}")
|
||||
rx = out.get("reply_raw") or b""
|
||||
print(f" rx ({len(rx)} B): {rx.hex() or '(empty)'}")
|
||||
if out.get("reply") is not None:
|
||||
print(" reply: " + json.dumps(out["reply"], default=str))
|
||||
soc = extract_soc(out["reply"])
|
||||
print(f" soc: {soc['value']} (source={soc['source']})")
|
||||
if out.get("error"):
|
||||
print(f" error: {out['error']}")
|
||||
return 0
|
||||
try:
|
||||
result = get_battery(args.sn, host=args.host, ports=ports,
|
||||
key_radix=args.key_radix, timeout=args.timeout)
|
||||
|
||||
Reference in new issue
Block a user