Files

210 lines
8.6 KiB
Python
Raw Permalink Normal View History

"""Play the phone over USB: configure the station, send CAMs at a fixed rate, and look at what goes on air.
py -3.11 tools/station_tx_test.py COM10 [--seconds 60] [--rate 1] [--unsigned] [--mac 02:11:22:33:44:55]
What it does, all over the native USB Serial/JTAG link (docs/station-link.pdf):
- STATION_CONFIGURE: the 6-octet form, or with --mac the 16-octet form (address_configuration 0, the
phone names the MAC, as the app does so that a pseudonym rotates it);
- POTI_UPDATE once a second and a BTP_DATA_REQUEST (port 2001, ITS-AID 36, SSP 010000) at --rate;
- RAW_CAPTURE with the own-transmission bit, so the station copies every frame it puts on the radio back
over the link (RAW_FRAME, an ITS5 record): that shows the 802.11 source address and whether the
packet is signed, without a second board;
- STATUS once a second, and the board's "TX observation" log lines (submitted / completed / failed).
At the end it prints how many requests were accepted, how many frames the radio submitted, how many
the driver reported as completed, and the MAC and security of the captured frames. Pair it with a second
board listening on the air (the bench listener on COM3) to count what actually arrives.
DTR and RTS stay low, but opening the port resets the board (USB Serial/JTAG), so a phone on BLE is dropped.
Needs pyserial (the ESP-IDF python env has it). The demo credentials must already be on the board (the app
provisions them on its first connect) for signed requests.
"""
import argparse
import collections
import struct
import sys
import time
import serial
LINK, LOG = 0x10, 0x7F
STATION_CONFIGURE, POTI_UPDATE, BTP_DATA_REQUEST, STATUS_REQUEST, RAW_CAPTURE = 0x01, 0x02, 0x03, 0x0C, 0x0D
CONFIRM, RAW_FRAME = 0x80, 0x85
ITS_EPOCH_UNIX_MS = 1072915200000 # 2004-01-01T00:00:00Z
LEAP_SECONDS_MS = 5000 # TimestampIts counts TAI: 5 leap seconds since 2004
def crc16(data, crc=0xFFFF):
for b in data:
crc ^= b << 8
for _ in range(8):
crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
return crc
def frame(ftype, payload):
head = bytes([ftype]) + struct.pack("<H", len(payload))
return b"\xAA\x55" + head + payload + struct.pack("<H", crc16(head + payload))
def link(opcode, seq, body=b""):
return frame(LINK, bytes([opcode, 0]) + struct.pack("<H", seq) + body)
def timestamp_its():
return int(time.time() * 1000) - ITS_EPOCH_UNIX_MS + LEAP_SECONDS_MS
def configure_body(mac, secured, power=20):
if mac is None: # type cyclist, channel 180, power, security, beaconing off
return struct.pack("<BHBBB", 2, 180, power, 1 if secured else 0, 0)
# type, security, address_configuration 0 (AUTO, the MID below), mid, beaconing, channel, power, radio 2, DP2, 1 s
return struct.pack("<BBB6sBHBBBB", 2, 1 if secured else 0, 0, mac, 0, 180, power, 2, 2, 5)
def poti_body():
# Hamburg St. Georg; speed 0, PAI set (flags: speed present + PAI)
return struct.pack("<QiiHHHBiHH", timestamp_its(), 535546667, 100223889, 300, 300, 0, 0x02 | 0x08, 0, 0, 0)
def btp_request_body(secured, payload):
return (struct.pack("<BHHBBBBBBHHI", 1, 2001, 0, 1, 1, 2 if secured else 1, 0xFF, 0xFF, 0, 0, 0, 36)
+ bytes([3]) + bytes.fromhex("010000") + bytes([0]) + struct.pack("<H", len(payload)) + payload)
def parse_raw_frame(body):
"""RAW_FRAME body -> (own_tx, rssi, 802.11 frame) or None. Layout: u32 counter, u8 flags, i8 rssi, 'ITS5' record."""
if len(body) < 6 + 14 or body[6:10] != b"ITS5":
return None
flags, rssi = body[4], struct.unpack("<b", body[5:6])[0]
length = struct.unpack("<H", body[18:20])[0]
return bool(flags & 1), rssi, body[20:20 + length]
def describe_frame(f):
"""Source MAC (addr2) and security of a GeoNetworking frame in an 802.11 QoS data frame."""
if len(f) < 26 + 8 + 4:
return None
mac = ":".join("%02x" % b for b in f[10:16])
snap = 26 if (f[0] & 0x0F) == 0x08 else 24 # QoS data (subtype 8) or plain data
basic_nh = f[snap + 8] & 0x0F # LLC/SNAP is 8 octets; GN basic header next-header: 1 common, 2 secured
return mac, "signed" if basic_nh == 2 else "unsigned"
def main():
ap = argparse.ArgumentParser()
ap.add_argument("port")
ap.add_argument("--seconds", type=float, default=60)
ap.add_argument("--rate", type=float, default=1.0, help="CAMs per second")
ap.add_argument("--unsigned", action="store_true")
ap.add_argument("--mac", help="name the MAC (02:11:22:33:44:55); default: the station's own")
args = ap.parse_args()
mac = bytes(int(x, 16) for x in args.mac.split(":")) if args.mac else None
secured = not args.unsigned
payload = bytes([2, 2]) + bytes(range(41)) # a 43-octet stand-in for a CAM (protocol 2, messageID 2)
ser = serial.Serial(args.port, 115200, timeout=0.05)
ser.dtr = False
ser.rts = False
time.sleep(3) # the port open reset the board: let it boot
buf = bytearray()
seq = 1
results = collections.Counter()
captured = collections.Counter()
fragments = {}
tx_obs = []
last_status = None
def send(op, body=b""):
nonlocal seq
ser.write(link(op, seq, body))
seq += 1
return seq - 1
def pump():
nonlocal last_status
buf.extend(ser.read(8192))
while True:
i = buf.find(b"\xAA\x55")
if i < 0 or len(buf) < i + 7:
return
ftype, n = buf[i + 2], struct.unpack("<H", buf[i + 3:i + 5])[0]
if len(buf) < i + 5 + n + 2:
return
payload = bytes(buf[i + 5:i + 5 + n])
del buf[:i + 5 + n + 2]
if ftype == LOG:
text = payload.decode("utf-8", "replace")
if "TX observation" in text:
tx_obs.append(text.strip())
elif "BLE interval" in text or "stale" in text or "rror" in text:
print("LOG", text.strip())
elif ftype == LINK and len(payload) >= 4:
op, fl, sq = payload[0], payload[1], struct.unpack("<H", payload[2:4])[0]
body = payload[4:]
if op == CONFIRM and len(body) >= 2:
if body[1] == 131:
last_status = body[2:]
else:
results[body[0]] += 1
elif op == RAW_FRAME:
if fl: # fragmented: total u16, offset u16, data
total, off = struct.unpack("<HH", body[:4])
got = fragments.setdefault(sq, bytearray())
if off == len(got):
got.extend(body[4:])
if fl == 3 and len(got) == total:
body = bytes(fragments.pop(sq))
else:
continue
parsed = parse_raw_frame(body)
if parsed and parsed[0]:
d = describe_frame(parsed[2])
if d:
captured[d] += 1
send(STATION_CONFIGURE, configure_body(mac, secured))
t0 = time.time()
while time.time() - t0 < 1.0:
pump()
send(POTI_UPDATE, poti_body())
send(RAW_CAPTURE, bytes([0x05])) # capture on + own transmissions
t0 = time.time()
next_cam = t0
next_poti = t0 + 1
next_status = t0 + 1
sent = 0
while time.time() - t0 < args.seconds:
now = time.time()
if now >= next_poti:
send(POTI_UPDATE, poti_body())
next_poti += 1
if now >= next_cam:
send(BTP_DATA_REQUEST, btp_request_body(secured, payload))
sent += 1
next_cam += 1.0 / args.rate
if now >= next_status:
send(STATUS_REQUEST)
next_status += 1
pump()
end = time.time() + 2
send(STATUS_REQUEST)
while time.time() < end:
pump()
print(f"\nrequests sent {sent}, CONFIRM results {dict(results)} (0 = accepted)")
if last_status:
u32 = lambda o: struct.unpack_from("<I", last_status, o)[0]
print(f"station: signed={u32(23)} requests accepted={u32(51)} refused={u32(55)} radio submitted={u32(63)} "
f"failed={u32(67)} sign failed={u32(39)} tickets={last_status[22]}")
for (m, kind), n in captured.most_common():
print(f"on air (own-TX capture): {n} x {kind}, 802.11 source {m}")
if not captured:
print("on air (own-TX capture): nothing captured")
if tx_obs:
print("last radio observation:", tx_obs[-1])
if __name__ == "__main__":
sys.exit(main())