From feae29c147cb76d347cdfc88ea4a2c59536ccd1a Mon Sep 17 00:00:00 2001 From: MJD948 Date: Tue, 24 Nov 2026 19:11:01 +0000 Subject: [PATCH] Register the Mobile Detector form and add RS-350 / Kromek D5 simulators The standard config gains the CustomUIConfig entry that gives the Mobile Detector System module (osh-oakridge-modules) its own admin form. tools/mobile-detector-mocks has stdlib-only RS-350 and Kromek D5 simulators, so a mobile detector lane can be exercised without hardware. Depends on the Mobile Detector System module in osh-oakridge-modules: the config entry names classes that exist only once that module is merged and pinned. Co-Authored-By: Claude Opus 5.5 --- dist/config/standard/config.json | 5 + tools/mobile-detector-mocks/README.md | 29 ++ tools/mobile-detector-mocks/d5_mock.py | 368 ++++++++++++++++++++++ tools/mobile-detector-mocks/rs350_mock.py | 346 ++++++++++++++++++++ 4 files changed, 748 insertions(+) create mode 100644 tools/mobile-detector-mocks/README.md create mode 100644 tools/mobile-detector-mocks/d5_mock.py create mode 100644 tools/mobile-detector-mocks/rs350_mock.py diff --git a/dist/config/standard/config.json b/dist/config/standard/config.json index 570fca6..26e2910 100644 --- a/dist/config/standard/config.json +++ b/dist/config/standard/config.json @@ -116,6 +116,11 @@ "configClass": "com.botts.impl.system.lane.config.LaneOptionsConfig", "uiClass": "com.botts.ui.oscar.forms.LaneConfigForm" }, + { + "objClass": "org.sensorhub.ui.CustomUIConfig", + "configClass": "com.botts.impl.system.lane.mobile.config.MobileDetectorConfig", + "uiClass": "com.botts.ui.oscar.forms.MobileDetectorConfigForm" + }, { "objClass": "org.sensorhub.ui.CustomUIConfig", "configClass": "org.sensorhub.api.sensor.PositionConfig.LLALocation", diff --git a/tools/mobile-detector-mocks/README.md b/tools/mobile-detector-mocks/README.md new file mode 100644 index 0000000..f97f7ec --- /dev/null +++ b/tools/mobile-detector-mocks/README.md @@ -0,0 +1,29 @@ +# Mobile detector simulators + +Stand-ins for an RS-350 backpack and a Kromek D5 walker, so a Mobile Detector System lane can be +exercised without hardware. Both are stdlib-only Python 3 TCP servers: point the lane's RPM host +and port at the machine that runs them. + +| Script | Device | Default port | Protocol | +|---|---|---|---| +| `rs350_mock.py` | RS-350 backpack | 10110 | Pushes one ANSI N42.42 (2011) document per second, framed STX…ETX. The driver only reads. | +| `d5_mock.py` | Kromek D5 RIID | 10111 | Answers the driver's polled Kromek serial requests over SLIP framing (RadiometricsV1, RadiometricStatus with GPS, Status, About). | + +```bash +python3 tools/mobile-detector-mocks/rs350_mock.py --port 10110 +python3 tools/mobile-detector-mocks/d5_mock.py --port 10111 +``` + +Each simulated walker loops a synthetic 1.2 km route near Oak Ridge, TN (the D5 runs it the +opposite way) at 1.4 m/s and reports its GPS position. Counts are Poisson background plus 1/r² +contributions from two hotspots on the route (Cs-137 and Co-60); while the expected rate exceeds +background × `alarm_factor`, the RS-350 documents carry alarm blocks and the D5 sets its dose-alarm +flag, so each pass by a hotspot produces an alarm occupancy on the lane. + +Override any default with `--config cfg.json`: a JSON object with any subset of the script's +`DEFAULT_CONFIG` keys (`route`, `hotspots`, `speed_mps`, `background_gamma_cps`, `alarm_factor`, +`serial`, …). + +Stopping a script and starting it again is the quickest way to test detector outages: the lane's +comm status, the RS-350 self-recovery and D5 reconnect backoff, and the Comm Failure indicator in +the viewer. diff --git a/tools/mobile-detector-mocks/d5_mock.py b/tools/mobile-detector-mocks/d5_mock.py new file mode 100644 index 0000000..1a43d22 --- /dev/null +++ b/tools/mobile-detector-mocks/d5_mock.py @@ -0,0 +1,368 @@ +#!/usr/bin/env python3 +""" +Kromek D5 RIID simulator (reference implementation). + +Emulates the device side of the OSH sensorhub-driver-kromek-d5 protocol: +a TCP *server* speaking the Kromek serial protocol over SLIP framing. +The driver is a polling TCP client: every second it sends one or more +header-only request frames and BLOCKS reading one response frame each — +so this server is a simple "read one request -> write one response" loop. + +Frame layout (logical bytes, before SLIP; ALL integers little-endian): + [length u16 = 7 + N] [mode 0x00] [componentId] [reportId] [payload N bytes] [crc u16 = 0x0000] +wrapped in 0xC0 ... 0xC0. CRC is never checked; requests carry N=0. +The response must ECHO the request's componentId/reportId (never 0xFE/0xFF). + +CRITICAL interop constraint: the driver reads `length` RAW bytes after the +frame byte but `length` counts LOGICAL (pre-SLIP-escape) bytes, and its SLIP +decoder treats interior 0xDB as an escape. Therefore the response body must +contain NO 0xC0 and NO 0xDB bytes, and must NOT be escaped. The clean_*() +helpers below nudge values minimally until their encoding is clean. + +Reports implemented (the two default-enabled ones plus cheap extras): + 0x07/0xC2 RadiometricsV1 - dose/counts + 4096 x u16 spectrum (payload 8246 B) + 0x08/0x82 RadiometricStatus - alarm flags + GPS lat/lon (this is the one + OSCAR uses for alarms and location) + 0x07/0xC5 Status - battery/temperature + 0x07/0xC7 About - firmware/product/serial strings +Unknown reports are answered with an empty payload (driver logs and skips). + +Stdlib only. Usage: + python3 d5_mock.py [--config cfg.json] [--port 10111] +""" +import argparse +import json +import math +import random +import socket +import struct +import threading +import time + +FRAME = 0xC0 +ESC = 0xDB +BAD = (0xC0, 0xDB) + +DEFAULT_CONFIG = { + "port": 10111, + "serial": "WALKER2", + "tick_s": 1.0, + "speed_mps": 1.4, + "background_gamma_cps": 900.0, + "background_neutron_cps": 0.3, + "alarm_factor": 1.6, + # The RS-350 mock's loop in the opposite direction, so two walkers separate visually. + "route": [ + [35.93000, -84.30334], + [35.92619, -84.30529], + [35.92461, -84.31000], + [35.92619, -84.31471], + [35.93000, -84.31666], + [35.93381, -84.31471], + [35.93539, -84.31000], + [35.93381, -84.30529], + [35.93000, -84.30334], + ], + "hotspots": [ + {"lat": 35.93539, "lon": -84.31000, "intensity_cps_at_1m": 90000.0, "isotope": "Cs-137"}, + {"lat": 35.92619, "lon": -84.31471, "intensity_cps_at_1m": 60000.0, "isotope": "Co-60"}, + ], +} + +M_PER_DEG_LAT = 111_320.0 + + +def dist_m(lat1, lon1, lat2, lon2): + dy = (lat2 - lat1) * M_PER_DEG_LAT + dx = (lon2 - lon1) * M_PER_DEG_LAT * math.cos(math.radians(lat1)) + return math.hypot(dx, dy) + + +def poisson(lam): + if lam > 50: + return max(0, int(random.gauss(lam, math.sqrt(lam)))) + l, k, p = math.exp(-lam), 0, 1.0 + while True: + p *= random.random() + if p <= l: + return k + k += 1 + + +class Walker: + def __init__(self, route, speed_mps): + self.route, self.speed, self.seg, self.seg_pos = route, speed_mps, 0, 0.0 + + def step(self, dt): + remaining = self.speed * dt + while remaining > 0: + a = self.route[self.seg] + b = self.route[(self.seg + 1) % len(self.route)] + seg_len = dist_m(a[0], a[1], b[0], b[1]) + if self.seg_pos + remaining < seg_len: + self.seg_pos += remaining + remaining = 0 + else: + remaining -= (seg_len - self.seg_pos) + self.seg = (self.seg + 1) % len(self.route) + self.seg_pos = 0.0 + + def position(self): + a = self.route[self.seg] + b = self.route[(self.seg + 1) % len(self.route)] + seg_len = max(dist_m(a[0], a[1], b[0], b[1]), 0.01) + f = min(self.seg_pos / seg_len, 1.0) + return a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f + + +# ---- byte-cleanliness helpers: keep 0xC0/0xDB out of the response body ---- + +def clean_u16(v): + v = max(0, min(0xFFFF, int(v))) + while any(b in BAD for b in struct.pack(" self.cfg["background_gamma_cps"] * self.cfg["alarm_factor"] + if self.alarming: + print(f"[d5-sim] ALARM at {lat:.5f},{lon:.5f}", flush=True) + time.sleep(self.cfg["tick_s"]) + + # ---- report payload builders ---- + + def radiometrics_v1(self): + with self.lock: + gamma_counts = int(self.gamma_cps) + dose_rate = self._expected_gamma(*self.walker.position()) / 12000.0 + p = b"".join([ + clean_u32(0), # status + clean_u32(int((time.time() - self.t0) * 1000)), # realTimeMs + clean_u32(self.seq), # sequenceNumber + clean_f32(self.dose_total), # dose (uSv) + clean_f32(dose_rate), # doseRate (uSv/h) + clean_f32(self.dose_total), # doseUserAccumulated + clean_u32(1000), # neutronLiveTime + clean_u32(self.neutron_counts_tick), # neutronCounts (per interval) + clean_i16(2500), # neutronTemperature (x100 C) + clean_f32(0.0), # neutronReserved + clean_u32(1000), # gammaLiveTime + clean_u32(gamma_counts), # gammaCounts + clean_i16(2500), # gammaTemperature (x100 C) + clean_f32(0.0), # gammaReserved + bytes([12, 0]), # spectrumBitsSize, reserved + ]) + # 4096 x u16 spectrum; values clamped to <=191 so every byte is + # trivially clean (low byte <0xC0, high byte 0x00). + decay = 4096 / 6.0 + total = max(gamma_counts, 1) + bins = bytearray() + wsum = sum(math.exp(-i / decay) for i in range(0, 4096, 16)) * 16 + for i in range(4096): + v = min(191, int(total * math.exp(-i / decay) / wsum * 16)) + bins += struct.pack(" ETX(0x03). +The driver never writes; there is no handshake, ACK, or CRC. + +A simulated walker follows a waypoint route (default: a synthetic 1.2 km +loop near Oak Ridge, TN). Radiation counts are Poisson background plus 1/r^2 +contributions from configurable hotspots; while the expected count rate +exceeds background*alarm_factor the documents also carry the alarm blocks +( + ), which is what the driver +keys its Alarm output on. + +Stdlib only. Usage: + python3 rs350_mock.py [--config cfg.json] [--port 10110] +Config file (JSON) overrides any subset of DEFAULT_CONFIG. +""" +import argparse +import json +import math +import random +import socket +import threading +import time +from datetime import datetime, timezone + +STX = b"\x02" +ETX = b"\x03" +N42_NS = "http://physics.nist.gov/N42/2011/N42" + +DEFAULT_CONFIG = { + "port": 10110, + "serial": "WALKER1", + "device_name": "RS350-WALKER1", + "tick_s": 1.0, + "speed_mps": 1.4, + "background_gamma_cps": 1200.0, + "background_neutron_cps": 0.4, + "alarm_factor": 1.6, + "background_block_every_s": 30, + # A 1.2 km synthetic loop of eight waypoints; the hotspots sit on two of them. + "route": [ + [35.93000, -84.30334], + [35.93381, -84.30529], + [35.93539, -84.31000], + [35.93381, -84.31471], + [35.93000, -84.31666], + [35.92619, -84.31471], + [35.92461, -84.31000], + [35.92619, -84.30529], + [35.93000, -84.30334], + ], + "hotspots": [ + {"lat": 35.93539, "lon": -84.31000, "intensity_cps_at_1m": 90000.0, "isotope": "Cs-137"}, + {"lat": 35.92619, "lon": -84.31471, "intensity_cps_at_1m": 60000.0, "isotope": "Co-60"}, + ], +} + +M_PER_DEG_LAT = 111_320.0 + + +def dist_m(lat1, lon1, lat2, lon2): + dy = (lat2 - lat1) * M_PER_DEG_LAT + dx = (lon2 - lon1) * M_PER_DEG_LAT * math.cos(math.radians(lat1)) + return math.hypot(dx, dy) + + +def poisson(lam): + """Poisson sample; gaussian approximation for large lambda.""" + if lam > 50: + return max(0, int(random.gauss(lam, math.sqrt(lam)))) + l, k, p = math.exp(-lam), 0, 1.0 + while True: + p *= random.random() + if p <= l: + return k + k += 1 + + +class Walker: + """Constant-speed waypoint follower, loops forever.""" + + def __init__(self, route, speed_mps): + self.route = route + self.speed = speed_mps + self.seg = 0 + self.seg_pos = 0.0 # meters into current segment + + def step(self, dt): + remaining = self.speed * dt + while remaining > 0: + a = self.route[self.seg] + b = self.route[(self.seg + 1) % len(self.route)] + seg_len = dist_m(a[0], a[1], b[0], b[1]) + if self.seg_pos + remaining < seg_len: + self.seg_pos += remaining + remaining = 0 + else: + remaining -= (seg_len - self.seg_pos) + self.seg = (self.seg + 1) % len(self.route) + self.seg_pos = 0.0 + + def position(self): + a = self.route[self.seg] + b = self.route[(self.seg + 1) % len(self.route)] + seg_len = max(dist_m(a[0], a[1], b[0], b[1]), 0.01) + f = min(self.seg_pos / seg_len, 1.0) + return a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f + + +class RadModel: + def __init__(self, cfg): + self.cfg = cfg + + def expected_gamma(self, lat, lon): + cps = self.cfg["background_gamma_cps"] + for h in self.cfg["hotspots"]: + d = dist_m(lat, lon, h["lat"], h["lon"]) + cps += h["intensity_cps_at_1m"] / max(d * d, 1.0) + return cps + + def nearest_hotspot(self, lat, lon): + return min(self.cfg["hotspots"], + key=lambda h: dist_m(lat, lon, h["lat"], h["lon"]), + default=None) if self.cfg["hotspots"] else None + + def is_alarming(self, lat, lon): + return self.expected_gamma(lat, lon) > \ + self.cfg["background_gamma_cps"] * self.cfg["alarm_factor"] + + +def spectrum(total_counts, n_channels, peak_channel=None): + """Cheap exponential continuum with an optional photopeak.""" + decay = n_channels / 6.0 + weights = [math.exp(-i / decay) for i in range(n_channels)] + if peak_channel is not None and 0 < peak_channel < n_channels: + for i in range(max(0, peak_channel - 6), min(n_channels, peak_channel + 7)): + weights[i] += 4.0 * math.exp(-((i - peak_channel) ** 2) / 8.0) + wsum = sum(weights) + return [int(total_counts * w / wsum) for w in weights] + + +ISOTOPE_PEAK_KEV = {"Cs-137": 662, "Co-60": 1332, "Am-241": 60, "Ba-133": 356} + + +def measurement_block(class_code, mid, start_iso, gamma_counts, neutron_counts, + dose_usvh=None, gps=None, isotope=None): + # Linear calibration is 0 + 3.0*ch keV (below), so peak channel = keV/3. + peak = None + if isotope in ISOTOPE_PEAK_KEV: + peak = ISOTOPE_PEAK_KEV[isotope] // 3 + lin = spectrum(gamma_counts, 1024, peak) + cmp_ = spectrum(gamma_counts, 256, peak // 4 if peak else None) + parts = [ + f' ', + f' {class_code}', + f' {start_iso}', + ' PT1.0S', + f' ', + ' PT1.0S', + f' {" ".join(map(str, lin))}', + ' ', + f' ', + ' PT1.0S', + f' {" ".join(map(str, cmp_))}', + ' ', + f' ', + ' PT1.0S', + f' {gamma_counts}', + ' ', + f' ', + ' PT1.0S', + f' {neutron_counts}', + ' ', + ] + if dose_usvh is not None: + parts += [ + f' ', + f' {dose_usvh:.4f}', + ' ', + ] + if gps is not None: + lat, lon, alt = gps + parts += [ + ' ', + ' ', + ' ', + f' {lat:.6f}', + f' {lon:.6f}', + f' {alt:.1f}', + ' ', + ' ', + ' ', + ] + parts.append(' ') + return "\n".join(parts) + + +def characteristic(name, value, units="unit-less", data_class="string"): + return (f' {name}' + f'{value}' + f'{units}' + f'{data_class}' + f'') + + +def build_document(cfg, walker, model, battery_pct, include_background, alarming): + now_iso = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + lat, lon = walker.position() + exp_gamma = model.expected_gamma(lat, lon) + gamma = poisson(exp_gamma) + neutron = poisson(cfg["background_neutron_cps"]) + dose = exp_gamma / 12000.0 # crude uSv/h mapping + hotspot = model.nearest_hotspot(lat, lon) + isotope = hotspot["isotope"] if (alarming and hotspot) else None + + doc = [ + f'', + ' ', + ' Radiation Solutions Inc', + f' {cfg["serial"]}', + ' RS-350', + ' Backpack', + ' Software' + 'sim-1.0' + '', + ' ', + characteristic("DeviceName", cfg["device_name"]), + characteristic("BatteryCharge", f"{battery_pct:.0f}", "percent", "double"), + ' ', + ' ', + ' ' + 'Gamma' + 'NaI', + ' ' + 'Neutron' + 'He3', + ' ', + ' ', + characteristic("ScanMode", "Search"), + characteristic("ScanNumber", "1", "unit-less", "double"), + characteristic("ScanTimeoutNumber", "0", "unit-less", "double"), + characteristic("AnalysisEnabled", "1", "unit-less", "integer"), + ' ', + ' ', + ' ', + ' 0 3.0 0', + ' ', + ' ', + ' 0 12.0 0', + ' ', + ] + if include_background: + bg_gamma = poisson(cfg["background_gamma_cps"]) + bg_neutron = poisson(cfg["background_neutron_cps"]) + doc.append(measurement_block("Background", "Bkg", now_iso, bg_gamma, bg_neutron)) + doc.append(measurement_block("Foreground", "Fg", now_iso, gamma, neutron, + dose_usvh=dose, gps=(lat, lon, 20.0), isotope=isotope)) + if alarming: + category = "Gamma" + description = isotope or "Unknown" + doc += [ + ' ', + ' NotSpecified', + f' {now_iso}', + ' PT1.0S', + ' Alarm', + ' ', + ' ', + ' ', + f' {category}', + f' {description}', + ' ', + ' ', + ] + doc.append('') + return "\n".join(doc) + + +def serve(cfg): + walker = Walker(cfg["route"], cfg["speed_mps"]) + model = RadModel(cfg) + state = {"battery": 100.0, "clients": [], "last_bkg": 0.0} + lock = threading.Lock() + + def ticker(): + while True: + t0 = time.time() + walker.step(cfg["tick_s"]) + state["battery"] = max(5.0, state["battery"] - 0.002) + include_bkg = (t0 - state["last_bkg"]) >= cfg["background_block_every_s"] + if include_bkg: + state["last_bkg"] = t0 + lat, lon = walker.position() + alarming = model.is_alarming(lat, lon) + xml = build_document(cfg, walker, model, state["battery"], include_bkg, alarming) + frame = STX + xml.encode("utf-8") + ETX + with lock: + dead = [] + for c in state["clients"]: + try: + c.sendall(frame) + except OSError: + dead.append(c) + for c in dead: + state["clients"].remove(c) + if alarming: + print(f"[rs350-sim] ALARM at {lat:.5f},{lon:.5f}", flush=True) + time.sleep(max(0.0, cfg["tick_s"] - (time.time() - t0))) + + threading.Thread(target=ticker, daemon=True).start() + + srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + srv.bind(("0.0.0.0", cfg["port"])) + srv.listen(4) + print(f"[rs350-sim] listening on :{cfg['port']}", flush=True) + while True: + conn, addr = srv.accept() + conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + print(f"[rs350-sim] client connected: {addr}", flush=True) + with lock: + state["clients"].append(conn) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--config", help="JSON file overriding DEFAULT_CONFIG keys") + ap.add_argument("--port", type=int) + args = ap.parse_args() + cfg = dict(DEFAULT_CONFIG) + if args.config: + with open(args.config) as f: + cfg.update(json.load(f)) + if args.port: + cfg["port"] = args.port + serve(cfg) + + +if __name__ == "__main__": + main()