Add the bench RSU to the stored MAPEMs and let the bundle script take new files

The list now includes Berliner Tor / Kolbergstrasse (-1/23 rev 2), taken
from the 2026-11-25 V2X log. tools/mapem_bundle.py merges MAPEMs from V2X
log databases or hex text files into the existing list instead of
rebuilding it from the test corpus.
This commit is contained in:
Ashin Walpola
2026-11-30 14:00:59 +01:00
parent 750a752527
commit 875b389496
4 changed files with 126 additions and 58 deletions
+78 -28
View File
@@ -1,46 +1,96 @@
"""Builds the stored-MAPEM bundle the app ships with, from the MAPEM test corpus.
"""Adds MAPEMs to the list the app ships with (app/src/main/assets/mapem/hamburg.txt).
python tools/mapem_bundle.py
py -3.11 tools/mapem_bundle.py FILE [FILE ...]
Reads app/src/test/resources/mapem/corpus.txt (tools/mapem_corpus.py: every distinct MAPEM on record,
UPER plus asn1tools' fields) and writes app/src/main/assets/mapem/hamburg.txt: one UPER MAPEM per
intersection and revision. Intersections without a region are left out: their id is not unique, and
the only one on record is the bench RSU's test crossroads.
FILE is either
- a .db saved by the app's V2X data logger (its MAPEM rows are taken), or
- a text file with one UPER MAPEM per line as hex (`#hex <hex>` lines, as in the test corpus, too).
The list keeps what it already has and gains one entry per intersection and revision. A MAPEM of an
intersection and revision already listed replaces that entry. Review the printed changes, run the
unit tests, rebuild the app. Needs asn1tools (the ETSI modules in asn1/).
"""
import re
import sqlite3
import sys
from pathlib import Path
import asn1tools
ROOT = Path(__file__).resolve().parent.parent
CORPUS = ROOT / 'app/src/test/resources/mapem/corpus.txt'
ASN = ROOT / 'asn1'
OUT = ROOT / 'app/src/main/assets/mapem/hamburg.txt'
RECORDED = '2026-03-18'
HEADER = ['# Stored MAPEMs. One UPER MAPEM per line, hex, each below a comment naming its intersections.',
'# Written by tools/mapem_bundle.py; add to it with that script.']
HEX = re.compile(r'(?:#hex )?((?:[0-9a-fA-F]{2})+)$')
def main():
messages = [] # (hex, [(key, revision, name)])
for line in CORPUS.read_text(encoding='ascii').splitlines():
if line.startswith('#hex '):
messages.append((line[5:], []))
elif line.startswith('I '):
key, revision, name = re.match(r'I key=(\S+) rev=(\d+) name=(.*?) ref=', line).groups()
messages[-1][1].append((key, int(revision), name))
def read_hex_lines(path):
for line in path.read_text(encoding='utf-8').splitlines():
found = HEX.match(line.strip())
if found:
yield bytes.fromhex(found[1])
def read_log(path):
db = sqlite3.connect(f'file:{path.resolve().as_posix()}?mode=ro', uri=True)
try:
for (payload,) in db.execute("select distinct payload from messages where msg_type = 'MAPEM'"):
yield bytes(payload)
finally:
db.close()
def add(entries, spec, uper, source):
"""Puts [uper] into entries {(key, revision): (uper, label)}; returns the keys that changed."""
try:
decoded = spec.decode('MAPEM', uper)
except Exception as error: # asn1tools raises several types
print(f' skipped a message from {source} that does not decode: {error}')
return []
changed = []
for i in decoded['map'].get('intersections', []):
key = (f"{i['id'].get('region', -1)}/{i['id']['id']}", i['revision'])
if key not in entries or entries[key][0] != uper:
changed.append((key, 'replaced' if key in entries else 'added', i.get('name')))
entries[key] = (uper, i.get('name'))
return changed
def main(files):
if not files:
raise SystemExit(__doc__)
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')
entries = {}
if OUT.exists():
for uper in read_hex_lines(OUT):
add(entries, spec, uper, OUT.name)
for name in files:
path = Path(name)
if not path.is_file():
raise SystemExit(f'{name}: no such file')
reader = read_log if path.suffix.lower() == '.db' else read_hex_lines
changed = [c for uper in reader(path) for c in add(entries, spec, uper, path.name)]
print(f'{path.name}: {len(changed)} change(s)')
for (key, revision), what, label in changed:
print(f' {what} {key} rev {revision} {label}')
seen = set()
body = []
for uper, intersections in messages:
new = {(k, r) for k, r, _ in intersections if not k.startswith('-1/')} - seen
if not new:
written = set()
for (key, revision), (uper, _) in sorted(entries.items()):
if uper in written:
continue
seen |= new
body += [f'# {k} rev {r} {name}' for k, r, name in intersections]
body.append(uper)
written.add(uper)
body += [f'# {k} rev {r} {label}' for (k, r), (u, label) in sorted(entries.items()) if u == uper]
body.append(uper.hex())
header = [f'# Stored MAPEMs, recorded on the {RECORDED} drive in Hamburg. {len(seen)} intersection revisions.',
'# One UPER MAPEM per line, hex. Generated by tools/mapem_bundle.py; do not edit.']
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text('\n'.join(header + body) + '\n', encoding='utf-8', newline='\n')
print(f'{OUT.relative_to(ROOT)}: {len(seen)} intersection revisions, {len({k for k, _ in seen})} intersections')
OUT.write_text('\n'.join(HEADER + body) + '\n', encoding='utf-8', newline='\n')
print(f'{OUT.relative_to(ROOT)}: {len(entries)} intersection revisions, '
f'{len({k for k, _ in entries})} intersections')
if __name__ == '__main__':
main()
main(sys.argv[1:])