Files
MicrOBU/tools/mapem_corpus.py
Ashin Walpola 8cbe3c337c Decode MAPEM and show traffic lights per lane
MapemUperCodec decodes MAPEM (MapData) from the ESP32-C5 (BTP port 2003)
and the CiT One's v2x/rx/mapem topic: intersection and lane names, the
reference point, lane types and directions, all node offset sizes and node
attributes, and each lane's connections with their signal groups. It
returns null on what it cannot size (extensions, regional data, computed
lanes) rather than guess.

TrafficLights.join places SPATEM signal groups on the MAPEM's ingress
lanes, gives each connection its turn (its maneuver, else the lane's, else
the angle between the lanes), picks the MAPEM whose revision the SPATEM
names when two are on air, and matches the rider to an ingress lane from
position and heading. The dashboard card then names the intersection and
shows the rider's lane, the distance to its stop line and one chip per
signal group with its turn arrows; the V2X map puts the light on the
reference point and draws the lanes in their signal colours.

Tested on recorded messages only: every distinct MAPEM on record (17 from
the 2026-03-18 drive, 288-1348 bytes, plus the bench RSU's) decodes field
for field like asn1tools; with a recorded SPATEM of the same intersection
and revision, 340 of 341 signalled exits find their movement (3/165's
group 65 never appears in its SPATEMs), and the geometric turn agrees with
198 of 201 stated maneuvers. tools/mapem_corpus.py rebuilds the fixtures.
2026-10-28 16:48:52 +01:00

177 lines
7.7 KiB
Python

"""Builds the MAPEM test corpus for MapemUperCodecTest: every distinct MAPEM on record, with every
field decoded by asn1tools (the ETSI modules in asn1/), as canonical text the Kotlin test re-creates
from MapemUperCodec's output and compares line by line.
py -3.11 tools/mapem_corpus.py
Sources: the 2026-03-18 drive (its-g5-receiver-firmware/recordings/its_messages_*.db, msg_type 5, the
UPER is field 3 of the CiT One protobuf blob) and any MAPEM in obu-firmware's replay TSV (the bench
RSU, captured by the ESP32-C5; run `make replay` in obu-firmware/test/host first).
Writes app/src/test/resources/mapem/corpus.txt, and spat_samples.txt beside it: for every intersection
in the corpus, one recorded SPATEM of the same intersection (`<key> <revision> <hex>`), for
TrafficLightsTest.
"""
import collections
import glob
import re
import sqlite3
from pathlib import Path
import asn1tools
ROOT = Path(__file__).resolve().parent.parent
ASN = ROOT / 'asn1'
OUT = ROOT / 'app/src/test/resources/mapem/corpus.txt'
SPAT_OUT = OUT.parent / 'spat_samples.txt'
LANE_TYPES = ['vehicle', 'crosswalk', 'bikeLane', 'sidewalk', 'median', 'striping', 'trackedVehicle', 'parking']
def enum_roots():
src = ''.join((ASN / n).read_text(encoding='utf-8', errors='replace') for n in ('dsrc_2_2_1.asn', 'cdd_2_2_1.asn'))
src = re.sub(r'/\*.*?\*/', '', src, flags=re.S)
src = re.sub(r'--.*', '', src)
roots = {}
for name in ('NodeAttributeXY', 'SegmentAttributeXY', 'SpeedLimitType'):
body = re.search(r'\b' + name + r'\s*::=\s*ENUMERATED\s*\{(.*?)\}', src, re.S).group(1).split('...')[0]
roots[name] = [x.strip() for x in body.split(',') if x.strip()]
return roots
def varint(b, i):
v = s = 0
while True:
x = b[i]
i += 1
v |= (x & 0x7F) << s
s += 7
if x < 0x80:
return v, i
def protobuf_field3(b):
i = 0
while i < len(b):
tag, i = varint(b, i)
field, wire = tag >> 3, tag & 7
if wire == 0:
_, i = varint(b, i)
elif wire == 2:
n, i = varint(b, i)
if field == 3:
return b[i:i + n]
i += n
elif wire == 5:
i += 4
elif wire == 1:
i += 8
else:
return None
return None
def bits(value):
data, n = value
return int.from_bytes(data, 'big') >> (len(data) * 8 - n) if n else 0
def dump(d, roots):
"""Canonical text; MapemUperCodecTest.dump() must produce the same."""
out = [f"station={d['header']['stationId']} rev={d['map']['msgIssueRevision']}"]
for i in d['map']['intersections']:
speeds = ','.join(f"{roots['SpeedLimitType'].index(s['type'])}:{s['speed']}" for s in i.get('speedLimits', []))
ref = i['refPoint']
out.append(f"I key={i['id'].get('region', -1)}/{i['id']['id']} rev={i['revision']} name={i.get('name')} "
f"ref={ref['lat']},{ref['long']} elev={ref.get('elevation')} width={i.get('laneWidth')} speeds={speeds}")
for lane in i['laneSet']:
a = lane['laneAttributes']
kind, attr = a['laneType']
man = bits(lane['maneuvers']) if 'maneuvers' in lane else None
out.append(f"L id={lane['laneID']} name={lane.get('name')} in={lane.get('ingressApproach')} "
f"eg={lane.get('egressApproach')} dir={bits(a['directionalUse'])} share={bits(a['sharedWith'])} "
f"type={LANE_TYPES.index(kind)} attr={bits(attr)} man={man}")
choice, nodes = lane['nodeList']
assert choice == 'nodes'
for node in nodes:
kind, v = node['delta']
pos = f"ll={v['lat']},{v['lon']}" if kind == 'node-LatLon' else f"xy={v['x']},{v['y']}"
at = node.get('attributes', {})
local = ','.join(str(roots['NodeAttributeXY'].index(x)) for x in at.get('localNode', []))
dis = ','.join(str(roots['SegmentAttributeXY'].index(x)) for x in at.get('disabled', []))
en = ','.join(str(roots['SegmentAttributeXY'].index(x)) for x in at.get('enabled', []))
out.append(f"N {pos} local={local} dis={dis} en={en} dw={at.get('dWidth')} de={at.get('dElevation')}")
for c in lane.get('connectsTo', []):
cl = c['connectingLane']
man = bits(cl['maneuver']) if 'maneuver' in cl else None
r = c.get('remoteIntersection')
remote = f"{r.get('region', -1)}/{r['id']}" if r else None
out.append(f"C to={cl['lane']} man={man} remote={remote} sg={c.get('signalGroup')} "
f"uc={c.get('userClass')} cid={c.get('connectionID')}")
if 'overlays' in lane:
out.append('O ' + ','.join(map(str, lane['overlays'])))
return out
def main():
spec = asn1tools.compile_files([str(ASN / n) for n in
('spatem_2_2_1.asn', 'mapem_2_2_1.asn', 'dsrc_2_2_1.asn', 'cdd_2_2_1.asn')], 'uper')
roots = enum_roots()
seen = collections.OrderedDict()
for path in sorted(glob.glob(str(ROOT / 'its-g5-receiver-firmware/recordings/its_messages_*.db'))):
db = sqlite3.connect(f'file:{path}?mode=ro', uri=True)
for (blob,) in db.execute('select asn1_message from messages where msg_type = 5'):
uper = protobuf_field3(bytes(blob))
if uper:
seen[uper] = seen.get(uper, 0) + 1
tsv = ROOT / 'obu-firmware/test/host/build/replay.tsv'
if tsv.exists():
for line in tsv.read_text().splitlines():
col = line.split('\t')
if len(col) > 10 and col[3] == '2003':
uper = bytes.fromhex(col[10])
seen[uper] = seen.get(uper, 0) + 1
lines = [f'# {len(seen)} distinct MAPEMs ({sum(seen.values())} received), fields by asn1tools. '
'Generated by tools/mapem_corpus.py; do not edit.']
for uper in seen:
lines.append('#hex ' + uper.hex())
lines.extend(dump(spec.decode('MAPEM', uper), roots))
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text('\n'.join(lines) + '\n', encoding='ascii')
print(f'{OUT.relative_to(ROOT)}: {len(seen)} MAPEMs, {len(lines)} lines')
# One SPATEM per (intersection, MAP revision) in the corpus, with at least 2 movements.
wanted = set()
for uper in seen:
for i in spec.decode('MAPEM', uper)['map']['intersections']:
wanted.add((f"{i['id'].get('region', -1)}/{i['id']['id']}", i['revision']))
samples = {}
def offer(uper):
try:
d = spec.decode('SPATEM', uper)
except Exception:
return
for i in d['spat']['intersections']:
k = (f"{i['id'].get('region', -1)}/{i['id']['id']}", i['revision'])
if k in wanted and k not in samples and len(i['states']) >= 2:
samples[k] = uper
for path in sorted(glob.glob(str(ROOT / 'its-g5-receiver-firmware/recordings/its_messages_*.db'))):
db = sqlite3.connect(f'file:{path}?mode=ro', uri=True)
for (blob,) in db.execute('select asn1_message from messages where msg_type = 4'):
if len(samples) == len(wanted):
break
uper = protobuf_field3(bytes(blob))
if uper:
offer(uper)
if tsv.exists():
for line in tsv.read_text().splitlines():
col = line.split('\t')
if len(col) > 10 and col[3] == '2004':
offer(bytes.fromhex(col[10]))
SPAT_OUT.write_text(''.join(f'{k} {r} {u.hex()}\n' for (k, r), u in sorted(samples.items())), encoding='ascii')
print(f'{SPAT_OUT.relative_to(ROOT)}: {len(samples)} of {len(wanted)} intersection revisions have a SPATEM')
if __name__ == '__main__':
main()