Compare commits

...

10 Commits

Author SHA1 Message Date
Danny c8a17afb21 Build 2026-11-24 10:39:57 -08:00
Danny ff4b154609 Reports: Add Bluetooth, Require Discord User 2026-11-24 10:30:42 -08:00
dirwin31 c9fea63596 Merge pull request #346 from dirwin31/Uniden
Uniden Radar Muting and Screen Integration
2026-11-24 09:19:57 -08:00
Danny 8852c7bce6 Build 2026-11-24 09:16:56 -08:00
Danny 71a9228954 Uniden: Integration 2026-11-24 09:16:53 -08:00
firestar5683 63fe5bb3e1 Pause highway smoothing while steering is limited 2026-11-24 10:31:29 -06:00
firestar5683 697dcf29e0 Show repeated steering requests in FLM drive reviews 2026-11-24 09:44:02 -06:00
firestar5683 591c5fcf53 Resume Corolla TSS2 from a PCM hold behind moving traffic 2026-11-24 09:35:27 -06:00
clementatt 78303dda84 Translate StarPilot into Simplified Chinese 2026-11-24 09:30:29 -06:00
clementatt fb4468b347 Translate StarPilot into Simplified Chinese
Complete app_zh-CHS.po for the device UI and Galaxy (5565 entries,
all translated).

Rebuild the Noto Sans CJK SC subset from the upstream font so it
covers the original cmap plus every character in app_zh-CHS.po, and
record the source and subset hashes in Noto-SOURCE.txt.

app_zh-CHS.po now exceeds the 120 KiB text limit, so add it to the
large-file allowlist alongside the other catalogs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 19:28:11 +09:00
89 changed files with 28931 additions and 341 deletions
+4
View File
@@ -49,3 +49,7 @@ The explicit StarPilot [jacobw Subaru adapter](opendbc_repo/opendbc/car/subaru/J
The previous optional StarPilot Controller, formerly in `openpilot/starpilot/car/ford/starpilot_tuning.py`, restored demand tuning from StarPilot `8da0c9d916^`, descended from BluePilot bp-7.0 `e1d051d7ba270261b4455068bd68f1a58db15a4a` through StarPilot `2efe6017bfe14cee4807833e05f9a7f6ba255cdb`. Contributors to that lineage include Alan Polk, John Christman, Jacob Neulight, tonesto7 and Haibin Wen. The current protocol adapter is maintained by StarPilot separately from the pinned BluePilot library; this attribution does not imply BluePilot maintains or endorses the adapted tune.
The current StarPilot Controller replaces that historical curvature-primary tune with a separately maintained adaptation of BluePilot v0.2.1's angle strategy (`2b9dc6cc784faac47a1885d0bda0561f7b76f74d`, `core/lateral_angle_ext.py`). Alan Polk is the principal controller author; John Christman contributed angle-mode anti-stall work, Jacob Neulight the pinion/shadow measurement, Nathan Ingraham and Praeuner high-speed damping, and other contributors are retained in the pinned library's `CREDITS.md`. StarPilot adds bounded small-signal conditioning ahead of the unchanged angle limit chain. This adaptation is not maintained or endorsed by BluePilot; the pinned library and its imported hooks are unchanged.
## Uniden radar detector link
The Uniden detector link builds on **inauner's** earlier Uniden R4/R8/R9 work in [inauner/StarPilot, uniden](https://github.com/inauner/StarPilot/tree/c4b694b2ac8742ddec44123d53f1f84d2990b47e) (`uniden_protocol.py`, `uniden_r4.py`, `uniden_radar_d.py`, the Galaxy Uniden panel and the radar alert banner), which established the detector's BLE alert flow and the Galaxy/UI integration approach. This branch's monitor, transport, widgets and tests are a separate implementation on the current StarPilot Bluetooth owner; the experimental settings and speed-limit slowdown logic are not included. The alert parser and command framing are based on AegisX86/UnidenR8wlink (see THIRD_PARTY_NOTICES.md).
+4
View File
@@ -154,3 +154,7 @@ The Subaru angle implementation includes work from Jacob Waller's `jul-angle-bas
The historical tuning formerly in `openpilot/starpilot/car/ford/starpilot_tuning.py` included the BluePilot bp-7.0-derived work identified in [CREDITS.md](CREDITS.md#starpilot-ford-demand-tuning). The published upstream license notices retained above and in the pinned BluePilot library remain applicable to the adapted source. StarPilot's separate protocol adapter does not modify those notices or resolve their scope.
The angle-primary adaptation in `openpilot/starpilot/car/ford/starpilot_controller.py` is derived from BluePilot v0.2.1. It retains the complete MIT copyright and permission notice in `opendbc_repo/opendbc/bluepilot_lateral/LICENSE`, including Comma.ai, BluePilot and StarPilot contributors. See the contributor attribution in `CREDITS.md`.
## Uniden detector protocol
The detector alert parser and command framing in `openpilot/starpilot/uniden/` are based on [AegisX86/UnidenR8wlink](https://github.com/AegisX86/UnidenR8wlink)'s MIT-licensed protocol documentation, copyright (c) 2026 Aegis "P.R Aigis". The complete notice is retained in [UPSTREAM-LICENSE](openpilot/starpilot/uniden/UPSTREAM-LICENSE).
Binary file not shown.
Binary file not shown.
+1
View File
@@ -136,6 +136,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"LaneCenterOffset", {PERSISTENT, FLOAT, "0.0"}},
{"LaneCenteringE2EAuthority", {PERSISTENT, FLOAT, "0.5"}},
{"LaneCenteringStrength", {PERSISTENT, FLOAT, "1.5"}},
{"UnidenConfig", {PERSISTENT | DONT_LOG, JSON}},
{"StarPortEnabled", {PERSISTENT | DONT_LOG, BOOL, "0"}},
{"AdvancedLateralTune", {PERSISTENT, BOOL}},
{"LateralControllerSelection", {PERSISTENT | DONT_LOG, JSON}},
@@ -1,6 +1,8 @@
Japanese and Korean subsets expanded for the shared StarPilot UI catalogs.
Generated with fontTools.subset, retaining the union of each original font cmap
and all characters in app_ja.po/app_ko.po. Original subset: Dom 1f1b1d5db9.
Japanese, Korean and Simplified Chinese subsets expanded for the shared StarPilot
UI catalogs. Generated with fontTools.subset (default options), retaining the
union of each original font cmap and all characters in app_ja.po/app_ko.po/
app_zh-CHS.po. Original subset: Dom 1f1b1d5db9. Regenerate the Simplified Chinese
subset whenever app_zh-CHS.po gains characters.
The official upstream source fonts are licensed under Noto-OFL.txt.
NotoSansCJKjp-Regular.otf
@@ -12,3 +14,8 @@ NotoSansCJKkr-Regular.otf
Source: https://raw.githubusercontent.com/notofonts/noto-cjk/main/Sans/OTF/Korean/NotoSansCJKkr-Regular.otf
Source SHA-256: 6bcb2a0703aa137e874fc2dffa85f6c21ba9a67fa329e81b8c801663af7e992a
Subset SHA-256: 846e22c2bf1afffc11718ee95e4acc258538cc528b20aab3aa122476e64533b8
NotoSansCJKsc-Regular.otf
Source: https://raw.githubusercontent.com/notofonts/noto-cjk/main/Sans/OTF/SimplifiedChinese/NotoSansCJKsc-Regular.otf
Source SHA-256: 2c76254f6fc379fddfce0a7e84fb5385bb135d3e399294f6eeb6680d0365b74b
Subset SHA-256: 159db5944e2e2d2fbeaea3dd6db56b95f57eff80036f93fb7ac612ef25f03e84
+9 -7
View File
@@ -633,6 +633,13 @@ class Controls:
new_desired_curvature = limit_curvature_to_plan(model_v2, new_desired_curvature, CS.vEgo, min_reach=4.0)
else:
self.subaru_twitch_guard_armed = update_twitch_guard(False, CS.vEgo, CS.standstill)
kona_tau = getattr(self, "kona_smoothing", 0.)
from openpilot.starpilot.car.subaru.smoothing import seconds as subaru_smooth_seconds, control_maximum
lat_delay = self.sm["lateralDelay"].lateralDelay + LAT_SMOOTH_SECONDS + subaru_smooth_seconds(CS.vEgo, control_maximum(self)) + kona_tau
if getattr(self, "volkswagen_smoothing", None) is not None:
lat_delay += self.volkswagen_smoothing.seconds(int(self.sm.logMonoTime["modelV2"]), time.monotonic_ns())
if self.highway_smoothing_supported:
preferences = getattr(self, "live_steering_preferences", None)
if preferences is not None:
@@ -656,12 +663,13 @@ class Controls:
or self.sm.valid['lateralManeuverPlan']
),
predicted=predicted,
steering_limited=self.steer_limited_by_safety,
actuator_delay_s=lat_delay,
)
lane_base_curvature = new_desired_curvature
self.lane_centering_applied = 0.0
self.lane_centering_inactive_reason = 'inactive'
self.last_lane_centering_result = None
kona_tau = getattr(self, "kona_smoothing", 0.)
lane_delay = None
if lane_centering is None and self.lane_centering_host is not None:
now_ns = int(self.sm.logMonoTime['carState']) if os.getenv('REPLAY') == '1' else time.monotonic_ns()
@@ -723,12 +731,6 @@ class Controls:
self.desired_curvature = guarded
curvature_limited = True
self.lane_centering_applied = self.desired_curvature - baseline_curvature
from openpilot.starpilot.car.subaru.smoothing import seconds as subaru_smooth_seconds, control_maximum
lat_delay = self.sm["lateralDelay"].lateralDelay + LAT_SMOOTH_SECONDS + subaru_smooth_seconds(CS.vEgo, control_maximum(self)) + kona_tau
if getattr(self, "volkswagen_smoothing", None) is not None:
lat_delay += self.volkswagen_smoothing.seconds(int(self.sm.logMonoTime["modelV2"]), time.monotonic_ns())
actuators.curvature = self.desired_curvature
if cycle_timing is not None:
cycle_timing.mark()
@@ -25,6 +25,7 @@ TIGHT_CURVE_OFF = 2.0 # m/s^2
ENVELOPE_HOLD = 2.0 # s
ENVELOPE_RELEASE_RATE = 0.3 # m/s^2 per second
BYPASS_FADE_RATE = 2.0 # per second
LIMIT_RECOVERY_RAMP = 0.4 # s
MIN_SETTING = 1.0
MAX_SETTING = 10.0
KEY = "HighwaySmoothingLevel"
@@ -83,9 +84,11 @@ class HighwayCorrectionGain:
self.prediction_envelope = _Envelope()
self.bypass_weight = 0.0
self.weight = 0.0
self.time_clear_of_limit: float | None = None
self.limit_recovery = 1.0
def update(self, curvature: float, v_ego: float, lat_active: bool, gain: float, bypass: bool,
predicted: tuple[float, ...] | None = None) -> float:
predicted: tuple[float, ...] | None = None, *, steering_limited: bool = False, actuator_delay_s: float = 0.0) -> float:
if not lat_active:
self.reset(curvature)
return curvature
@@ -117,8 +120,19 @@ class HighwayCorrectionGain:
step = BYPASS_FADE_RATE * DT_CTRL
self.bypass_weight += min(max((0.0 if bypass else 1.0) - self.bypass_weight, -step), step)
# Leave the original request intact while limited and let the delayed commands clear before blending back in.
if steering_limited:
self.time_clear_of_limit = self.limit_recovery = 0.0
elif self.time_clear_of_limit is not None:
if math.isfinite(actuator_delay_s) and actuator_delay_s >= 0.0:
target = max((self.time_clear_of_limit - actuator_delay_s) / LIMIT_RECOVERY_RAMP, 0.0)
self.limit_recovery = min(target, self.limit_recovery + DT_CTRL / LIMIT_RECOVERY_RAMP, 1.0)
self.time_clear_of_limit = None if self.limit_recovery == 1.0 else self.time_clear_of_limit + DT_CTRL
else:
self.time_clear_of_limit = self.limit_recovery = 0.0
gain = min(max(gain, MIN_SETTING / MAX_SETTING), 1.0)
self.weight = self.bypass_weight * _smoothstep(v_ego, SPEED_OFF, SPEED_ON) * gate
self.weight = self.bypass_weight * _smoothstep(v_ego, SPEED_OFF, SPEED_ON) * gate * self.limit_recovery
k = 1.0 - self.weight * (1.0 - gain)
if k >= 1.0:
return curvature
@@ -119,6 +119,28 @@ def test_bypass_fades_without_steps():
assert np.max(np.abs(np.diff(out))) < 1.5 * max_raw_step
def test_limit_pauses_smoothing_until_the_actuator_delay_clears():
hcg = HighwayCorrectionGain()
_run(hcg, _weave(seconds=5.0), gain=0.5)
assert hcg.weight == 1.0
raw = 0.04 / _V_HWY ** 2
delay = 0.3
assert hcg.update(raw, _V_HWY, True, 0.5, False, steering_limited=True, actuator_delay_s=delay) == raw
for _ in range(round(delay / DT_CTRL)):
assert hcg.update(raw, _V_HWY, True, 0.5, False, actuator_delay_s=delay) == raw
weights = []
for _ in range(41):
hcg.update(raw, _V_HWY, True, 0.5, False, actuator_delay_s=delay)
weights.append(hcg.weight)
assert 0.4 < weights[20] < 0.6
assert weights[-1] == 1.0
assert np.max(np.diff(weights)) < 0.026
assert hcg.update(raw, _V_HWY, True, 0.5, False, steering_limited=True, actuator_delay_s=delay) == raw
for _ in range(100):
assert hcg.update(raw, _V_HWY, True, 0.5, False, actuator_delay_s=math.nan) == raw
def test_active_from_40_mph():
v = 40.0 * 0.44704
raw = _weave(v_ego=v)
File diff suppressed because it is too large Load Diff
+1
View File
@@ -29,6 +29,7 @@ def update_frame(preview=None, controllers=None, star=None, game_mode=None, arab
star._poll_projection_bookmark(time.monotonic_ns())
star._poll_projection_slc(time.monotonic_ns())
poll_screen_off_wheel(star, device.awake, time.monotonic_ns())
star._poll_detector()
if game_mode is not None:
game_mode()
if controllers is not None:
+17 -2
View File
@@ -45,6 +45,9 @@ def set_device_class(major: int, minor: int) -> bool:
BLUEZ = 'org.bluez'
ADAPTER = 'org.bluez.Adapter1'
DEVICE = 'org.bluez.Device1'
# BlueZ Connect failures that mean the device never answered.
UNREACHABLE_ERRORS = ('org.bluez.Error.Failed', 'org.bluez.Error.NotAvailable', 'org.bluez.Error.NotReady',
'org.bluez.Error.ConnectionAttemptFailed', 'org.bluez.Error.BREDR.ProfileUnavailable')
AGENT = 'org.bluez.Agent1'
AGENT_PATH = '/org/starpilot/bluetooth/pairing'
ADMISSION_LOCK = Path('/data/starpilot/bluetooth-owner.lock')
@@ -294,8 +297,18 @@ class BlueZ:
path = self._device_path(address)
if operation == 'forget':
self._call(adapter_path, ADAPTER, 'RemoveDevice', 'o', (path,))
elif operation in ('connect', 'disconnect'):
self._call(path, DEVICE, operation.capitalize())
elif operation == 'connect':
try:
self._call(path, DEVICE, 'Connect')
except TimeoutError:
raise BluetoothRejected('Device did not respond', code='unreachable') from None
except BluetoothRejected as error:
# Off, out of range or held by another phone/app; not a changed device.
if str(error) in UNREACHABLE_ERRORS:
raise BluetoothRejected(f'Device did not respond ({error})', code='unreachable') from None
raise
elif operation == 'disconnect':
self._call(path, DEVICE, 'Disconnect')
else:
raise ValueError('Unsupported Bluetooth operation')
@@ -583,6 +596,7 @@ class BluetoothOwner:
self.admission_lock = admission_lock
self.admission_file = None
self.power_change_active = False
self.uniden: Any = None
def _admission_enter(self) -> None:
if self.admission_file is not None:
@@ -951,6 +965,7 @@ class BluetoothOwner:
self._client().operation(operation, address)
if operation == 'forget':
assert address is not None
self.uniden = None
self._forget_starport_car(address)
if operation == 'power' and not enabled:
self.systemctl(['sudo', '-n', 'systemctl', 'stop', RADIO_UNIT], check=True, timeout=15)
@@ -838,6 +838,32 @@ class BluetoothOwnerTest(unittest.TestCase):
bluez.snapshot()
self.assertIn('Set', calls)
def test_connect_to_silent_device_reports_unreachable_not_changed(self):
bluez = BlueZ.__new__(BlueZ)
objects = {
'/org/bluez/hci0': {'org.bluez.Adapter1': {'Powered': ('b', True)}},
'/org/bluez/hci0/dev_AA_BB_CC_DD_EE_FF': {'org.bluez.Device1': {'Address': ('s', 'AA:BB:CC:DD:EE:FF'), 'Paired': ('b', True)}},
}
failure = []
def call(path, interface, member, signature=None, body=()):
if member == 'GetManagedObjects':
return (objects,)
raise failure[0]
self.enterContext(patch.object(bluez, '_call', call))
for error, code in [(BluetoothRejected('org.bluez.Error.Failed'), 'unreachable'), (TimeoutError(), 'unreachable'),
(BluetoothRejected('org.bluez.Error.NotAuthorized'), 'changed')]:
failure[:] = [error]
with self.assertRaises(BluetoothRejected) as raised:
bluez.operation('connect', 'AA:BB:CC:DD:EE:FF')
self.assertEqual(raised.exception.code, code)
failure[:] = [BluetoothRejected('org.bluez.Error.Failed')]
with self.assertRaises(BluetoothRejected) as raised:
bluez.operation('disconnect', 'AA:BB:CC:DD:EE:FF')
self.assertEqual(raised.exception.code, 'changed')
def test_each_bluez_close_releases_router_and_underlying_connection(self):
closed = []
+45 -6
View File
@@ -7,6 +7,7 @@ from itertools import islice
import os
from pathlib import Path
import re
import secrets
import stat
import struct
import time
@@ -95,22 +96,60 @@ def _button_capable(sysfs: Path) -> bool:
any(ABS_HAT0X <= axis <= ABS_HAT3Y for axis in axes)
def _inspect(path: Path) -> _Identity | None:
if not EVENT_NAME.fullmatch(path.name):
def _external(name: str) -> tuple[Path, re.Match[str]] | None:
"""The sysfs device and modalias of a USB or Bluetooth event node."""
if not EVENT_NAME.fullmatch(name):
return None
sysfs = SYS_ROOT / path.name / "device"
sysfs = SYS_ROOT / name / "device"
match = MODALIAS.match(_text(sysfs / "modalias"))
if match is None:
if match is None or int(match[1], 16) not in EXTERNAL_BUSES:
return None
return sysfs, match
def _inspect(path: Path) -> _Identity | None:
external = _external(path.name)
if external is None or not _button_capable(external[0]):
return None
sysfs, match = external
bus, vendor, product, _version = (int(token, 16) for token in match.groups())
if bus not in EXTERNAL_BUSES or not _button_capable(sysfs):
return None
name = _text(sysfs / "name") or "External input"
uniq = _text(sysfs / "uniq")
identity = f"{bus:04x}:{vendor:04x}:{product:04x}:{name.casefold()}:{uniq.casefold()}"
return _Identity(path, hashlib.sha256(identity.encode()).hexdigest()[:20], name[:80], bus)
def controller_input_report() -> dict:
"""Snapshot external input interfaces, including ones omitted from Attached Controllers; names are masked."""
devices = []
groups: dict[str, list[str]] = {}
salt = secrets.token_bytes(8) # equal names match within one report only
truncated = False
for entry in sorted(SYS_ROOT.iterdir()):
if (external := _external(entry.name)) is None:
continue
if len(devices) == MAX_CANDIDATES:
truncated = True
break
device, match = external
identity = _inspect(DEV_ROOT / entry.name)
if identity is not None:
groups.setdefault(identity.device_id, []).append(entry.name)
name = _text(device / "name")
devices.append({
"event": entry.name, "name": f"masked-{hashlib.sha256(salt + name.encode()).hexdigest()[:8]}" if name else "", "inputId": match[0],
"properties": _text(device / "properties"),
"capabilities": {key: _text(device / "capabilities" / key) for key in ("ev", "key", "rel", "abs")},
"discovery": "eligible" if identity else "filtered",
"eventNodePresent": (DEV_ROOT / entry.name).exists(),
})
duplicates = {event: events for events in groups.values() if len(events) > 1 for event in events}
for row in devices:
if row["event"] in duplicates:
row.update(discovery="duplicate identity", matchingEvents=duplicates[row["event"]])
return {"externalInputInterfaces": devices, "truncated": truncated}
def _fresh(seconds: int, microseconds: int, now_ns: int) -> int | None:
if seconds < 0 or not 0 <= microseconds < 1_000_000:
return None
@@ -260,3 +260,41 @@ def test_device_and_scan_candidate_caps(kernel):
reader.poll(NOW + source.RESCAN_NS)
assert reader.devices() == []
reader.close()
def test_report_includes_filtered_and_duplicate_external_interfaces(monkeypatch, tmp_path):
kernel = Kernel(monkeypatch, tmp_path)
kernel.device(1, bus=5)
kernel.device(2, bus=5)
kernel.device(3, bus=5, keys=(115,), rel=(0, 1))
kernel.device(4, bus=5, name="Media", keys=(115,))
kernel.device(5, bus=1)
report = source.controller_input_report()
rows = report["externalInputInterfaces"]
assert [row["discovery"] for row in rows] == ["duplicate identity", "duplicate identity", "filtered", "eligible"]
assert rows[0]["matchingEvents"] == ["event1", "event2"]
assert rows[2]["capabilities"]["rel"] == "3"
assert not report["truncated"]
assert not kernel.path_by_fd
def test_report_masks_names(monkeypatch, tmp_path):
kernel = Kernel(monkeypatch, tmp_path)
kernel.device(1, bus=5, name="Danny's Pad")
kernel.device(2, bus=5, name="Danny's Pad", uniq="02")
kernel.device(3, bus=5, name="Media", keys=(115,))
report = source.controller_input_report()
names = [row["name"] for row in report["externalInputInterfaces"]]
assert all(name.startswith("masked-") for name in names)
assert names[0] == names[1] != names[2]
assert "Danny" not in str(report) and "Media" not in str(report)
assert source.controller_input_report()["externalInputInterfaces"][0]["name"] != names[0]
def test_report_is_capped(monkeypatch, tmp_path):
kernel = Kernel(monkeypatch, tmp_path)
for index in range(source.MAX_CANDIDATES + 1):
kernel.device(index, bus=5, uniq=str(index))
report = source.controller_input_report()
assert len(report["externalInputInterfaces"]) == source.MAX_CANDIDATES
assert report["truncated"]
+74 -11
View File
@@ -3,12 +3,13 @@
from dataclasses import asdict, dataclass, field, replace
from bisect import bisect_left
import hashlib
from statistics import fmean
from openpilot.starpilot.flm.offroad_analysis import analyze, MAX_WINDOWS, cohort, _spread, MAX_COHORT_WINDOWS
from openpilot.starpilot.flm.offroad_baseline_windows import baseline_windows
from openpilot.starpilot.flm.canonical_surface_adapter import NAMES as AMPLITUDE_NAMES
from openpilot.starpilot.flm.offroad_residual import analyze_stable_windows
from openpilot.starpilot.flm.offroad_evidence import read_point, whole_windows, eligible_points, tracking_metrics, window_demand
from openpilot.starpilot.flm.offroad_evidence import read_point, whole_windows, eligible_points, tracking_metrics, window_demand, MAX_GAP_NS
from openpilot.starpilot.flm.offroad_route import (
latest_route, walk_completed_route, RouteInputCancelled, RouteReceipt, SelectedSourceReceipt, PartialRouteReceipt, route_permission,
)
@@ -119,8 +120,67 @@ def _separate_qualification(report, continuous, *, proposal_windows=None, route_
]
def _recorded_tracking(windows):
"""Measured route summary and one input-ordered window, never a trial result."""
def _repeated_request_span(windows):
"""Find near-center oscillation the car followed in contiguous original windows."""
section = []
best = ()
best_variance = 0.0
for window in windows:
points = window.points
first = points[0]
if window.domain != 'lateral_acceleration' or any(p.speed_mps < 15 for p in points):
section.clear()
continue
if section:
last = section[-1][-1]
if (first.route, first.segment, first.context_key) != (last.route, last.segment, last.context_key) or not (
0 < first.mono_ns - last.mono_ns <= MAX_GAP_NS
):
section.clear()
section.append(points)
if len(section) < 6:
continue
span = tuple(p for part in section for p in part)
section.pop(0)
start = span[0].mono_ns
sample = _spread(span, 61)
if len(sample) != 61 or any(abs(p.mono_ns - start - i * 200_000_000) > MAX_GAP_NS for i, p in enumerate(sample)):
continue
desired = [p.desired for p in sample]
if fmean(map(abs, desired)) > .18 or max(map(abs, desired)) > .35:
continue
# Require four alternating excursions with at least 0.6 s between them.
mean = fmean(desired)
side = last_change = changes = 0
for i, value in enumerate(desired):
if abs(value - mean) >= .025:
current = 1 if value > mean else -1
if current != side and (not side or i - last_change >= 3):
changes += bool(side)
side, last_change = current, i
if changes < 3:
continue
# Compare to the original request at short, plausible response lags.
# Neither this observation nor its illustrative lag supplies tuning evidence.
actual = [p.actual for p in sample[3:]]
center = fmean(actual)
variance = fmean((a - center) ** 2 for a in actual)
if variance < .025 ** 2 or variance <= best_variance:
continue
for lag in range(4):
errors = [a - d for a, d in zip(actual, desired[3 - lag:len(desired) - lag], strict=True)]
bias = fmean(errors)
if fmean((e - bias) ** 2 for e in errors) <= .20 * variance:
best, best_variance = span, variance
break
return best
def _recorded_tracking(windows, raw_windows):
"""Measured route summary and one observed section, never a trial result."""
import math
ordered = sorted((w for rows in windows.values() for w in rows), key=lambda w: (w.points[0].segment, w.points[0].mono_ns))
@@ -128,19 +188,22 @@ def _recorded_tracking(windows):
return None
samples = sum(len(w.points) for w in ordered)
squared_error = sum((p.desired - p.actual) ** 2 for w in ordered for p in w.points)
first = ordered[0]
raw = sorted((w for rows in raw_windows.values() for w in rows), key=lambda w: (w.points[0].route, w.points[0].segment, w.points[0].mono_ns))
repeated = _repeated_request_span(raw) if ordered[0].domain == 'lateral_acceleration' else ()
points = repeated or ordered[0].points
return {
'version': 1,
'domain': first.domain,
'domain': points[0].domain,
'samples': samples,
'windows': len(ordered),
'error_rms': math.sqrt(squared_error / samples),
'route': first.points[0].route,
'segment': first.points[0].segment,
'source_start_ns': first.points[0].mono_ns,
'source_end_ns': first.points[-1].mono_ns,
'points': [[p.mono_ns, p.desired, p.actual] for p in _spread(first.points, 64)],
'route': points[0].route,
'segment': points[0].segment,
'source_start_ns': points[0].mono_ns,
'source_end_ns': points[-1].mono_ns,
'points': [[p.mono_ns, p.desired, p.actual] for p in _spread(points, 64)],
'sampling': 'input_ordered_original_endpoints_no_interpolation',
**({'observation': 'followed_repeated_steering_request'} if repeated else {}),
}
@@ -658,6 +721,6 @@ def _assess_inputs(route, collected, previous, *, permitted, sources=None, route
counts['diagnostic_whole_windows'] = sum(map(len, raw_windows.values()))
return CompletedAssessment(
receipt, reports, counts, state['cp'], (), route, tuple(quality_stops), tuple(diagnostic), tuple(stable),
_recorded_tracking(proposal_windows) or _recorded_tracking(raw_windows), sources,
_recorded_tracking(proposal_windows, raw_windows) or _recorded_tracking(raw_windows, raw_windows), sources,
)
@@ -1,17 +1,56 @@
"""Broader original observations remain separate from automatic qualification."""
from dataclasses import replace
from math import pi, sin
from types import SimpleNamespace
import pytest
from openpilot.starpilot.flm.offroad_evidence import RouteWindow, window_identity
from openpilot.starpilot.flm.offroad_processor import CompletedAssessment, _assess_inputs
from openpilot.starpilot.flm.offroad_processor import CompletedAssessment, _assess_inputs, _recorded_tracking
from openpilot.starpilot.flm.offroad_stable_bridge import StableRouteSelector
from openpilot.starpilot.flm.offroad_stable_policy import FLMSample
from openpilot.starpilot.flm.tests.test_offroad_backend import scope, values
from openpilot.starpilot.flm.tests import test_offroad_coordinate_policy as fixtures
@pytest.mark.parametrize('case', ('followed', 'steady_curve', 'lane_change', 'uncommanded', 'gap'))
def test_report_displays_repeated_steering_request_only_with_matching_original_response(case):
# Keep a genuine 0.4 s delay between the request and measured response.
def requested(t):
if case in ('steady_curve', 'uncommanded'):
return .1
if case == 'lane_change':
return .08 * sin(pi * t / 12)
return .075 * sin(2 * pi * t / 4.5)
collected, _ = fixtures.TestCrossDriveEvidence.inputs(1)
base = next(iter(collected.windows.values()))[0].points[0]
windows = []
for w in range(6):
if case == 'gap' and w == 3:
continue
points = []
for i in range(200):
t = (200 * w + i) / 100
actual = .08 * sin(2 * pi * t / 4.5) if case == 'uncommanded' else requested(t - .4)
points.append(replace(base, speed_mps=26., mono_ns=base.mono_ns + (200 * w + i) * 10_000_000,
desired=requested(t), actual=actual))
points = tuple(points)
windows.append(RouteWindow(window_identity(points), points))
inputs = {base.context_key: windows}
result = _recorded_tracking(inputs, inputs)
assert result is not None
assert result['windows'] == len(windows)
assert result['points'][0] == [base.mono_ns, windows[0].points[0].desired, windows[0].points[0].actual]
if case == 'followed':
assert result['observation'] == 'followed_repeated_steering_request'
assert result['source_end_ns'] == windows[-1].points[-1].mono_ns
else:
assert 'observation' not in result
assert result['source_end_ns'] == windows[0].points[-1].mono_ns
def mixed_drive(number):
collected, inventory = fixtures.TestCrossDriveEvidence.inputs(number)
for key, windows in collected.windows.items():
@@ -0,0 +1,43 @@
"""Send the controller input report to the developer's Discord forum, beside StarPort logs."""
import json
from openpilot.starpilot.controllers.input import controller_input_report
from openpilot.starpilot.galaxy import starport_send
from openpilot.starpilot.system.starport import identity as identity_store
TITLE = "Bluetooth Log"
WEBHOOK_OVERRIDE_PATH = identity_store.DATA_DIR / "bluetooth_webhook_url"
# Obfuscation only; device-local configuration overrides this built-in webhook.
_WEBHOOK_KEY = b"bluetooth-log"
_WEBHOOK_DATA = "".join(("ChgBFQdVQFsMRB8MCBAIWwYbAkAVGERDGAIABBoKHxxARV0aWFdTU11GVU1aVkZcFFhdXk0PFAMMNlgjG1",
"RdDiMjOSVURjZaPTxjNStXJB0NExAhDgZZWi0cElEuRTUTHBotWmwqVyE0LkwjWVkoAQ9LVAIeJAFYSA=="))
def webhook_url() -> str:
return starport_send.webhook_url(WEBHOOK_OVERRIDE_PATH, _WEBHOOK_KEY, _WEBHOOK_DATA)
def summary() -> dict:
from openpilot.starpilot.system.starport.bugsink_transport import device_metadata
result = device_metadata()
try:
result["car_fingerprint"] = starport_send.car_fingerprint()
except Exception as error:
result["car_fingerprint_error"] = str(error)
return result
def report(**_) -> tuple[str, bytes]:
return "bluetooth-log.json", json.dumps(controller_input_report(), indent=2).encode()
def send(data: bytes, name: str, note: str, details: dict, *, discord: str, url: str | None = None, post=None, thread_dir=None) -> str | None:
return starport_send.send(data, name, note, details, url=webhook_url() if url is None else url, post=post, thread_dir=thread_dir,
discord=discord, heading=TITLE, fields=(), content_type="application/json",
title=f"{TITLE} {starport_send.thread_title(details)}"[:100])
def sender() -> starport_send.StarPortLogSender:
return starport_send.StarPortLogSender(report, sender=send, summary=summary, url=webhook_url,
busy="The Bluetooth Log is already being sent.")
+79 -32
View File
@@ -99,7 +99,7 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
sounds=None, software_operations=None, drive_stats=None, layout_preview_socket=None, controllers_socket=None,
remote_pairing=None, parked=None, camera_snapshot=None, clock=time.monotonic, starport_setup=None,
starport_client=None, navigation=None, offline_maps=None, drive_state=None, cloud_provider=None, cloud_offroad=None, projection_layout=None,
local_access=None, tmux_live=None, starport_logs=None, starport_log_sender=None, hotspot=None, toyota_tools=None,
local_access=None, tmux_live=None, starport_logs=None, starport_log_sender=None, bluetooth_log_sender=None, hotspot=None, toyota_tools=None,
replay_client=None, replay_root=None,
spotify_setup=None, companion=None, phone_location=None, reverse_proxy=None, local_hostnames=None, sound_preview=None):
from openpilot.starpilot.galaxy.local_hostnames import LocalHostnames
@@ -165,6 +165,16 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
source = starport_logs()
starport_log_sender_source = StarPortLogSender(source.bundle, summary=lambda: device_summary(source.directory))
return starport_log_sender_source
bluetooth_log_sender_source = bluetooth_log_sender
bluetooth_log_sender_lock = threading.Lock()
def bluetooth_log_sender():
nonlocal bluetooth_log_sender_source
with bluetooth_log_sender_lock:
if bluetooth_log_sender_source is None:
from openpilot.starpilot.galaxy.bluetooth_send import sender
bluetooth_log_sender_source = sender()
return bluetooth_log_sender_source
software_source = software
software_operations_source = software_operations
software_lock = threading.Lock()
@@ -254,6 +264,8 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
plots_lock = threading.Lock()
bluetooth_lock = threading.Lock()
bluetooth_source = bluetooth
uniden_source = None
uniden_lock = threading.Lock()
starport_setup_source = starport_setup
spotify_setup_source = spotify_setup
starport_client_source = starport_client
@@ -390,6 +402,15 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
link_music_phone(address)
spotify_owner().adopt_phone(address, name, uuids)
def uniden_owner():
nonlocal uniden_source
with uniden_lock:
if uniden_source is None:
from openpilot.common.params import Params
from openpilot.starpilot.uniden.service import DetectorService
uniden_source = DetectorService(Params(), configuration_allowed)
return uniden_source
def bluetooth_owner():
nonlocal bluetooth_source
with bluetooth_lock:
@@ -1002,37 +1023,18 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
elif path == '/api/starport/logs/send':
if self.require_session():
self.json(200, starport_log_sender().status())
elif path == '/api/starport/logs' or path.startswith('/api/starport/logs/'):
elif path == '/api/starport/logs':
if not self.require_session():
return
from openpilot.starpilot.galaxy.starport_logs import LogMissing, LogsUnavailable
name = unquote(path.removeprefix('/api/starport/logs/file/')) if path.startswith('/api/starport/logs/file/') else None
if name is not None and not re.fullmatch(r'[\w.-]{1,128}', name):
self.json(400, {'error': 'Invalid log name'})
return
if path not in ('/api/starport/logs', '/api/starport/logs/bundle') and name is None:
self.json(404, {'error': 'Not found'})
return
from openpilot.starpilot.galaxy.starport_logs import LogsUnavailable
try:
if path == '/api/starport/logs':
result = starport_logs().list()
elif name is None:
result = starport_logs().bundle()
else:
result = starport_logs().file(name)
except LogMissing:
self.json(404, {'error': 'That log is no longer kept; refresh the list'})
result = starport_logs().list()
except LogsUnavailable:
self.json(503, {'error': 'Android Auto logs are unavailable'})
else:
# The session can be revoked while logs are read; check again right before sending them.
if not self.require_session():
return
if path == '/api/starport/logs':
if self.require_session():
self.json(200, result)
else:
filename, body = result
self.attachment(filename, body, 'application/zip' if filename.endswith('.zip') else 'text/plain; charset=utf-8')
elif path.startswith('/api/navigation/map/tiles/'):
if not self.require_session():
return
@@ -1222,6 +1224,9 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
self.json(200, {'valid': True})
else:
self.json(410, {'valid': False})
elif path == '/api/controllers/log/send':
if self.require_session():
self.json(200, bluetooth_log_sender().status())
elif path == '/api/controllers/status':
if not self.require_session():
return
@@ -1732,12 +1737,12 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
'/api/galaxy/pair', '/api/galaxy/unpair', '/api/galaxy/device-name', '/api/galaxy/hotspot', '/api/galaxy/networks',
'/api/cameras/snapshot', '/api/cameras/white-balance',
'/api/starport/layout', '/api/starport/enable', '/api/starport/control', '/api/starport/pairing',
'/api/starport/logs/send',
'/api/starport/logs/send', '/api/controllers/log/send',
'/api/starport/pairing/response', '/api/starport/pairing/cancel', '/api/starport/pairing/select',
'/api/spotify/enable', '/api/spotify/key', '/api/spotify/preferences', '/api/spotify/control', '/api/spotify/maintenance',
'/api/ui/layout', '/api/ui/layout/preview', '/api/favorites/slots',
'/api/maps/start', '/api/maps/cancel',
'/api/bluetooth/action', '/api/controllers/action',
'/api/bluetooth/action', '/api/bluetooth/uniden', '/api/controllers/action',
'/api/models/active', '/api/models/preferences', '/api/models/download', '/api/models/download_all',
'/api/models/cancel', '/api/models/delete', '/api/models/refresh_manifest', '/api/models/jetlink',
'/api/models/laboratory', '/api/models/laboratory/download', '/api/models/laboratory/delete',
@@ -2511,9 +2516,9 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
else:
self.json(401, {'error': 'Sign in to Galaxy'})
return
if path == '/api/starport/logs/send':
if type(payload) is not dict or set(payload) not in ({'message'}, {'message', 'discord'}):
self.json(400, {'error': 'Invalid StarPort log send request'})
if path in ('/api/starport/logs/send', '/api/controllers/log/send'):
if type(payload) is not dict or set(payload) != {'message', 'discord'}:
self.json(400, {'error': 'Invalid log send request'})
return
identity = self.settings_session()
if identity is None:
@@ -2521,7 +2526,8 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
return
from openpilot.starpilot.galaxy.starport_send import SendBusy, SendRejected
try:
result = starport_log_sender().start(payload['message'], payload.get('discord', ''))
job = starport_log_sender() if path == '/api/starport/logs/send' else bluetooth_log_sender()
result = job.start(payload['message'], payload['discord'])
except SendRejected as error:
self.json(400, {'error': str(error)})
except SendBusy as error:
@@ -2811,6 +2817,45 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
else:
self.json(401, {'error': 'Sign in to Galaxy'})
return
if path == '/api/bluetooth/uniden':
identity = self.settings_session()
if identity is None:
self.json(401, {'error': 'Sign in to Galaxy'})
return
def detector_exchange(config, mute, situation=None):
from openpilot.starpilot.uniden.transport import exchange
if self.settings_session() != identity:
raise BluetoothRejected('Session expired', code='session_expired')
if starport_setup_owner().enabled():
try:
delegated = self.starport_command(identity, 'uniden', address=config['address'], model=config['model'], mute=mute,
auto_mute=config['auto_mute'], frequency_rules=config['frequency_rules'],
situation=situation)
except (OSError, RuntimeError):
if mute is not None:
raise BluetoothUnavailable('Mute delivery was not confirmed; check the detector') from None
delegated = {'handled': False} # Local admission still fails if AA owns the lock.
if delegated.get('handled'):
if 'error_code' in delegated:
message, code = delegated.get('message'), delegated['error_code']
raise BluetoothRejected(message if isinstance(message, str) else 'Bluetooth is busy', code=code if isinstance(code, str) else 'busy')
return delegated['detector']
return exchange(bluetooth_owner(), config['address'], config['model'], identity, mute=mute,
auto_mute=config['auto_mute'], frequency_rules=config['frequency_rules'], situation=situation)
try:
result = uniden_owner().request(payload, detector_exchange, valid=lambda: self.settings_session() == identity)
except ValueError as error:
self.json(400, {'error': str(error)})
except BluetoothRejected as error:
self.json(409, {'error': str(error), 'code': error.code})
except (BluetoothUnavailable, OSError, RuntimeError):
self.json(503, {'error': 'Detector connection unavailable'})
else:
if self.settings_session() == identity:
self.json(200, result)
else:
self.json(401, {'error': 'Sign in to Galaxy'})
return
if path == '/api/bluetooth/action':
identity = self.settings_session()
if identity is None:
@@ -2858,8 +2903,10 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
raise BluetoothUnavailable('service_unavailable')
if 'error_code' in delegated:
code = delegated['error_code']
if type(code) is str and code in ('busy', 'park_required', 'changed', 'session_expired', 'projection_active'):
raise BluetoothRejected('Android Auto could not complete the Bluetooth change', code=code)
if type(code) is str and code in ('busy', 'park_required', 'changed', 'session_expired', 'projection_active', 'unreachable'):
why = delegated.get('message')
raise BluetoothRejected(f'Android Auto: {why}' if type(why) is str and why else
'Android Auto could not complete the Bluetooth change', code=code)
unavailable = ('service_unavailable', 'adapter_unavailable', 'radio_unavailable', 'radio_preference_unavailable')
raise BluetoothUnavailable('Android Auto Bluetooth service is unavailable',
code=code if type(code) is str and code in unavailable else 'service_unavailable')
+1 -21
View File
@@ -1,8 +1,6 @@
"""Read-only access to the Android Auto logs under /data/starport/logs, for Logs & Diagnostics.
Lists the kept session logs with a one-line summary each, and serves one log or the shareable
bundle (``compat_report.bundle``: every session with its report, the settings without Bluetooth
addresses, and the renderer logs). Only names the log directory itself lists are served.
Lists the kept session logs with a one-line summary each, and builds the bundle that is sent to Discord.
"""
from __future__ import annotations
@@ -14,17 +12,10 @@ from pathlib import Path
from openpilot.starpilot.system.starport import compat_report
from openpilot.starpilot.system.starport import identity as identity_store
MAX_FILE_BYTES = 8 << 20 # a session log is normally well under 1 MiB; the renderer logs rotate at 256 KiB
class LogsUnavailable(Exception):
pass
class LogMissing(Exception):
pass
def _car(report: dict) -> str:
car = report.get("car") or {}
make = car.get("car_make") or car.get("head_unit_make") or ""
@@ -60,17 +51,6 @@ class StarPortLogs:
raise LogsUnavailable from None
return {"schemaVersion": 1, "sessions": sessions, "others": others}
def file(self, name: str) -> tuple[str, bytes]:
path = next((path for path in self._files() if path.name == name), None)
if path is None or path.is_symlink():
raise LogMissing
try:
return path.name, compat_report.read_log(path, MAX_FILE_BYTES)
except FileNotFoundError:
raise LogMissing from None
except OSError:
raise LogsUnavailable from None
def bundle(self, now: datetime | None = None, *, system_snapshot: bool = True) -> tuple[str, bytes]:
try:
data = compat_report.bundle(self.directory, self.config_path, **({} if system_snapshot else {"snapshot": None}))
+27 -24
View File
@@ -26,6 +26,7 @@ _WEBHOOK_DATA = "".join(("GwAVAgNVXVtJBRwEHAEQTxEfAl0VXQVAEBYRHA4dGxxdRRhaWlJLRE
DISCORD_FILE_LIMIT = 10 * 1024 * 1024 - 64 * 1024 # 10 MiB attachment limit, with room for the form fields
THREAD_CACHE_WARNING = "The forum thread could not be remembered on this device. The next upload may create another post."
CONTROL = re.compile(r"[\x00-\x1f\x7f]+")
STARPORT_FIELDS = (("Head unit", "head_unit"), ("Setup", "setup"), ("Handshake", "handshake"))
class SendRejected(Exception):
@@ -41,17 +42,17 @@ def official_install() -> bool:
return is_official_repo(device_metadata().get("repo"))
def webhook_url(override_path: Path = WEBHOOK_OVERRIDE_PATH) -> str:
def webhook_url(override_path: Path = WEBHOOK_OVERRIDE_PATH, key: bytes = _WEBHOOK_KEY, encoded: str = _WEBHOOK_DATA) -> str:
try:
override = override_path.read_text().strip()
except (OSError, UnicodeError):
override = ""
if override:
return override
if not _WEBHOOK_DATA:
if not encoded:
return ""
data = base64.b64decode(_WEBHOOK_DATA)
return bytes(byte ^ _WEBHOOK_KEY[index % len(_WEBHOOK_KEY)] for index, byte in enumerate(data)).decode()
data = base64.b64decode(encoded)
return bytes(byte ^ key[index % len(key)] for index, byte in enumerate(data)).decode()
def clean_message(value) -> str:
@@ -66,16 +67,18 @@ def clean_message(value) -> str:
def clean_discord(value) -> str:
"""An optional Discord username for a follow-up, without the leading @; "" when none was given."""
"""The required Discord username for a follow-up, without the leading @."""
if not isinstance(value, str):
raise SendRejected("The Discord username must be text.")
handle = value.strip().removeprefix("@")
if handle and not DISCORD_HANDLE.fullmatch(handle):
if not handle:
raise SendRejected("Add your Discord username so we can follow up.")
if not DISCORD_HANDLE.fullmatch(handle):
raise SendRejected("That doesn't look like a Discord username.")
return handle
def _car_fingerprint() -> str:
def car_fingerprint() -> str:
from openpilot.common.params import Params
from openpilot.starpilot.saved_source import read_saved
raw, readable = read_saved(Params(), "CarParamsPersistent", 1 << 20)
@@ -128,7 +131,7 @@ def _handshake(log_dir: Path | None, logs_to_check: int = 3) -> str:
def device_summary(log_dir: Path | None = None) -> dict:
from openpilot.starpilot.system.starport.bugsink_transport import device_metadata
summary = device_metadata()
for key, read in (("car_fingerprint", _car_fingerprint), ("head_unit", lambda: _head_unit(log_dir)), ("setup", lambda: _setup(log_dir)),
for key, read in (("car_fingerprint", car_fingerprint), ("head_unit", lambda: _head_unit(log_dir)), ("setup", lambda: _setup(log_dir)),
("handshake", lambda: _handshake(log_dir))):
try:
summary[key] = read()
@@ -163,25 +166,24 @@ def _save_thread_id(path: Path, key: str, thread_id: str) -> None:
def send(data: bytes, name: str, note: str, summary: dict, url: str | None = None, post=None,
thread_dir: Path | None = None, discord: str = "") -> str | None:
thread_dir: Path | None = None, *, discord: str, heading: str = "StarPort logs", fields=STARPORT_FIELDS,
content_type: str = "application/zip", title: str | None = None) -> str | None:
"""Post the zip; return a cache warning after success, or raise SendRejected on an upload failure."""
url = webhook_url() if url is None else url
if not url:
raise SendRejected("Sending isn't set up on this build. Use Download all logs and send the file instead.")
raise SendRejected("Sending isn't set up on this build.")
if len(data) > DISCORD_FILE_LIMIT:
raise SendRejected(f"The logs are {len(data) / 1e6:.1f} MB, over Discord's 10 MB limit. Use Download all logs instead.")
raise SendRejected(f"The logs are {len(data) / 1e6:.1f} MB, over Discord's 10 MB limit.")
if post is None:
import requests
post = requests.post
dongle_id = summary.get("device_id") or "device"
lines = [f"**StarPort logs from {device_tag(summary)}**",
lines = [f"**{heading} from {device_tag(summary)}**",
f"Car: {summary.get('car_fingerprint') or 'unknown'}",
f"Head unit: {summary.get('head_unit') or 'unknown'}",
f"Setup: {summary.get('setup') or 'unknown'}",
f"Handshake: {summary.get('handshake') or 'unknown'}",
*(f"{label}: {summary.get(key) or 'unknown'}" for label, key in fields),
f"Repo {summary.get('repo', '?')} · Branch {summary.get('branch', '?')} @ {str(summary.get('commit', '?'))[:10]}",
f"Note: {note.strip() or '(none)'}",
f"Follow-up: Discord `{discord}`" if discord else "Follow-up: not requested"]
f"Follow-up: Discord `{discord}`"]
payload = {"content": "\n".join(lines)[:1900], "username": "StarPilot diagnostics", "allowed_mentions": {"parse": []}}
parts = urlsplit(url)
@@ -209,13 +211,13 @@ def send(data: bytes, name: str, note: str, summary: dict, url: str | None = Non
query["thread_id"] = cached_id
elif not explicit_thread:
query.pop("thread_id", None)
payload["thread_name"] = thread_title(summary)
payload["thread_name"] = title or thread_title(summary)
post_url = urlunsplit(parts._replace(query=urlencode(query)))
try:
response = post(post_url, data={"payload_json": json.dumps(payload)}, files={"files[0]": (name, data, "application/zip")}, timeout=120)
response = post(post_url, data={"payload_json": json.dumps(payload)}, files={"files[0]": (name, data, content_type)}, timeout=120)
except Exception as error:
raise SendRejected(f"Could not send the logs: {type(error).__name__}. Check the internet connection, or use Download all logs.") from error
raise SendRejected(f"Could not send the logs: {type(error).__name__}. Check the internet connection.") from error
# Unknown Channel means the cached thread was deleted (Discord answers 400 for webhooks, 404 elsewhere).
# Unknown Webhook does not.
@@ -231,7 +233,7 @@ def send(data: bytes, name: str, note: str, summary: dict, url: str | None = Non
if response.status_code not in (200, 204):
reason = str(_response_json(response).get("message") or "")[:120]
detail = f"HTTP {response.status_code}{f': {reason}' if reason else ''}"
raise SendRejected(f"Discord refused the logs ({detail}). Use Download all logs instead.")
raise SendRejected(f"Discord refused the logs ({detail}).")
if not explicit_thread and not cached_id:
new_thread_id = _response_json(response).get("channel_id")
@@ -249,8 +251,9 @@ class StarPortLogSender:
def __init__(self, bundle: Callable[..., tuple[str, bytes]], *, sender: Callable[..., str | None] = send,
summary: Callable[[], dict] = device_summary, url: Callable[[], str] = webhook_url,
official: Callable[[], bool] = official_install):
official: Callable[[], bool] = official_install, busy: str = "StarPort logs are already being sent."):
self._bundle, self._sender, self._summary, self._url, self._official = bundle, sender, summary, url, official
self._busy = busy
self._lock = threading.Lock()
self._thread: threading.Thread | None = None
self._state = {"state": "idle", "message": ""}
@@ -262,11 +265,11 @@ class StarPortLogSender:
self._fork = not self._official()
return {**self._state, "available": bool(self._url()), "fork": self._fork, "messageLimit": MESSAGE_LIMIT}
def start(self, message, discord="") -> dict:
def start(self, message, discord) -> dict:
note, handle = clean_message(message), clean_discord(discord)
with self._lock:
if self._thread is not None and self._thread.is_alive():
raise SendBusy("StarPort logs are already being sent.")
raise SendBusy(self._busy)
self._state = {"state": "sending", "message": "Collecting logs"}
self._thread = threading.Thread(target=self._run, args=(note, handle), name="starport_log_send", daemon=True)
self._thread.start()
@@ -291,4 +294,4 @@ class StarPortLogSender:
except SendRejected as error:
self._set(state="failed", message=str(error)[:400])
except Exception as error:
self._set(state="failed", message=f"Could not send the logs: {type(error).__name__}. Use Download all logs instead.")
self._set(state="failed", message=f"Could not send the logs: {type(error).__name__}.")
@@ -217,7 +217,7 @@ class ProjectionBluetoothHttpTest(unittest.TestCase):
self.assertEqual(self.action('connect')[0], 503)
def test_owner_busy_and_error_codes_never_fall_back(self):
for error, code in [('busy', 409), ('park_required', 409), ('changed', 409), ('service_unavailable', 503)]:
for error, code in [('busy', 409), ('park_required', 409), ('changed', 409), ('unreachable', 409), ('service_unavailable', 503)]:
self.starport.result = {'handled': True, 'error_code': error}
actual, result, _ = self.action()
self.assertEqual(actual, code)
@@ -0,0 +1,120 @@
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright')
const { readFileSync } = require('node:fs')
const path = require('node:path')
const assert = require('node:assert/strict')
const web = path.resolve(__dirname, '../../web')
const detector = { name: 'Uniden R8', address: 'AA:BB:CC:DD:EE:FF', paired: true, trusted: true, connected: true }
const status = { version: 1, available: true, parked: true, powered: true, discovering: false, errorCode: null, pairing: null,
devices: [detector, { name: 'Steering remote', address: '11:22:33:44:55:66', paired: true, trusted: true, connected: false }] }
let config = { enabled: false, address: '', model: 'R8', transparency: 8, hide_when_no_alert: true,
auto_mute: false, hide_filtered: false, frequency_rules: [] }
const controller = { version: 1, available: true, editable: true, enabled: false, valid: true,
revision: 'a'.repeat(64), devices: [], slots: Array.from({ length: 13 }, (_, index) => ({ index,
label: index < 3 ? `Quick Select ${index + 1}` : `Button ${index - 2}`, key: null, available: index < 3 })),
options: [], bindings: [], learning: null, testing: false, lastPress: null }
;(async () => {
const browser = await chromium.launch({ headless: true,
...(process.env.PLAYWRIGHT_EXECUTABLE_PATH ? { executablePath: process.env.PLAYWRIGHT_EXECUTABLE_PATH } : {}) })
try {
const page = await browser.newPage({ viewport: { width: 390, height: 844 } })
const errors = [], requests = [], actions = []
page.on('pageerror', error => errors.push(error.message))
await page.route('http://bluetooth.test/**', async route => {
const pathname = new URL(route.request().url()).pathname
requests.push(pathname)
if (pathname === '/api/bluetooth/action') {
const body = route.request().postDataJSON(); actions.push(body)
const device = status.devices.find(device => device.address === body.address)
if (device && ['connect', 'disconnect'].includes(body.operation)) device.connected = body.operation === 'connect'
if (body.operation === 'forget') status.devices = status.devices.filter(device => device.address !== body.address)
if (body.operation === 'scan') status.discovering = true
if (body.operation === 'stop_scan') status.discovering = false
return route.fulfill({ json: status })
}
if (pathname === '/api/bluetooth/status') return route.fulfill({ json: status })
if (pathname === '/api/controllers/status') return route.fulfill({ json: controller })
if (pathname === '/api/bluetooth/uniden') {
const body = route.request().postDataJSON()
if (body.operation === 'configure') config = body.config
return route.fulfill({ json: { config, connected: config.enabled, alerts: [] } })
}
if (pathname === '/') return route.fulfill({ contentType: 'text/html', body: `<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="/vendor/bootstrap-icons/bootstrap-icons.min.css"><link rel="stylesheet" href="/css/galaxy.css"><link rel="stylesheet" href="/css/settings.css">
<main class="gx-content"><div id="app"></div></main><script type="module">
import {createApp} from '/vendor/vue/vue.esm-browser.js'; import {BluetoothPage} from '/js/bluetooth.js';
import {ControllersPage} from '/js/controllers.js';
window.app = createApp({ components:{BluetoothPage,ControllersPage}, data:()=>({path:'/bluetooth', mode:'local'}),
methods:{go(path){this.path=path}},
template:\`<ControllersPage v-if="path === '/bluetooth/controllers'" :mode="mode" :go="go" :unauthorized="()=>{}" />
<BluetoothPage v-else ref="bluetooth" :key="path" :mode="mode" :uniden-settings="path === '/bluetooth/uniden'" :go="go" :unauthorized="()=>{}" />\` }).mount('#app');</script>` })
return route.fulfill({ body: readFileSync(path.join(web, pathname)),
contentType: pathname.endsWith('.js') ? 'text/javascript' : pathname.endsWith('.css') ? 'text/css' : 'application/octet-stream' })
})
await page.goto('http://bluetooth.test/')
await page.getByRole('button', { name: 'Add a device', exact: true }).waitFor()
assert.equal(requests.includes('/api/controllers/status'), false)
assert.equal(requests.includes('/api/bluetooth/uniden'), false)
assert.equal(await page.getByRole('button', { name: 'Pair phone', exact: true }).count(), 0)
assert.equal(await page.getByRole('button', { name: 'Learn Button' }).count(), 0)
assert.equal(await page.getByText(detector.address, { exact: true }).isVisible(), false)
for (const theme of ['dark', 'light']) {
await page.locator('html').evaluate((el, theme) => el.dataset.theme = theme, theme)
for (const width of [390, 1280]) {
await page.setViewportSize({ width, height: 844 })
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true)
await page.screenshot({ path: `/tmp/bluetooth-${theme}-${width}.png`, fullPage: true })
}
}
await page.getByRole('button', { name: 'Add a device', exact: true }).click()
await page.getByRole('button', { name: 'Pair phone', exact: true }).waitFor()
await page.getByRole('button', { name: 'Search', exact: true }).click()
await page.getByRole('button', { name: 'Stop search', exact: true }).waitFor()
await page.getByRole('button', { name: 'Done', exact: true }).click()
await page.getByRole('button', { name: 'Add a device', exact: true }).waitFor()
assert.deepEqual(actions.map(action => action.operation), ['scan', 'stop_scan'])
await page.getByRole('button', { name: /^StarPort/ }).click()
assert.equal(await page.evaluate(() => window.app.path), '/starport')
assert.equal(actions.length, 2)
await page.evaluate(() => window.app.go('/bluetooth'))
await page.getByRole('button', { name: /^Uniden/ }).click()
await page.getByLabel('Uniden detector').selectOption(detector.address)
await page.getByRole('button', { name: 'Use this detector' }).click()
await page.getByRole('switch', { name: 'Automatically mute matching frequencies' }).waitFor()
assert.equal(await page.getByRole('button', { name: 'Pair phone' }).count(), 0)
assert.equal(await page.getByRole('button', { name: 'Search', exact: true }).count(), 0)
await page.evaluate(() => window.app.go('/bluetooth'))
await page.getByRole('button', { name: /^Controllers/ }).click()
await page.getByRole('heading', { name: 'Controllers', exact: true }).waitFor()
await page.getByRole('link', { name: 'pair in Bluetooth', exact: true }).waitFor()
assert.equal(await page.getByRole('button', { name: 'Pair phone' }).count(), 0)
assert.equal(await page.getByRole('button', { name: 'Search', exact: true }).count(), 0)
await page.evaluate(() => window.app.go('/bluetooth'))
await page.getByRole('button', { name: 'Add a device', exact: true }).waitFor()
const detectorRow = page.locator('.gx-bluetooth__device').filter({ hasText: 'Uniden R8' })
assert.equal(await detectorRow.locator('summary').count(), 0)
await detectorRow.getByRole('button', { name: 'Disconnect', exact: true }).click()
await detectorRow.getByRole('button', { name: 'Connect', exact: true }).click()
await detectorRow.getByRole('button', { name: 'Disconnect', exact: true }).waitFor()
const remoteRow = page.locator('.gx-bluetooth__device').filter({ hasText: 'Steering remote' })
await remoteRow.getByRole('button', { name: 'Forget', exact: true }).click()
const dialog = page.getByRole('alertdialog')
await dialog.getByRole('button', { name: 'Cancel', exact: true }).click()
assert.equal(actions.some(action => action.operation === 'forget'), false)
await remoteRow.getByRole('button', { name: 'Forget', exact: true }).click()
await dialog.getByRole('button', { name: 'Forget', exact: true }).click()
await dialog.getByRole('button', { name: 'Done', exact: true }).click()
assert.equal(await remoteRow.count(), 0)
assert.deepEqual(actions.slice(-3), [
{ operation: 'disconnect', address: detector.address },
{ operation: 'connect', address: detector.address },
{ operation: 'forget', address: '11:22:33:44:55:66' },
])
status.parked = false
await page.evaluate(() => window.app.$refs.bluetooth.refresh())
assert.equal(await page.getByRole('button', { name: 'Add a device', exact: true }).isDisabled(), true)
assert.equal(await detectorRow.getByRole('button', { name: 'Disconnect', exact: true }).isDisabled(), true)
assert.equal(await detectorRow.getByRole('button', { name: 'Forget', exact: true }).isDisabled(), true)
assert.deepEqual(errors, [])
console.log('Bluetooth tabs, shared pairing, device rows, StarPort link, Uniden selection and standalone controllers passed')
} finally { await browser.close() }
})().catch(error => { console.error(error); process.exitCode = 1 })
@@ -86,13 +86,10 @@ const { resolve } = require('node:path')
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false, 'Android Auto logs fit a phone viewport')
const phoneCards = await page.locator('.gx-starport-log').evaluateAll(cards => cards.map(card => {
const row = card.getBoundingClientRect(), body = card.querySelector('.gx-starport-log__body').getBoundingClientRect()
const download = card.querySelector('.gx-starport-log__download').getBoundingClientRect()
return { leftInset: body.left - row.left, rightInset: row.right - download.right, width: download.width, height: download.height }
return { leftInset: body.left - row.left }
}))
assert.ok(phoneCards.every(card => card.leftInset >= 11 && card.rightInset >= 11), 'log text and downloads are padded inside cards')
assert.ok(phoneCards.every(card => card.width === 44 && card.height === 44), 'individual downloads remain compact touch targets')
assert.deepEqual(await page.locator('.gx-starport-log__download').evaluateAll(links => links.map(link => link.getAttribute('download'))),
['session-000003.jsonl', 'session-000002.jsonl', 'car_ui.log'])
assert.ok(phoneCards.every(card => card.leftInset >= 11), 'log text is padded inside cards')
assert.equal(await page.locator('.gx-starport-logs a[download]').count(), 0, 'StarPort logs are sent, not downloaded')
await page.setViewportSize({ width: 1280, height: 900 })
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))))
const desktop = await page.locator('.gx-starport-logs').evaluate(section => {
@@ -0,0 +1,88 @@
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright')
const { readFileSync } = require('node:fs')
const path = require('node:path')
const assert = require('node:assert/strict')
const web = path.resolve(__dirname, '../../web')
let config = { enabled: false, address: '', model: 'R8', auto_mute: false, hide_filtered: false, hide_below_limit: false,
hide_q_ride: false, hide_mute_memory: false, frequency_rules: [], quiet_ride: false, quiet_margin: 0, quiet_bands: ['X', 'K'],
auto_learn: false, learn_bands: ['X', 'K'], border_bands: ['KA', 'LASER'], border_colors: { KA: 'coral', K: 'amber', LASER: 'coral' },
border_edge: { line: true, dashes: true, glow: false, veil: false, chevrons: true }, border_muted_percent: 50,
timed_mute: false, timed_mute_seconds: 5, timed_mute_strength: 6, timed_mute_bands: ['X', 'K', 'KA'],
timed_mute_settings: { X: { seconds: 5, strength: 6 }, K: { seconds: 5, strength: 6 }, KA: { seconds: 5, strength: 6 } } }
let connection = null
;(async () => {
const browser = await chromium.launch({ headless: true,
...(process.env.PLAYWRIGHT_EXECUTABLE_PATH ? { executablePath: process.env.PLAYWRIGHT_EXECUTABLE_PATH } : {}) })
try {
const page = await browser.newPage({ viewport: { width: 390, height: 844 } })
const errors = []
page.on('pageerror', error => errors.push(error.message))
await page.route('http://uniden.test/**', async route => {
const pathname = new URL(route.request().url()).pathname
if (pathname === '/api/bluetooth/uniden') {
const body = route.request().postDataJSON()
if (body.operation === 'configure') config = body.config
return route.fulfill({ json: { config, connected: !!config.enabled, alerts: [], locks: [], candidates: [], learning: [], metric: false, ...(connection || {}) } })
}
if (pathname === '/') return route.fulfill({ contentType: 'text/html', body: `<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="/css/galaxy.css"><link rel="stylesheet" href="/css/settings.css">
<main class="gx-content"><div id="app"></div></main><script type="module">
import {createApp} from '/vendor/vue/vue.esm-browser.js'; import {UnidenPanel} from '/js/uniden.js';
window.panel = createApp({components:{UnidenPanel}, data:()=>({settings:false, parked:true,
devices:[{name:'R8W@12',address:'AA:BB:CC:DD:EE:FF',paired:true}]}),
template:'<UnidenPanel ref="panel" :settings="settings" :devices="devices" :parked="parked" />'}).mount('#app');</script>` })
return route.fulfill({ body: readFileSync(path.join(web, pathname)),
contentType: pathname.endsWith('.js') ? 'text/javascript' : pathname.endsWith('.css') ? 'text/css' : 'application/octet-stream' })
})
await page.goto('http://uniden.test/')
await page.getByLabel('Uniden detector').selectOption('AA:BB:CC:DD:EE:FF')
await page.getByRole('button', { name: 'Use this detector' }).click()
await page.getByRole('link', { name: 'Uniden settings' }).waitFor()
assert.equal(config.enabled, true)
assert.equal(await page.getByRole('button', { name: 'Use this detector' }).count(), 0)
await page.evaluate(() => window.panel.settings = true)
await page.getByRole('switch', { name: 'Automatically mute matching frequencies' }).check()
await page.getByRole('switch', { name: 'Hide lockouts and frequency rules' }).check()
await page.getByRole('button', { name: 'Rules', exact: true }).click()
await page.getByRole('button', { name: 'Add frequency' }).click()
await page.getByLabel('Label', { exact: true }).fill('Head unit')
await page.getByRole('button', { name: 'Save changes' }).click()
await page.getByRole('status').filter({ hasText: /^Saved$/ }).waitFor()
assert.equal(config.frequency_rules[0].frequency, 34.313)
assert.equal(config.auto_mute, true)
await page.reload()
await page.getByRole('link', { name: 'Uniden settings' }).waitFor()
await page.evaluate(() => window.panel.settings = true)
await page.getByRole('button', { name: 'Rules', exact: true }).click()
assert.equal(await page.getByLabel('Label', { exact: true }).inputValue(), 'Head unit')
for (const theme of ['dark', 'light']) {
await page.locator('html').evaluate((el, theme) => el.dataset.theme = theme, theme)
for (const width of [390, 1280]) {
await page.setViewportSize({ width, height: 844 })
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true)
await page.screenshot({ path: `/tmp/uniden-${theme}-${width}.png`, fullPage: true })
}
}
await page.getByLabel('Frequency (GHz)').fill('34.315')
for (const error of ['org.bluez.Error.Failed', 'Waiting to reconnect detector']) {
connection = { connected: false, connection_state: 'reconnecting', error }
await page.evaluate(() => window.panel.$refs.panel.refresh())
await page.getByText('Reconnecting', { exact: true }).waitFor()
assert.equal(await page.getByText(error, { exact: true }).count(), 0)
assert.equal(await page.getByLabel('Frequency (GHz)').inputValue(), '34.315')
}
connection = null
await page.evaluate(() => window.panel.$refs.panel.refresh())
await page.getByText('Connected', { exact: true }).waitFor()
await page.getByRole('button', { name: 'Discard changes' }).click()
assert.equal(await page.getByLabel('Frequency (GHz)').inputValue(), '34.313')
await page.evaluate(() => window.panel.parked = false)
await page.getByRole('button', { name: 'Preferences', exact: true }).click()
assert.equal(await page.getByRole('switch', { name: 'Enable Uniden integration' }).isDisabled(), true)
await page.evaluate(() => window.panel.devices = [])
await page.getByRole('link', { name: 'Pair in Bluetooth' }).waitFor()
assert.equal(await page.getByRole('button', { name: 'Add frequency' }).count(), 0)
assert.deepEqual(errors, [])
console.log('Uniden setup, saved state, rules, reload, discard, paired/parked gating and responsive layouts passed')
} finally { await browser.close() }
})().catch(error => { console.error(error); process.exitCode = 1 })
@@ -0,0 +1,24 @@
"""Fake Discord webhook responses shared by the log send tests."""
import json
URL = "https://discord.example/api/webhooks/1/token"
SUMMARY = {"device_id": "0123456789abcdef", "car_fingerprint": "HONDA_CIVIC_2022", "head_unit": "Honda Display Audio",
"branch": "Dom", "commit": "abcdef1234567890"}
class Response:
def __init__(self, status_code=200, body=None):
self.status_code, self.body = status_code, body if body is not None else {"channel_id": "555"}
def json(self):
return self.body
class Poster:
def __init__(self, *responses):
self.responses, self.calls = list(responses), []
def __call__(self, url, data, files, timeout):
self.calls.append({"url": url, "payload": json.loads(data["payload_json"]), "files": files})
return self.responses.pop(0)
@@ -0,0 +1,111 @@
"""Bluetooth Log: the controller report sent to the developer's Discord forum and its routes."""
import http.client
import json
import tempfile
import threading
import unittest
from pathlib import Path
from unittest import mock
from openpilot.starpilot.galaxy import bluetooth_send
from openpilot.starpilot.galaxy.access import GalaxyAccessOwner
from openpilot.starpilot.galaxy.server import make_server
from openpilot.starpilot.galaxy.starport_send import SendBusy, SendRejected
from openpilot.starpilot.galaxy.tests.discord_fakes import SUMMARY, URL, Poster, Response
class BluetoothSendTest(unittest.TestCase):
def test_posts_the_report_as_a_bluetooth_log_thread(self):
post = Poster(Response(body={"channel_id": "777"}))
with tempfile.TemporaryDirectory() as directory:
self.assertIsNone(bluetooth_send.send(b"{}", "bluetooth-log.json", "Pad not found", SUMMARY, url=URL, post=post,
thread_dir=Path(directory), discord="starfan_42"))
call = post.calls[0]
content = call["payload"]["content"]
self.assertTrue(content.startswith("**Bluetooth Log from "))
self.assertIn("Car: HONDA_CIVIC_2022", content)
self.assertIn("Follow-up: Discord `starfan_42`", content)
self.assertNotIn("Head unit", content)
self.assertTrue(call["payload"]["thread_name"].startswith("Bluetooth Log HONDA_CIVIC_2022 "))
self.assertEqual(call["files"]["files[0]"], ("bluetooth-log.json", b"{}", "application/json"))
def test_report_is_json(self):
with mock.patch.object(bluetooth_send, "controller_input_report", return_value={"externalInputInterfaces": []}):
name, data = bluetooth_send.report(system_snapshot=False)
self.assertEqual((name, json.loads(data)), ("bluetooth-log.json", {"externalInputInterfaces": []}))
def test_unset_webhook_refuses_and_override_wins(self):
with tempfile.TemporaryDirectory() as directory:
override = Path(directory) / "bluetooth_webhook_url"
with mock.patch.object(bluetooth_send, "WEBHOOK_OVERRIDE_PATH", override), mock.patch.object(bluetooth_send, "_WEBHOOK_DATA", ""):
self.assertEqual(bluetooth_send.webhook_url(), "")
with self.assertRaisesRegex(SendRejected, "isn't set up"):
bluetooth_send.send(b"{}", "bluetooth-log.json", "hi", SUMMARY, post=Poster(), discord="starfan_42")
override.write_text(URL + "\n")
self.assertEqual(bluetooth_send.webhook_url(), URL)
class BluetoothSendHTTPTest(unittest.TestCase):
def setUp(self):
temporary = tempfile.TemporaryDirectory()
self.addCleanup(temporary.cleanup)
self.owner = GalaxyAccessOwner(Path(temporary.name) / "access")
self.job = mock.Mock()
self.job.status.return_value = {"state": "idle", "message": "", "available": True, "messageLimit": 60}
self.job.start.return_value = {"state": "sending", "message": "Collecting logs", "available": True, "messageLimit": 60}
self.starport = mock.Mock()
self.server = make_server(port=0, owner=self.owner, bluetooth_log_sender=self.job, starport_log_sender=self.starport)
self.thread = threading.Thread(target=self.server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True)
self.thread.start()
self.addCleanup(self.close_server)
self.assertTrue(self.owner.configure("password123", lambda: True))
def close_server(self):
self.server.shutdown()
self.thread.join(timeout=2)
self.server.server_close()
def request(self, path, *, method="GET", body=None, headers=None):
connection = http.client.HTTPConnection("127.0.0.1", self.server.server_port, timeout=2)
try:
origin = {"Origin": f"http://127.0.0.1:{self.server.server_port}"} if method == "POST" else {}
connection.request(method, path, body=body, headers={"Forwarded": "for=203.0.113.8", **origin, **(headers or {})})
response = connection.getresponse()
return response.status, response.read(), dict(response.getheaders())
finally:
connection.close()
def post(self, body, cookie=None):
headers = {"Content-Type": "application/json", **({"Cookie": cookie} if cookie else {})}
return self.request("/api/controllers/log/send", method="POST", body=json.dumps(body), headers=headers)
def login(self):
status, _, headers = self.request("/api/auth/login", method="POST", body=json.dumps({"password": "password123"}),
headers={"Content-Type": "application/json"})
self.assertEqual(status, 200)
return headers["Set-Cookie"].split(";", 1)[0]
def test_requires_a_session(self):
self.assertEqual(self.request("/api/controllers/log/send")[0], 401)
self.assertEqual(self.post({"message": "hi"})[0], 401)
self.job.start.assert_not_called()
def test_status_start_and_rejections(self):
cookie = self.login()
status, body, _ = self.request("/api/controllers/log/send", headers={"Cookie": cookie})
self.assertEqual((status, json.loads(body)["state"]), (200, "idle"))
status, body, _ = self.post({"message": "Pad not found", "discord": "starfan_42"}, cookie)
self.assertEqual((status, json.loads(body)["state"]), (202, "sending"))
self.job.start.assert_called_once_with("Pad not found", "starfan_42")
self.starport.start.assert_not_called()
self.assertEqual(self.post({"message": "hi"}, cookie)[0], 400)
self.assertEqual(self.post({"message": "hi", "discord": "starfan_42", "extra": 1}, cookie)[0], 400)
self.job.start.side_effect = SendRejected("Keep the message to 60 characters.")
self.assertEqual(self.post({"message": "x" * 61, "discord": "starfan_42"}, cookie)[0], 400)
self.job.start.side_effect = SendBusy("The Bluetooth Log is already being sent.")
self.assertEqual(self.post({"message": "hi", "discord": "starfan_42"}, cookie)[0], 409)
if __name__ == "__main__":
unittest.main()
@@ -17,7 +17,7 @@ function harness(fetcher, unauthorized = () => {}) {
test('first-load connection errors render without accessing missing adapter state', () => {
const render = compile(BluetoothPage.template, {decodeEntities: value => value});
const vm = {...BluetoothPage.data(), mode:'local', error:'Connection interrupted', unauthorized() {}};
const vm = {...BluetoothPage.data(), mode:'local', unidenSettings: false, go() {}, error:'Connection interrupted', unauthorized() {}};
for (const [key, getter] of Object.entries(BluetoothPage.computed)) {
Object.defineProperty(vm, key, {get: () => getter.call(vm)});
}
@@ -14,7 +14,9 @@ assert.equal(validControllersStatus({ ...status(), slots: status().slots.slice(1
assert.equal(validControllersStatus({ ...status(), options: [{ key: "x\n", label: "Bad", section: "Display" }] }), false)
assert.equal(validControllersStatus({ ...status(), lastPress: { deviceId: "hardware-1", code: 65551,
slot: null, executed: false, message: "Test press detected" } }), true)
assert.match(BluetoothPage.template, /<ControllersPage :mode="mode" :unauthorized="unauthorized"/)
assert.doesNotMatch(BluetoothPage.template, /<ControllersPage/)
assert.match(BluetoothPage.template, /<BluetoothTabs/)
assert.match(ControllersPage.template, /href="#\/bluetooth"/)
assert.match(ControllersPage.template, /Test buttons \(20s\)/)
assert.match(ControllersPage.template, /Press a button for/)
assert.match(ControllersPage.template, /class="gx-switch"/)
@@ -73,6 +73,20 @@ assert.equal(offroadView(completed).evidenceDrives, null, 'Older reports must no
assert.equal(tunerStatus(completed, true, true).title, 'Completed drive analyzed', 'Parked status must not mask completed analysis')
assert.match(tunerStatus(completed, true, true).description, /left your tune unchanged/)
assert.equal(completed.current.application.applied, false)
const oscillation = structuredClone(completed)
const observedPoints = Array.from({ length: 61 }, (_, i) => [1e9 + i * 2e8, .08 * Math.sin(i / 4), .08 * Math.sin((i - 2) / 4)])
const oscillationResponse = {
version: 1, domain: 'lateral_acceleration', samples: 1200, windows: 6, error_rms: .02, route: 'declared-drive', segment: 18,
source_start_ns: observedPoints[0][0], source_end_ns: observedPoints.at(-1)[0], points: observedPoints,
sampling: 'input_ordered_original_endpoints_no_interpolation', observation: 'followed_repeated_steering_request',
}
oscillation.current.details['Recorded steering response'] = oscillationResponse
assert(validTrainingResults(oscillation))
assert.equal(offroadView(oscillation).observed.followedRepeatedRequest, true)
assert.equal(offroadView(oscillation).observed.points.at(-1).at, 12000)
assert.equal(offroadView(oscillation).saved, false)
delete oscillationResponse.observation
assert.equal(offroadView(oscillation).observed.followedRepeatedRequest, false)
const ignitionWait = { ...report(), preference: { version: 1, valid: true, enabled: true, parked: true,
vehicle: 'TOYOTA_RAV4_PRIME', controller: 'torque' } }
ignitionWait.current.reason = 'waiting_for_ignition_off'
@@ -1,5 +1,5 @@
import assert from "node:assert/strict"
import { StarPortLogsFeed, BUNDLE_URL, fileUrl, outcomeLabel } from "../web/js/starport-logs.js"
import { StarPortLogsFeed, outcomeLabel } from "../web/js/starport-logs.js"
const flush = async () => { for (let i = 0; i < 8; i++) await Promise.resolve() }
function fixture() {
@@ -14,9 +14,6 @@ function fixture() {
return { feed, requests, states, reply, get unauthorized() { return unauthorized } }
}
assert.equal(BUNDLE_URL, "./api/starport/logs/bundle")
assert.equal(fileUrl("session-000002-20261005-094551.jsonl"), "./api/starport/logs/file/session-000002-20261005-094551.jsonl")
assert.equal(fileUrl("a b/c"), "./api/starport/logs/file/a%20b%2Fc")
assert.equal(outcomeLabel("failed: RFCOMM: timed out"), "Failed: RFCOMM: timed out")
assert.equal(outcomeLabel(""), "Unknown")
@@ -1,4 +1,4 @@
"""Android Auto logs in Logs & Diagnostics: the read-only reader and its authenticated download routes."""
"""Android Auto logs in Logs & Diagnostics: the read-only reader and its authenticated list route."""
import http.client
import io
@@ -11,9 +11,8 @@ from unittest import mock
import zipfile
from openpilot.starpilot.galaxy.access import GalaxyAccessOwner
from openpilot.starpilot.galaxy.starport_logs import StarPortLogs, LogMissing
from openpilot.starpilot.galaxy.starport_logs import StarPortLogs
from openpilot.starpilot.galaxy.server import make_server
from openpilot.starpilot.system.starport import system_snapshot
SESSION = "\n".join(json.dumps(event) for event in (
{"t": "2026-10-05T16:45:51.000+00:00", "event": "session_start", "receiver": "Honda CIVIC", "trigger": "auto"},
@@ -51,14 +50,8 @@ class StarPortLogsReaderTest(unittest.TestCase):
self.assertEqual(session["trigger"], "auto")
self.assertEqual([item["name"] for item in listing["others"]], ["car_ui.log"])
def test_serves_only_listed_logs(self):
self.assertEqual(self.reader.file("car_ui.log"), ("car_ui.log", b"car view pipeline: nv12, async readback\n"))
for name in ("notes.txt", "../config.json", "missing.jsonl", ""):
with self.assertRaises(LogMissing):
self.reader.file(name)
def test_symlinked_logs_are_not_listed(self):
(self.logs / "render_profile.txt").symlink_to(self.config)
with self.assertRaises(LogMissing):
self.reader.file("render_profile.txt")
self.assertNotIn("render_profile.txt", [item["name"] for item in self.reader.list()["others"]])
def test_bundle_is_a_zip_without_bluetooth_addresses(self):
@@ -98,9 +91,7 @@ class StarPortLogsHTTPTest(unittest.TestCase):
self.server.server_close()
def request(self, path, *, method="GET", body=None, headers=None):
# Bundles include the real bounded system report; allow cleanup and ZIP/HTTP delivery.
timeout = system_snapshot.DEADLINE_SECONDS + 3 if path == "/api/starport/logs/bundle" else 2
connection = http.client.HTTPConnection("127.0.0.1", self.server.server_port, timeout=timeout)
connection = http.client.HTTPConnection("127.0.0.1", self.server.server_port, timeout=2)
try:
connection.request(method, path, body=body, headers={"Forwarded": "for=203.0.113.8", **(headers or {})})
response = connection.getresponse()
@@ -116,14 +107,11 @@ class StarPortLogsHTTPTest(unittest.TestCase):
def test_requires_a_session_before_reading_anything(self):
self.assertTrue(self.owner.configure("password123", lambda: True))
with mock.patch.object(self.reader, "list", wraps=self.reader.list) as listing, \
mock.patch.object(self.reader, "bundle", wraps=self.reader.bundle) as bundle:
for path in ("/api/starport/logs", "/api/starport/logs/bundle", "/api/starport/logs/file/car_ui.log"):
self.assertEqual(self.request(path)[0], 401)
with mock.patch.object(self.reader, "list", wraps=self.reader.list) as listing:
self.assertEqual(self.request("/api/starport/logs")[0], 401)
listing.assert_not_called()
bundle.assert_not_called()
def test_list_file_and_bundle_downloads(self):
def test_list(self):
self.assertTrue(self.owner.configure("password123", lambda: True))
cookie = {"Cookie": self.login()}
status, body, headers = self.request("/api/starport/logs", headers=cookie)
@@ -131,24 +119,13 @@ class StarPortLogsHTTPTest(unittest.TestCase):
self.assertEqual(headers["Cache-Control"], "no-store")
self.assertEqual(len(json.loads(body)["sessions"]), 2)
status, body, headers = self.request("/api/starport/logs/file/session-000001-20261004-221339.jsonl", headers=cookie)
self.assertEqual(status, 200)
self.assertEqual(headers["Content-Disposition"], 'attachment; filename="session-000001-20261004-221339.jsonl"')
self.assertEqual(body.decode(), SESSION)
status, body, headers = self.request("/api/starport/logs/bundle", headers=cookie)
self.assertEqual(status, 200)
self.assertEqual(headers["Content-Type"], "application/zip")
self.assertRegex(headers["Content-Disposition"], r'^attachment; filename="starpilot-starport-logs-\d{8}-\d{6}\.zip"$')
with zipfile.ZipFile(io.BytesIO(body)) as archive:
self.assertIn("REPORT.txt", archive.namelist())
def test_unknown_and_invalid_names(self):
def test_logs_cannot_be_downloaded(self):
self.assertTrue(self.owner.configure("password123", lambda: True))
cookie = {"Cookie": self.login()}
self.assertEqual(self.request("/api/starport/logs/file/notes.txt", headers=cookie)[0], 404)
self.assertEqual(self.request("/api/starport/logs/file/..%2Fconfig.json", headers=cookie)[0], 400)
self.assertEqual(self.request("/api/starport/logs/other", headers=cookie)[0], 404)
with mock.patch.object(self.reader, "bundle") as bundle:
for path in ("/api/starport/logs/bundle", "/api/starport/logs/file/car_ui.log"):
self.assertEqual(self.request(path, headers=cookie)[0], 404)
bundle.assert_not_called()
if __name__ == "__main__":
@@ -1,5 +1,5 @@
import assert from "node:assert/strict"
import { StarPortLogSend, SEND_URL, MESSAGE_LIMIT } from "../web/js/starport-logs.js"
import { StarPortLogSend, SEND_URL, BLUETOOTH_SEND_URL, MESSAGE_LIMIT } from "../web/js/starport-logs.js"
const flush = async () => { for (let i = 0; i < 8; i++) await Promise.resolve() }
function fixture() {
@@ -24,10 +24,10 @@ normal.client.start()
assert.equal(normal.requests[0].url, SEND_URL)
await normal.reply(0, { state: "idle", message: "", available: true })
assert.equal(normal.states.at(-1).state, "idle")
const sending = normal.client.send(" Black screen ")
const sending = normal.client.send(" Black screen ", "starfan_42")
assert.equal(normal.states.at(-1).state, "sending")
assert.equal(normal.requests[1].options.method, "POST")
assert.deepEqual(JSON.parse(normal.requests[1].options.body), { message: "Black screen" })
assert.deepEqual(JSON.parse(normal.requests[1].options.body), { message: "Black screen", discord: "starfan_42" })
await normal.reply(1, { state: "sending", message: "Collecting logs" }, 202)
assert.equal(await sending, true)
assert.equal(normal.timers.length, 1)
@@ -40,13 +40,16 @@ assert.equal(normal.timers.length, 1)
const limited = fixture()
limited.client.start()
await limited.reply(0, { state: "idle" })
assert.equal(await limited.client.send("x".repeat(61)), false)
assert.equal(await limited.client.send("x".repeat(61), "starfan_42"), false)
assert.equal(limited.requests.length, 1)
assert.match(limited.states.at(-1).error, /60 characters/)
assert.equal(await limited.client.send(" "), false)
assert.equal(await limited.client.send(" ", "starfan_42"), false)
assert.equal(limited.requests.length, 1)
assert.match(limited.states.at(-1).error, /short note/)
const busy = limited.client.send("hi")
assert.equal(await limited.client.send("hi", " @ "), false)
assert.equal(limited.requests.length, 1)
assert.match(limited.states.at(-1).error, /Discord username/)
const busy = limited.client.send("hi", "starfan_42")
await limited.reply(1, { error: "StarPort logs are already being sent." }, 409)
assert.equal(await busy, false)
assert.equal(limited.states.at(-1).error, "StarPort logs are already being sent.")
@@ -56,7 +59,7 @@ const signedOut = fixture()
signedOut.client.start()
await signedOut.reply(0, {}, 401)
assert.equal(signedOut.unauthorized, 1)
assert.equal(await signedOut.client.send("hi"), false)
assert.equal(await signedOut.client.send("hi", "starfan_42"), false)
// Sending unavailable on this build hides the card.
const unset = fixture()
@@ -88,7 +91,7 @@ assert.ok(interrupted.requests.every(({ options }) => options.method !== "POST")
// An older status read cannot replace a send's newer status, even across navigation.
const stale = fixture()
stale.client.start()
const pendingSend = stale.client.send("hello")
const pendingSend = stale.client.send("hello", "starfan_42")
await stale.reply(1, { state: "sending" }, 202)
assert.equal(await pendingSend, true)
await stale.reply(0, { state: "idle" })
@@ -100,7 +103,7 @@ assert.equal(stale.unauthorized, 0)
await stale.reply(3, { state: "sent" })
assert.equal(stale.states.at(-1).state, "sent")
// A Discord username for a follow-up rides along only when given.
// The Discord username is sent as typed; the device strips the @.
{
const followUp = fixture()
followUp.client.start()
@@ -108,4 +111,47 @@ assert.equal(stale.states.at(-1).state, "sent")
followUp.client.send("No video", " @star.fan_42 ")
assert.deepEqual(JSON.parse(followUp.requests[1].options.body), { message: "No video", discord: "@star.fan_42" })
}
// The Bluetooth Log uses the same client with its own route and wording.
{
const requests = [], states = []
const client = new StarPortLogSend({ url: BLUETOOTH_SEND_URL, unavailable: "Sending the Bluetooth Log is unavailable",
publish: (state) => states.push(state), fetcher: (url) => { requests.push(url); return Promise.reject(new TypeError("offline")) },
schedule: () => 1, cancel: () => {} })
client.start()
await flush()
assert.equal(requests[0], "./api/controllers/log/send")
assert.equal(states.at(-1).error, "offline")
const failing = new StarPortLogSend({ url: BLUETOOTH_SEND_URL, unavailable: "Sending the Bluetooth Log is unavailable",
publish: (state) => states.push(state), fetcher: () => Promise.resolve({ ok: false, status: 503, json: async () => ({}) }),
schedule: () => 1, cancel: () => {} })
failing.start()
await flush()
assert.equal(states.at(-1).error, "Sending the Bluetooth Log is unavailable")
}
// Clicking Send with an empty field outlines it like the theme maker's save prompt, without sending.
{
const { LogSendCard } = await import("../web/js/starport-logs.js")
const sent = [], focused = []
const card = { ...LogSendCard.data(), feed: { send: async (...args) => { sent.push(args); return true } },
$refs: { note: { focus: () => focused.push("note") }, discord: { focus: () => focused.push("discord") } } }
const submit = LogSendCard.methods.submit.bind(card)
await submit()
assert.deepEqual(card.missing, ["note", "discord"])
assert.deepEqual(focused, ["note"])
card.note = "No pad"
LogSendCard.watch.note.call(card, card.note)
assert.deepEqual(card.missing, ["discord"])
card.discord = "@"
await submit()
assert.deepEqual(card.missing, ["discord"])
assert.equal(sent.length, 0)
card.discord = "starfan_42"
await submit()
assert.deepEqual(card.missing, [])
assert.deepEqual(sent, [["No pad", "starfan_42"]])
assert.equal(card.note, "")
assert.match(LogSendCard.template, /gx-field--required/)
}
console.log("StarPort log send: Discord follow-up passed")
@@ -16,26 +16,7 @@ from openpilot.starpilot.galaxy.server import make_server
from openpilot.starpilot.galaxy.starport_send import (DISCORD_FILE_LIMIT, MESSAGE_LIMIT, SendBusy, SendRejected, StarPortLogSender,
clean_discord, clean_message, send, thread_title)
URL = "https://discord.example/api/webhooks/1/token"
SUMMARY = {"device_id": "0123456789abcdef", "car_fingerprint": "HONDA_CIVIC_2022", "head_unit": "Honda Display Audio",
"branch": "Dom", "commit": "abcdef1234567890"}
class Response:
def __init__(self, status_code=200, body=None):
self.status_code, self.body = status_code, body if body is not None else {"channel_id": "555"}
def json(self):
return self.body
class Poster:
def __init__(self, *responses):
self.responses, self.calls = list(responses), []
def __call__(self, url, data, files, timeout):
self.calls.append({"url": url, "payload": json.loads(data["payload_json"]), "files": files})
return self.responses.pop(0)
from openpilot.starpilot.galaxy.tests.discord_fakes import SUMMARY, URL, Poster, Response
def query(call):
@@ -49,7 +30,7 @@ class SendTest(unittest.TestCase):
self.threads = Path(temporary.name)
def send(self, post, note="Dropped at the light", data=b"zip"):
return send(data, "logs.zip", note, SUMMARY, url=URL, post=post, thread_dir=self.threads)
return send(data, "logs.zip", note, SUMMARY, url=URL, post=post, thread_dir=self.threads, discord="starfan_42")
def test_first_send_opens_a_device_thread_and_later_sends_reuse_it(self):
first = Poster(Response(body={"channel_id": "555"}))
@@ -91,7 +72,7 @@ class SendTest(unittest.TestCase):
self.send(poster, data=b"x" * (DISCORD_FILE_LIMIT + 1))
self.assertEqual(poster.calls, [])
with self.assertRaisesRegex(SendRejected, "isn't set up"):
send(b"zip", "logs.zip", "", SUMMARY, url="", post=poster, thread_dir=self.threads)
send(b"zip", "logs.zip", "", SUMMARY, url="", post=poster, thread_dir=self.threads, discord="starfan_42")
def test_message_is_limited_and_single_line(self):
self.assertEqual(MESSAGE_LIMIT, 60)
@@ -133,7 +114,7 @@ class SenderJobTest(unittest.TestCase):
job = StarPortLogSender(bundle, sender=sender, summary=lambda: SUMMARY, url=lambda: URL, official=lambda: True)
try:
self.assertEqual(job.start("hello")["state"], "sending")
self.assertEqual(job.start("hello", "starfan_42")["state"], "sending")
self.assertTrue(sending.wait(2))
self.assertEqual(job.status()["state"], "sending")
self.assertEqual(sent, [])
@@ -146,7 +127,7 @@ class SenderJobTest(unittest.TestCase):
self.assertEqual(status["state"], "sent")
self.assertIn("snapshot was left out", status["message"])
self.assertEqual(bundles, [True, False])
self.assertEqual(sent, [((b"x" * 10, "logs.zip", "hello", SUMMARY), {"discord": ""})])
self.assertEqual(sent, [((b"x" * 10, "logs.zip", "hello", SUMMARY), {"discord": "starfan_42"})])
def test_one_send_at_a_time_and_failures_are_reported(self):
release = threading.Event()
@@ -156,9 +137,9 @@ class SenderJobTest(unittest.TestCase):
raise SendRejected("Discord refused the logs (HTTP 500).")
job = StarPortLogSender(lambda **_: ("logs.zip", b"zip"), sender=sender, summary=lambda: SUMMARY, url=lambda: URL, official=lambda: True)
job.start("first")
job.start("first", "starfan_42")
with self.assertRaises(SendBusy):
job.start("again")
job.start("again", "starfan_42")
release.set()
self.assertEqual(self.wait(job), {"state": "failed", "message": "Discord refused the logs (HTTP 500).", "available": True,
"fork": False, "messageLimit": 60})
@@ -216,26 +197,25 @@ class SendHTTPTest(unittest.TestCase):
status, body, _ = self.request("/api/starport/logs/send", headers={"Cookie": cookie})
self.assertEqual((status, json.loads(body)["state"]), (200, "idle"))
status, body, _ = self.post({"message": "Black screen after unlock"}, cookie)
status, body, _ = self.post({"message": "Black screen after unlock", "discord": "starfan_42"}, cookie)
self.assertEqual((status, json.loads(body)["state"]), (202, "sending"))
self.job.start.assert_called_once_with("Black screen after unlock", "")
self.assertEqual(self.post({"message": "hi", "discord": "starfan_42"}, cookie)[0], 202)
self.job.start.assert_called_with("hi", "starfan_42")
self.job.start.assert_called_once_with("Black screen after unlock", "starfan_42")
self.assertEqual(self.post({"message": "hi", "extra": 1}, cookie)[0], 400)
self.assertEqual(self.post({"message": "hi"}, cookie)[0], 400)
self.assertEqual(self.post({"message": "hi", "discord": "starfan_42", "extra": 1}, cookie)[0], 400)
self.assertEqual(self.job.start.call_count, 1)
self.job.start.side_effect = SendRejected("Keep the message to 60 characters.")
self.assertEqual(self.post({"message": "x" * 61}, cookie)[0], 400)
self.assertEqual(self.post({"message": "x" * 61, "discord": "starfan_42"}, cookie)[0], 400)
self.job.start.side_effect = SendBusy("StarPort logs are already being sent.")
self.assertEqual(self.post({"message": "hi"}, cookie)[0], 409)
self.assertEqual(self.post({"message": "hi", "discord": "starfan_42"}, cookie)[0], 409)
class DiscordFollowUpTest(unittest.TestCase):
def test_a_handle_is_optional_and_checked(self):
self.assertEqual(clean_discord(""), "")
def test_a_handle_is_required_and_checked(self):
self.assertEqual(clean_discord(" @star.fan_42 "), "star.fan_42")
self.assertEqual(clean_discord("OldName#1234"), "OldName#1234")
for bad in ("x", "has space", "<@123>", "a" * 33, 5):
for bad in ("", " ", "@", "x", "has space", "<@123>", "a" * 33, 5):
with self.assertRaises(SendRejected):
clean_discord(bad)
@@ -246,14 +226,12 @@ class DiscordFollowUpTest(unittest.TestCase):
payload = post.calls[0]["payload"]
self.assertIn("Follow-up: Discord `star.fan_42`", payload["content"])
self.assertEqual(payload["allowed_mentions"], {"parse": []})
post = Poster(Response())
send(b"zip", "logs.zip", "", SUMMARY, url=URL, post=post, thread_dir=Path(directory))
self.assertIn("Follow-up: not requested", post.calls[0]["payload"]["content"])
def test_a_bad_handle_is_refused_before_anything_is_sent(self):
def test_a_missing_or_bad_handle_is_refused_before_anything_is_sent(self):
job = StarPortLogSender(lambda **_: ("logs.zip", b"zip"), sender=mock.Mock(), summary=lambda: SUMMARY, url=lambda: URL, official=lambda: True)
with self.assertRaises(SendRejected):
job.start("hi", "not a handle")
for handle in ("not a handle", ""):
with self.assertRaises(SendRejected):
job.start("hi", handle)
self.assertIsNone(job._thread)
def test_a_failed_fork_check_is_raised_and_retried(self):
@@ -278,7 +256,7 @@ class DiscordFollowUpTest(unittest.TestCase):
official=lambda: False)
self.assertEqual(job.status()["fork"], True)
self.assertEqual(job.status()["available"], True)
job.start("hi")
job.start("hi", "starfan_42")
job._thread.join(2)
self.assertEqual(job.status()["state"], "sent")
sender.assert_called_once()
@@ -0,0 +1,208 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { compile } from '../web/vendor/vue/vue.esm-browser.js'
import { UnidenPanel, SWATCHES, detectorConfig, savedConfig } from '../web/js/uniden.js'
test('detector panel compiles and only offers bonded R4/R8 names', () => {
assert.equal(typeof compile(UnidenPanel.template, { decodeEntities: value => value }), 'function')
const devices = [{ name: 'R8W@12', paired: true }, { name: 'Uniden R4', paired: true },
{ name: 'R8', paired: false }, { name: 'Phone', paired: true }, { name: 'R7', paired: true }]
assert.deepEqual(UnidenPanel.computed.detectors.call({ devices }), devices.slice(0, 2))
})
test('setup cannot save onroad or while another save is pending', async () => {
const state = { parked: false, busy: false, request: () => assert.fail('must not send') }
await UnidenPanel.methods.save.call(state)
state.parked = true; state.busy = true
await UnidenPanel.methods.save.call(state)
})
test('theme maker edits Uniden display settings through draft history', async () => {
const { OnroadLayoutPage } = await import('../web/js/onroad-layout.js')
const { ONROAD_LAYOUT_TEMPLATE } = await import('../web/js/onroad-layout-template.js')
assert.equal(typeof compile(ONROAD_LAYOUT_TEMPLATE, { decodeEntities: value => value }), 'function')
const position = { transparency: 8, hide_when_no_alert: true, scale: 100 }
const history = []
const context = { editable: true, selectedWidget: { kind: 'uniden_alerts' }, selectedPosition: position,
state: { profile: 'large', selected: 'uniden_alerts', draft: { position } },
finishColorEdit() {}, recordChange(before) { history.push(before) } }
const edit = (field, value) => OnroadLayoutPage.methods.setUnidenDisplay.call(context, field, value)
edit('transparency', 65)
edit('hide_when_no_alert', false)
edit('hide_quiet_ride', true)
edit('hide_mute_memory', true)
edit('scale', 130)
assert.deepEqual(position, { transparency: 65, hide_when_no_alert: false, scale: 130 }, 'retired layout fields are not editable')
assert.equal(history[0].position.transparency, 8)
assert.equal(history[1].position.hide_when_no_alert, true)
edit('transparency', 101)
edit('scale', 151)
edit('scale', 49)
edit('hide_quiet_ride', 1)
context.editable = false
edit('hide_when_no_alert', true)
assert.equal(history.length, 3)
assert.ok(!UnidenPanel.template.includes('uniden-transparency'))
assert.ok(ONROAD_LAYOUT_TEMPLATE.includes(`:save-value="(index, value) => setUnidenDisplay('hide_when_no_alert'`))
for (const field of ['hide_quiet_ride', 'hide_mute_memory'])
assert.ok(!ONROAD_LAYOUT_TEMPLATE.includes(`setUnidenDisplay('${field}'`), 'which alerts show is a detector setting now')
for (const key of ['hide_filtered', 'hide_below_limit', 'hide_q_ride', 'hide_mute_memory'])
assert.ok(UnidenPanel.template.includes(`v-model="config.${key}"`), key)
assert.ok(ONROAD_LAYOUT_TEMPLATE.includes("setUnidenDisplay('scale'"))
})
test('saved setup only offers settings while matching a paired detector', () => {
const devices = [{ name: 'R8', address: 'AA:BB:CC:DD:EE:FF', paired: true }]
const state = { saved: { address: devices[0].address }, detectors: devices }
assert.equal(UnidenPanel.computed.ready.call(state), true)
state.detectors = []
assert.equal(UnidenPanel.computed.ready.call(state), false)
assert.equal(UnidenPanel.computed.dirty.call({ saved: { enabled: true }, config: { enabled: true } }), false)
assert.equal(UnidenPanel.computed.dirty.call({ saved: { enabled: true }, config: { enabled: false } }), true)
})
test('selecting a paired detector infers model and enables integration', () => {
const state = { selected: { name: 'Uniden R4W' }, config: { enabled: false, model: 'R8' } }
UnidenPanel.methods.selectDetector.call(state)
assert.deepEqual(state.config, { enabled: true, model: 'R4' })
})
test('reconnecting status stays stable and does not display transport errors', async () => {
const { detectorStatus } = await import('../web/js/uniden.js')
const failed = detectorStatus({ connected: false, connection_state: 'reconnecting', error: 'org.bluez.Error.Failed' })
const waiting = detectorStatus({ connected: false, connection_state: 'reconnecting', error: 'Waiting to reconnect detector' })
assert.deepEqual(failed, waiting)
assert.equal(failed.label, 'Reconnecting')
assert.equal(detectorStatus({ connected: true }).label, 'Connected')
assert.equal(detectorStatus({ connection_state: 'radio_off' }).label, 'Bluetooth off')
assert.equal(detectorStatus({ connection_state: 'detector_pairing_required' }).label, 'Check pairing')
})
test('rule summary explains exact matching and MHz tolerance in GHz', () => {
assert.equal(UnidenPanel.methods.ruleRange({ frequency: 34.313, tolerance_mhz: 0 }), 'Matches 34.313 GHz exactly')
assert.equal(UnidenPanel.methods.ruleRange({ frequency: 34.313, tolerance_mhz: 2 }), 'Matches 34.3110–34.3150 GHz')
})
test('one warning for every band: colors and on/off only, with a scenario preview beside the settings', () => {
assert.ok(!UnidenPanel.template.includes('border_styles'), 'no per-band style picker')
assert.deepEqual(Object.values(UnidenPanel.data().sections), ['Preferences', 'Colors', 'Rules', 'Lockouts'])
assert.equal(UnidenPanel.data().panel, 'alerts', 'opens on Preferences')
for (const hook of ['gx-layout__savebar', 'gx-layout__workspace', 'gx-layout__preview-card', 'aria-label="Preview scenario"', '<edge-preview'])
assert.ok(UnidenPanel.template.includes(hook), hook)
assert.deepEqual(Object.keys(SWATCHES), ['amber', 'coral', 'magenta', 'ice', 'lime', 'white', 'ultraviolet'])
const state = { config: { border_bands: ['KA', 'LASER'] } }
UnidenPanel.methods.toggleBand.call(state, 'border_bands', 'K')
UnidenPanel.methods.toggleBand.call(state, 'border_bands', 'KA')
assert.deepEqual(state.config.border_bands, ['LASER', 'K'])
})
test('saved lockouts make learning progress stand out', () => {
const { computed } = UnidenPanel
const learning = [{ id: 'a', band: 'K', frequency: 24.15, count: 2, need: 3, misses: 1 }, { id: 'b', band: 'KA', frequency: 34.7, count: 1, need: 5, misses: 0 }]
const panel = { saved: { auto_learn: false, learn_bands: [] }, config: { auto_learn: true, learn_bands: ['X', 'K'] }, learning }
panel.learningOn = computed.learningOn.call(panel)
assert.equal(panel.learningOn, true, 'follows the unsaved toggle')
const rows = computed.learningRows.call(panel)
assert.deepEqual(rows.map(r => [r.learnable, r.percent, r.left]), [[true, 67, 1], [false, 20, 4]])
assert.deepEqual(rows.map(r => r.stage), ['Locks out next pass', 'Just started'], 'a stage, not a pass count')
assert.equal(computed.learningTitle.call(panel), 'Learning 2 sources')
assert.equal(computed.learningTitle.call({ ...panel, learning: [] }), 'Learning: watching for repeat sources')
assert.equal(computed.learningTitle.call({ ...panel, learningOn: false }), 'Learning is off')
})
test('edge preview follows the device rules', async () => {
const { EdgePreview, EdgeMotion, chevronCount, edgeAlpha } = await import('../web/js/uniden-preview.js')
const { EDGE_PARTS } = await import('../web/js/uniden.js')
assert.equal(typeof compile(EdgePreview.template, { decodeEntities: value => value }), 'function')
assert.deepEqual([1, 2, 3, 6, 7, 8].map(chevronCount), [1, 1, 2, 3, 4, 4])
assert.equal(edgeAlpha({ glow: false }, 'K', 1), 0.85)
assert.equal(edgeAlpha({ glow: false }, 'LASER', 1), 1)
assert.ok(edgeAlpha({ glow: true }, 'K', 8) > edgeAlpha({ glow: true }, 'K', 1))
assert.deepEqual(Object.keys(EDGE_PARTS), ['line', 'dashes', 'glow', 'veil', 'chevrons'])
const motion = new EdgeMotion()
motion.update({ band: 'K', strength: 3 }, 10, false)
assert.equal(motion.pulses[0][1], 2)
motion.update({ band: 'K', strength: 4 }, 11, false)
assert.equal(motion.boost(11.1), 0)
motion.update({ band: 'K', strength: 5 }, 12, false)
assert.ok(motion.boost(12.15) > 0.9)
motion.update({ band: 'LASER', strength: 5 }, 13, false)
assert.equal(motion.pulses.at(-1)[1], 3)
motion.update(null, 14, false)
assert.equal(motion.fading(14.25)[1], 0.5)
assert.equal(UnidenPanel.data().swatches, SWATCHES, 'every band lists the same current colors')
for (const retired of ['purple', 'violet', 'yellow']) assert.ok(!(retired in SWATCHES), retired)
})
test('frequency rules keep a stable client id that is never saved', () => {
const rule = { enabled: true, label: 'Head unit', band: 'KA', frequency: 34.313, tolerance_mhz: 0 }
const first = detectorConfig({ frequency_rules: [rule, { ...rule, label: 'Dash cam' }] })
const [a, b] = first.frequency_rules.map(item => item.uid)
assert.ok(Number.isInteger(a) && a !== b)
const again = detectorConfig({ frequency_rules: [rule, { ...rule, label: 'Dash cam' }] }, first.frequency_rules)
assert.deepEqual(again.frequency_rules.map(item => item.uid), [a, b], 'a refresh keeps the rows')
assert.deepEqual(savedConfig(first).frequency_rules, [rule, { ...rule, label: 'Dash cam' }])
for (const key of ['transparency', 'hide_when_no_alert', 'border_styles', 'unmute_on_breakthrough']) assert.ok(!(key in savedConfig(first)), key)
const state = { config: { frequency_rules: [...first.frequency_rules] } }
UnidenPanel.methods.addRule.call(state)
assert.ok(!first.frequency_rules.some(item => item.uid === state.config.frequency_rules[2].uid))
assert.ok(UnidenPanel.template.includes(':key="rule.uid"'))
})
test('leaving with unsaved changes asks first, like the theme maker', async () => {
const { requestLeave, cancelLeave, discardAndLeave } = UnidenPanel.methods
const left = []
const panel = { dirty: false, busy: false, leaveAction: null, leaveModal: false, $nextTick() {}, cancelLeave, cancel() { this.dirty = false } }
requestLeave.call(panel, () => left.push('clean'))
assert.deepEqual(left, ['clean'])
panel.dirty = true
requestLeave.call(panel, () => left.push('dirty'), 'modal')
assert.deepEqual(left, ['clean']) && assert.equal(panel.leaveModal, true)
assert.equal(UnidenPanel.computed.leaveInline.call(panel), false, 'menu navigation shows the dialog')
discardAndLeave.call(panel)
assert.deepEqual(left, ['clean', 'dirty'])
assert.equal(panel.leaveAction, null)
const { PREVIEW_SCENARIOS, previewScenario } = await import('../web/js/uniden-preview.js')
assert.ok(Object.keys(PREVIEW_SCENARIOS).length >= 2 && previewScenario('laser').alert.band === 'LASER')
assert.equal(previewScenario('missing').script, true, 'unknown scenarios fall back to the drive-by')
})
test('picking a color shows that band in the preview', () => {
const { pickColor } = UnidenPanel.methods
const panel = { config: { border_colors: { K: 'amber', KA: 'coral', LASER: 'coral' } }, scenario: 'drive', replay: 0 }
pickColor.call(panel, 'LASER', 'white')
assert.equal(panel.config.border_colors.LASER, 'white')
assert.equal(panel.scenario, 'laser')
pickColor.call(panel, 'LASER', 'lime')
assert.deepEqual([panel.scenario, panel.replay], ['laser', 1], 'already showing laser: replay it')
pickColor.call(panel, 'KA', 'magenta')
assert.equal(panel.scenario, 'ka-strong')
panel.scenario = 'drive'
pickColor.call(panel, 'K', 'ice')
assert.deepEqual([panel.scenario, panel.replay], ['drive', 2], 'the drive-by is a K pass')
})
test('turning on Ka or laser learning asks first; X, K and turning off do not', () => {
const { requestLearnBand, confirmLearnBand, toggleBand } = UnidenPanel.methods
const panel = { config: { learn_bands: ['X', 'K'] }, confirmLearn: null, toggleBand }
requestLearnBand.call(panel, 'KA')
assert.deepEqual([panel.confirmLearn, panel.config.learn_bands], ['KA', ['X', 'K']], 'waits for the dialog')
confirmLearnBand.call(panel)
assert.deepEqual([panel.confirmLearn, panel.config.learn_bands], [null, ['X', 'K', 'KA']])
requestLearnBand.call(panel, 'LASER')
panel.confirmLearn = null // Keep it off
assert.ok(!panel.config.learn_bands.includes('LASER'))
requestLearnBand.call(panel, 'KA')
assert.ok(!panel.config.learn_bands.includes('KA') && panel.confirmLearn === null, 'turning off is immediate')
requestLearnBand.call(panel, 'X')
assert.ok(!panel.config.learn_bands.includes('X'))
})
test('timed mute migrates shared settings and keeps band edits independent', () => {
const config = detectorConfig({ timed_mute_seconds: 12, timed_mute_strength: 0, timed_mute_bands: ['K'] })
assert.deepEqual(config.timed_mute_settings, Object.fromEntries(['X', 'K', 'KA'].map(band => [band, { seconds: 12, strength: 0 }])))
config.timed_mute_settings.KA.seconds = 30
assert.equal(config.timed_mute_settings.K.seconds, 12)
assert.deepEqual(detectorConfig(config), config)
assert.deepEqual(config.timed_mute_bands, ['K'])
})
@@ -0,0 +1,76 @@
"""Real authenticated HTTP with only detector IO and configuration storage replaced."""
import time
import unittest
from types import SimpleNamespace
from typing import Any, cast
from unittest.mock import Mock, patch
from openpilot.starpilot.galaxy.tests import test_bluetooth_http as bluetooth_http
from openpilot.starpilot.uniden.service import DetectorService
from openpilot.starpilot.uniden.protocol import DEFAULT_CONFIG, alert_key, normalize_config, parse_alerts
ADDRESS = 'AA:BB:CC:DD:EE:FF'
CONFIG = {**DEFAULT_CONFIG, 'enabled': True, 'address': ADDRESS, 'model': 'R8'}
class UnidenHttpTest(unittest.TestCase):
def setUp(self):
self.aa = Mock()
self.aa_enabled = False
original = bluetooth_http.make_server
def server(**kwargs):
kwargs.update(starport_setup=SimpleNamespace(enabled=lambda: self.aa_enabled), starport_client=self.aa)
return original(**kwargs)
with patch.object(bluetooth_http, 'make_server', side_effect=server):
bluetooth_http.BluetoothHttpTest.setUp(cast(Any, self))
def stop(self):
bluetooth_http.BluetoothHttpTest.stop(cast(Any, self))
def request(self, path, payload=None, cookie=''):
return bluetooth_http.BluetoothHttpTest.request(cast(Any, self), path, payload, cookie)
def test_auth_configuration_and_onroad_mute(self):
payload = {'operation': 'status'}
assert self.request('/api/bluetooth/uniden', payload)[0] == 401
_, _, headers = self.request('/api/auth/login', {'password': 'password123'})
cookie = headers['Set-Cookie'].split(';', 1)[0]
params = Mock()
params.get.return_value = CONFIG
service = DetectorService(params, lambda: False)
state = {'connected': True, 'address': ADDRESS, 'model': 'R8', 'observed_at': time.monotonic(),
'alerts': parse_alerts(b'1,00,KA,3,0,33.785,R,1'), 'can_mute': True}
with patch('openpilot.starpilot.uniden.service.DetectorService', return_value=service), \
patch('openpilot.starpilot.uniden.transport.exchange', return_value=state) as exchange:
status, result, _ = self.request('/api/bluetooth/uniden', payload, cookie)
assert status == 200 and result['config'] == normalize_config(CONFIG)
assert self.request('/api/bluetooth/uniden', {'operation': 'configure', 'config': CONFIG}, cookie)[0] == 409
params.put.assert_not_called()
mute = {'operation': 'mute', 'address': ADDRESS, 'observed_at': state['observed_at'], 'alerts': alert_key(state['alerts'])}
assert self.request('/api/bluetooth/uniden', mute, cookie)[0] == 200
assert exchange.call_args.kwargs['mute'] == mute
assert self.request('/api/bluetooth/uniden', {'operation': 'write', 'command': 'arbitrary'}, cookie)[0] == 400
assert self.request('/api/bluetooth/uniden', {**mute, 'address': 'another'}, cookie)[0] == 409
def test_projection_delegates_and_uncertain_mute_is_never_replayed_locally(self):
self.aa_enabled = True
_, _, headers = self.request('/api/auth/login', {'password': 'password123'})
cookie = headers['Set-Cookie'].split(';', 1)[0]
params = Mock()
params.get.return_value = CONFIG
service = DetectorService(params, lambda: True)
self.aa.call.return_value = {'handled': True, 'detector': {'connected': True, 'alerts': []}}
with patch('openpilot.starpilot.uniden.service.DetectorService', return_value=service), \
patch('openpilot.starpilot.uniden.transport.exchange') as local:
status, result, _ = self.request('/api/bluetooth/uniden', {'operation': 'status'}, cookie)
assert status == 200 and result['connected']
assert self.aa.call.call_args.args == ('uniden',)
assert self.aa.call.call_args.kwargs['address'] == ADDRESS
assert self.aa.call.call_args.kwargs['auto_mute'] is False
assert self.aa.call.call_args.kwargs['frequency_rules'] == []
self.aa.call.side_effect = TimeoutError('Uncertain delivery')
mute = {'operation': 'mute', 'address': ADDRESS, 'observed_at': time.monotonic(), 'alerts': []}
assert self.request('/api/bluetooth/uniden', mute, cookie)[0] == 503
local.assert_not_called()
assert self.request('/api/bluetooth/uniden', {'operation': 'configure', 'config': {**CONFIG, 'enabled': False}}, cookie)[0] == 200
params.put.assert_called_once_with('UnidenConfig', normalize_config({**CONFIG, 'enabled': False}))
@@ -939,14 +939,11 @@ background: var(--glass-bg-hover);
.gx-crash-preview { margin-top: var(--sp-3); }
.gx-crash-preview__head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); overflow-wrap: anywhere; }
.gx-starport-logs { width: min(100%, 960px); margin-inline: auto; }
.gx-starport-logs__format { padding: 2px 7px; border-radius: var(--radius-full); background: rgba(255, 255, 255, .16); font-size: var(--fs-xs); letter-spacing: .04em; }
.gx-starport-log-list { display: grid; gap: var(--sp-3); }
.gx-starport-log { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: var(--sp-4); margin: 0; padding: var(--sp-4); cursor: default; }
.gx-starport-log__body { display: grid; gap: var(--sp-1); min-width: 0; }
.gx-starport-log__body strong { line-height: 1.35; overflow-wrap: anywhere; }
.gx-starport-log__body span { color: var(--text-muted); font-size: var(--fs-sm); line-height: 1.45; overflow-wrap: anywhere; }
.gx-starport-log__download { flex: none; width: var(--touch-target); height: var(--touch-target); border: 1px solid var(--glass-border); background: var(--primary-container); color: var(--on-primary-container); }
.gx-starport-log__download:hover { background: var(--primary); color: var(--on-primary); }
.gx-starport-logs__section-title { margin: var(--sp-6) 0 var(--sp-3); }
.gx-starport-send__fork { justify-content: center; text-align: center; margin-block: var(--sp-4); }
.gx-starport-send__fork .gx-alert__body { flex: 0 1 auto; }
@@ -1632,6 +1629,8 @@ progress { max-width: 100%; accent-color: var(--primary); }
.gx-driving .gx-row { flex-wrap: wrap; }
.gx-driving .gx-row > strong { flex: 1; min-width: 0; overflow-wrap: anywhere; }
.gx-bt-card > h3 { margin: 0 0 var(--sp-2); }
.gx-bluetooth__radio { padding-block: var(--sp-3); }
.gx-bluetooth__radio > .gx-row { min-height: var(--touch-target); padding-block: 0; }
.gx-bt-adapter__actions { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: var(--sp-2); }
.gx-bt-adapter__actions > .gx-btn { padding-inline: var(--sp-2); white-space: nowrap; }
.gx-row__desc.gx-bt-device__state { display: flex; align-items: center; gap: 6px; margin-top: 2px; }
+104 -1
View File
@@ -554,7 +554,7 @@ input[type="range"].gx-slider:active::-moz-range-thumb {
.gx-layout__color-values input[type="text"] { min-width: 0; width: 100%; font-family: ui-monospace, monospace; }
.gx-layout__color input[type="range"] { width: 100%; accent-color: var(--primary); min-height: 36px; }
.gx-layout__color > label { color: var(--on-surface-variant); }
.gx-layout__savebar.gx-layout__savebar--leave, .gx-card.gx-layout__leave-dialog { --leave-glow: 0 0 0 1px var(--primary-glow), 0 0 24px var(--primary-glow); border: 1px solid var(--primary); box-shadow: var(--leave-glow); }
.gx-layout__savebar.gx-layout__savebar--leave, .gx-card.gx-layout__leave-dialog, .gx-field.gx-field--required { --leave-glow: 0 0 0 1px var(--primary-glow), 0 0 24px var(--primary-glow); border: 1px solid var(--primary); box-shadow: var(--leave-glow); }
/* One workspace structure at every size; panels replace long stacked controls. */
.gx-layout { max-width: 1440px; margin-inline: auto; gap: 12px; }
.gx-layout__workspace { grid-template-columns: minmax(0, 1.4fr) minmax(320px, 1fr); gap: 16px; }
@@ -989,3 +989,106 @@ html.gx-maker-open, html.gx-maker-open body { touch-action: manipulation; }
.gx-maintenance > summary::-webkit-details-marker { display: none; }
.gx-maintenance__chevron { margin-left: auto; }
.gx-maintenance[open] .gx-maintenance__chevron { transform: rotate(180deg); }
/* Simple Bluetooth device name and connection-status rows. */
.gx-bluetooth__device + .gx-bluetooth__device { border-top: 1px solid var(--glass-border); }
.gx-bluetooth__device .gx-row__info { min-width: 0; overflow-wrap: anywhere; }
@media (max-width: 600px) {
.gx-bluetooth .gx-row { flex-wrap: wrap; }
}
.gx-uniden { display: grid; gap: var(--sp-4); min-width: 0; }
.gx-uniden > .gx-card { margin: 0; }
.gx-uniden__fieldset { border: 0; padding: 0; margin: 0; min-width: 0; }
.gx-uniden__heading, .gx-uniden__rule-footer, .gx-uniden__savebar { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-4); }
.gx-uniden__heading h3, .gx-uniden__heading h4, .gx-uniden__rule-footer p, .gx-uniden__empty p { margin: 0; }
.gx-uniden__heading h3, .gx-uniden__heading h4 { overflow-wrap: anywhere; }
.gx-uniden__eyebrow { display: block; font-size: var(--fs-xs); color: var(--text-muted); margin-bottom: var(--sp-2); }
.gx-uniden__status { flex-shrink: 0; font-size: var(--fs-xs); border-radius: 999px; padding: var(--sp-2) var(--sp-3); background: var(--surface-container); color: var(--text-muted); }
.gx-uniden__status--connected { color: var(--secondary); }
.gx-uniden__preference .gx-row__info { min-width: 0; }
.gx-uniden__preference .gx-switch { flex-shrink: 0; }
.gx-uniden__rule { display: grid; gap: var(--sp-4); padding: var(--sp-4); border: 1px solid var(--glass-border); border-radius: var(--radius-lg); }
.gx-uniden__enable { display: flex; align-items: center; gap: var(--sp-2); color: var(--text-muted); font-size: var(--fs-xs); flex-shrink: 0; }
.gx-uniden__fields { display: grid; grid-template-columns: minmax(0, 1.4fr) minmax(80px, .6fr) repeat(2, minmax(0, 1fr)); gap: var(--sp-3); }
.gx-uniden__field { display: grid; gap: var(--sp-2); min-width: 0; align-content: start; font-size: var(--fs-sm); }
.gx-uniden__field .gx-field { width: 100%; min-width: 0; box-sizing: border-box; }
.gx-uniden__rule-footer { align-items: flex-end; }
.gx-uniden__rule-footer > div { display: grid; gap: var(--sp-2); }
.gx-uniden__empty { display: grid; gap: var(--sp-2); padding: var(--sp-4) 0; }
.gx-uniden__savebar { flex-wrap: wrap; }
.gx-uniden__error { color: var(--error); }
.gx-uniden__sub { display: grid; gap: var(--sp-3); padding: var(--sp-2) var(--sp-4) var(--sp-4); }
.gx-uniden__choices { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); }
.gx-uniden__narrow .gx-field { max-width: 180px; }
.gx-uniden__pair { display: grid; grid-template-columns: repeat(2, minmax(0, 180px)); gap: var(--sp-3); }
button.gx-chip.gx-uniden__choice { min-height: var(--touch-target); padding: 0 var(--sp-4); font-size: var(--fs-sm); }
button.gx-chip.gx-uniden__choice[aria-pressed="true"] { background: var(--primary); border-color: transparent; color: var(--on-primary); }
.gx-uniden__dot { width: var(--touch-target); height: var(--touch-target); padding: 0; border-radius: 50%; border: 2px solid var(--glass-border); cursor: pointer; }
.gx-uniden__dot[aria-pressed="true"] { box-shadow: 0 0 0 2px var(--surface-container), 0 0 0 4px var(--primary); }
.gx-uniden__learning { display: grid; gap: var(--sp-3); padding: var(--sp-3) var(--sp-4); border: 1px solid var(--glass-border); border-radius: var(--radius-lg); }
.gx-uniden__learning-head { display: flex; align-items: center; gap: var(--sp-2); }
.gx-uniden__learning-head strong { font-weight: var(--fw-bold); }
.gx-uniden__learning .gx-note, .gx-uniden__learning-list { margin: 0; }
.gx-uniden__learning-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--on-surface-variant); flex: none; }
.gx-uniden__learning--on .gx-uniden__learning-dot { background: var(--secondary); }
.gx-uniden__learning-list { display: grid; gap: var(--sp-3); padding: 0; list-style: none; }
.gx-uniden__learning-list li { display: grid; gap: 6px; }
.gx-uniden__learning-line { display: flex; justify-content: space-between; gap: var(--sp-3); flex-wrap: wrap; }
.gx-uniden__learning-count { color: var(--on-surface-variant); font-size: var(--fs-sm); white-space: nowrap; }
.gx-uniden__learning-item--paused { opacity: .6; }
.gx-uniden__meter { height: 4px; border-radius: 999px; background: var(--surface-container-high); overflow: hidden; }
.gx-uniden__meter > span { display: block; height: 100%; border-radius: inherit; background: color-mix(in srgb, var(--secondary) 55%, var(--on-surface-variant)); transition: width .3s ease; }
.gx-uniden__lock-source { display: inline-block; margin-left: var(--sp-2); padding: 2px 8px; border-radius: 999px; vertical-align: middle; font-size: var(--fs-xs); font-weight: var(--fw-bold); background: var(--surface-container-high); color: var(--text-muted); }
.gx-uniden__lock-source--auto { color: var(--on-surface-variant); }
/* Uniden editor: the theme maker's save bar and workspace, preview beside the settings. */
.gx-uniden__controls { margin: 0; align-content: start; }
.gx-uniden__section { display: grid; gap: var(--sp-3); min-width: 0; }
.gx-uniden__section > .gx-section__header { padding: 0; background: none; }
.gx-uniden__section .gx-panel { padding: 0; }
.gx-uniden-editor { display: grid; gap: 12px; }
.gx-uniden__group { border-top: 1px solid var(--outline); }
.gx-uniden__group-head { display: grid; gap: 2px; padding: var(--sp-3) var(--sp-4) 0; }
.gx-uniden__group > .gx-note { padding: var(--sp-2) var(--sp-4) var(--sp-3); margin: 0; }
/* Set-up detector: one compact row, name and status, a one-line detail, Change on the right. */
.gx-uniden__detector--compact > .gx-panel { padding: var(--sp-3) var(--sp-4); }
.gx-uniden__summary { display: flex; align-items: center; gap: var(--sp-3); min-width: 0; }
.gx-uniden__summary-text { flex: 1 1 0; min-width: 0; display: grid; gap: 2px; }
.gx-uniden__summary-title { display: flex; align-items: center; gap: var(--sp-2); min-width: 0; }
.gx-uniden__summary-title h3 { margin: 0; font-size: var(--fs-base); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.gx-uniden__summary-title .gx-uniden__status { padding: 2px var(--sp-2); }
.gx-uniden__summary .gx-note { margin: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.gx-uniden__summary-actions { display: flex; gap: var(--sp-2); flex: none; }
.gx-uniden__summary-actions .gx-btn { min-height: 36px; padding: 6px 14px; }
.gx-uniden__pages { display: flex; width: fit-content; max-width: 100%; overflow-x: auto; scrollbar-width: none; }
.gx-uniden__pages > .gx-btn { flex: none; }
@container (max-width: 480px) { .gx-uniden__pages { width: 100%; } .gx-uniden__pages > .gx-btn { flex: 1 0 auto; padding-inline: 10px; font-size: var(--fs-sm); } }
.gx-uniden__page { margin: 0; }
.gx-uniden__preview-card > .gx-uniden__preview-canvas { margin-inline: 0; height: auto; aspect-ratio: 1860 / 1080; background: #000; }
/* The preview leads: on the left on desktop, pinned above the settings on narrow screens. */
.gx-uniden__preview-card { order: -1; }
@container (min-width: 1041px) { .gx-uniden__workspace { grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr); } }
.gx-uniden__bands { display: grid; gap: var(--sp-3); }
.gx-uniden__band { display: grid; gap: var(--sp-2); padding: var(--sp-3) var(--sp-4); border: 1px solid var(--glass-border); border-radius: var(--radius-lg); }
.gx-uniden__band--off .gx-uniden__choices { opacity: .45; }
/* Colors stay on one row and scroll sideways rather than wrapping; padding keeps the selected ring visible. */
.gx-uniden__band .gx-uniden__choices { flex-wrap: nowrap; overflow-x: auto; scrollbar-width: none; scroll-snap-type: x proximity; padding: 4px; margin: -4px; }
.gx-uniden__band .gx-uniden__choices::-webkit-scrollbar { display: none; }
.gx-uniden__band .gx-uniden__dot { flex: none; scroll-snap-align: start; }
.gx-uniden__edge-parts input[type="range"] { width: 100%; accent-color: var(--primary); }
.gx-uniden__edge-parts { display: grid; gap: 0; padding-block: 0 var(--sp-4); border: 1px solid var(--glass-border); border-radius: var(--radius-lg); overflow: hidden; }
.gx-uniden__edge-parts > .gx-row:first-child { border-top: 0; }
.gx-uniden__edge-parts > .gx-uniden__field, .gx-uniden__edge-parts > .gx-note { padding-inline: var(--sp-4); }
.gx-uniden__edge-parts > .gx-uniden__field { padding-top: var(--sp-3); border-top: 1px solid var(--outline); }
@media (prefers-reduced-motion: reduce) {
.gx-uniden__meter > span { transition: none; }
}
@media (max-width: 600px) {
.gx-uniden__pair { grid-template-columns: minmax(0, 1fr); }
}
@media (max-width: 800px) {
.gx-uniden__fields { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.gx-uniden__name { grid-column: 1 / -1; }
.gx-uniden__field:last-child { grid-column: 1 / -1; }
.gx-uniden__heading, .gx-uniden__rule-footer { flex-wrap: wrap; }
}
@@ -67,6 +67,13 @@
"description": "Read local reports",
"availability": "local-only"
},
{
"name": "Bluetooth Log",
"path": "/logs/bluetooth",
"icon": "bi-controller",
"description": "Send a USB and Bluetooth controller report",
"availability": "local-only"
},
{
"name": "StarPort Logs",
"path": "/logs/starport",
+7 -2
View File
@@ -37,6 +37,7 @@ const PipPage = page(() => import("./pip.js").then((module) => module.PipPage))
import { DrivingPage, drivingPage } from "./driving.js"
const LongitudinalCurvesPage = page(() => import("./longitudinal-curves.js").then((module) => module.LongitudinalCurvesPage))
import { DevicePreferencesPage, devicePage } from "./device-preferences.js"
const ControllersPage = page(() => import("./controllers.js").then((module) => module.ControllersPage))
const BluetoothPage = page(() => import("./bluetooth.js").then((module) => module.BluetoothPage))
const StarPortPage = page(() => import("./starport.js").then((module) => module.StarPortPage))
const SpotifyPage = page(() => import("./spotify.js").then((module) => module.SpotifyPage))
@@ -91,7 +92,7 @@ const auth = new LocalAuth({ publish: (update) => {
createApp({
components: { AppDownloadReminder, BottomNav, Home, LocalAccess, Tools, Logs, SoftwarePage, NavigationPage, ModelsPage, SettingsPage, SettingsRecoveryPage, ToggleSearch, SaveFeedback, FlmPage, LocalRecordingsPage, CamerasPage, SentryEventsPage, VasmPage, PipPage, DrivingPage, DevicePreferencesPage, BluetoothPage, StarPortPage, SpotifyPage, LongitudinalCurvesPage, OnroadLayoutPage, GalaxyPage, NetworksPage, DevicePicker, DeviceState, MenuTile },
components: { AppDownloadReminder, BottomNav, Home, LocalAccess, Tools, Logs, SoftwarePage, NavigationPage, ModelsPage, SettingsPage, SettingsRecoveryPage, ToggleSearch, SaveFeedback, FlmPage, LocalRecordingsPage, CamerasPage, SentryEventsPage, VasmPage, PipPage, DrivingPage, DevicePreferencesPage, BluetoothPage, ControllersPage, StarPortPage, SpotifyPage, LongitudinalCurvesPage, OnroadLayoutPage, GalaxyPage, NetworksPage, DevicePicker, DeviceState, MenuTile },
data: () => ({ state, authState, authForm, route, NAV, routeDirection: 1, updateRestart, deviceRestart, nextLayoutLeavePresentation: "inline" }),
computed: {
visibleTools() { return state.tools.filter(tool => tool.visibility !== "authenticated" ||
@@ -101,6 +102,8 @@ createApp({
drivingSettingsPage() { return drivingPage(route.path) },
deviceSettingsPage() { return devicePage(route.path) },
pageName() {
if (route.path === "/bluetooth/controllers") return "Controllers"
if (route.path === "/bluetooth/uniden") return "Uniden"
if (this.currentTool) return this.currentTool.name
if (route.path === "/device-preferences") return "Force Drive State"
return NAV.find((item) => item.path === route.path)?.name || "This page"
@@ -179,6 +182,7 @@ createApp({
this.nextLayoutLeavePresentation = "inline"
if (this.$refs.activeLayout) this.$refs.activeLayout.requestLeave(proceed, presentation)
else if (this.$refs.activeSettings) this.$refs.activeSettings.requestRouteLeave(proceed)
else if (this.$refs.activeBluetooth) this.$refs.activeBluetooth.requestLeave(proceed, presentation)
else proceed()
})
},
@@ -260,7 +264,8 @@ createApp({
<NavigationPage v-else-if="['/navigation', '/navigation/maps', '/navigation/setup'].includes(route.path)" :mode="state.monitorMode" :unauthorized="sessionExpired" :go="go" :tabs="currentTool?.children || []"
:initial-tab="route.path === '/navigation/maps' ? 'maps' : route.path === '/navigation/setup' ? 'setup' : 'route'" />
<ModelsPage v-else-if="['/manage_models', '/model_laboratory'].includes(route.path)" :mode="state.monitorMode" :unauthorized="sessionExpired" :focus="route.path === '/model_laboratory' ? 'laboratory' : ''" />
<BluetoothPage v-else-if="route.path === '/bluetooth'" :mode="state.monitorMode" :unauthorized="sessionExpired" />
<BluetoothPage ref="activeBluetooth" v-else-if="['/bluetooth', '/bluetooth/uniden'].includes(route.path)" :uniden-settings="route.path === '/bluetooth/uniden'" :key="route.path" :mode="state.monitorMode" :unauthorized="sessionExpired" :go="go" />
<ControllersPage v-else-if="route.path === '/bluetooth/controllers'" :mode="state.monitorMode" :unauthorized="sessionExpired" :go="go" />
<StarPortPage v-else-if="route.path === '/starport'" :mode="state.monitorMode" :local-access="authState.localAccess" :unauthorized="sessionExpired" />
<SpotifyPage v-else-if="['/starport/audio', '/spotify'].includes(route.path)" :mode="state.monitorMode" :unauthorized="sessionExpired" />
<SettingsPage @nested="ensureBackEntry" ref="activeSettings" v-else-if="route.path === '/settings/vehicle'" :mode="state.monitorMode" :unauthorized="sessionExpired" initial-section="vehicle" />
@@ -0,0 +1,17 @@
export const BluetoothTabs = {
props: {
active: { type: String, default: 'devices' },
go: { type: Function, default: path => { location.hash = path } },
},
data: () => ({ tabs: [
{ id: 'devices', label: 'Devices', path: '/bluetooth' },
{ id: 'audio', label: 'Phones & Audio', path: '/spotify' },
{ id: 'starport', label: 'StarPort', path: '/starport' },
{ id: 'uniden', label: 'Uniden', path: '/bluetooth/uniden' },
{ id: 'controllers', label: 'Controllers', path: '/bluetooth/controllers' },
] }),
template: `<nav class="gx-settings-tabs" aria-label="Bluetooth sections">
<button v-for="tab in tabs" :key="tab.id" type="button" class="gx-chip"
:aria-pressed="active === tab.id" @click="go(tab.path)">{{ tab.label }}</button>
</nav>`,
}
+72 -30
View File
@@ -1,9 +1,10 @@
import { WikiHelp } from './wiki-help.js'
import { UnidenPanel } from './uniden.js'
import { GxState } from "./state.js"
import { GxNotice } from "./notice.js"
import { reportSave } from "./save-feedback.js"
import { connectionError } from "./polling.js"
import { ControllersPage } from "./controllers.js"
import { BluetoothTabs } from "./bluetooth-tabs.js"
import { BluetoothDeviceList } from "./bluetooth-devices.js"
import { GxDialog } from "./dialog.js"
@@ -20,6 +21,7 @@ const BLUETOOTH_ERRORS = {
projection_active: "StarPort is using this device. Stop StarPort, then try again.",
session_expired: "The pairing session expired. Refresh and start pairing again.",
changed: "The Bluetooth device or pairing request changed. Refresh and try again.",
unreachable: "The device didn't respond. Make sure it's on, nearby and not connected to another phone or app (like the Uniden app), then try again.",
}
export const bluetoothError = (code) => BLUETOOTH_ERRORS[code] || "Bluetooth could not complete the request. Refresh to try again."
const PROMPT_KINDS = new Set(["pin", "passkey", "confirmation", "authorization", "display_pin", "display_passkey"])
@@ -167,12 +169,12 @@ export class BluetoothFeed {
}
export const BluetoothPage = {
components: { WikiHelp, GxState, GxNotice, ControllersPage, GxDialog },
props: { mode: { type: String, required: true }, unauthorized: { type: Function, required: true } },
data: () => ({ status: null, busy: false, error: "", pairValue: "", now: Date.now(), claimAt: Date.now(), forgetting: null }),
components: { WikiHelp, UnidenPanel, GxState, GxNotice, BluetoothTabs, GxDialog },
props: { go: { type: Function, default: path => { location.hash = path } }, unidenSettings: Boolean, mode: { type: String, required: true }, unauthorized: { type: Function, required: true } },
data: () => ({ status: null, busy: false, error: "", pairValue: "", now: Date.now(), claimAt: Date.now(), forgetting: null, adding: false, dismissedPairing: null }),
mounted() {
this.feed = new BluetoothFeed({ publish: (value) => Object.assign(this, value), unauthorized: this.unauthorized })
this.visibility = () => document.hidden ? this.feed.stop(true) : this.feed.start()
this.visibility = () => this.mode !== "local" || document.hidden ? this.feed.stop(true) : this.feed.start()
document.addEventListener("visibilitychange", this.visibility)
this.clock = setInterval(() => { this.now = Date.now() }, 1000)
if (this.mode === "local" && !document.hidden) this.feed.start()
@@ -184,6 +186,8 @@ export const BluetoothPage = {
'status.claim'() { this.claimAt = Date.now(); this.now = this.claimAt },
},
computed: {
pairingKey() { return this.status?.pairing ? `${this.status.pairing.address}:${this.status.pairing.state}` : null },
addingDevice() { return this.adding || !!this.status?.discovering },
saved() { return this.status?.devices?.filter((device) => device.paired || device.trusted) || [] },
// A phone running the StarPilot app is connected to comma's Bluetooth bridge but not bonded: list it apart from real pairings.
appLinks() { return this.status?.devices?.filter((device) => device.connected && !device.paired && !device.trusted) || [] },
@@ -194,8 +198,30 @@ export const BluetoothPage = {
methods: {
reportSave,
bluetoothError,
// Unsaved Uniden settings hold navigation the way the theme maker does.
requestLeave(proceed, presentation) {
if (this.$refs.uniden) this.$refs.uniden.requestLeave(proceed, presentation)
else proceed()
},
async openAdd() {
this.adding = true
await this.$nextTick()
this.$refs.addDevice?.scrollIntoView({ block: 'nearest' })
},
async closeAdd() {
if (this.status?.discovering && !await this.action('stop_scan')) return
this.adding = false
},
refresh() { return this.feed.refresh() },
action(operation, fields) { return this.feed.action(operation, fields) },
async action(operation, fields) {
if (['pair', 'accept_pair'].includes(operation)) this.dismissedPairing = null
const accepted = await this.feed.action(operation, fields)
if (accepted && ['pair', 'accept_pair'].includes(operation)) {
await this.$nextTick()
; (this.$refs.phonePairing || this.$refs.devicePairing)?.scrollIntoView({ block: 'nearest' })
}
return accepted
},
respond(accepted) {
const prompt = this.status?.pairing?.prompt
if (!prompt || prompt.displayOnly || accepted && !validPairInput(prompt, this.pairValue)) return
@@ -211,30 +237,30 @@ export const BluetoothPage = {
closeForget() { if (this.forgetting?.state !== "working") this.forgetting = null },
},
template: `
<section class="gx-driving" aria-label="Bluetooth" :inert="busy" :aria-busy="busy || undefined">
<header class="gx-settings__header gx-page-header"><div><h2>Bluetooth</h2>
<p>View, pair and manage nearby and saved devices.</p></div><WikiHelp /></header>
<section class="gx-driving gx-bluetooth" :aria-label="unidenSettings ? 'Uniden settings' : 'Bluetooth'" :inert="busy" :aria-busy="busy || undefined">
<header class="gx-settings__header gx-page-header"><div><h2>{{ unidenSettings ? 'Uniden' : 'Bluetooth' }}</h2>
<p>{{ unidenSettings ? 'Detector preferences and custom frequency rules.' : 'Pair and manage devices here. Use the tabs for integration settings.' }}</p></div><WikiHelp /></header>
<BluetoothTabs :active="unidenSettings ? 'uniden' : 'devices'" :go="go" />
<GxState v-if="mode !== 'local'">Bluetooth requires the device. No radio was checked in preview.</GxState>
<template v-else>
<GxNotice tone="danger" v-if="error">{{ error }}</GxNotice>
<GxState v-if="!status && !error" loading>Checking Bluetooth…</GxState>
<template v-else-if="status">
<GxNotice tone="info">Using a wireless Android Auto adapter? Set up StarPort on the <a class="gx-link" href="#/starport">StarPort page</a>, then pair and connect your car here.</GxNotice>
<section class="gx-card"><div class="gx-section__header"><i class="bi bi-bluetooth" aria-hidden="true"></i><span class="gx-section__title">Adapter</span></div>
<div class="gx-panel gx-stack">
<template v-else-if="status && !unidenSettings">
<section class="gx-card"><div class="gx-section__header"><i class="bi bi-bluetooth" aria-hidden="true"></i><span class="gx-section__title">Bluetooth radio</span></div>
<div class="gx-panel gx-stack gx-bluetooth__radio">
<GxNotice v-if="status.errorCode" tone="danger">{{ bluetoothError(status.errorCode) }}</GxNotice>
<GxNotice v-else-if="!status.parked" tone="warn">Park to restart the Bluetooth radio.</GxNotice>
<div class="gx-row gx-row--borderless"><div class="gx-row__info"><span class="gx-row__label">Power</span></div>
<GxNotice v-else-if="!status.parked" tone="warn">Park to pair devices or change Bluetooth connections.</GxNotice>
<div class="gx-row gx-row--borderless"><div class="gx-row__info"><span class="gx-row__label">{{ status.powered ? 'Bluetooth on' : 'Bluetooth off' }}</span><span class="gx-row__desc">Connected devices · {{ saved.filter(device => device.connected).length }}</span></div>
<label class="gx-switch"><input type="checkbox" role="switch" aria-label="Bluetooth power" :checked="status.powered" :disabled="!status.parked || !status.available" @change="$event.target.checked=status.powered; reportSave(() => action('power', {enabled: !status.powered}))"><span class="gx-switch__track"></span><span class="gx-switch__thumb"></span></label></div>
<button class="gx-btn gx-btn--tonal" :disabled="!status.powered || !status.parked || status.discovering || status.pairing?.state === 'pairing'" @click="action('accept_pair')">Pair phone</button>
<button v-if="!addingDevice" class="gx-btn" :disabled="!status.powered || !status.available || !status.parked" @click="openAdd">Add a device</button>
</div></section>
<div v-if="status.claim?.open || status.claim?.claimed" class="gx-card gx-driving__intro gx-bt-card" role="status"><h3>Pair phone</h3>
<div ref="phonePairing" v-if="status.claim?.open || addingDevice && status.claim?.claimed" class="gx-card gx-driving__intro gx-bt-card" role="status"><h3>Pair phone</h3>
<p v-if="status.claim.open && !status.claim.claimed">Open the StarPilot app and tap <strong>Pair with comma</strong>. No app? Tap <strong>{{ status.adapterName || 'this comma' }}</strong> in your phone’s Bluetooth settings.</p>
<p v-else-if="status.claim.claimed && !status.claim.paired">App paired ({{ status.claim.claimed }}). iPhone: tap <strong>{{ status.adapterName || 'this comma' }}</strong> in Settings → Bluetooth to add music. Android pairs music on its own.</p>
<p v-else-if="status.claim.claimed">All set. {{ status.claim.claimed }} is paired for the app and music.</p>
<p>App: {{ status.claim.claimed || (status.claim.open ? 'waiting' : 'not paired') }} · Music: {{ status.claim.paired || status.pairing?.state === 'paired' ? 'paired' : (status.claim.open ? 'waiting' : 'not paired') }}</p>
<p v-if="status.claim.open && claimLeft > 0"><strong>{{ Math.floor(claimLeft / 60) }}:{{ String(claimLeft % 60).padStart(2, '0') }}</strong> left. Accepts one phone.</p></div>
<section v-if="status.pairing" class="gx-card" role="status"><div class="gx-section__header"><i class="bi bi-link-45deg" aria-hidden="true"></i><span class="gx-section__title">Pairing</span><span class="gx-chip">{{ status.pairing.name || status.pairing.address }}</span></div>
<section ref="devicePairing" v-if="status.pairing && (status.pairing.state === 'pairing' || dismissedPairing !== pairingKey)" class="gx-card" role="status"><div class="gx-section__header"><i class="bi bi-link-45deg" aria-hidden="true"></i><span class="gx-section__title">Pairing</span><span class="gx-chip">{{ status.pairing.name || status.pairing.address }}</span></div>
<div class="gx-panel gx-stack"><p v-if="status.pairing.incoming && status.pairing.state === 'pairing' && !status.pairing.address">Open Bluetooth settings on your phone and tap <strong>{{ status.adapterName || 'this comma' }}</strong>.</p>
<p v-else-if="status.pairing.state === 'pairing'">Waiting for the device and any confirmation below.</p>
<GxNotice v-else :tone="status.pairing.state === 'paired' ? 'success' : status.pairing.state === 'failed' ? 'danger' : 'info'">{{ status.pairing.state === 'paired' ? 'Device paired.' : status.pairing.state === 'canceled' ? 'Pairing canceled.' : 'Pairing did not complete.' }}</GxNotice>
@@ -247,25 +273,41 @@ export const BluetoothPage = {
<input v-if="['pin', 'passkey'].includes(status.pairing.prompt.kind)" v-model="pairValue" class="gx-field" type="text" maxlength="16" autocomplete="off" placeholder="PIN or passkey" />
<div v-if="!status.pairing.prompt.displayOnly" class="gx-driving__actions gx-actions"><button class="gx-btn gx-btn--tonal" @click="respond(false)">Reject</button>
<button class="gx-btn" :disabled="!canAllowPair" @click="respond(true)">{{ status.pairing.prompt.kind === 'pin' ? 'Submit PIN' : status.pairing.prompt.kind === 'passkey' ? 'Submit Passkey' : 'Allow' }}</button></div></div>
<button v-if="status.pairing.state === 'pairing'" class="gx-btn gx-btn--tonal" @click="action('cancel_pair')">Cancel Pairing</button></div></section>
<section class="gx-card"><div class="gx-section__header"><i class="bi bi-hdd-stack" aria-hidden="true"></i><span class="gx-section__title">Saved Devices</span></div>
<p v-if="!saved.length" class="gx-note gx-inset">No saved devices found.</p>
<div v-for="device in saved" :key="device.address" class="gx-row"><div class="gx-row__info"><span class="gx-row__label"><i class="bi bi-bluetooth gx-bluetooth__device-icon" aria-hidden="true"></i>{{ device.name || device.address }}</span><span class="gx-row__desc">{{ device.connected ? 'Connected' : 'Disconnected' }} · {{ device.address }}</span></div>
<div class="gx-actions"><button class="gx-btn gx-btn--tonal" :disabled="!status.powered" @click="action(device.connected ? 'disconnect' : 'connect', {address:device.address})">{{ device.connected ? 'Disconnect' : 'Connect' }}</button>
<button class="gx-btn gx-btn--tonal" @click="forgetting = { address: device.address, name: device.name, state: 'confirm' }">Forget</button></div></div></section>
<button v-if="status.pairing.state === 'pairing'" class="gx-btn gx-btn--tonal" @click="action('cancel_pair')">Cancel Pairing</button><button v-else class="gx-btn gx-btn--tonal" @click="dismissedPairing = pairingKey">Dismiss</button></div></section>
<section class="gx-card"><div class="gx-section__header"><i class="bi bi-hdd-stack" aria-hidden="true"></i><span class="gx-section__title">Saved devices</span></div>
<p v-if="!saved.length" class="gx-note gx-inset">No saved devices yet. Choose Add a device to pair one.</p>
<div v-for="device in saved" :key="device.address" class="gx-row gx-bluetooth__device">
<div class="gx-row__info"><span class="gx-row__label">{{ device.name || device.address }}</span>
<span class="gx-row__desc">{{ device.connected ? 'Connected' : 'Disconnected' }}</span></div>
<div class="gx-actions">
<button class="gx-btn gx-btn--tonal" :disabled="!status.powered || !status.parked" @click="action(device.connected ? 'disconnect' : 'connect', {address:device.address})">{{ device.connected ? 'Disconnect' : 'Connect' }}</button>
<button class="gx-btn gx-btn--tonal" :disabled="!status.parked" @click="forgetting = { address: device.address, name: device.name, state: 'confirm' }">Forget</button>
</div>
</div></section>
<section v-if="appLinks.length" class="gx-card"><div class="gx-section__header"><i class="bi bi-phone" aria-hidden="true"></i><span class="gx-section__title">App Pairings</span></div>
<p class="gx-note gx-inset">Phones connected through the StarPilot app. These are not Bluetooth pairings.</p>
<div v-for="device in appLinks" :key="device.address" class="gx-row"><div class="gx-row__info"><span class="gx-row__label">{{ device.name }}</span>
<span class="gx-row__desc">Connected through the app</span></div>
<div class="gx-actions"><button class="gx-btn gx-btn--tonal" @click="forgetting = { address: device.address, name: device.name, state: 'confirm' }">Forget</button></div></div></section>
<section class="gx-card"><div class="gx-section__header"><i class="bi bi-broadcast" aria-hidden="true"></i><span class="gx-section__title">Nearby Devices</span>
<button class="gx-btn gx-btn--tonal" :disabled="!status.powered" @click="action(status.discovering ? 'stop_scan' : 'scan')"><i class="bi" :class="status.discovering ? 'bi-x-circle' : 'bi-search'" aria-hidden="true"></i>{{ status.discovering ? 'Stop Search' : 'Search' }}</button></div>
<p v-if="!nearby.length" class="gx-note gx-inset">{{ status.discovering ? 'Searching…' : 'No nearby devices found.' }}</p>
<div v-for="device in nearby" :key="device.address" class="gx-row"><div class="gx-row__info"><span class="gx-row__label"><i class="bi bi-bluetooth gx-bluetooth__device-icon" aria-hidden="true"></i>{{ device.name || device.address }}</span><span class="gx-row__desc">{{ device.address }}</span></div>
<button class="gx-btn" :disabled="!status.powered || status.pairing?.state === 'pairing'" @click="action('pair', {address:device.address})">Pair</button></div></section>
<section ref="addDevice" v-if="addingDevice" class="gx-card" aria-label="Add a device">
<div class="gx-section__header"><i class="bi bi-plus-circle" aria-hidden="true"></i><span class="gx-section__title">Add a device</span>
<button class="gx-btn gx-btn--tonal" @click="closeAdd">Done</button></div>
<div class="gx-panel gx-stack">
<div class="gx-row"><div class="gx-row__info"><span class="gx-row__label">Phone</span><span class="gx-row__desc">Connect the StarPilot app and phone audio.</span></div>
<button class="gx-btn gx-btn--tonal" :disabled="!status.powered || !status.parked || status.discovering || status.pairing?.state === 'pairing'" @click="action('accept_pair')">Pair phone</button></div>
<div class="gx-row"><div class="gx-row__info"><span class="gx-row__label">Detector, controller or audio device</span><span class="gx-row__desc">Put the device in pairing mode, then search.</span></div>
<button class="gx-btn gx-btn--tonal" :disabled="!status.powered || !status.parked || status.pairing?.state === 'pairing'" @click="action(status.discovering ? 'stop_scan' : 'scan')">{{ status.discovering ? 'Stop search' : 'Search' }}</button></div>
<details><summary class="gx-link">Pairing a Uniden detector?</summary><p class="gx-note">Enable Bluetooth and open BT Pairing on the detector. Close other apps connected to it. After pairing, open the Uniden tab to select it.</p></details>
<p class="gx-note">Android Auto pairing is found on the <a class="gx-link" href="#/starport">StarPort page</a>.</p>
</div>
<div v-if="status.discovering || nearby.length" class="gx-section__header"><span class="gx-section__title">Nearby devices</span></div>
<p v-if="status.discovering && !nearby.length" class="gx-note gx-inset" role="status">Searching for devices…</p>
<div v-for="device in nearby" :key="device.address" class="gx-row"><div class="gx-row__info"><span class="gx-row__label">{{ device.name || device.address }}</span><span class="gx-row__desc">{{ device.address }}</span></div>
<button class="gx-btn" :disabled="!status.powered || !status.parked || status.pairing?.state === 'pairing'" @click="action('pair', {address:device.address})">Pair</button></div>
</section>
</template>
</template>
<ControllersPage :mode="mode" :unauthorized="unauthorized" />
<UnidenPanel ref="uniden" v-if="unidenSettings && mode === 'local' && status" :settings="unidenSettings" :devices="status.devices" :parked="status.parked" :unauthorized="unauthorized" />
<GxDialog v-if="forgetting" labelledby="gx-bt-forget-title" describedby="gx-bt-forget-body" alert @close="closeForget">
<template v-if="forgetting.state === 'done'">
<h3 id="gx-bt-forget-title">{{ forgetting.name }} forgotten</h3>
@@ -1,3 +1,4 @@
import { BluetoothTabs } from "./bluetooth-tabs.js"
import { guardUnload } from "./unload-guard.js"
import { GxNotice } from "./notice.js"
import { reportSave } from "./save-feedback.js"
@@ -120,8 +121,8 @@ export class ControllersFeed {
}
export const ControllersPage = {
components: { GxNotice },
props: { mode: { type: String, required: true }, unauthorized: { type: Function, required: true } },
components: { GxNotice, BluetoothTabs },
props: { go: { type: Function, default: path => { location.hash = path } }, mode: { type: String, required: true }, unauthorized: { type: Function, required: true } },
setup(props) {
const state = reactive({ status: null, busy: false, error: "", draft: null })
const feed = new ControllersFeed({ unauthorized: props.unauthorized, publish(update) {
@@ -173,6 +174,9 @@ export const ControllersPage = {
},
},
template: `
<section class="gx-driving" aria-label="Controllers">
<header class="gx-settings__header gx-page-header"><div><h2>Controllers</h2><p>Assign buttons and test your connected controllers.</p></div></header>
<BluetoothTabs active="controllers" :go="go" />
<section class="gx-card gx-controllers" aria-label="Controller Buttons" :inert="state.busy" :aria-busy="state.busy || undefined">
<div class="gx-section__header"><i class="bi bi-controller" aria-hidden="true"></i><span class="gx-section__title">Controller Buttons</span></div>
<div class="gx-panel gx-stack">
@@ -190,7 +194,7 @@ export const ControllersPage = {
<div class="gx-row gx-row--borderless"><div class="gx-row__info"><span class="gx-row__label">Enable assigned controller buttons</span></div>
<label class="gx-switch"><input type="checkbox" role="switch" aria-label="Enable assigned controller buttons" v-model="state.draft.enabled" :disabled="!canEdit" @change="save"><span class="gx-switch__track"></span><span class="gx-switch__thumb"></span></label></div>
<h4>Attached Controllers</h4>
<p v-if="!state.status.devices.length" class="gx-note">No controller is attached.</p>
<p v-if="!state.status.devices.length" class="gx-note">No controller is attached. Plug in a USB controller or <a class="gx-link" href="#/bluetooth">pair in Bluetooth</a>.</p>
<div v-for="device in state.status.devices" :key="device.id" class="gx-row gx-controllers__row"><div class="gx-row__info"><span class="gx-row__label">{{ device.name }}</span><span class="gx-row__desc">{{ device.bus === 3 ? 'USB' : 'Bluetooth' }}</span></div></div>
<h4>Favorite Buttons</h4>
<div v-for="slot in favorites" :key="slot.index" class="gx-row gx-controllers__row"><div class="gx-row__info"><span class="gx-row__label">{{ slot.label }}</span>
@@ -213,5 +217,5 @@ export const ControllersPage = {
<button class="gx-btn gx-btn--tonal" type="button" :disabled="!editable || dirty" @click="remove(binding)">Remove</button></div>
</template>
</template></div>
</section>`,
</section></section>`,
}
@@ -399,6 +399,7 @@ export function recordedSteeringView(value) {
value.points[0][0] !== value.source_start_ns || value.points.at(-1)[0] !== value.source_end_ns) return null
return { errorRms: value.error_rms, samples: value.samples, windows: value.windows, route: value.route,
segment: value.segment, units: value.domain === 'lateral_acceleration' ? 'm/s²' : 'degrees',
followedRepeatedRequest: value.domain === 'lateral_acceleration' && value.observation === 'followed_repeated_steering_request',
points: value.points.map(([ns, desired, actual]) => ({ at: (ns - value.source_start_ns) / 1e6, desired, actual })) }
}
+3 -2
View File
@@ -427,9 +427,10 @@ export const FlmPage = {
<div class="gx-tuner__drive-actions"><button v-if="review.saved.length" type="button" class="gx-btn gx-btn--tonal" @click="selectView('tune')">{{ review.historical ? 'View earlier saved values' : 'View saved change' }}<i class="bi bi-arrow-right" aria-hidden="true"></i></button><button v-if="review.count" type="button" class="gx-btn gx-btn--tonal gx-tuner__review-button" data-action="view-findings" @click="selectView('tune')">{{ review.saved.length ? 'View other findings' : 'View ' + review.count + (review.count === 1 ? ' finding' : ' findings') }}<i class="bi bi-arrow-right" aria-hidden="true"></i></button></div>
</section>
<div class="gx-tuner__overview-grid"><section class="gx-card gx-tuner__section gx-tuner__response"><div class="gx-tuner__section-heading"><div><p class="gx-tuner__eyebrow">STEERING RESPONSE</p><h3>How your car followed the steering request</h3></div><span class="gx-tuner__pill">{{ trackingPlot ? 'Completed window' : offroad?.observed ? 'One recorded section · ' + recordedDuration + 's' : offroad ? 'Recorded drive' : 'Waiting for samples' }}</span></div>
<p class="gx-tuner__graph-explainer">When these lines are close, the car is following the steering request closely in this sample.</p>
<p v-if="!trackingPlot && offroad?.observed?.followedRepeatedRequest" class="gx-tuner__graph-explainer">The steering request kept swinging back and forth, and the car followed it.</p>
<p v-else class="gx-tuner__graph-explainer">When these lines are close, the car is following the steering request closely in this sample.</p>
<template v-if="trackingPlot"><PlotGraph :chart="pairedTrackingChart" title="Requested and measured steering acceleration, paired using the learner's measured delay" /><div class="gx-tuner__legend"><span class="gx-tuner__requested">What StarPilot asked for</span><span class="gx-tuner__measured">What the car did</span><small>m/s² · delay aligned</small></div><p class="gx-tuner__caption">{{ trackingPlot.totalEndpoints }} measured endpoints · {{ trackingPlot.age.toFixed(1) }}s since the last pose</p></template>
<template v-else-if="offroad?.observed"><PlotGraph :chart="recordedTrackingChart" title="Recorded requested and measured steering" start-label="Start · 0s" :end-label="'End · ' + recordedDuration + 's'" /><div class="gx-tuner__legend"><span class="gx-tuner__requested">What StarPilot asked for</span><span class="gx-tuner__measured">What the car did</span></div><p class="gx-tuner__caption">One short recorded section, not a full-drive score or a before-and-after comparison.</p><details class="gx-tuner__disclosure"><summary>About this graph</summary><p>{{ offroad.observed.units }} · original source times. Drive {{ offroad.observed.route }} · segment {{ offroad.observed.segment }} · one input-ordered recorded window. No interpolation or delay alignment. Baseline statistics use {{ amount(offroad.observed.windows) }} windows.</p></details></template>
<template v-else-if="offroad?.observed"><PlotGraph :chart="recordedTrackingChart" title="Recorded requested and measured steering" start-label="Start · 0s" :end-label="'End · ' + recordedDuration + 's'" /><div class="gx-tuner__legend"><span class="gx-tuner__requested">What StarPilot asked for</span><span class="gx-tuner__measured">What the car did</span></div><p class="gx-tuner__caption">One short recorded section, not a full-drive score or a before-and-after comparison.</p><details class="gx-tuner__disclosure"><summary>About this graph</summary><p>{{ offroad.observed.units }} · original source times. Drive {{ offroad.observed.route }} · segment {{ offroad.observed.segment }} · original samples without interpolation or delay alignment. Baseline statistics use {{ amount(offroad.observed.windows) }} windows.</p></details></template>
<div v-else-if="offroad" class="gx-tuner__empty"><i class="bi bi-activity" aria-hidden="true"></i><h4>{{ amount(offroad.samples) }} recorded steering observations</h4><p>{{ learningReason(offroad.reason) }}</p><p class="gx-tuner__caption">No recorded response series was included in this report.</p></div>
<div v-else class="gx-tuner__empty"><i class="bi bi-activity" aria-hidden="true"></i><h4>No steering recording yet</h4><p>Once the device reports steering measurements, the request and the car response will appear here.</p></div>
</section>
+20 -29
View File
@@ -6,21 +6,21 @@ import { navigate } from "./router.js"
import { SystemMonitor } from "./system-monitor.js"
import { CrashReportsFeed } from "./crash-reports.js"
import { storedSize } from "./record-deletion.js"
import { StarPortLogsFeed, StarPortLogSend, BUNDLE_URL, MESSAGE_LIMIT, fileUrl, outcomeLabel } from "./starport-logs.js"
import { StarPortLogsFeed, StarPortLogSend, LogSendCard, BLUETOOTH_SEND_URL, outcomeLabel } from "./starport-logs.js"
import { MenuTile } from "./menu-tile.js"
import { BluetoothNotice, bluetoothConnection } from "./bluetooth-notice.js"
export const Logs = {
name: "Logs",
components: { WikiHelp, GxState, GxNotice, BluetoothNotice, SystemMonitor, TroubleshootPage, TmuxPage, MenuTile },
components: { WikiHelp, GxState, GxNotice, LogSendCard, SystemMonitor, TroubleshootPage, TmuxPage, MenuTile },
props: {
path: { type: String, required: true }, mode: { type: String, required: true }, unauthorized: { type: Function, required: true },
tools: { type: Array, required: true }
},
data: () => ({
crashes: { reports: [], scanIncomplete: false, listLimited: false, status: "idle", error: "", selected: null, preview: null, previewStatus: "idle", deleting: false, storageBytes: 0, reportCount: 0 }, search: "",
starportLogs: { sessions: [], others: [], status: "idle", error: "" }, bluetooth: bluetoothConnection(),
logSend: { state: "idle", message: "", available: true, fork: false, error: "" }, sendNote: "", sendDiscord: "", messageLimit: MESSAGE_LIMIT
starportLogs: { sessions: [], others: [], status: "idle", error: "" },
logSend: { state: "idle", message: "", available: true, fork: false, error: "" },
bluetoothSend: { state: "idle", message: "", available: true, fork: false, error: "" }
}),
computed: {
visibleReports() { return this.crashes.reports.filter((item) => item.name.toLowerCase().includes(this.search.toLowerCase())) },
@@ -29,29 +29,29 @@ export const Logs = {
this.crashFeed = new CrashReportsFeed({ publish: (update) => Object.assign(this.crashes, update), unauthorized: this.unauthorized })
this.starportFeed = new StarPortLogsFeed({ publish: (update) => Object.assign(this.starportLogs, update), unauthorized: this.unauthorized })
this.sendFeed = new StarPortLogSend({ publish: (update) => Object.assign(this.logSend, update), unauthorized: this.unauthorized })
this.bluetoothFeed = new StarPortLogSend({ url: BLUETOOTH_SEND_URL, unavailable: "Sending the Bluetooth Log is unavailable",
publish: (update) => Object.assign(this.bluetoothSend, update), unauthorized: this.unauthorized })
},
mounted() {
if (this.path === "/logs/crashes" && this.mode === "local") this.crashFeed.start()
if (this.path === "/logs/starport" && this.mode === "local") { this.starportFeed.start(); this.sendFeed.start() }
if (this.path === "/logs/bluetooth" && this.mode === "local") this.bluetoothFeed.start()
},
beforeUnmount() { this.crashFeed.stop(); this.starportFeed.stop(); this.sendFeed.stop() },
beforeUnmount() { this.crashFeed.stop(); this.starportFeed.stop(); this.sendFeed.stop(); this.bluetoothFeed.stop() },
watch: {
path(next, previous) {
if (next === "/logs/crashes" && this.mode === "local") this.crashFeed.start()
else if (previous === "/logs/crashes") { this.crashFeed.stop(); this.search = "" }
if (next === "/logs/starport" && this.mode === "local") { this.starportFeed.start(); this.sendFeed.start() }
else if (previous === "/logs/starport") { this.starportFeed.stop(); this.sendFeed.stop() }
if (next === "/logs/bluetooth" && this.mode === "local") this.bluetoothFeed.start()
else if (previous === "/logs/bluetooth") this.bluetoothFeed.stop()
},
},
methods: {
storedSize,
go: navigate,
bundleUrl: () => BUNDLE_URL,
fileUrl,
outcomeLabel,
async sendLogs() {
if (await this.sendFeed.send(this.sendNote, this.sendDiscord)) this.sendNote = ""
},
reportDate(seconds) { return new Date(seconds * 1000).toLocaleString() },
reportSize(bytes) { return `${(bytes / 1024).toFixed(1)} KiB` },
async copyPreview() {
@@ -70,6 +70,12 @@ export const Logs = {
:availability="mode !== 'local' && tool.availability === 'local-only' ? 'Unavailable in preview' : ''"
:disabled="mode !== 'local' && tool.availability === 'local-only'" @select="go(tool.path)" />
</div>
<section v-else-if="path === '/logs/bluetooth' && mode === 'local'" class="gx-settings">
<header class="gx-settings__header gx-page-header"><div><h2>Bluetooth Log</h2>
<p>Sends the USB and Bluetooth input devices the comma sees to the developer.</p></div></header>
<LogSendCard v-if="bluetoothSend.available" :feed="bluetoothFeed" :state="bluetoothSend" title="Send Bluetooth Log">Connect the controller and wake it before sending. A short note and your Discord username are required.</LogSendCard>
<GxNotice v-else tone="warn">Sending isn't set up on this build.</GxNotice>
</section>
<section v-else-if="path === '/logs/help'" class="gx-settings">
<header class="gx-settings__header gx-page-header"><div><h2>Help & Community</h2><p>Guides and help from the community.</p></div><WikiHelp path="/logs/help" /></header>
<section class="gx-card"><div class="gx-section__header"><i class="bi bi-discord" aria-hidden="true"></i><span class="gx-section__title">Discord</span></div>
@@ -98,23 +104,10 @@ export const Logs = {
</template>
<section v-else-if="path === '/logs/starport' && mode === 'local'" class="gx-settings gx-starport-logs" aria-labelledby="gx-starport-logs-title">
<header class="gx-settings__header gx-page-header"><div><h2 id="gx-starport-logs-title">StarPort Logs</h2>
<p>The last 20 connection sessions, newest first. The archive includes every session, a readable report for each, StarPort settings, the car view's renderer logs, and a snapshot of the device (Wi-Fi, Bluetooth and kernel logs, build, CPU load). Hardware addresses are masked.</p></div><WikiHelp /></header>
<BluetoothNotice v-if="bluetooth" feature="Log downloads">Log summaries remain available.</BluetoothNotice>
<div class="gx-settings__controls gx-actions"><a v-if="!bluetooth" class="gx-btn" :href="bundleUrl()" download><i class="bi bi-file-earmark-zip" aria-hidden="true"></i><span>Download all logs</span><span class="gx-starport-logs__format">ZIP</span></a><button type="button" class="gx-btn gx-btn--tonal" @click="starportFeed.load()"><i class="bi bi-arrow-clockwise" aria-hidden="true"></i><span>Refresh</span></button></div>
<p>The last 20 connection sessions, newest first. Sent logs include every session, a readable report for each, StarPort settings, the car view's renderer logs, and a snapshot of the device (Wi-Fi, Bluetooth and kernel logs, build, CPU load). Hardware addresses are masked.</p></div><WikiHelp /></header>
<div class="gx-settings__controls gx-actions"><button type="button" class="gx-btn gx-btn--tonal" @click="starportFeed.load()"><i class="bi bi-arrow-clockwise" aria-hidden="true"></i><span>Refresh</span></button></div>
<GxNotice v-if="logSend.fork" class="gx-starport-send__fork" tone="warn" title="This device is running a StarPilot fork">Custom forks may have changed StarPort or be out of date. Make sure your branch is up to date with StarPilotHQ before sending, or share the logs with your branch's maintainer or in the StarPilot Discord.</GxNotice>
<section v-if="logSend.available" class="gx-card gx-panel gx-starport-send" aria-labelledby="gx-starport-send-title">
<div class="gx-section__header"><i class="bi bi-send" aria-hidden="true"></i><span id="gx-starport-send-title" class="gx-section__title">Send StarPort logs</span></div>
<p class="gx-note">Only for StarPort issues. For anything else, ask in the Discord. Sends the same archive as Download all logs straight from the device. A short note about what happened is required.</p>
<div class="gx-starport-send__row">
<div class="gx-starport-send__field"><input class="gx-field" type="text" v-model="sendNote" :maxlength="messageLimit" placeholder="What happened?" aria-label="Note for the developer" :disabled="logSend.state === 'sending'" @keydown.enter="sendLogs"><span class="gx-starport-send__count" aria-live="polite">{{ sendNote.length }}/{{ messageLimit }}</span></div>
<input class="gx-field" type="text" v-model="sendDiscord" maxlength="40" autocomplete="off" autocapitalize="off" spellcheck="false" placeholder="Discord username (optional)" aria-label="Discord username for a follow-up" :disabled="logSend.state === 'sending'" @keydown.enter="sendLogs">
<button type="button" class="gx-btn" :disabled="logSend.state === 'sending' || !sendNote.trim()" @click="sendLogs"><i class="bi bi-send" aria-hidden="true"></i><span>Send StarPort logs</span></button>
</div>
<GxState v-if="logSend.state === 'sending'" loading>{{ logSend.message || 'Sending logs' }}…</GxState>
<GxNotice v-else-if="logSend.state === 'sent'" tone="success">{{ logSend.message }}</GxNotice>
<GxNotice v-else-if="logSend.state === 'failed'" tone="danger">{{ logSend.message }}</GxNotice>
<GxNotice v-if="logSend.error" tone="danger">{{ logSend.error }}</GxNotice>
</section>
<LogSendCard v-if="logSend.available" :feed="sendFeed" :state="logSend" title="Send StarPort logs">Only for StarPort issues. For anything else, ask in the Discord. Sends every session with its report, StarPort settings, renderer logs and a device snapshot straight from the device. A short note and your Discord username are required.</LogSendCard>
<GxState v-if="starportLogs.status === 'loading'" loading>Loading StarPort logs…</GxState>
<GxNotice v-else-if="starportLogs.status === 'unavailable'" tone="danger">{{ starportLogs.error || 'StarPort logs are unavailable.' }}</GxNotice>
@@ -122,7 +115,6 @@ export const Logs = {
<div v-if="starportLogs.status === 'ready'" class="gx-starport-log-list">
<article v-for="log in starportLogs.sessions" :key="log.name" class="gx-card gx-starport-log">
<div class="gx-starport-log__body"><strong>{{ outcomeLabel(log.outcome) }}</strong><span>{{ log.car || 'Car not identified' }}{{ log.transport ? ' · ' + log.transport : '' }}{{ log.trigger ? ' · ' + log.trigger : '' }}</span><span>{{ reportDate(log.modifiedAt) }} · {{ reportSize(log.size) }}</span></div>
<a v-if="!bluetooth" class="gx-icon-btn gx-starport-log__download" :href="fileUrl(log.name)" :download="log.name" :aria-label="'Download ' + log.name" :title="'Download ' + log.name"><i class="bi bi-download" aria-hidden="true"></i></a>
</article>
</div>
<template v-if="starportLogs.status === 'ready' && starportLogs.others.length">
@@ -130,7 +122,6 @@ export const Logs = {
<div class="gx-starport-log-list">
<article v-for="log in starportLogs.others" :key="log.name" class="gx-card gx-starport-log">
<div class="gx-starport-log__body"><strong>{{ log.name }}</strong><span>{{ reportDate(log.modifiedAt) }} · {{ reportSize(log.size) }}</span></div>
<a v-if="!bluetooth" class="gx-icon-btn gx-starport-log__download" :href="fileUrl(log.name)" :download="log.name" :aria-label="'Download ' + log.name" :title="'Download ' + log.name"><i class="bi bi-download" aria-hidden="true"></i></a>
</article>
</div>
</template>
@@ -50,6 +50,7 @@ export function widgetSize(widget, position) {
const [width, height] = widget.sizes[position.size]
return [width, height + (widget.wifiNameHeight && position.wifiName === true ? widget.wifiNameHeight : 0)].map(side => Math.round(side * scale))
}
if (widget.kind === "uniden_alerts" && Number.isInteger(position?.scale)) return [Math.round(widget.width * position.scale / 100), Math.round(widget.height * position.scale / 100)]
if (widget.box) return [position?.width ?? widget.width, position?.height ?? widget.height]
if (widget.resizable) return [position?.size ?? widget.width, position?.size ?? widget.height]
return [widget.width, widget.height]
@@ -179,8 +180,11 @@ export function validDocument(document, metadata) {
const resizable = widget.resizable, box = widget.box, opacity = widget.opacity
const rotate = wheelRotationAvailable(widget, name, metadata?.projection === true) && object(position) && Object.hasOwn(position, "rotate")
return keysEqual(position, ["x", "y", "enabled", ...(resizable ? ["size"] : []), ...(box ? ["width", "height"] : []),
...(opacity ? ["opacity"] : []), ...(widget.iconSize ? ["display"] : []), ...(widget.backgroundToggle ? ["background"] : []), ...(widget.collapseToggle ? ["collapse"] : []), ...(widget.bluetoothToggle ? ["bluetooth"] : []), ...(widget.wifiNameHeight ? ["wifiName"] : []), ...(widget.sizes ? ["size"] : []), ...(widget.scale ? ["scale"] : []), ...(rotate ? ["rotate"] : [])]) &&
...(widget.kind === "uniden_alerts" ? ["transparency", "hide_when_no_alert", "scale"] : []), ...(opacity ? ["opacity"] : []), ...(widget.iconSize ? ["display"] : []), ...(widget.backgroundToggle ? ["background"] : []), ...(widget.collapseToggle ? ["collapse"] : []), ...(widget.bluetoothToggle ? ["bluetooth"] : []), ...(widget.wifiNameHeight ? ["wifiName"] : []), ...(widget.sizes ? ["size"] : []), ...(widget.scale ? ["scale"] : []), ...(rotate ? ["rotate"] : [])]) &&
(!rotate || typeof position.rotate === "boolean") &&
(widget.kind !== "uniden_alerts" || (Number.isInteger(position.transparency) && position.transparency >= 0 &&
position.transparency <= 100 && typeof position.hide_when_no_alert === "boolean" &&
Number.isInteger(position.scale) && position.scale >= 50 && position.scale <= 150)) &&
(!widget.iconSize || ["words", "icons"].includes(position.display)) &&
(!widget.backgroundToggle || typeof position.background === "boolean") &&
(!widget.collapseToggle || typeof position.collapse === "boolean") &&
@@ -252,6 +252,21 @@ export const ONROAD_LAYOUT_TEMPLATE = `
:value="selectedPosition.size" :disabled="!editAvailable || !!state.drag" @change="resizeSelected($event)"></label>
<input v-if="selectedWidget.resizable" class="gx-slider" type="range" step="1" aria-label="Size" :min="selectedWidget.resizable.min" :max="selectedWidget.resizable.max"
:value="selectedPosition.size" :disabled="!editAvailable || !!state.drag || !!state.layerDrag" @input="sizeSlider($event)" @change="finishColorEdit" @blur="finishColorEdit">
<template v-if="selectedWidget.kind === 'uniden_alerts'">
<label for="layout-uniden-scale">Size · {{ selectedPosition.scale }}%</label>
<input id="layout-uniden-scale" class="gx-slider" type="range" min="50" max="150" step="5"
:value="selectedPosition.scale" :disabled="!editAvailable"
@input="setUnidenDisplay('scale', Number($event.target.value))" @change="finishColorEdit" @blur="finishColorEdit" />
<label for="layout-uniden-transparency">Background transparency · {{ selectedPosition.transparency }}%</label>
<input id="layout-uniden-transparency" class="gx-slider" type="range" min="0" max="100" step="1"
:value="selectedPosition.transparency" :disabled="!editAvailable"
@input="setUnidenDisplay('transparency', Number($event.target.value))" @change="finishColorEdit" @blur="finishColorEdit" />
<p class="gx-note">0% is solid; 100% removes the background. Text and arrows stay visible.</p>
<GalaxySettingRow feedback="draft" :row="switchRow('Hide when no alert', selectedPosition.hide_when_no_alert === true)" :index="0"
:disabled="!editAvailable || !!state.drag || !!state.layerDrag" :save-value="(index, value) => setUnidenDisplay('hide_when_no_alert', value === 'On')" />
<p class="gx-note">Hide quiet and disconnected cards. Turn off to show detector readiness and connection status.</p>
<p class="gx-note">Which alerts appear is set in Uniden Preferences, under On the screen. It applies to this widget and the full-screen warning.</p>
</template>
<template v-if="selectedWidget.opacity">
<label for="layout-widget-opacity">{{ selectedWidget.box ? 'Map opacity' : ['cruise_limits', 'jetlink_status', 'network_signal'].includes(selectedWidget.kind) ? 'Background opacity' : 'Opacity' }} · {{ selectedPosition.opacity }}%</label>
<input id="layout-widget-opacity" class="gx-slider" type="range" step="1" :min="selectedWidget.opacity.min" :max="selectedWidget.opacity.max"
@@ -10,6 +10,7 @@ import { LEAD_INFO, PROJECTION_WORDMARK, editorSnapshot, projectionPayload } fro
import { GalaxySelect } from "./galaxy-select.js"
import { GxNotice } from "./notice.js"
import { GxDialog } from "./dialog.js"
import { signalColor } from "./uniden-preview.js"
import { GalaxySettingRow, switchRow } from "./galaxy-setting-row.js"
import { showDraftChange } from "./save-feedback.js"
import { snapTargets, snapMove, snapResize, snapThreshold } from "./layout-snap.js"
@@ -175,6 +176,7 @@ export const LayoutWidgetPreview = {
sprite() { return this.art?.url && this.art.sprites?.sprites?.[this.widget.id] },
},
methods: {
unidenSignal: signalColor,
withAlpha,
modeLines(scene, profile) {
const { mode, experimental } = previewScene(scene), aol = scene === "aol"
@@ -347,6 +349,16 @@ export const LayoutWidgetPreview = {
</g>
</g>
</g>
<g v-else-if="widget.kind === 'uniden_alerts'">
<g :transform="'scale(' + (widget.scale ?? 100) / 100 + ')'">
<rect x="1" y="1" width="458" height="74" rx="14" :stroke="palette.cardBorder || '#9d72ff'" stroke-width="2" :fill="palette.cardFill || '#10191f'" :fill-opacity="(100 - (widget.transparency ?? 8)) / 100" />
<text x="24" y="51" font-size="36" font-weight="600" fill="#ff5b65">KA</text>
<text x="97" y="48" font-size="28" font-weight="600" :fill="palette.text || '#ffffff'">35.500 GHz</text>
<rect v-for="i in 8" :key="i" :x="283 + (i - 1) * 11" :y="53 - (8 + (i - 1) * 3)" width="8" :height="8 + (i - 1) * 3"
:fill="i > 6 ? '#35434d' : unidenSignal(6, i - 1)" />
<path d="M411 25 L426 51 L396 51 Z" fill="#ff5b65" />
</g>
</g>
<g v-else-if="widget.kind === 'jetlink_status'">
<rect x="0" y="0" :width="widget.width" :height="widget.height" :rx="widget.height / 2" fill="#0f0d17" :fill-opacity="(widget.opacity ?? 85) / 100 * .92" />
<circle cx="40" cy="30" r="7.5" fill="#46c86e" />
@@ -714,6 +726,7 @@ export const OnroadLayoutPage = {
: { x: 0, y: -widget.visualInsetTop, width, height: height + widget.visualInsetTop + widget.visualInsetBottom }
return {
...widget, width, height, outline, ...(widget.iconSize ? { display: this.layout[widget.id].display } : {}),
...(widget.kind === "uniden_alerts" ? { transparency: this.layout[widget.id].transparency, scale: this.layout[widget.id].scale } : {}),
...(widget.opacity ? { opacity: this.layout[widget.id].opacity } : {}),
...(widget.backgroundToggle ? { background: this.layout[widget.id].background } : {}),
...(widget.collapseToggle ? { collapse: this.layout[widget.id].collapse } : {}),
@@ -1437,6 +1450,17 @@ export const OnroadLayoutPage = {
this.recordChange(before, this.state.profile + ":" + this.state.selected + ":scale")
this.state.notice = ""
},
setUnidenDisplay(field, value) {
if (!this.editable || this.state.drag || this.state.layerDrag || this.selectedWidget?.kind !== 'uniden_alerts') return
const range = { transparency: [0, 100], scale: [50, 150] }[field]
if (range ? !Number.isInteger(value) || value < range[0] || value > range[1] :
field !== 'hide_when_no_alert' || typeof value !== 'boolean') return
this.finishColorEdit()
const before = clone(this.state.draft)
this.selectedPosition[field] = value
this.recordChange(before, this.state.profile + ":" + this.state.selected + ":" + field)
this.state.notice = ""
},
opacityInput(event) {
const value = Number(event.target.value), range = this.selectedWidget?.opacity
if (!this.editable || this.state.drag || this.state.layerDrag || !range || !Number.isInteger(value) || value < range.min || value > range.max) return
+1 -1
View File
@@ -447,7 +447,7 @@ export const SpotifyPage = {
</label>
<p v-if="!phoneSource" class="gx-note">Spotify streams on the comma. Your phone controls playback in Spotify; the comma sends the music to the audio output you choose below.</p>
<template v-if="phoneSource">
<p class="gx-note">Pair your phone in the companion app, or tap <strong>Pair phone</strong> on the <a class="gx-link" href="#/bluetooth">Bluetooth page</a>. Then choose it below and turn on phone audio. On your phone, select the comma as the media audio output. No Spotify install or API key is needed.</p>
<p class="gx-note">Pair your phone in the companion app, or choose <strong>Add a device → Pair phone</strong> on the <a class="gx-link" href="#/bluetooth">Bluetooth page</a>. Then choose it below and turn on phone audio. On your phone, select the comma as the media audio output. No Spotify install or API key is needed.</p>
<label class="gx-stack"><span>Phone</span>
<select class="gx-field" :value="setup.preferences.phoneAddress" :disabled="busy || !setup.parked" @change="choosePhone">
<option value="">Choose your paired phone…</option>
@@ -1,7 +1,8 @@
// Read-only StarPort session logs. State is cleared on navigation and sign-out.
import { GxState } from "./state.js"
import { GxNotice } from "./notice.js"
export const LOGS_URL = "./api/starport/logs"
export const BUNDLE_URL = `${LOGS_URL}/bundle`
export const fileUrl = (name) => `${LOGS_URL}/file/${encodeURIComponent(name)}`
// compat_report's outcome is a short phrase: "projected", "failed: <error>", "stopped at rfcomm", "no session".
export const outcomeLabel = (outcome) => (outcome ? outcome[0].toUpperCase() + outcome.slice(1) : "Unknown")
@@ -70,15 +71,16 @@ export class StarPortLogsFeed {
}
export const SEND_URL = `${LOGS_URL}/send`
export const BLUETOOTH_SEND_URL = "./api/controllers/log/send"
export const MESSAGE_LIMIT = 60
const POLL_MS = 1500
// "Send StarPort logs": the device builds the same zip as Download all logs and posts it to the developer's Discord.
// The device builds the log and posts it to the developer's Discord.
// Only small JSON crosses the connection, so this also works over Bluetooth.
export class StarPortLogSend {
constructor({ publish, unauthorized = () => {}, fetcher = (...args) => fetch(...args), schedule = (fn, ms) => setTimeout(fn, ms),
cancel = (id) => clearTimeout(id) }) {
Object.assign(this, { publish, unauthorized, fetcher, schedule, cancel })
cancel = (id) => clearTimeout(id), url = SEND_URL, unavailable = "Sending StarPort logs is unavailable" }) {
Object.assign(this, { publish, unauthorized, fetcher, schedule, cancel, url, unavailable })
this.active = false
this.timer = null
this.generation = 0
@@ -98,7 +100,7 @@ export class StarPortLogSend {
}
async call(options, generation) {
const response = await this.fetcher(SEND_URL, { cache: "no-store", credentials: "same-origin", ...options })
const response = await this.fetcher(this.url, { cache: "no-store", credentials: "same-origin", ...options })
if (!this.active || generation !== this.generation) return null
if (response.status === 401) {
this.stop()
@@ -107,7 +109,7 @@ export class StarPortLogSend {
}
const body = await response.json().catch(() => null)
if (!this.active || generation !== this.generation) return null
if (!response.ok) throw new Error(body?.error || "Sending StarPort logs is unavailable")
if (!response.ok) throw new Error(body?.error || this.unavailable)
return body
}
@@ -129,13 +131,13 @@ export class StarPortLogSend {
this.apply(await this.call({}, generation))
} catch (error) {
if (this.active && generation === this.generation) {
this.publish({ error: error?.message || "Sending StarPort logs is unavailable" })
this.publish({ error: error?.message || this.unavailable })
this.queuePoll()
}
}
}
async send(message, discord = "") {
async send(message, discord) {
if (!this.active) return false
const text = String(message ?? "").trim()
const handle = String(discord ?? "").trim()
@@ -147,20 +149,56 @@ export class StarPortLogSend {
this.publish({ error: `Keep the message to ${MESSAGE_LIMIT} characters.` })
return false
}
if (!handle.replace(/^@/, "")) {
this.publish({ error: "Add your Discord username so we can follow up." })
return false
}
const generation = ++this.generation
this.queuePoll(false)
this.publish({ state: "sending", message: "Starting", error: "" })
try {
const body = await this.call({ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(handle ? { message: text, discord: handle } : { message: text }) }, generation)
const body = await this.call({ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ message: text, discord: handle }) }, generation)
if (body === null) return false
this.apply(body)
return true
} catch (error) {
if (this.active && generation === this.generation) {
this.publish({ state: "idle", error: error?.message || "Sending StarPort logs is unavailable" })
this.publish({ state: "idle", error: error?.message || this.unavailable })
this.queuePoll()
}
return false
}
}
}
export const LogSendCard = {
name: "LogSendCard",
components: { GxState, GxNotice },
props: { feed: { type: Object, required: true }, state: { type: Object, required: true }, title: { type: String, required: true } },
data: () => ({ note: "", discord: "", limit: MESSAGE_LIMIT, missing: [] }),
watch: {
note(value) { if (value.trim()) this.missing = this.missing.filter((field) => field !== "note") },
discord(value) { if (value.trim().replace(/^@/, "")) this.missing = this.missing.filter((field) => field !== "discord") },
},
methods: {
async submit() {
this.missing = [!this.note.trim() && "note", !this.discord.trim().replace(/^@/, "") && "discord"].filter(Boolean)
if (this.missing.length) return this.$refs[this.missing[0]]?.focus()
if (await this.feed.send(this.note, this.discord)) this.note = ""
},
},
template: `
<section class="gx-card gx-panel gx-starport-send" :aria-label="title">
<div class="gx-section__header"><i class="bi bi-send" aria-hidden="true"></i><span class="gx-section__title">{{ title }}</span></div>
<p class="gx-note"><slot /></p>
<div class="gx-starport-send__row">
<div class="gx-starport-send__field"><input ref="note" class="gx-field" :class="{ 'gx-field--required': missing.includes('note') }" :aria-invalid="missing.includes('note')" type="text" v-model="note" :maxlength="limit" placeholder="What happened?" aria-label="Note for the developer" :disabled="state.state === 'sending'" @keydown.enter="submit"><span class="gx-starport-send__count" aria-live="polite">{{ note.length }}/{{ limit }}</span></div>
<input ref="discord" class="gx-field" :class="{ 'gx-field--required': missing.includes('discord') }" :aria-invalid="missing.includes('discord')" type="text" v-model="discord" maxlength="40" autocomplete="off" autocapitalize="off" spellcheck="false" placeholder="Discord username" aria-label="Discord username for a follow-up" :disabled="state.state === 'sending'" @keydown.enter="submit">
<button type="button" class="gx-btn" :disabled="state.state === 'sending'" @click="submit"><i class="bi bi-send" aria-hidden="true"></i><span>{{ title }}</span></button>
</div>
<GxState v-if="state.state === 'sending'" loading>{{ state.message || 'Sending logs' }}…</GxState>
<GxNotice v-else-if="state.state === 'sent'" tone="success">{{ state.message }}</GxNotice>
<GxNotice v-else-if="state.state === 'failed'" tone="danger">{{ state.message }}</GxNotice>
<GxNotice v-if="state.error" tone="danger">{{ state.error }}</GxNotice>
</section>`,
}
@@ -0,0 +1,300 @@
// Live preview of the detector's full-screen warning, drawn the way onroad_uniden.py draws it on the car screen.
// Runs only while it is on screen and the page is visible, and holds still under reduced motion.
const W = 1860, H = 1080, FRAME = 30
const CONTENT = { x: FRAME, y: FRAME, w: W - 2 * FRAME, h: H - 2 * FRAME }
const RADIUS = 0.12 * CONTENT.h / 2
const EDGE_GAP = 12, EDGE_LINE = 8, DASH = 56, DASH_GAP = 30
const GLOW_DEPTH = [35, 135], GLOW_STEPS = 12, VEIL_ALPHA = 0.62
const CHEVRON = { size: 48, width: 13, fromSpeed: 300, fromEdge: 44 }
const BAND_RANK = { K: 0, KA: 1, LASER: 2 }
const FREQUENCY = { K: '24.150 GHz', KA: '34.700 GHz', LASER: '' }
// Galaxy update progress colors, secondary teal to primary purple, as the card's signal bars draw them.
export function signalColor(strength, index) {
const t = index / Math.max(1, strength - 1)
return `rgb(${Math.round(77 + 80 * t)},${Math.round(232 - 118 * t)},${Math.round(232 + 23 * t)})`
}
export const chevronCount = strength => Math.ceil(Math.min(8, Math.max(1, strength)) / 2)
// Brightness before pulses, mute and fade: the line and chevrons stay bright; with the glow, strength sets it.
export function edgeAlpha(parts, band, strength) {
const s = (strength - 1) / 7
return parts.glow ? (band === 'LASER' ? 0.95 : 0.45 + 0.45 * s) : (band === 'LASER' ? 1 : 0.85)
}
// The same pulse rules as EdgeMotion on the device.
export class EdgeMotion {
constructor() { this.alert = null; this.baseline = 0; this.pulses = []; this.ended = null }
update(alert, now, still) {
if (!alert) { if (this.alert) { this.ended = [now, this.alert]; this.alert = null } return }
const previous = this.alert
this.alert = alert; this.ended = null
const fresh = !previous || previous.band !== alert.band
if (fresh) {
this.baseline = alert.strength
if (!previous || (BAND_RANK[alert.band] ?? 0) > (BAND_RANK[previous.band] ?? 0))
this.pulse(now, still, alert.band === 'LASER' ? 3 : previous ? 1 : 2)
} else if (alert.strength >= this.baseline + 2) {
this.baseline = alert.strength
this.pulse(now, still, 1)
} else this.baseline = Math.min(this.baseline, alert.strength)
}
pulse(now, still, count) { if (!still) this.pulses.push([now, count, count === 3 ? 0.25 : 0.3]) }
boost(now) {
this.pulses = this.pulses.filter(([at, count, period]) => now - at < count * period)
return this.pulses.reduce((best, [at, , period]) => Math.max(best, Math.sin(Math.PI * (((now - at) / period) % 1))), 0)
}
fading(now) {
if (!this.ended || now - this.ended[0] >= 0.5) { this.ended = null; return null }
return [this.ended[1], 1 - (now - this.ended[0]) / 0.5]
}
}
function roundRect(ctx, x, y, w, h, r) {
r = Math.max(0, Math.min(r, w / 2, h / 2))
ctx.beginPath()
ctx.moveTo(x + r, y); ctx.arcTo(x + w, y, x + w, y + h, r); ctx.arcTo(x + w, y + h, x, y + h, r)
ctx.arcTo(x, y + h, x, y, r); ctx.arcTo(x, y, x + w, y, r); ctx.closePath()
}
const rgba = (rgb, a) => `rgba(${rgb[0]},${rgb[1]},${rgb[2]},${Math.max(0, Math.min(1, a)).toFixed(3)})`
const hexRgb = hex => { const n = parseInt(hex.slice(1, 7), 16); return [n >> 16 & 255, n >> 8 & 255, n & 255] }
function glowRing(ctx, depth, alpha, rgb) {
const band = depth / GLOW_STEPS
for (let i = 0; i < GLOW_STEPS; i++) {
const inset = i * band + band / 2, fall = 1 - i / GLOW_STEPS
ctx.strokeStyle = rgba(rgb, alpha * fall * fall); ctx.lineWidth = band + 0.6
roundRect(ctx, CONTENT.x + inset, CONTENT.y + inset, CONTENT.w - 2 * inset, CONTENT.h - 2 * inset, RADIUS - inset)
ctx.stroke()
}
}
function sideGlow(ctx, side, depth, alpha, rgb) {
const { x, y, w, h } = CONTENT
const geometry = { top: [0, y, 0, y + depth, x + RADIUS, y, w - 2 * RADIUS, depth],
bottom: [0, y + h, 0, y + h - depth, x + RADIUS, y + h - depth, w - 2 * RADIUS, depth],
left: [x, 0, x + depth, 0, x, y + RADIUS, depth, h - 2 * RADIUS],
right: [x + w, 0, x + w - depth, 0, x + w - depth, y + RADIUS, depth, h - 2 * RADIUS] }[side]
const g = ctx.createLinearGradient(...geometry.slice(0, 4))
g.addColorStop(0, rgba(rgb, alpha)); g.addColorStop(0.45, rgba(rgb, alpha * 0.35)); g.addColorStop(1, rgba(rgb, 0))
ctx.fillStyle = g; ctx.fillRect(...geometry.slice(4))
}
function chevronSets(direction, speedX) {
const top = [['top', speedX - CHEVRON.fromSpeed], ['top', speedX + CHEVRON.fromSpeed]]
return { front: top, '': top, rear: [['bottom', speedX]], side: [['left', H / 2], ['right', H / 2]] }[direction] || top
}
function drawChevrons(ctx, direction, strength, color, speedX) {
const { size, fromEdge } = CHEVRON
ctx.lineWidth = CHEVRON.width; ctx.strokeStyle = color; ctx.lineCap = 'butt'; ctx.lineJoin = 'miter'
for (const [side, along] of chevronSets(direction, speedX)) {
for (let i = 0; i < chevronCount(strength); i++) {
const off = fromEdge + i * size * 0.8 + size * 0.4
const [cx, cy, dx, dy] = { top: [along, CONTENT.y + off, 0, -1], bottom: [along, CONTENT.y + CONTENT.h - off, 0, 1],
left: [CONTENT.x + off, along, -1, 0], right: [CONTENT.x + CONTENT.w - off, along, 1, 0] }[side]
ctx.beginPath()
ctx.moveTo(cx - dy * size - dx * size * 0.5, cy + dx * size - dy * size * 0.5)
ctx.lineTo(cx + dx * size * 0.5, cy + dy * size * 0.5)
ctx.lineTo(cx + dy * size - dx * size * 0.5, cy - dx * size - dy * size * 0.5)
ctx.stroke()
}
}
}
// Draw one alert in the Edge style. `look` is { parts, color, mutedPercent }.
export function drawEdge(ctx, alert, look, boost, presence, speedX = W / 2) {
const mute = alert.muted ? look.mutedPercent / 100 : 1
if (mute === 0) return
const { parts } = look, rgb = hexRgb(look.color), s = (alert.strength - 1) / 7
const alpha = Math.min(1, edgeAlpha(parts, alert.band, alert.strength) * (1 + 0.9 * boost)) * mute * presence
const depth = (GLOW_DEPTH[0] + (GLOW_DEPTH[1] - GLOW_DEPTH[0]) * s) * (1 + 0.35 * boost)
const sides = { front: ['top'], rear: ['bottom'], side: ['left', 'right'] }[alert.direction]
ctx.save()
roundRect(ctx, CONTENT.x, CONTENT.y, CONTENT.w, CONTENT.h, RADIUS); ctx.clip()
if (parts.veil) glowRing(ctx, depth * 1.3, VEIL_ALPHA * Math.min(1, alpha / 0.6), [0, 0, 0])
if (parts.glow && sides) {
glowRing(ctx, Math.max(18, depth * 0.3), alpha * 0.5, rgb)
for (const side of sides) sideGlow(ctx, side, depth * 1.6, alpha, rgb)
} else if (parts.glow) glowRing(ctx, depth, alpha, rgb)
ctx.restore()
if (parts.line) {
const half = EDGE_GAP + EDGE_LINE / 2
ctx.lineWidth = EDGE_LINE; ctx.strokeStyle = rgba(rgb, alpha * 1.15)
ctx.setLineDash(parts.dashes ? [DASH, DASH_GAP] : [])
roundRect(ctx, CONTENT.x + half, CONTENT.y + half, CONTENT.w - 2 * half, CONTENT.h - 2 * half, RADIUS - half); ctx.stroke()
ctx.setLineDash([])
}
if (parts.chevrons) drawChevrons(ctx, alert.direction, alert.strength, rgba(rgb, alpha * 1.1), speedX)
}
function curveGlow(ctx, kind, t) {
if (kind === 'off') return
const s = { learning: 0.7, gentle: 0.79, tight: 1 }[kind], f = (s - 0.7) / 0.3
const blend = (a, b, x) => a.map((v, i) => v + Math.trunc((b[i] - v) * Math.max(0, Math.min(1, x))))
const rgb = kind === 'learning' ? [112, 192, 216] : f < 0.5 ? blend([34, 197, 94], [251, 191, 36], f / 0.5) :
f < 0.6 ? blend([251, 191, 36], [234, 88, 12], (f - 0.5) / 0.1) : blend([234, 88, 12], [201, 34, 49], (f - 0.6) / 0.4)
const cycle = 4.5 / (1 + 2 * f), amplitude = 0.3 + 0.7 * f
const breath = Math.max(0, Math.min(1, 0.5 + amplitude * Math.sin((t % cycle) / cycle * 2 * Math.PI)))
const alpha = 200 * s * (0.6 + 0.4 * breath) / 255, span = 75, { x, y, w, h } = CONTENT
for (const [x0, y0, x1, y1, rx, ry, rw, rh] of [[0, y, 0, y + span, x, y, w, span], [0, y + h, 0, y + h - span, x, y + h - span, w, span],
[x, 0, x + span, 0, x, y, span, h], [x + w, 0, x + w - span, 0, x + w - span, y, span, h]]) {
const g = ctx.createLinearGradient(x0, y0, x1, y1)
g.addColorStop(0, rgba(rgb, alpha)); g.addColorStop(1, rgba(rgb, 0))
ctx.fillStyle = g; ctx.fillRect(rx, ry, rw, rh)
}
}
function paintRoad(canvas) {
const g = canvas.getContext('2d')
const sky = g.createLinearGradient(0, 0, 0, H * 0.55)
sky.addColorStop(0, '#5f87a8'); sky.addColorStop(1, '#c9d3d6')
g.fillStyle = sky; g.fillRect(0, 0, W, H * 0.55)
g.fillStyle = '#3d4a3c'; g.fillRect(0, H * 0.47, W, H * 0.1)
const asphalt = g.createLinearGradient(0, H * 0.55, 0, H)
asphalt.addColorStop(0, '#5a5e63'); asphalt.addColorStop(1, '#2c2f33')
g.fillStyle = '#7f8f74'; g.fillRect(0, H * 0.55, W, H * 0.45)
g.fillStyle = asphalt
g.beginPath(); g.moveTo(W * 0.47, H * 0.55); g.lineTo(W * 0.53, H * 0.55); g.lineTo(W * 1.05, H); g.lineTo(-W * 0.05, H); g.closePath(); g.fill()
g.strokeStyle = 'rgba(240,240,230,.85)'; g.lineWidth = 8
for (let i = 0; i < 6; i++) { const t0 = 0.56 + i * 0.075; g.beginPath(); g.moveTo(W / 2, H * t0); g.lineTo(W / 2, H * (t0 + 0.035)); g.stroke() }
}
function drawCard(ctx, alert, font) {
const x = 700, y = 560, w = 460, h = 76
roundRect(ctx, x, y, w, h, 14); ctx.fillStyle = 'rgba(0,0,0,.62)'; ctx.fill()
ctx.font = `600 23px ${font}`
const muteWidth = alert.muted ? ctx.measureText('MUTED').width : 0
ctx.save()
if (alert.muted) {
ctx.beginPath(); ctx.rect(x - 2, y - 2, w + 4, h + 4)
ctx.rect(x + w - 36 - muteWidth, y - 2, muteWidth + 16, 4); ctx.clip('evenodd')
}
roundRect(ctx, x, y, w, h, 14)
ctx.lineWidth = 2; ctx.strokeStyle = '#9D72FF'; ctx.stroke()
ctx.restore()
const tone = alert.band === 'K' ? '#FFBA4E' : '#FF5B65'
ctx.textBaseline = 'middle'
ctx.fillStyle = tone; ctx.font = `600 36px ${font}`; ctx.fillText({ K: 'K', KA: 'Ka', LASER: 'Laser' }[alert.band], x + 24, y + h / 2)
ctx.fillStyle = '#fff'; ctx.font = `600 28px ${font}`; ctx.fillText(FREQUENCY[alert.band] || 'Gatso', x + 112, y + h / 2)
const barsX = x + w - 160
for (let i = 0; i < 8; i++) {
const bh = 8 + i * 3
ctx.fillStyle = i < alert.strength ? signalColor(alert.strength, i) : '#35434d'
ctx.fillRect(barsX + i * 11, y + h / 2 + 15 - bh, 8, bh)
}
if (alert.muted) {
ctx.font = `600 23px ${font}`; ctx.fillStyle = '#FF5B65'; ctx.fillText('MUTED', x + w - 28 - muteWidth, y + 1)
}
}
// Preview scenarios: what is on the road, not settings. `drive` plays a scripted pass on repeat.
const scene = (label, band, strength, direction, extra = {}) => ({ label, alert: { band, strength, direction, muted: false, ...extra.alert }, curve: extra.curve || 'off', border: extra.border || '#167F40' })
// Grouped by setting, then K, Ka and Laser together inside each group.
export const PREVIEW_SCENARIOS = {
'On the road': {
drive: { label: 'K drive-by: builds, gets muted, passes', script: true, curve: 'off', border: '#167F40' },
'k-ahead': scene('K ahead', 'K', 4, 'front'),
'k-weak': scene('K ahead, weak', 'K', 1, 'front'),
'k-behind': scene('K behind', 'K', 3, 'rear'),
'k-muted': scene('K muted on the detector', 'K', 4, 'front', { alert: { muted: true } }),
r4: scene('K on an R4, no direction', 'K', 4, ''),
'ka-strong': scene('Ka ahead, strong', 'KA', 7, 'front'),
'ka-beside': scene('Ka beside', 'KA', 5, 'side'),
laser: scene('Laser', 'LASER', 8, 'front'),
},
'With openpilot': {
'learning-curve': scene('K while curves are learning', 'K', 4, 'front', { curve: 'learning' }),
experimental: scene('K in Experimental mode', 'K', 4, 'front', { border: '#DA6F25' }),
chill: scene('K in Chill mode', 'K', 4, 'front', { border: '#FFD600' }),
disengaged: scene('K while disengaged', 'K', 4, 'front', { border: '#122839' }),
'tight-curve': scene('Ka in a tight curve', 'KA', 5, 'front', { curve: 'tight' }),
switchback: scene('Ka with Switchback', 'KA', 5, 'side', { border: '#8B6CC5' }),
'laser-curve': scene('Laser in a tight curve', 'LASER', 8, 'front', { curve: 'tight' }),
},
}
export const previewScenario = id => Object.values(PREVIEW_SCENARIOS).map(group => group[id]).find(Boolean) || PREVIEW_SCENARIOS['On the road'].drive
// One pass, as on the road: [seconds, change]. The pass repeats after it ends.
const DRIVE = [[0.4, { active: true }], [1.6, { strength: 3 }], [2.6, { strength: 4 }], [3.6, { strength: 6 }], [5.6, { muted: true }],
[7.2, { direction: 'side' }], [8.2, { strength: 4 }], [9, { direction: 'rear', strength: 2 }], [10.4, { active: false }]]
const DRIVE_START = { active: false, band: 'K', strength: 2, direction: 'front', muted: false }, DRIVE_LAP = 12
export const EdgePreview = {
props: { config: { type: Object, required: true }, swatches: { type: Object, required: true },
scenario: { type: String, default: 'drive' }, replay: { type: Number, default: 0 } },
watch: {
scenario() { this.restart() },
replay() { this.restart() },
config: { deep: true, handler() { this.loop() } },
},
mounted() {
this.visible = true
this.road = document.createElement('canvas'); this.road.width = W; this.road.height = H; paintRoad(this.road)
this.reduce = window.matchMedia('(prefers-reduced-motion: reduce)')
this.font = getComputedStyle(document.body).fontFamily || 'system-ui, sans-serif'
this.observer = typeof IntersectionObserver === 'function' ? new IntersectionObserver(([entry]) => { this.visible = entry.isIntersecting; this.loop() }) : null
this.observer?.observe(this.$el)
this.onVisibility = () => this.loop()
document.addEventListener('visibilitychange', this.onVisibility)
this.restart()
},
unmounted() {
cancelAnimationFrame(this.frame); this.frame = null
this.observer?.disconnect(); document.removeEventListener('visibilitychange', this.onVisibility)
},
methods: {
now() { return performance.now() / 1000 },
still() { return this.reduce.matches },
restart() {
this.motion = new EdgeMotion(); this.started = this.now(); this.step = -1
const chosen = previewScenario(this.scenario)
this.state = chosen.script ? { ...DRIVE_START } : { active: true, ...chosen.alert }
this.motion.update(this.alert(), this.started, this.still())
this.loop()
},
alert() { return this.state.active ? { band: this.state.band, strength: this.state.strength, direction: this.state.direction, muted: this.state.muted } : null },
// Advance the scripted pass to time t; the pass restarts after DRIVE_LAP seconds.
advance(t) {
if (!previewScenario(this.scenario).script) return
if (t - this.started >= DRIVE_LAP) { this.restart(); return }
while (this.step + 1 < DRIVE.length && t - this.started >= DRIVE[this.step + 1][0]) {
this.step++; Object.assign(this.state, DRIVE[this.step][1])
this.motion.update(this.alert(), t, this.still())
}
},
look(band) {
return { parts: this.config.border_edge, color: this.swatches[this.config.border_colors[band]] || '#FFFFFF',
mutedPercent: this.config.border_muted_percent }
},
loop() {
const running = this.visible && !document.hidden && !this.still()
if (running && !this.frame) this.frame = requestAnimationFrame(() => { this.frame = null; this.draw(); this.loop() })
else if (!running) this.draw()
},
draw() {
const canvas = this.$el
if (!canvas?.getContext) return
const t = this.now(), chosen = previewScenario(this.scenario)
// With motion reduced the pass would never move, so show its strongest moment instead.
if (this.still() && chosen.script) Object.assign(this.state, { active: true, strength: 6, muted: false, direction: 'front' })
else this.advance(t)
const ctx = canvas.getContext('2d')
ctx.fillStyle = '#000'; ctx.fillRect(0, 0, W, H)
ctx.save(); roundRect(ctx, CONTENT.x, CONTENT.y, CONTENT.w, CONTENT.h, RADIUS); ctx.clip()
ctx.drawImage(this.road, 0, 0); ctx.fillStyle = 'rgba(0,0,0,.18)'; ctx.fillRect(0, 0, W, H); ctx.restore()
curveGlow(ctx, chosen.curve, t)
let alert = this.alert(), presence = 1
if (!alert) { const fade = this.motion.fading(t); if (fade) [alert, presence] = fade }
if (alert && this.config.border_bands.includes(alert.band)) drawEdge(ctx, alert, this.look(alert.band), this.motion.boost(t), presence)
ctx.lineWidth = FRAME; ctx.strokeStyle = chosen.border
roundRect(ctx, CONTENT.x - FRAME / 2, CONTENT.y - FRAME / 2, CONTENT.w + FRAME, CONTENT.h + FRAME, RADIUS + FRAME / 2); ctx.stroke()
ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'alphabetic'
ctx.font = `700 150px ${this.font}`; ctx.fillText('47', W / 2, 220)
ctx.font = `500 34px ${this.font}`; ctx.fillText('mph', W / 2, 262); ctx.textAlign = 'left'
if (this.state.active) drawCard(ctx, this.state, this.font)
},
},
template: `<canvas class="gx-layout__preview gx-uniden__preview-canvas" width="1860" height="1080" role="img" aria-label="Preview of the full-screen warning on the driving screen"></canvas>`,
}
+430
View File
@@ -0,0 +1,430 @@
import { EdgePreview, PREVIEW_SCENARIOS, previewScenario } from './uniden-preview.js'
import { GalaxySelect } from './galaxy-select.js'
import { GxDialog } from './dialog.js'
import { guardUnload } from './unload-guard.js'
export function detectorStatus(state) {
if (state?.connected) return { label: 'Connected', detail: 'Ready to receive detector alerts.', tone: 'connected' }
const code = state?.connection_state
if (code === 'radio_off') return { label: 'Bluetooth off', detail: 'Turn on Bluetooth on the Devices tab.', tone: 'waiting' }
if (code === 'detector_pairing_required') return { label: 'Check pairing', detail: 'Pair the detector in Bluetooth, then select it here.', tone: 'waiting' }
if (code === 'session_expired') return { label: 'Sign in required', detail: 'Sign in to Galaxy again to reconnect.', tone: 'waiting' }
if (code === 'busy') return { label: 'Waiting for Bluetooth', detail: 'Finish any device search or pairing. Connection will resume automatically.', tone: 'waiting' }
if (code === 'unavailable') return { label: 'Connection unavailable', detail: 'Check that the detector is on and another app is not connected. Retrying automatically.', tone: 'waiting' }
return { label: 'Reconnecting', detail: 'Keep the detector on and close other apps connected to it. Retrying automatically.', tone: 'waiting' }
}
const LEARNING_ROWS = 5
let nextRuleId = 0
// A client-only id keeps each rule row stable; normalize_rules takes exact fields, so it is stripped before saving.
const ruleIds = (rules, previous = []) => rules.map((rule, index) => ({ ...rule, uid: previous[index]?.uid ?? ++nextRuleId }))
export const savedConfig = config => ({ ...config, frequency_rules: config.frequency_rules.map(({ uid, ...rule }) => rule) })
export const detectorConfig = (value = {}, previous = []) => {
const config = { ...defaults(), ...value }
config.frequency_rules = ruleIds(config.frequency_rules, previous)
config.timed_mute_settings = Object.fromEntries(['X', 'K', 'KA'].map(band => [band,
{ seconds: config.timed_mute_seconds, strength: config.timed_mute_strength, ...value.timed_mute_settings?.[band] }]))
return config
}
const defaults = () => ({ enabled: false, address: '', model: 'R8',
auto_mute: false, hide_filtered: false, hide_below_limit: false, hide_q_ride: false, hide_mute_memory: false, frequency_rules: [], quiet_ride: false, quiet_margin: 0, quiet_bands: ['X', 'K'],
auto_learn: false, learn_bands: ['X', 'K'], border_bands: ['KA', 'LASER'], border_colors: { KA: 'coral', K: 'amber', LASER: 'coral' },
border_edge: { line: true, dashes: true, glow: false, veil: false, chevrons: true }, border_muted_percent: 50,
timed_mute: false, timed_mute_seconds: 5, timed_mute_strength: 6, timed_mute_bands: ['X', 'K', 'KA'] })
export const SWATCHES = { amber: '#FFBA4E', coral: '#FF5B65', magenta: '#FF1FCE', ice: '#9FE8FF', lime: '#A6FF00', white: '#FFFFFF', ultraviolet: '#7A1FFF' }
export const EDGE_PARTS = {
line: ['Line along the border', 'A line just inside the openpilot border.'],
dashes: ['Segmented line', 'Break the line into dashes so it never reads as the openpilot border.'],
glow: ['Soft glow band', 'A glow fading in from the edge. Deeper and brighter as the signal grows.'],
veil: ['Dark veil under the line', 'Darken the edge of the picture so the line stands out in daylight.'],
chevrons: ['Chevrons', 'Point toward the signal: beside the speed for ahead, at the bottom for behind, on both sides for beside. One to four chevrons show strength. An R4 shows them beside the speed.'],
}
// Ka and laser are what police radar and lidar use, so learning them asks first.
export const LEARN_WARNINGS = {
KA: { title: 'Learn Ka lockouts automatically?', body: 'Ka is the band most police radar uses. A learned Ka lockout keeps that signal quiet at that place on later drives, so a real radar set up there could go unannounced. StarPilot learns a Ka source only after five separate passes, and a signal stronger than any seen there still alerts.' },
LASER: { title: 'Learn laser lockouts automatically?', body: 'Laser is almost always police lidar aimed at you, and by the time it alerts the reading is usually taken. A learned laser lockout keeps laser quiet at that place on later drives. StarPilot learns a laser source only after five separate passes.' },
}
const BAND_SCENARIO = { K: 'k-ahead', KA: 'ka-strong', LASER: 'laser' }
const BANDS = { X: 'X', K: 'K', KA: 'Ka', LASER: 'Laser' }
const copy = value => JSON.parse(JSON.stringify(value))
export const UnidenPanel = {
components: { EdgePreview, GalaxySelect, GxDialog },
props: { devices: { type: Array, default: () => [] }, parked: Boolean, unauthorized: Function, settings: Boolean },
data: () => ({ config: detectorConfig(), saved: null, loaded: false, busy: false, error: '', state: null, editing: false,
locks: [], candidates: 0, learning: [], metric: false, swatches: SWATCHES, edgeParts: EDGE_PARTS, bands: BANDS,
scenarios: PREVIEW_SCENARIOS, scenario: 'drive', panel: 'alerts',
sections: { alerts: 'Preferences', warning: 'Colors', frequencies: 'Rules', lockouts: 'Lockouts' }, replay: 0, leaveAction: null, leaveModal: false, confirmLearn: null, learnWarnings: LEARN_WARNINGS }),
computed: {
detectors() { return this.devices.filter(d => d.paired && /(?:^|[^a-z0-9])r[48]w?(?=$|[^a-z0-9])/i.test(d.name)) },
selected() { return this.detectors.find(d => d.address.toUpperCase() === this.config.address.toUpperCase()) },
dirty() { return this.saved !== null && JSON.stringify(this.config) !== JSON.stringify(this.saved) },
ready() { return !!this.saved?.address && this.detectors.some(d => d.address.toUpperCase() === this.saved.address.toUpperCase()) },
leaveInline() { return !!this.leaveAction && !this.leaveModal },
learningOn() { return !!this.config.auto_learn },
learningRows() {
const bands = this.config.learn_bands || []
return this.learning.slice(0, LEARNING_ROWS).map(item => ({ ...item, learnable: bands.includes(item.band),
percent: Math.min(100, Math.round(item.count / item.need * 100)), left: Math.max(0, item.need - item.count),
stage: item.need - item.count <= 1 ? 'Locks out next pass' : item.count * 2 < item.need ? 'Just started' : 'Learning' }))
},
learningTitle() {
if (!this.learningOn) return 'Learning is off'
const count = this.learning.length
return count ? `Learning ${count} ${count === 1 ? 'source' : 'sources'}` : 'Learning: watching for repeat sources'
},
savedName() { return this.detectors.find(d => d.address.toUpperCase() === this.saved?.address)?.name || (this.saved?.address ? `Uniden ${this.saved.model}` : 'Select your detector') },
connection() {
if (!this.saved?.address) return { label: 'Not configured', detail: 'Choose a paired detector to get started.', tone: 'waiting' }
if (!this.ready) return { label: 'Not paired', detail: 'Pair the selected detector again on the Devices tab.', tone: 'waiting' }
if (!this.saved.enabled) return { label: 'Integration off', detail: 'Enable the integration below to receive alerts.', tone: 'off' }
return detectorStatus(this.state)
},
},
mounted() {
this.alive = true; this.epoch = 0
this.visibility = () => { clearTimeout(this.timer); this.locksLoaded = false; if (!document.hidden) this.refresh() }
document.addEventListener('visibilitychange', this.visibility)
if (!document.hidden) this.refresh()
this.stopUnloadGuard = guardUnload(() => this.dirty || this.busy)
},
updated() { this.measureEditor() },
beforeUnmount() { this.resizer?.disconnect(); this.stopUnloadGuard?.(); this.alive = false; this.epoch++; clearTimeout(this.timer); document.removeEventListener('visibilitychange', this.visibility) },
methods: {
async request(payload) {
const response = await fetch('./api/bluetooth/uniden', { method: 'POST', credentials: 'same-origin',
headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), signal: AbortSignal.timeout(15000) })
const value = await response.json()
if (response.status === 401) this.unauthorized?.()
if (!response.ok) throw new Error(value.error || 'Detector unavailable')
return value
},
async refresh() {
if (!this.alive || this.busy || document.hidden) return
const epoch = ++this.epoch
try {
const value = await this.request({ operation: 'status' })
if (!this.alive || this.epoch !== epoch) return
this.state = value
if (!this.locksLoaded) { this.locksLoaded = true; this.loadLocks() }
if (!this.loaded || !this.dirty && !this.editing) {
this.config = copy(detectorConfig(value.config, this.saved?.frequency_rules)); this.saved = copy(this.config)
if (!this.loaded) this.error = ''
this.loaded = true
}
} catch {
if (this.alive && this.epoch === epoch) {
this.state = { connected: false, alerts: [], connection_state: 'unavailable' }
if (!this.loaded) this.error = 'Unable to load detector settings. Retrying automatically.'
}
}
finally { if (this.alive && this.epoch === epoch && !document.hidden) this.timer = setTimeout(() => this.refresh(), 2000) }
},
// The pinned save bar and preview set where the section tabs stick on narrow screens, as in the theme maker.
measureEditor() {
const editor = this.$refs.editor
if (!editor || this.measured === editor || typeof ResizeObserver !== 'function') return
this.resizer?.disconnect(); this.measured = editor
this.resizer = new ResizeObserver(() => {
const bar = this.$refs.leaveBar, pin = editor.querySelector('.gx-uniden__preview-card')
if (bar) editor.style.setProperty('--layout-bar-h', bar.offsetHeight + 'px')
if (pin) editor.style.setProperty('--layout-pin-h', getComputedStyle(pin).position === 'sticky' ? pin.offsetHeight + 'px' : '0px')
})
for (const el of [this.$refs.leaveBar, editor.querySelector('.gx-uniden__preview-card'), editor]) if (el) this.resizer.observe(el)
},
// Turning on Ka or laser learning waits for the dialog; turning anything off, or X and K on, is immediate.
requestLearnBand(band) {
if (band in LEARN_WARNINGS && !this.config.learn_bands.includes(band)) this.confirmLearn = band
else this.toggleBand('learn_bands', band)
},
confirmLearnBand() {
const band = this.confirmLearn
this.confirmLearn = null
if (band && !this.config.learn_bands.includes(band)) this.toggleBand('learn_bands', band)
},
// Show the band being colored: switch the preview to that band's scenario, or replay it if it is already showing.
pickColor(band, name) {
this.config.border_colors[band] = name
const showing = previewScenario(this.scenario).script ? 'K' : previewScenario(this.scenario).alert.band
if (showing === band) this.replay++
else this.scenario = BAND_SCENARIO[band]
},
toggleBand(key, band) {
const list = this.config[key]
this.config[key] = list.includes(band) ? list.filter(item => item !== band) : [...list, band]
},
async unlock(id) { await this.loadLocks({ operation: 'unlock', id }) },
async loadLocks(payload = { operation: 'locks' }) {
try {
const value = await this.request(payload)
if (this.alive) { this.locks = value.locks; this.candidates = value.candidates; this.learning = value.learning || []; this.metric = value.metric }
} catch (error) { if (this.alive && payload.operation === 'unlock') this.error = error.message }
},
lockLabel(lock) { return BANDS[lock.band] + (lock.frequency ? ` ${lock.frequency.toFixed(3)} GHz` : '') },
lockDetail(lock) {
return `${lock.count} ${lock.count === 1 ? 'pass' : 'passes'} · ${lock.lat.toFixed(4)}, ${lock.lon.toFixed(4)} · ${lock.radius_m} m`
},
selectDetector() {
const match = this.selected?.name.match(/(?:^|[^a-z0-9])(r[48])w?(?=$|[^a-z0-9])/i)
if (match) { this.config.model = match[1].toUpperCase(); this.config.enabled = true }
},
ruleRange(rule) {
const frequency = Number(rule.frequency), tolerance = Number(rule.tolerance_mhz)
if (rule.frequency === '' || rule.tolerance_mhz === '' || !Number.isFinite(frequency) || !Number.isFinite(tolerance) || tolerance < 0) return 'Enter a frequency and tolerance.'
return tolerance === 0 ? `Matches ${frequency.toFixed(3)} GHz exactly` :
`Matches ${(frequency - tolerance / 1000).toFixed(4)}–${(frequency + tolerance / 1000).toFixed(4)} GHz`
},
cancel() { this.config = copy(this.saved); this.editing = false; this.error = '' },
// The same leave flow as the theme maker: an inline prompt in the save bar, or a dialog when leaving from the menu.
requestLeave(proceed, presentation = 'inline') {
if (this.busy) return
if (!this.dirty) { proceed(); return }
this.leaveAction = proceed
this.leaveModal = presentation === 'modal'
if (!this.leaveModal) this.$nextTick(() => {
const bar = this.$refs.leaveBar
bar?.scrollIntoView({ block: 'nearest', behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'instant' : 'smooth' })
bar?.querySelector('button')?.focus({ preventScroll: true })
})
},
cancelLeave() { if (!this.busy) { this.leaveAction = null; this.leaveModal = false } },
discardAndLeave() {
const proceed = this.leaveAction
this.cancelLeave(); this.cancel(); proceed?.()
},
async saveAndLeave() {
const proceed = this.leaveAction
await this.save()
if (!this.dirty && this.leaveAction === proceed) { this.cancelLeave(); proceed?.() }
},
addRule() {
if (this.config.frequency_rules.length < 32) this.config.frequency_rules.push({ uid: ++nextRuleId, enabled: true, label: '', band: 'KA', frequency: 34.313, tolerance_mhz: 0 })
},
async save() {
if (!this.parked || this.busy || !this.dirty || !this.selected) return
this.busy = true
this.epoch++
clearTimeout(this.timer)
try {
const value = await this.request({ operation: 'configure', config: savedConfig(copy(this.config)) })
if (this.alive) {
this.state = this.saved?.address === value.config.address ? { ...this.state, config: value.config } : value
const config = detectorConfig(value.config, this.config.frequency_rules)
this.config = copy(config); this.saved = copy(config); this.error = ''; this.editing = false
}
} catch (error) { if (this.alive) this.error = error.message }
finally { this.busy = false; if (this.alive) this.refresh() }
},
},
template: `<div class="gx-uniden">
<p v-if="!loaded" class="gx-note" role="status">Loading detector setup…</p>
<p v-if="error" role="alert" class="gx-uniden__error">{{ error }}</p>
<template v-if="loaded">
<section class="gx-card gx-uniden__detector" :class="{ 'gx-uniden__detector--compact': ready && !editing }" aria-label="Detector connection">
<div class="gx-panel gx-stack">
<div v-if="ready && !editing" class="gx-uniden__summary">
<div class="gx-uniden__summary-text">
<div class="gx-uniden__summary-title"><h3>{{ savedName }}</h3><span class="gx-uniden__status" :class="'gx-uniden__status--' + connection.tone" role="status">{{ connection.label }}</span></div>
<p class="gx-note">{{ connection.detail }}</p>
</div>
<div class="gx-uniden__summary-actions">
<a v-if="!settings" class="gx-btn" href="#/bluetooth/uniden">Uniden settings</a>
<button class="gx-btn gx-btn--tonal" type="button" :disabled="!parked || busy || dirty" aria-label="Change detector" @click="editing = true">Change</button>
</div>
</div>
<template v-else>
<div class="gx-uniden__heading">
<div><span class="gx-uniden__eyebrow">DETECTOR</span><h3>{{ savedName }}</h3></div>
<span class="gx-uniden__status" :class="'gx-uniden__status--' + connection.tone" role="status">{{ connection.label }}</span>
</div>
<p class="gx-note">{{ connection.detail }}</p>
</template>
<template v-if="!ready || editing">
<p v-if="!detectors.length" class="gx-note">No paired detector found. <a class="gx-link" href="#/bluetooth">Pair in Bluetooth</a>, then return here.</p>
<fieldset v-else :disabled="!parked || busy" class="gx-uniden__fieldset gx-stack">
<label class="gx-uniden__field">Detector <select v-model="config.address" @change="selectDetector" class="gx-field" aria-label="Uniden detector"><option value="">Select a paired detector</option>
<option v-for="d in detectors" :key="d.address" :value="d.address">{{ d.name }} · {{ d.address }}</option></select></label>
<p class="gx-note">{{ selected ? config.model + ' detected. Saving enables the integration.' : 'Choose a paired detector to finish setup.' }}</p>
<div class="gx-actions"><button class="gx-btn" type="button" :disabled="!dirty || !selected" @click="save">{{ busy ? 'Saving…' : saved.address ? 'Save changes' : 'Use this detector' }}</button>
<button v-if="ready" class="gx-btn gx-btn--tonal" type="button" @click="cancel">Cancel</button></div>
</fieldset>
</template>
</div>
</section>
<p v-if="!parked" class="gx-note">Park to change detector settings.</p>
<div v-if="settings && ready && !editing" ref="editor" class="gx-layout gx-uniden-editor">
<div ref="leaveBar" class="gx-layout__savebar" :class="{'gx-layout__savebar--leave': leaveInline}">
<span role="status" :class="{'is-dirty': dirty && !leaveInline && !busy}">{{ leaveInline ? 'Leave without saving your changes?' : busy ? 'Saving…' : !parked ? 'Park to change settings' : dirty ? 'Unsaved' : 'Saved' }}</span>
<template v-if="leaveInline">
<button class="gx-btn gx-btn--tonal" type="button" aria-label="Keep editing" title="Keep editing" @click="cancelLeave"><svg class="gx-layout__action-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 12a8 8 0 1 0 3-6M4 4v6h6"/></svg><span class="gx-layout__action-label">Keep editing</span></button>
<button class="gx-btn gx-btn--danger" type="button" aria-label="Discard and leave" title="Discard and leave" @click="discardAndLeave"><svg class="gx-layout__action-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 7h16M9 7V4h6v3m-8 0 1 13h8l1-13"/></svg><span class="gx-layout__action-label">Discard and leave</span></button>
<button class="gx-btn" type="button" :disabled="!parked || busy" aria-label="Save changes" title="Save changes" @click="saveAndLeave"><svg class="gx-layout__action-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 3h12l4 4v14H3V3h2Zm2 0v6h10V3M7 21v-8h10v8"/></svg><span class="gx-layout__action-label">{{ busy ? 'Saving…' : 'Save changes' }}</span></button>
</template>
<template v-else>
<button class="gx-btn gx-btn--tonal" type="button" :disabled="!dirty || busy" aria-label="Discard changes" title="Discard changes" @click="cancel"><svg class="gx-layout__action-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 7h16M9 7V4h6v3m-8 0 1 13h8l1-13"/></svg><span class="gx-layout__action-label">Discard</span></button>
<button class="gx-btn gx-layout__save" type="button" :disabled="!parked || busy || !dirty" aria-label="Save changes" title="Save changes" @click="save"><svg class="gx-layout__action-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 3h12l4 4v14H3V3h2Zm2 0v6h10V3M7 21v-8h10v8"/></svg><span class="gx-layout__action-label gx-layout__save-label">{{ busy ? 'Saving…' : 'Save' }}<span class="gx-layout__long"> changes</span></span></button>
</template>
</div>
<nav class="gx-layout__segment gx-uniden__pages" aria-label="Uniden settings pages">
<button v-for="(label, id) in sections" :key="id" class="gx-btn gx-btn--tonal" type="button" :aria-pressed="panel === id" @click="panel = id">{{ label }}</button>
</nav>
<div v-show="panel === 'warning'" class="gx-layout__workspace gx-uniden__workspace">
<div class="gx-card gx-layout__inspector gx-uniden__controls">
<section class="gx-uniden__section" aria-label="Full-screen warning">
<div class="gx-section__header"><span class="gx-section__title">Full-screen warning</span></div>
<fieldset :disabled="!parked || busy" class="gx-uniden__fieldset"><div class="gx-panel gx-stack">
<p class="gx-note">Drawn around the driving screen during a live alert, above any openpilot alert. Each band uses the same warning in its own color.</p>
<div class="gx-uniden__bands">
<div v-for="band in ['KA', 'K', 'LASER']" :key="band" class="gx-uniden__band" :class="{ 'gx-uniden__band--off': !config.border_bands.includes(band) }">
<div class="gx-uniden__heading">
<h4>{{ bands[band] }}</h4>
<label class="gx-uniden__enable"><span>{{ config.border_bands.includes(band) ? 'Warning on' : 'Warning off' }}</span><span class="gx-switch"><input type="checkbox" role="switch" :aria-label="bands[band] + ' full-screen warning'" :checked="config.border_bands.includes(band)" @change="toggleBand('border_bands', band)" /><span class="gx-switch__track"></span><span class="gx-switch__thumb"></span></span></label>
</div>
<div class="gx-uniden__choices" role="group" :aria-label="bands[band] + ' warning color'">
<button v-for="(hex, name) in swatches" :key="name" type="button" class="gx-uniden__dot" :style="{ background: hex }" :aria-pressed="config.border_colors[band] === name" :aria-label="name" :title="name" @click="pickColor(band, name)"></button>
</div>
</div>
</div>
<div class="gx-uniden__edge-parts" role="group" aria-label="What the warning shows">
<div v-for="(text, part) in edgeParts" :key="part" class="gx-row gx-uniden__preference">
<div class="gx-row__info"><span class="gx-row__label">{{ text[0] }}</span><span class="gx-row__desc">{{ text[1] }}</span></div>
<label class="gx-switch"><input type="checkbox" role="switch" :aria-label="text[0]" v-model="config.border_edge[part]" :disabled="part === 'dashes' && !config.border_edge.line" /><span class="gx-switch__track"></span><span class="gx-switch__thumb"></span></label>
</div>
<label class="gx-uniden__field">When the detector is muted, show the warning at {{ config.border_muted_percent ? config.border_muted_percent + '%' : 'off' }}
<input type="range" min="0" max="100" step="5" v-model.number="config.border_muted_percent" aria-describedby="uniden-muted-note" /></label>
<p id="uniden-muted-note" class="gx-note">0% hides the warning while the detector is muted.</p>
</div>
</div></fieldset>
</section>
<p class="gx-note">Widget size, position and appearance are in the theme maker.</p>
</div>
<section class="gx-card gx-layout__preview-card gx-uniden__preview-card" aria-label="Warning preview" style="--layout-ratio: 1.7222">
<div class="gx-layout__subhead"><strong>Warning preview</strong><span>{{ dirty ? 'Showing unsaved changes' : 'Showing saved settings' }}</span></div>
<div class="gx-layout__preview-bar">
<GalaxySelect class="gx-field gx-field--full" aria-label="Preview scenario" :value="scenario" @change="scenario = $event.target.value">
<optgroup v-for="(group, title) in scenarios" :key="title" :label="title">
<option v-for="(item, id) in group" :key="id" :value="id">{{ item.label }}</option>
</optgroup>
</GalaxySelect>
<button class="gx-icon-btn gx-layout__bar-toggle" type="button" aria-label="Replay the scenario" title="Replay" @click="replay++"><i class="bi bi-arrow-repeat" aria-hidden="true"></i></button>
</div>
<edge-preview :config="config" :swatches="swatches" :scenario="scenario" :replay="replay" />
<p class="gx-note">A sample scene. Choosing a scenario never changes your settings.</p>
</section>
</div>
<section v-show="panel === 'alerts'" class="gx-card gx-uniden__page" aria-label="Alert preferences">
<div class="gx-section__header"><span class="gx-section__title">Alert preferences</span></div>
<fieldset :disabled="!parked || busy" class="gx-uniden__fieldset">
<div class="gx-row gx-uniden__preference"><div class="gx-row__info"><span class="gx-row__label">Enable Uniden integration</span><span class="gx-row__desc">Receive alerts while the driving screen is active, even with the widget hidden.</span></div>
<label class="gx-switch"><input type="checkbox" role="switch" aria-label="Enable Uniden integration" v-model="config.enabled" /><span class="gx-switch__track"></span><span class="gx-switch__thumb"></span></label></div>
<div class="gx-row gx-uniden__preference"><div class="gx-row__info"><span class="gx-row__label">Auto-mute saved frequencies</span><span class="gx-row__desc">Mute when every active signal matches an enabled rule. A brief initial beep may occur.</span></div>
<label class="gx-switch"><input type="checkbox" role="switch" aria-label="Automatically mute matching frequencies" v-model="config.auto_mute" /><span class="gx-switch__track"></span><span class="gx-switch__thumb"></span></label></div>
<div class="gx-row gx-uniden__preference"><div class="gx-row__info"><span class="gx-row__label">Quiet Ride at the posted limit</span><span class="gx-row__desc">Mute the beep, keep the alert on screen, while you are at or under the posted limit plus the margin. Sudden strong signals are never quieted. Needs a known limit and a GPS fix.</span></div>
<label class="gx-switch"><input type="checkbox" role="switch" aria-label="Quiet Ride at the posted limit" v-model="config.quiet_ride" /><span class="gx-switch__track"></span><span class="gx-switch__thumb"></span></label></div>
<div v-if="config.quiet_ride" class="gx-uniden__sub">
<label class="gx-uniden__field gx-uniden__narrow">Margin over the limit ({{ metric ? 'km/h' : 'mph' }}) <input class="gx-field" type="number" min="0" max="15" step="1" inputmode="numeric" v-model.number="config.quiet_margin" /></label>
<div class="gx-uniden__choices" role="group" aria-label="Bands Quiet Ride may mute"><span class="gx-note">Mute</span>
<button v-for="band in Object.keys(bands)" :key="band" type="button" class="gx-chip gx-uniden__choice" :class="{ 'gx-chip--selected': config.quiet_bands.includes(band) }" :aria-pressed="config.quiet_bands.includes(band)" @click="toggleBand('quiet_bands', band)">{{ bands[band] }}</button></div>
<p v-if="config.quiet_bands.includes('LASER')" class="gx-note">Laser is muted too. The detector mutes everything at once, so a new signal that arrives after a mute may stay quiet until the detector re-alerts.</p>
</div>
<div class="gx-row gx-uniden__preference"><div class="gx-row__info"><span class="gx-row__label">Mute after a few seconds</span><span class="gx-row__desc">Let each new signal beep for a moment, then mute it. The alert stays on screen. If it reaches the chosen strength, the detector is unmuted, the card says Strong signal and the warning flashes. Choose Never to keep it quiet. Laser is never muted this way.</span></div>
<label class="gx-switch"><input type="checkbox" role="switch" aria-label="Mute after a few seconds" v-model="config.timed_mute" /><span class="gx-switch__track"></span><span class="gx-switch__thumb"></span></label></div>
<div v-if="config.timed_mute" class="gx-uniden__sub">
<div v-for="band in ['X', 'K', 'KA']" :key="band">
<label class="gx-uniden__field"><span><input type="checkbox" :value="band" v-model="config.timed_mute_bands" /> {{ bands[band] }}</span></label>
<div v-if="config.timed_mute_bands.includes(band)" class="gx-uniden__pair">
<label class="gx-uniden__field">{{ bands[band] }} mute after (seconds) <input class="gx-field" type="number" min="1" max="60" step="1" inputmode="numeric" v-model.number="config.timed_mute_settings[band].seconds" /></label>
<label class="gx-uniden__field">{{ bands[band] }} warn again at strength <select class="gx-field" v-model.number="config.timed_mute_settings[band].strength"><option :value="0">Never</option><option v-for="n in [2, 3, 4, 5, 6, 7, 8]" :key="n" :value="n">{{ n }} of 8</option></select></label>
</div>
</div>
</div>
<div class="gx-row gx-uniden__preference"><div class="gx-row__info"><span class="gx-row__label">Learn lockouts automatically</span><span class="gx-row__desc">After the same fixed source is passed on separate trips (three for X and K, five for Ka and Laser), lock it out at that place. A source that repeats at one spot but is missing on many drive-bys, like a patrol spot, is not learned. A signal stronger than ever seen there still alerts.</span></div>
<label class="gx-switch"><input type="checkbox" role="switch" aria-label="Learn lockouts automatically" v-model="config.auto_learn" /><span class="gx-switch__track"></span><span class="gx-switch__thumb"></span></label></div>
<div v-if="config.auto_learn" class="gx-uniden__sub">
<div class="gx-uniden__choices" role="group" aria-label="Bands to learn"><span class="gx-note">Learn</span>
<button v-for="band in Object.keys(bands)" :key="band" type="button" class="gx-chip gx-uniden__choice" :class="{ 'gx-chip--selected': config.learn_bands.includes(band) }" :aria-pressed="config.learn_bands.includes(band)" @click="requestLearnBand(band)">{{ bands[band] }}</button></div>
</div>
<div class="gx-uniden__group" role="group" aria-labelledby="uniden-on-screen">
<div class="gx-uniden__group-head"><strong id="uniden-on-screen">On the screen</strong><span class="gx-note">For the widget and the full-screen warning. Each works without the other.</span></div>
<div class="gx-row gx-uniden__preference"><div class="gx-row__info"><span class="gx-row__label">Hide lockouts and frequency rules</span><span class="gx-row__desc">Alerts that match a saved lockout or an enabled frequency rule.</span></div>
<label class="gx-switch"><input type="checkbox" role="switch" aria-label="Hide lockouts and frequency rules" v-model="config.hide_filtered" /><span class="gx-switch__track"></span><span class="gx-switch__thumb"></span></label></div>
<div class="gx-row gx-uniden__preference"><div class="gx-row__info"><span class="gx-row__label">Hide alerts muted below the limit</span><span class="gx-row__desc">Alerts Quiet Ride is muting while you are at or under the posted limit.</span></div>
<label class="gx-switch"><input type="checkbox" role="switch" aria-label="Hide alerts muted below the limit" v-model="config.hide_below_limit" /><span class="gx-switch__track"></span><span class="gx-switch__thumb"></span></label></div>
<div class="gx-row gx-uniden__preference"><div class="gx-row__info"><span class="gx-row__label">Hide Q-Ride alerts</span><span class="gx-row__desc">Alerts the detector's own Q-Ride mode is silencing.</span></div>
<label class="gx-switch"><input type="checkbox" role="switch" aria-label="Hide Q-Ride alerts" v-model="config.hide_q_ride" /><span class="gx-switch__track"></span><span class="gx-switch__thumb"></span></label></div>
<div class="gx-row gx-uniden__preference"><div class="gx-row__info"><span class="gx-row__label">Hide mute memory alerts</span><span class="gx-row__desc">Alerts the detector silences from a saved or learned mute location.</span></div>
<label class="gx-switch"><input type="checkbox" role="switch" aria-label="Hide mute memory alerts" v-model="config.hide_mute_memory" /><span class="gx-switch__track"></span><span class="gx-switch__thumb"></span></label></div>
<p class="gx-note">Shown alerts that are muted stay on screen: the widget names the reason, and the warning dims to the muted brightness on the Colors page.</p>
</div>
</fieldset>
</section>
<section v-show="panel === 'lockouts'" class="gx-card gx-uniden__page" aria-label="Saved lockouts">
<div class="gx-section__header"><span class="gx-section__title">Saved lockouts</span></div>
<div class="gx-panel gx-stack">
<div class="gx-uniden__learning" :class="{ 'gx-uniden__learning--on': learningOn }" role="status">
<div class="gx-uniden__learning-head"><span class="gx-uniden__learning-dot" aria-hidden="true"></span><strong>{{ learningTitle }}</strong></div>
<p v-if="!learningOn" class="gx-note">Turn on Learn lockouts automatically in Preferences to lock out sources you pass again and again.</p>
<p v-else-if="!learning.length" class="gx-note">A fixed source becomes a lockout after you pass it on separate trips: three for X and K, five for Ka and Laser.</p>
<ul v-if="learningOn && learningRows.length" class="gx-uniden__learning-list">
<li v-for="item in learningRows" :key="item.id" :class="{ 'gx-uniden__learning-item--paused': !item.learnable }">
<div class="gx-uniden__learning-line">
<span class="gx-uniden__learning-name">{{ lockLabel(item) }}</span>
<span class="gx-uniden__learning-count">{{ item.learnable ? item.stage : 'Band not learned' }}</span>
</div>
<div v-if="item.learnable" class="gx-uniden__meter" role="progressbar" :aria-label="lockLabel(item) + ' learning progress'"
aria-valuemin="0" :aria-valuemax="item.need" :aria-valuenow="item.count"><span :style="{ width: item.percent + '%' }"></span></div>
</li>
</ul>
<p v-if="learningOn && learning.length > learningRows.length" class="gx-note">+{{ learning.length - learningRows.length }} more being learned</p>
</div>
<p class="gx-note">Hold an alert on the driving screen to lock it out where you are. Lockouts only apply near that place.</p>
<div v-if="!locks.length" class="gx-uniden__empty"><strong>No saved lockouts</strong></div>
<div v-for="lock in locks" :key="lock.id" class="gx-uniden__rule-footer">
<div><h4>{{ lockLabel(lock) }} <span class="gx-uniden__lock-source" :class="{ 'gx-uniden__lock-source--auto': lock.source === 'auto' }">{{ lock.source === 'auto' ? 'Learned' : 'Held on screen' }}</span></h4><p class="gx-note">{{ lockDetail(lock) }}</p></div>
<button class="gx-btn gx-btn--tonal" type="button" @click="unlock(lock.id)" :aria-label="'Remove lockout ' + lockLabel(lock)">Remove</button>
</div>
</div>
</section>
<section v-show="panel === 'frequencies'" class="gx-card gx-uniden__page" aria-label="Frequency rules">
<div class="gx-section__header"><span class="gx-section__title">Frequency rules</span>
<button class="gx-btn gx-btn--tonal" type="button" :disabled="!parked || busy || config.frequency_rules.length >= 32" @click="addRule">Add frequency</button></div>
<div class="gx-panel gx-stack">
<p class="gx-note">Save known false alerts such as your head unit. Rules apply wherever you drive.</p>
<div v-if="!config.frequency_rules.length" class="gx-uniden__empty"><strong>No saved frequencies</strong><p class="gx-note">Choose Add frequency, then enter the reading shown by your detector.</p></div>
<fieldset v-for="(rule, index) in config.frequency_rules" :key="rule.uid" :disabled="!parked || busy" class="gx-uniden__fieldset gx-uniden__rule">
<div class="gx-uniden__heading">
<h4>{{ rule.label || 'Frequency ' + (index + 1) }}</h4>
<label class="gx-uniden__enable"><span>{{ rule.enabled ? 'Enabled' : 'Off' }}</span><span class="gx-switch"><input type="checkbox" role="switch" :aria-label="'Rule ' + (index + 1) + ' enabled'" v-model="rule.enabled" /><span class="gx-switch__track"></span><span class="gx-switch__thumb"></span></span></label>
</div>
<div class="gx-uniden__fields">
<label class="gx-uniden__field gx-uniden__name">Label <input class="gx-field" v-model="rule.label" maxlength="60" placeholder="e.g. Head unit" /></label>
<label class="gx-uniden__field">Band <select class="gx-field" v-model="rule.band"><option>X</option><option>K</option><option>KA</option></select></label>
<label class="gx-uniden__field">Frequency (GHz) <input class="gx-field" type="number" step="0.001" inputmode="decimal" v-model.number="rule.frequency" /></label>
<label class="gx-uniden__field">Tolerance (± MHz) <input class="gx-field" type="number" min="0" max="10" step="0.1" inputmode="decimal" v-model.number="rule.tolerance_mhz" /></label>
</div>
<div class="gx-uniden__rule-footer"><div><p class="gx-note">{{ ruleRange(rule) }}</p><p class="gx-note">Keep tolerance at 0 unless the reading drifts.</p></div>
<button class="gx-btn gx-btn--tonal" type="button" @click="config.frequency_rules.splice(index, 1)" :aria-label="'Remove rule ' + (index + 1)">Remove</button></div>
</fieldset>
<p v-if="config.frequency_rules.length" class="gx-note">Another source at the same frequency will also match. These rules are saved in StarPilot, not the detector’s lockout memory.</p>
</div>
</section>
<GxDialog v-if="confirmLearn" class="gx-layout__leave-dialog" labelledby="gx-uniden-learn-title" describedby="gx-uniden-learn-body" alert @close="confirmLearn = null">
<div class="gx-layout__leave-copy"><h3 id="gx-uniden-learn-title">{{ learnWarnings[confirmLearn].title }}</h3>
<p id="gx-uniden-learn-body">{{ learnWarnings[confirmLearn].body }}</p></div>
<div class="gx-layout__leave-actions">
<button type="button" class="gx-btn gx-btn--tonal" @click="confirmLearn = null">Keep it off</button>
<button type="button" class="gx-btn" @click="confirmLearnBand">Learn {{ bands[confirmLearn] }} lockouts</button>
</div>
</GxDialog>
<GxDialog v-if="leaveModal" class="gx-layout__leave-dialog" labelledby="gx-uniden-leave-title" describedby="gx-uniden-leave-body" alert @close="cancelLeave">
<div class="gx-layout__leave-copy"><h3 id="gx-uniden-leave-title">Leave without saving your changes?</h3>
<p id="gx-uniden-leave-body">Save your Uniden settings before leaving, keep editing, or discard the changes.</p></div>
<div class="gx-layout__leave-actions">
<button type="button" class="gx-btn gx-btn--tonal" @click="cancelLeave">Keep editing</button>
<button type="button" class="gx-btn gx-btn--danger" @click="discardAndLeave">Discard and leave</button>
<button type="button" class="gx-btn" :disabled="!parked || busy" @click="saveAndLeave">{{ busy ? 'Saving…' : 'Save changes' }}</button>
</div>
</GxDialog>
</div>
</template>
</div>`,
}
@@ -1,5 +1,6 @@
"""Vehicle-owned longitudinal behavior at the shared control boundary."""
from dataclasses import dataclass
import math
from openpilot.common.realtime import DT_CTRL
from openpilot.starpilot.longitudinal.force_stop_braking import eligible as distance_braking_eligible
@@ -26,6 +27,7 @@ class LongitudinalContext:
profile_max_accel: float | None = None
faster_takeoffs: bool = False
force_stop_braking: bool = False
toyota_resume_fresh: bool = False
class LongitudinalExtension:
@@ -40,6 +42,7 @@ class LongitudinalExtension:
self.vehicle_stop = self.vehicle_policy.stop_policy() if hasattr(self.vehicle_policy, "stop_policy") else None
toyota_production = production_enabled(CP)
self.toyota_stopped_lead = toyota_production and str(CP.carFingerprint) == COROLLA
self.toyota_pcm_resume = self.toyota_stopped_lead and CP.autoResumeSng
self.toyota_output = ToyotaOutputPolicy(CP) if toyota_production or development_enabled(CP) else None
self.ioniq6_start = Ioniq6StartPolicy() if ioniq6_start_eligible(CP) else None
self.force_stop_distance_braking = distance_braking_eligible(CP)
@@ -95,6 +98,14 @@ class LongitudinalExtension:
if self.stopping_policy is not None:
state = self.stopping_policy.transition(state, previous_state, active, CS, a_target, should_stop,
has_lead=context.has_lead)
if (self.toyota_pcm_resume and active and
CS.standstill and CS.cruiseState.standstill):
# The PCM clears its hold after the controller sends a positive request.
can_resume = (context.toyota_resume_fresh and CS.canValid and not CS.canTimeout and not CS.accFaulted and
not CS.stockAeb and CS.cruiseState.enabled and not CS.brakePressed and not CS.gasPressed and
not should_stop and not context.force_stop_braking and math.isfinite(a_target) and a_target >= 0.1 and
self.toyota_output.moving_lead_for_resume(context.leads))
return LongCtrlState.pid if can_resume else LongCtrlState.stopping
if (self.toyota_stopped_lead and active and previous_state == LongCtrlState.stopping and
state != LongCtrlState.off and not should_stop and not CS.brakePressed and
self.toyota_output.hold_stopped_lead(CS.vEgo, context.leads)):
+4 -1
View File
@@ -173,7 +173,10 @@ class LongitudinalInputs:
if self.ev9_long_enabled:
return self._ev9_context(active)
if self.toyota_sienna_replay or self.toyota_sienna_production or self.toyota_corolla_stop:
return LongitudinalContext(leads=self._toyota_leads() if active else None)
leads = self._toyota_leads() if active else None
resume_fresh = (leads is not None and self.toyota_corolla_stop and self.sm.all_checks(['longitudinalPlan']) and
self.sm['carState'].cruiseState.standstill and self.resume_sources_current())
return LongitudinalContext(leads=leads, toyota_resume_fresh=resume_fresh)
cc_evidence = (self.gm_cc_evidence if self.gm_cc_enabled else self._gm_cc_evidence()
if self.gm_cc_stop_enabled and active else None)
volt_observation = self._gm_volt_observation() if self.gm_volt_enabled and active else None
@@ -0,0 +1,80 @@
from dataclasses import replace
from types import SimpleNamespace
import pytest
from opendbc.car import gen_empty_fingerprint, structs
from opendbc.car.toyota.interface import CarInterface
from opendbc.car.toyota.values import CAR
from openpilot.selfdrive.controls.lib.longcontrol import LongControl
from openpilot.starpilot.longitudinal.extension import LongitudinalContext
from openpilot.starpilot.longitudinal.inputs import LongitudinalInputs, ResumeFreshness
from openpilot.starpilot.longitudinal.toyota_output_policy import Lead
LONG_STATE = structs.CarControl.Actuators.LongControlState
MOVING_LEAD = Lead(True, 23.0, 0.4, 2.0, 0.0)
STOPPED_LEAD = Lead(True, 5.0, 0.2, 0.0, 0.0)
@pytest.mark.parametrize('blocker', (None, 'brake', 'gas', 'aeb', 'can', 'plan', 'hold', 'stale', 'no_lead', 'stopped_lead', 'auto_resume_off'))
def test_corolla_pcm_hold_requires_current_plan_and_moving_lead(blocker):
cp = CarInterface.get_params(CAR.TOYOTA_COROLLA_TSS2, gen_empty_fingerprint(), [], False, False, False)
assert cp.autoResumeSng and cp.safetyConfigs[0].safetyParam == 73
if blocker == 'auto_resume_off':
cp.autoResumeSng = False
driver_state = structs.CarState(vEgo=0., standstill=True, canValid=True)
driver_state.cruiseState.enabled = driver_state.cruiseState.standstill = True
driver_state.brakePressed = blocker == 'brake'
driver_state.gasPressed = blocker == 'gas'
driver_state.stockAeb = blocker == 'aeb'
driver_state.canTimeout = blocker == 'can'
leads = () if blocker == 'no_lead' else (MOVING_LEAD, STOPPED_LEAD) if blocker == 'stopped_lead' else (MOVING_LEAD,)
context = LongitudinalContext(leads=leads, toyota_resume_fresh=blocker != 'stale', force_stop_braking=blocker == 'hold')
owner = LongControl(cp)
for _ in range(20):
assert owner.update(True, driver_state, -0.3, True, (-3.5, 2.0), context=context) < 0
target, should_stop = (0.8, blocker == 'plan')
outputs = [owner.update(True, driver_state, target, should_stop, (-3.5, 2.0), context=context) for _ in range(60)]
if blocker is None:
assert owner.long_control_state == LONG_STATE.pid
assert outputs[-1] > 0
assert owner.update(True, driver_state, target, False, (-3.5, 2.0),
context=replace(context, toyota_resume_fresh=False)) < 0
assert owner.long_control_state == LONG_STATE.stopping
else:
assert owner.long_control_state == LONG_STATE.stopping
assert max(outputs) <= 0
def test_corolla_resume_evidence_requires_current_car_and_plan(monkeypatch):
names = ('carState', 'longitudinalPlan', 'deviceState')
now = [1_050_000_000]
car_state = structs.CarState()
car_state.cruiseState.standstill = True
class Messages(SimpleNamespace):
def __getitem__(self, name):
return {'carState': car_state, 'deviceState': SimpleNamespace(started=True, startedMonoTime=900_000_000)}[name]
sm = Messages(seen={'deviceState': True}, alive={'deviceState': True}, valid={'deviceState': True},
all_checks=lambda requested: bool(requested) and requested[0] in names)
def publish():
sm.logMonoTime = dict.fromkeys(names, now[0] - 5_000_000)
sm.recv_time = dict.fromkeys(names, (now[0] - 2_000_000) / 1e9)
monkeypatch.setattr('openpilot.starpilot.longitudinal.inputs.clock_pair_ns', lambda: (now[0], now[0] + 500_000_000))
inputs = LongitudinalInputs.__new__(LongitudinalInputs)
inputs.messages = lambda: sm
inputs.resume_freshness = ResumeFreshness()
inputs.ev9_long_enabled = inputs.toyota_sienna_replay = inputs.toyota_sienna_production = False
inputs.toyota_corolla_stop = True
inputs._toyota_leads = lambda: (MOVING_LEAD,)
publish()
assert not inputs._vehicle_context(True).toyota_resume_fresh
now[0] += 20_000_000
publish()
assert inputs._vehicle_context(True).toyota_resume_fresh
now[0] += 170_000_000
publish()
sm.logMonoTime['longitudinalPlan'] = now[0] - 160_000_000
assert not inputs._vehicle_context(True).toyota_resume_fresh
assert not inputs._vehicle_context(False).toyota_resume_fresh
@@ -196,6 +196,13 @@ class ToyotaOutputPolicy:
lead.present and 0 < lead.distance_m <= 8.0 and
abs(lead.lateral_m) <= 1.75 and abs(lead.speed_mps) <= 0.35 for lead in leads))
def moving_lead_for_resume(self, leads):
if not self._leads_valid(leads):
return False
nearest = min((lead for lead in leads if lead.present and lead.distance_m > 0 and abs(lead.lateral_m) <= 1.75),
key=lambda lead: lead.distance_m, default=None)
return nearest is not None and nearest.speed_mps > 0.35
def target(self, a_target: float, v_ego: float, should_stop: bool, last_output_accel: float,
*, leads: tuple[Lead, ...] | None = None) -> float | None:
"""Return a shaped target, or None for invalid/missing required evidence."""
+14 -2
View File
@@ -30,7 +30,7 @@ from openpilot.starpilot.system.starport.supervisor import Supervisor
PAIRING_COMMANDS = {"prepare_pairing", "pairing_status", "pairing_response", "cancel_pairing", "pair_device"}
AUTHENTICATED_COMMANDS = {"start", "set_auto_connect", "select_receiver", "set_view", "set_connection", "set_car_type", "set_car_profile",
"prepare_pairing", "pairing_status", "pairing_response", "cancel_pairing", "pair_device", "devices", "bluetooth_action",
"phone_window", "bluetooth_power", "reset_handshake", "continue_ladder"}
"phone_window", "bluetooth_power", "reset_handshake", "continue_ladder", "uniden"}
def _offroad() -> bool:
@@ -61,10 +61,22 @@ def handle(supervisor: Supervisor, request: dict[str, Any], verifier: StarPortSo
source = request.get('source')
if not isinstance(source, str) or verifier is None or not verifier.valid(source):
raise RuntimeError('Authenticated Galaxy StarPort source required')
if command not in ('bluetooth_action', 'phone_window', 'bluetooth_power'):
if command not in ('bluetooth_action', 'phone_window', 'bluetooth_power', 'uniden'):
supervisor.bind_source_session(('galaxy', source))
if command in PAIRING_COMMANDS and not (parked or _offroad)():
raise RuntimeError("Disengage and shift into Park before pairing")
if command == 'uniden':
from openpilot.starpilot.bluetooth.owner import BluetoothRejected, BluetoothUnavailable
allowed = {'command', 'source', 'address', 'model', 'mute', 'auto_mute', 'frequency_rules', 'situation'}
if set(request) - allowed or not {'command', 'source', 'address', 'model', 'mute'} <= set(request):
raise ValueError('Invalid detector request')
try:
result = supervisor.uniden_exchange(request['address'], request['model'], ('galaxy', request['source']), mute=request['mute'],
auto_mute=request.get('auto_mute', False), frequency_rules=request.get('frequency_rules', []),
situation=request.get('situation'))
except (BluetoothRejected, BluetoothUnavailable) as error:
return {'handled': True, 'error_code': error.code, 'message': str(error)[:160]}
return {'handled': result is not None, 'detector': result}
if command == 'bluetooth_action':
from openpilot.starpilot.bluetooth.owner import BluetoothRejected, BluetoothUnavailable
if set(request) != {'command', 'source', 'operation', 'address'}:
@@ -7,9 +7,9 @@ from pathlib import Path
from openpilot.starpilot.system.starport.identity import DATA_DIR
from openpilot.starpilot.system.starport.display_profile import screen_geometry
from openpilot.starpilot.ui.onroad_customization import (CEM_GAUGE_WIDGET, CLOCK_WIDGET, JETLINK_WIDGET, MODE_WIDGET, SIGNAL_OPACITY, SIGNAL_WIDGET,
SIGNAL_SCALE_RANGE, SIGNAL_SIZES,
SIGNAL_SCALE_RANGE, SIGNAL_SIZES, UNIDEN_WIDGET, UNIDEN_DISPLAY_FIELDS, scaled_size, uniden_display,
STOPPED_TIMER_WIDGET, WEATHER_WIDGET, CEM_GAUGE_FRAME, CEM_GAUGE_INSET, MAP_MIN_SIZE, NAV_CARD_SIZE,
SPEED_ALIGNMENTS, customization_metadata, signal_size, valid_signal_scale,
SPEED_ALIGNMENTS, customization_metadata, signal_size, valid_signal_scale, valid_uniden_display,
validate_map_box, validate_widget_order)
from openpilot.starpilot.ui.onroad_stopped_timer import timer_size
from openpilot.starpilot.ui.onroad_torque_geometry import maximum_footprint
@@ -42,8 +42,8 @@ JETLINK_SIZE = (420, 100)
JETLINK_OPACITY = (0, 100, 85)
CARD_WIDGETS = {NOW_PLAYING_WIDGET: NOW_PLAYING_OPACITY, JETLINK_WIDGET: JETLINK_OPACITY, SIGNAL_WIDGET: SIGNAL_OPACITY}
# StarPort widgets the comma also draws as real editor sprites; the map stays a sketch.
SPRITE_WIDGETS = (NAV_CARD, *DISPLAY_WIDGETS, STOPPED_TIMER_WIDGET, NOW_PLAYING_WIDGET, JETLINK_WIDGET, SIGNAL_WIDGET, CAR_EXIT)
PROJECTION_WIDGETS = (NAV_CARD, NAV_MAP, *DISPLAY_WIDGETS, STOPPED_TIMER_WIDGET, NOW_PLAYING_WIDGET, JETLINK_WIDGET, SIGNAL_WIDGET, CAR_EXIT,
SPRITE_WIDGETS = (NAV_CARD, *DISPLAY_WIDGETS, STOPPED_TIMER_WIDGET, NOW_PLAYING_WIDGET, JETLINK_WIDGET, SIGNAL_WIDGET, UNIDEN_WIDGET, CAR_EXIT)
PROJECTION_WIDGETS = (NAV_CARD, NAV_MAP, *DISPLAY_WIDGETS, STOPPED_TIMER_WIDGET, NOW_PLAYING_WIDGET, JETLINK_WIDGET, SIGNAL_WIDGET, UNIDEN_WIDGET, CAR_EXIT,
'following_distance')
@@ -221,6 +221,8 @@ def placement_size(key, widget, placement):
return (placement.get('size', widget['resizable']['default']),) * 2
if widget.get('box'):
return placement['width'], placement['height']
if key == UNIDEN_WIDGET and type(placement.get('scale')) is int:
return scaled_size(widget['width'], widget['height'], placement['scale'])
return widget['width'], widget['height']
@@ -276,6 +278,8 @@ def validate_layout_for_viewport(value, viewport, *, _legacy_geometry=False):
bounds = metadata['bounds']
for key, widget in metadata['widgets'].items():
placement = result['widgets'][key]
if key == UNIDEN_WIDGET and type(placement) is dict:
placement = result['widgets'][key] = uniden_display(placement)
if key in DISPLAY_WIDGETS and type(placement) is dict:
placement.setdefault('display', 'words')
if key in ACTION_WIDGETS and type(placement) is dict:
@@ -310,10 +314,13 @@ def validate_layout_for_viewport(value, viewport, *, _legacy_geometry=False):
({'opacity'} if key == 'cruise_limits' or key in CARD_WIDGETS else set()) |
({'collapse', 'size'} if key == NOW_PLAYING_WIDGET else set()) |
({'size', 'scale', 'bluetooth', 'wifiName'} if key == SIGNAL_WIDGET else set()) |
(UNIDEN_DISPLAY_FIELDS if key == UNIDEN_WIDGET else set()) |
({'width', 'height'} if widget.get('box') else set()) |
({'opacity'} if key == NAV_MAP else set()))
if type(placement) is not dict or set(placement) != fields or type(placement['enabled']) is not bool:
raise ValueError('Invalid projection widget')
if key == UNIDEN_WIDGET and not valid_uniden_display(placement):
raise ValueError('Invalid Uniden display settings')
if widget.get('required') is True and placement['enabled'] is not True:
raise ValueError('Required projection widget is disabled')
if key in DISPLAY_WIDGETS and placement['display'] not in ('words', 'icons'):
@@ -370,7 +377,7 @@ def validate_layout_for_viewport(value, viewport, *, _legacy_geometry=False):
type(placement[axis]) in (int, float) and math.isfinite(placement[axis]) and
bounds[axis] <= placement[axis] <= bounds[axis] + bounds[extent] - dimension
for (axis, extent), dimension in zip((('x', 'width'), ('y', 'height')), pair, strict=True))), dimensions)
if key in (NOW_PLAYING_WIDGET, SIGNAL_WIDGET, JETLINK_WIDGET):
if key in (NOW_PLAYING_WIDGET, SIGNAL_WIDGET, JETLINK_WIDGET, UNIDEN_WIDGET):
# A larger scale or card size may overhang a saved spot; pull it back in.
for (axis, extent), dimension in zip((('x', 'width'), ('y', 'height')), dimensions, strict=True):
if type(placement[axis]) in (int, float) and math.isfinite(placement[axis]):
@@ -197,6 +197,9 @@ class ProjectionOnroad:
self._resources.callback(self._close_camera)
self.onroad = self.create_view(native.onroad, self.fonts, camera_layer=self._camera_layer, viewport=viewport)
self._resources.callback(self._close_onroad)
if getattr(self.onroad, 'uniden', None):
self.onroad.uniden.runtime_active = True
self._resources.callback(self.onroad.uniden.close)
self.now_playing_feed = None
if getattr(native, 'now_playing_feed', None) is not None:
self.now_playing_feed = native.now_playing_feed()
@@ -581,6 +584,8 @@ class ProjectionOnroad:
if self.pip is not None:
self.pip.deactivate()
self._set_pip_showing(False)
if getattr(self.onroad, "uniden", None):
self.onroad.uniden.feed.set_enabled(False)
self._standby()
self.exit.draw(self.exit.document_placement(self.customization))
@@ -592,6 +597,10 @@ class ProjectionOnroad:
if self.favorites is not None:
self.favorites.cancel()
continue
if getattr(self.onroad, 'uniden', None) and self.onroad.uniden.touch(event.kind, x, y, self._state):
if self.favorites is not None:
self.favorites.cancel()
continue
if self._slc_touch(event.kind, x, y):
if self.favorites is not None:
self.favorites.cancel()
@@ -662,6 +671,8 @@ class ProjectionOnroad:
self.fonts.draw(text, role, size, text_x, y - size / 2)
def cancel_touch(self):
if getattr(self.onroad, 'uniden', None):
self.onroad.uniden.touch('cancel', 0, 0, None)
self.exit.cancel()
if self.now_playing_touch is not None:
self.now_playing_touch.cancel()
@@ -1123,6 +1123,17 @@ class Supervisor:
with self._lock:
return owner.companion_power(enabled, session)
def uniden_exchange(self, address, model, session, *, mute=None, auto_mute=False, frequency_rules=None, situation=None):
from openpilot.starpilot.uniden.transport import exchange
owner = self._shared_bluetooth_owner
if owner is None:
return None
with owner.lock:
if owner.phone_lease is None:
return None
return exchange(owner, address, model, session, mute=mute, auto_mute=auto_mute, frequency_rules=frequency_rules,
situation=situation)
def companion_bluetooth_action(self, operation: str, address: str, session: tuple):
owner = self._shared_bluetooth_owner
if owner is None:
@@ -54,6 +54,14 @@ class TestProjectionLayout(unittest.TestCase):
with self.assertRaises(ValueError):
decode_layout(json.dumps(document).encode(), SCREEN)
def test_uniden_scale_counts_toward_bounds_and_pulls_old_overhang_back_in(self):
document = default_layout(SCREEN)
bounds = layout_metadata(SCREEN)['bounds']
document['widgets']['uniden_alerts'].update(y=774, scale=130)
placed = validate_layout(document, SCREEN)['widgets']['uniden_alerts']
self.assertEqual(placed['y'], bounds['y'] + bounds['height'] - round(260 * 1.3))
self.assertEqual(validate_layout(validate_layout(document, SCREEN), SCREEN)['widgets']['uniden_alerts'], placed)
def test_unsaved_layer_order_draws_the_editor_default(self):
document = default_layout(SCREEN)
self.assertNotIn('widgetOrder', document)
@@ -0,0 +1,21 @@
"""A slow detector exchange must not hold the supervisor lock the video loop needs."""
import threading
from unittest.mock import Mock, patch
from openpilot.starpilot.system.starport.supervisor import Supervisor
def test_detector_exchange_leaves_supervisor_lock_free():
host = Supervisor.__new__(Supervisor)
host._lock = threading.RLock()
host._shared_bluetooth_owner = Mock(lock=threading.RLock(), phone_lease=object())
free = []
def exchange(owner, *args, **kwargs):
# Stands in for a BlueZ Connect that blocks; another thread (the stream's _set) must still get in.
probe = threading.Thread(target=lambda: free.append(host._lock.acquire(timeout=0.5) and (host._lock.release() or True)))
probe.start()
probe.join()
assert owner.lock._is_owned()
return {'connected': True}
with patch('openpilot.starpilot.uniden.transport.exchange', exchange):
assert host.uniden_exchange('E0:00:00:00:0B:4D', 'R8', ('galaxy', 'test')) == {'connected': True}
assert free == [True]
@@ -245,6 +245,9 @@ class _Canvas:
cast(JetlinkStatusWidget, self.view.jetlink_status).status = JetlinkStatus('iPhone', 'active', 24.6, 'connected', model='Cinque v3')
from openpilot.starpilot.ui.network_signal import Signal
self.view.network_signal.preview = Signal(2, 4, 'wifi', 'LTE', 'connected', ('iPhone 15',), 'Home Wi-Fi')
self.view.uniden.preview_data = {'config': {'enabled': True}, 'connected': True, 'model': 'R8', 'can_mute': True,
'alerts': [{'band': 'KA', 'strength': 6, 'frequency': 35.5, 'direction': 'rear', 'muted': False},
{'band': 'K', 'strength': 3, 'frequency': 24.15, 'direction': 'front', 'muted': False}]}
self.monitor = _DriverMonitorArt(profile)
self.view.driver_monitor_layer = self._render_driver_monitor
self.view.preview_pip_layer = self._render_preview_pip
+11
View File
@@ -164,6 +164,8 @@ class OnroadView:
self.jetlink_status = JetlinkStatusWidget(fonts)
from openpilot.starpilot.ui.onroad_signal import SignalWidget
self.network_signal = SignalWidget(fonts)
from openpilot.starpilot.ui.onroad_uniden import UnidenWidget
self.uniden = UnidenWidget(fonts)
else:
self.compact_hud = CompactHudRenderer(fonts, asset_directory)
self.compact_sidebar = MiciSidebarWidgets(fonts)
@@ -177,10 +179,14 @@ class OnroadView:
def render(self, state: OnroadState) -> None:
if uniden := getattr(self, "uniden", None):
uniden.feed.set_enabled(uniden.runtime_active)
if state.camera_available and self.camera_layer is None:
raise ValueError("Camera observation requires a camera renderer")
if self.fonts.profile == Profile.LARGE:
self._large(state)
if uniden := getattr(self, "uniden", None):
uniden.render_border(state, *(self.projection_viewport or (state.viewport_width, 1080)))
else:
self._compact(state)
@@ -312,6 +318,9 @@ class OnroadView:
if "now_playing" in state.customization["layouts"]["large"]:
if now_playing := getattr(self, "now_playing", None):
submit("now_playing", lambda: now_playing.render(state))
if "uniden_alerts" in state.customization["layouts"]["large"]:
if uniden := getattr(self, "uniden", None):
submit("uniden_alerts", lambda: uniden.render(state))
if "jetlink_status" in state.customization["layouts"]["large"]:
if jetlink := getattr(self, "jetlink_status", None):
submit("jetlink_status", lambda: jetlink.render(state))
@@ -431,6 +440,8 @@ class OnroadView:
self.navigation_favorites.render(key, state)
if now_playing := getattr(self, "now_playing", None):
now_playing.render(state)
if uniden := getattr(self, "uniden", None):
uniden.render(state)
if jetlink := getattr(self, "jetlink_status", None):
jetlink.render(state)
if signal := getattr(self, "network_signal", None):
+38 -2
View File
@@ -41,6 +41,8 @@ class WidgetPlacement(TypedDict):
size: NotRequired[int | str]
width: NotRequired[int]
height: NotRequired[int]
transparency: NotRequired[int]
hide_when_no_alert: NotRequired[bool]
opacity: NotRequired[int]
bluetooth: NotRequired[bool]
wifiName: NotRequired[bool]
@@ -204,6 +206,31 @@ _nav_map["note"] = ("Road lines and your route over the camera. Drag the corner
+ "Turning it on here turns it off in the other screen's layout.")
PROFILES["large"]["widgets"][NAV_MAP_WIDGET] = _nav_map
UNIDEN_WIDGET = "uniden_alerts"
UNIDEN_DISPLAY_DEFAULTS = {"transparency": 8, "hide_when_no_alert": True, "scale": 100}
UNIDEN_DISPLAY_FIELDS = set(UNIDEN_DISPLAY_DEFAULTS)
UNIDEN_RETIRED_FIELDS = ("hide_quiet_ride", "hide_mute_memory")
UNIDEN_SCALE_RANGE = (50, 150) # percent
def valid_uniden_display(placement: dict) -> bool:
return (type(placement.get("transparency")) is int and 0 <= placement["transparency"] <= 100 and
type(placement.get("hide_when_no_alert")) is bool and
type(placement.get("scale")) is int and UNIDEN_SCALE_RANGE[0] <= placement["scale"] <= UNIDEN_SCALE_RANGE[1])
def uniden_display(placement: dict) -> dict:
return {**UNIDEN_DISPLAY_DEFAULTS, **{key: value for key, value in placement.items() if key not in UNIDEN_RETIRED_FIELDS}}
def scaled_size(width: float, height: float, scale: int) -> tuple[int, int]:
"""Rounds half up, like the editor's Math.round."""
return math.floor(width * scale / 100 + .5), math.floor(height * scale / 100 + .5)
_uniden = _widget("Uniden alerts", UNIDEN_WIDGET, 460, 260, 700, 780)
_uniden["default"].update(cast(WidgetPlacement, UNIDEN_DISPLAY_DEFAULTS))
_uniden["note"] = "R4/R8 detector alerts. Pair and select the detector in Galaxy Bluetooth. Tap an alert to mute."
PROFILES["large"]["widgets"][UNIDEN_WIDGET] = _uniden
JETLINK_WIDGET = "jetlink_status"
JETLINK_SIZE = (420, 100)
JETLINK_OPACITY = (0, 100, 85) # percent: min, max, default
@@ -277,7 +304,7 @@ for _key, _widget_data in PROFILES["large"]["widgets"].items():
_widget_data["expandable"] = True
# Older documents retain every saved placement and gain this independent widget.
OPTIONAL_WIDGETS = frozenset({WEATHER_WIDGET, MODE_WIDGET, CLOCK_WIDGET, STOPPED_TIMER_WIDGET, CEM_GAUGE_WIDGET,
NAV_CARD_WIDGET, NAV_MAP_WIDGET, JETLINK_WIDGET, SIGNAL_WIDGET, "rear_fog"})
NAV_CARD_WIDGET, NAV_MAP_WIDGET, JETLINK_WIDGET, SIGNAL_WIDGET, UNIDEN_WIDGET, "rear_fog"})
# The torque arc grows when the developer sidebar closes; protect both road widths.
_torque = PROFILES['large']['widgets']['torque_bar']
@@ -304,6 +331,7 @@ WIDGET_COLORS = {
CLOCK_WIDGET: {"text": "#FFFFFFFF"},
WEATHER_WIDGET: {"cardFill": "#0F0D17CC", "cardBorder": "#C7AEF744", "text": "#F5F2FCFF"},
CEM_GAUGE_WIDGET: {},
UNIDEN_WIDGET: {"cardFill": "#10191FFF", "cardBorder": "#9D72FFFF", "text": None},
"current_speed": {"text": None},
"cruise_limits": {"cardFill": "#10191FFF", "cardBorder": "#35434DFF", "text": None},
"steering_wheel": {"cardFill": None, "cardBorder": "#00000000"},
@@ -341,7 +369,7 @@ def _fit_legacy_signal(placement: dict, bounds: Bounds) -> None:
DEFAULT_WIDGET_ORDER = {
"large": (NAV_MAP_WIDGET, "cruise_limits", CEM_GAUGE_WIDGET, "current_speed",
"steering_wheel", "torque_bar", "following_distance", "driver_monitor", MODE_WIDGET, CLOCK_WIDGET, WEATHER_WIDGET,
STOPPED_TIMER_WIDGET, NAV_CARD_WIDGET, JETLINK_WIDGET, SIGNAL_WIDGET, "rear_fog", "pip_left", "pip_right"),
STOPPED_TIMER_WIDGET, NAV_CARD_WIDGET, JETLINK_WIDGET, SIGNAL_WIDGET, UNIDEN_WIDGET, "rear_fog", "pip_left", "pip_right"),
"compact": ("speed_limit", "max_speed", "steering_wheel", "torque_bar",
"driver_monitor", *RAIL_WIDGETS, MODE_WIDGET, CLOCK_WIDGET, WEATHER_WIDGET,
STOPPED_TIMER_WIDGET, NAV_CARD_WIDGET, "rear_fog", "pip_left", "pip_right"),
@@ -635,6 +663,8 @@ def validate_document(value):
placement.setdefault('bluetooth', True)
placement.setdefault('wifiName', False)
layout[key] = placement
if key == UNIDEN_WIDGET and type(placement) is dict:
placement = layout[key] = uniden_display(placement)
bounds = widget_bounds(profile, key)
if value['version'] < 8 and key in SPEED_LAYOUT_V7[profile]:
bounds = data['bounds']
@@ -657,6 +687,10 @@ def validate_document(value):
expected.add("size")
if key == SIGNAL_WIDGET:
expected |= {"scale", "bluetooth", "wifiName"}
if key == UNIDEN_WIDGET:
expected |= UNIDEN_DISPLAY_FIELDS
if type(placement) is not dict or not valid_uniden_display(placement):
raise ValueError("Invalid Uniden display settings")
if type(placement) is not dict or set(placement) != expected or type(placement["enabled"]) is not bool:
raise ValueError("Invalid widget placement")
if has_rotation and type(placement['rotate']) is not bool:
@@ -831,6 +865,8 @@ def widget_size(document, profile, widget):
position = placement(document, profile, widget)
if widget == "cruise_limits":
return default["width"], default["height"] + sources_extent(document)
if widget == UNIDEN_WIDGET and type(position.get("scale")) is int:
return scaled_size(default["width"], default["height"], position["scale"])
if default.get("box"):
return position["width"], position["height"]
if widget == SIGNAL_WIDGET:
+533
View File
@@ -0,0 +1,533 @@
"""Shared R4/R8 alert card and touch target for comma 3X and Android Auto."""
import math
import time
from openpilot.starpilot.ui.raylib import rl
from openpilot.starpilot.ui.presentation import FontRole
from openpilot.starpilot.ui.shell import ShellMode
from openpilot.starpilot.ui.onroad_customization import PALETTE, UNIDEN_SCALE_RANGE, UNIDEN_WIDGET, offset, widget_palette
from openpilot.starpilot.uniden.feed import DetectorFeed
from openpilot.starpilot.uniden.protocol import BORDER_SWATCHES, DEFAULT_CONFIG, alert_key
SIZE = (460, 150)
MAX_ROWS = 4
ROW, PAD, RADIUS, BORDER = 60, 8, 14, 2
MEMORY_MUTES = ('memory', 'auto_memory')
NOTE_SIZE = 23
HOLD_S = .8
BADGE_TOP = 42
EDGE_FRAME, EDGE_ROUNDNESS = 30, .12 # onroad's engagement edge, whose rounded corners the warning follows
DIRECTION_SIDES = {'front': ('top',), 'rear': ('bottom',), 'side': ('left', 'right')}
EDGE_GAP, EDGE_LINE, DASH, DASH_GAP = 12, 8, 56, 30
GLOW_DEPTH, GLOW_STEPS, VEIL_ALPHA = (35, 135), 12, .62
CHEVRON_SIZE, CHEVRON_WIDTH, CHEVRON_FROM_SPEED, CHEVRON_FROM_EDGE = 48, 13, 300, 44
FADE_S = .5
BAND_RANK = {'K': 0, 'KA': 1, 'LASER': 2}
OFFLINE_SIZE = (330, 56)
def mute_reason(alert):
"""Why an alert is quiet. StarPilot's own reasons come first, since they are why it sent the mute; then the detector's."""
if alert.get('locked'):
return 'Lockout'
if alert.get('ruled'):
return 'Frequency rule'
if alert.get('filtered'):
return 'Filtered'
if alert.get('quiet'):
return 'Below limit'
if alert.get('timed'):
return 'Timed mute'
if not alert['muted']:
return ''
mode = alert.get('mute_mode')
return 'Q-Ride' if mode == 'quiet_ride' else 'Mute Memory' if mode in MEMORY_MUTES else 'Manual mute' if mode == 'manual' else 'Muted'
def mute_note(alerts):
"""The reason in the card's top edge: one shared reason, counted when only some alerts have it, or plain Muted."""
reasons = [reason for reason in map(mute_reason, alerts) if reason]
if not reasons:
return ''
name = reasons[0] if len(set(reasons)) == 1 else 'Muted'
return name if len(reasons) == len(alerts) else f'{len(reasons)} {name}'
def shown_alerts(alerts, config):
"""Alerts the driver wants on screen, by the detector settings shared by the card and the full-screen warning."""
return [item for item in alerts if not (
(config.get('hide_filtered') and item.get('filtered')) or
(config.get('hide_below_limit') and item.get('quiet')) or
(config.get('hide_q_ride') and item.get('mute_mode') == 'quiet_ride') or
(config.get('hide_mute_memory') and item.get('mute_mode') in MEMORY_MUTES))]
def hex_color(value):
return rl.Color(*(int(value[i:i + 2], 16) for i in (1, 3, 5, 7)))
def threat(alerts, bands):
"""The most serious shown alert in a band the driver chose; muted ones count, so the warning stays up, dimmed."""
for band in ('LASER', 'KA', 'K'):
if band in bands:
for alert in alerts:
if alert['band'] == band:
return alert
return None
class RoundedFrame:
"""A rounded line's clockwise path from the top-left end of the top edge: straight sides and quarter-circle corners."""
CORNERS = {'top': 270, 'right': 0, 'bottom': 90, 'left': 180} # raylib angle where the corner after each side starts
def __init__(self, rect, thickness, radius):
self.rect, self.thickness, self.radius = rect, thickness, radius
self.arc = math.pi / 2 * (radius - thickness / 2) # quarter-circle length along the stroke's centre
straight = {'top': rect.width - 2 * radius, 'right': rect.height - 2 * radius}
straight.update(bottom=straight['top'], left=straight['right'])
self.pieces, at = [], 0.
for side in ('top', 'right', 'bottom', 'left'):
self.pieces += [(side, at, straight[side]), (side + '_corner', at + straight[side], self.arc)]
at += straight[side] + self.arc
self.total = at
def draw(self, start, length, color):
start %= self.total
for begin, end in [(start, min(start + length, self.total))] + ([(0., start + length - self.total)] if start + length > self.total else []):
for name, at, size in self.pieces:
low, high = max(begin, at), min(end, at + size)
if high > low:
self._piece(name, low - at, high - at, color)
def _piece(self, name, low, high, color):
x, y, width, height, t, r = self.rect.x, self.rect.y, self.rect.width, self.rect.height, self.thickness, self.radius
if name.endswith('_corner'):
side = name[:-7]
cx = x + r if side in ('bottom', 'left') else x + width - r
cy = y + r if side in ('top', 'left') else y + height - r
start = self.CORNERS[side] + math.degrees(low / (r - t / 2))
end = self.CORNERS[side] + math.degrees(high / (r - t / 2))
rl.draw_ring(rl.Vector2(cx, cy), r - t, r, start, end, max(2, round(16 * (high - low) / self.arc)), color)
elif name == 'top':
rl.draw_rectangle_rec(rl.Rectangle(x + r + low, y, high - low, t), color)
elif name == 'right':
rl.draw_rectangle_rec(rl.Rectangle(x + width - t, y + r + low, t, high - low), color)
elif name == 'bottom':
rl.draw_rectangle_rec(rl.Rectangle(x + width - r - high, y + height - t, high - low, t), color)
else:
rl.draw_rectangle_rec(rl.Rectangle(x, y + height - r - high, t, high - low), color)
def ring(self, color):
t, rect = self.thickness, self.rect
inner = rl.Rectangle(rect.x + t, rect.y + t, rect.width - 2 * t, rect.height - 2 * t)
# raylib strokes rounded lines outward from the rectangle, so `inner` carries the stroke's inner radius.
rl.draw_rectangle_rounded_lines_ex(inner, 2 * (self.radius - t) / min(inner.width, inner.height), 24, t, color)
def card_scale(config):
value = config.get('scale', 100)
return min(UNIDEN_SCALE_RANGE[1], max(UNIDEN_SCALE_RANGE[0], value)) / 100 if type(value) is int else 1.
def signal_color(strength, index):
"""Galaxy update progress colors: secondary teal to primary purple."""
t = index / max(1, strength - 1)
return rl.Color(math.floor(77 + 80 * t + .5), math.floor(232 - 118 * t + .5), math.floor(232 + 23 * t + .5), 255)
def card_size(alerts):
"""One row per alert, the band, frequency, signal and arrow side by side."""
return (SIZE[0], PAD * 2 + ROW * min(len(alerts), MAX_ROWS)) if alerts else SIZE
def outline(x, y, width, height, color, gaps=()):
"""Rounded card edge, with openings for inline labels on the top edge."""
r, t = RADIUS, BORDER
top, start = [], x + r
for left, right in sorted(gaps):
top.append((start, left))
start = max(start, right)
top.append((start, x + width - r))
for left, right in top:
if right > left:
rl.draw_rectangle_rec(rl.Rectangle(left, y, right - left, t), color)
rl.draw_rectangle_rec(rl.Rectangle(x + r, y + height - t, width - 2 * r, t), color)
rl.draw_rectangle_rec(rl.Rectangle(x, y + r, t, height - 2 * r), color)
rl.draw_rectangle_rec(rl.Rectangle(x + width - t, y + r, t, height - 2 * r), color)
for cx, cy, start in ((x + r, y + r, 180), (x + width - r, y + r, 270), (x + width - r, y + height - r, 0), (x + r, y + height - r, 90)):
rl.draw_ring(rl.Vector2(cx, cy), r - t, r, start, start + 90, 8, color)
def direction_arrows(cx, cy, direction, accent, radius):
# Side means both sides: this detector protocol cannot distinguish left/right.
for name, dx, dy in (('front', 0, -1), ('rear', 0, 1), ('side', -1, 0), ('side', 1, 0)):
if name != direction:
continue
# Center the active glyph in its row, rather than leaving it on a compass edge.
center_x = cx + dx * radius if direction == 'side' else cx
half_length = radius * (.65 if direction == 'side' else .85)
tip = rl.Vector2(center_x + dx * half_length, cy + dy * half_length)
left = rl.Vector2(center_x - dx * half_length - dy * radius, cy - dy * half_length + dx * radius)
right = rl.Vector2(center_x - dx * half_length + dy * radius, cy - dy * half_length - dx * radius)
rl.draw_triangle(tip, right, left, accent)
class EdgeMotion:
"""Pulses when an alert starts or gets worse, a short fade when it ends, and stillness in between."""
def __init__(self):
self.alert, self.baseline, self.pulses, self.ended = None, 0, [], None
def update(self, alert, now, still):
if alert is None:
if self.alert is not None:
self.ended, self.alert = (now, self.alert), None
return
previous, self.alert, self.ended = self.alert, alert, None
new = previous is None or previous['band'] != alert['band'] or \
(alert['frequency'] is not None and previous['frequency'] is not None and abs(alert['frequency'] - previous['frequency']) > .01)
if new:
self.baseline = alert['strength']
if previous is None or BAND_RANK.get(alert['band'], 0) > BAND_RANK.get(previous['band'], 0):
self._pulse(now, still, 3 if alert['band'] == 'LASER' else 2 if previous is None else 1)
elif alert['strength'] >= self.baseline + 2:
self.baseline = alert['strength']
self._pulse(now, still, 1)
else:
self.baseline = min(self.baseline, alert['strength'])
def _pulse(self, now, still, count):
if not still:
self.pulses.append((now, count, .25 if count == 3 else .3))
def boost(self, now):
self.pulses = [p for p in self.pulses if now - p[0] < p[1] * p[2]]
return max((math.sin(math.pi * (((now - at) / period) % 1)) for at, _, period in self.pulses), default=0.)
def fading(self, now):
"""The last alert and how much of it is left while it fades out, or None."""
if self.ended is None or now - self.ended[0] >= FADE_S:
self.ended = None
return None
return self.ended[1], 1 - (now - self.ended[0]) / FADE_S
def tint(color, alpha):
return rl.Color(color.r, color.g, color.b, max(0, min(255, round(255 * alpha))))
def rounded_band(content, radius, inset, width, color):
"""A stroke `width` wide whose outer edge is `inset` inside `content`, concentric with its rounded corners."""
inner = rl.Rectangle(content.x + inset + width, content.y + inset + width, content.width - 2 * (inset + width), content.height - 2 * (inset + width))
r = max(1., radius - inset - width)
rl.draw_rectangle_rounded_lines_ex(inner, min(1., 2 * r / min(inner.width, inner.height)), 16, width, color)
def glow_ring(content, radius, depth, alpha, color):
"""Concentric strokes fading inward: a soft band along the whole edge."""
band = depth / GLOW_STEPS
for i in range(GLOW_STEPS):
fall = 1 - i / GLOW_STEPS
rounded_band(content, radius, i * band, band + .6, tint(color, alpha * fall * fall))
def chevron_points(side, along, content, index):
"""Apex and the two arm ends of one chevron pointing toward `side`, `index` steps in from that edge."""
size, off = CHEVRON_SIZE, CHEVRON_FROM_EDGE + index * CHEVRON_SIZE * .8 + CHEVRON_SIZE * .4
if side == 'top':
cx, cy, dx, dy = along, content.y + off, 0, -1
elif side == 'bottom':
cx, cy, dx, dy = along, content.y + content.height - off, 0, 1
elif side == 'left':
cx, cy, dx, dy = content.x + off, along, -1, 0
else:
cx, cy, dx, dy = content.x + content.width - off, along, 1, 0
apex = rl.Vector2(cx + dx * size * .5, cy + dy * size * .5)
return (rl.Vector2(cx - dy * size - dx * size * .5, cy + dx * size - dy * size * .5), apex,
rl.Vector2(cx + dy * size - dx * size * .5, cy - dx * size - dy * size * .5))
def chevron_sets(direction, width, height, speed_x):
"""Ahead (and the R4, which gives no direction) flank the speed; behind is bottom centre; beside is both side edges."""
top = [('top', speed_x - CHEVRON_FROM_SPEED), ('top', speed_x + CHEVRON_FROM_SPEED)]
return {'front': top, '': top, 'rear': [('bottom', speed_x)], 'side': [('left', height / 2), ('right', height / 2)]}.get(direction, top)
class UnidenWidget:
def __init__(self, fonts, feed=None):
self.fonts = fonts
self.feed = feed or DetectorFeed()
self.pressed = None
self.held = False
self.motion = EdgeMotion()
self.runtime_active = False
self.preview_data = None
self.visible_until = 0.
self.session = None
self.claimed = False
def activate(self, session):
self.session, self.runtime_active = session, True
return self
@staticmethod
def placement(state):
if state is None or state.alert.size != 'none':
return None
p = state.customization['layouts']['large'].get(UNIDEN_WIDGET)
return p if p and p['enabled'] else None
def render(self, state):
p = self.placement(state)
self.visible_until = 0.
if self.session is None: # the comma shell drives its own feed
self.feed.set_enabled(self.runtime_active)
data = self.preview_data or self.feed.snapshot()
if not p or not data.get('config', {}).get('enabled'):
return
config = {**data.get('config', {}), **p}
if data.get('offline'):
self._offline(state, config, p['x'], p['y'])
return
if self.pressed and not self.held and time.monotonic() - self.pressed[3] >= HOLD_S:
self.held = True
self.feed.lock_here(data)
alerts = shown_alerts(data.get('alerts', []), data.get('config', {}))
if not alerts and config.get('hide_when_no_alert', True):
return
self.visible_until = time.monotonic() + 1
scale = card_scale(config)
if scale == 1:
self._card(state, data, alerts, config, p['x'], p['y'])
return
rl.rl_push_matrix()
try:
rl.rl_translatef(p['x'], p['y'], 0)
rl.rl_scalef(scale, scale, 1)
self._card(state, data, alerts, config, 0, 0)
finally:
rl.rl_pop_matrix()
def _offline(self, state, config, x, y):
width, height = OFFLINE_SIZE
palette = widget_palette({'palette': PALETTE, **state.customization}, 'large', UNIDEN_WIDGET)
fill = hex_color(palette['cardFill'])
rl.draw_rectangle_rounded(rl.Rectangle(x, y, width, height), .5, 12,
rl.Color(fill.r, fill.g, fill.b, round(fill.a * (100 - config.get('transparency', 8)) / 100)))
outline(x, y, width, height, hex_color(palette['cardBorder']))
self.fonts.draw('DETECTOR OFFLINE', FontRole.SEMI_BOLD, 26, x + 24, y + 13, rl.Color(255, 186, 78, 255))
def render_border(self, state, width, height):
"""Frame the view for a live Ka, K or Laser alert, on top of the engagement border and any openpilot alert."""
data = self.feed.snapshot()
if data.get('offline') and data.get('config', {}).get('enabled') and self.placement(state) is None:
self._offline(state, data['config'], (width - OFFLINE_SIZE[0]) / 2, BADGE_TOP)
config = data.get('config', {})
alert = threat(shown_alerts(data.get('alerts', []), config), config.get('border_bands', ())) if data.get('connected') else None
still = state.customization.get('reduceMotion')
now = time.monotonic()
self.motion.update(alert, now, still)
if alert is None:
if (fade := self.motion.fading(now)) is not None:
self._edge(state, data.get('config', {}), fade[0], width, height, now, fade[1])
return
self._edge(state, data['config'], alert, width, height, now, 1.)
@staticmethod
def _color(config, alert):
"""The band's frame color, and how much of it a mute leaves: 0 hides the frame while muted."""
colors = {**DEFAULT_CONFIG['border_colors'], **config.get('border_colors', {})}
# Muted by the detector, or quieted by StarPilot (timed mute, below the limit, lockout or frequency rule).
muted = alert.get('muted') or alert.get('timed') or alert.get('quiet') or alert.get('filtered')
return hex_color(BORDER_SWATCHES[colors[alert['band']]] + 'FF'), \
config.get('border_muted_percent', DEFAULT_CONFIG['border_muted_percent']) / 100 if muted else 1.
def _edge(self, state, config, alert, width, height, now, presence):
color, mute = self._color(config, alert)
if mute == 0:
return
parts = {**DEFAULT_CONFIG['border_edge'], **config.get('border_edge', {})}
content = rl.Rectangle(EDGE_FRAME, EDGE_FRAME, width - 2 * EDGE_FRAME, height - 2 * EDGE_FRAME)
radius = EDGE_ROUNDNESS * min(content.width, content.height) / 2
s, boost, laser = (alert['strength'] - 1) / 7, self.motion.boost(now), alert['band'] == 'LASER'
alpha = (.95 if laser else .45 + .45 * s) if parts['glow'] else (1. if laser else .85)
alpha = min(1., alpha * (1 + .9 * boost)) * mute * presence
depth = (GLOW_DEPTH[0] + (GLOW_DEPTH[1] - GLOW_DEPTH[0]) * s) * (1 + .35 * boost)
sides = DIRECTION_SIDES.get(alert['direction'])
if parts['veil']:
glow_ring(content, radius, depth * 1.3, VEIL_ALPHA * min(1., alpha / .6), rl.Color(0, 0, 0, 255))
if parts['glow'] and sides:
# The facing edge carries the glow; the rest keeps a faint rim. Corners stay with the rim.
glow_ring(content, radius, max(18., depth * .3), alpha * .5, color)
deep, x, y, w, h = depth * 1.6, content.x, content.y, content.width, content.height
for side in sides:
for near, far, a, b in ((0, .45, 1., .35), (.45, 1., .35, 0.)):
start, size = deep * near, deep * (far - near)
first, second = tint(color, alpha * a), tint(color, alpha * b)
if side == 'top':
rl.draw_rectangle_gradient_v(int(x + radius), int(y + start), int(w - 2 * radius), int(size), first, second)
elif side == 'bottom':
rl.draw_rectangle_gradient_v(int(x + radius), int(y + h - start - size), int(w - 2 * radius), int(size), second, first)
elif side == 'left':
rl.draw_rectangle_gradient_h(int(x + start), int(y + radius), int(size), int(h - 2 * radius), first, second)
else:
rl.draw_rectangle_gradient_h(int(x + w - start - size), int(y + radius), int(size), int(h - 2 * radius), second, first)
elif parts['glow']:
glow_ring(content, radius, depth, alpha, color)
if parts['line']:
frame = RoundedFrame(rl.Rectangle(content.x + EDGE_GAP, content.y + EDGE_GAP, content.width - 2 * EDGE_GAP, content.height - 2 * EDGE_GAP),
EDGE_LINE, radius - EDGE_GAP)
line = tint(color, min(1., alpha * 1.15))
if parts['dashes']:
at = 0.
while at < frame.total:
frame.draw(at, min(DASH, frame.total - at), line)
at += DASH + DASH_GAP
else:
frame.ring(line)
if parts['chevrons']:
try:
speed_x = width / 2 + offset(state.customization, 'large', 'current_speed')[0]
except (KeyError, TypeError):
speed_x = width / 2
mark = tint(color, min(1., alpha * 1.1))
for side, along in chevron_sets(alert['direction'], width, height, speed_x):
for i in range(math.ceil(alert['strength'] / 2)):
first, apex, last = chevron_points(side, along, content, i)
rl.draw_line_ex(first, apex, CHEVRON_WIDTH, mark)
rl.draw_line_ex(apex, last, CHEVRON_WIDTH, mark)
def _card(self, state, data, alerts, config, x, y):
width, height = card_size(alerts)
palette = widget_palette({'palette': PALETTE, **state.customization}, 'large', UNIDEN_WIDGET)
ink, fill, border = (hex_color(palette[key]) for key in ('text', 'cardFill', 'cardBorder'))
text = rl.Color(ink.r, ink.g, ink.b, 255)
dim = rl.Color(round(ink.r * .7), round(ink.g * .7), round(ink.b * .7), 255)
rl.draw_rectangle_rounded(rl.Rectangle(x, y, width, height), RADIUS * 2 / min(width, height), 12,
rl.Color(fill.r, fill.g, fill.b, round(fill.a * (100 - config.get('transparency', 8)) / 100)))
def label(value, size, dx, dy, color=text):
self.fonts.draw(value, FontRole.SEMI_BOLD, size, x + dx, y + dy, color)
if not data.get('connected') or not alerts:
outline(x, y, width, height, border)
label('UNIDEN', 22, 24, 20, dim)
if not data.get('connected'):
label('Detector disconnected', 28, 24, 56)
label('Waiting for fresh alerts', 20, 24, 105, dim)
else:
label('Detector ready', 28, 24, 56, rl.Color(100, 214, 151, 255))
label('No active alerts', 20, 24, 105, dim)
return
# Mute status has its own right-hand label so strength and notices cannot hide it.
muted = sum(bool(item['muted']) for item in alerts)
quieted = sum(bool(mute_reason(item)) for item in alerts)
gaps = []
note_right = x + width - 20
if quieted:
status = 'MUTED' if quieted == len(alerts) else f'{quieted} MUTED'
measured = self.fonts.measure(status, FontRole.SEMI_BOLD, NOTE_SIZE)
mute_gap = (x + width - 20 - measured.width - 16, x + width - 20)
gaps.append(mute_gap)
self.fonts.draw(status, FontRole.SEMI_BOLD, NOTE_SIZE, mute_gap[0] + 8,
y + BORDER / 2 - measured.height / 2, rl.Color(255, 91, 101, 255))
note_right = mute_gap[0] - 12
notes = [data.get('notice') or ('Strong signal' if any(a.get('breakthrough') for a in alerts) else
mute_note(alerts) or ('Mute sent' if data.get('command') and muted < len(alerts) else ''))]
if len(alerts) > MAX_ROWS:
notes.append(f'+{len(alerts) - MAX_ROWS} more')
note = ' • '.join(n for n in notes if n)
if note:
size = NOTE_SIZE
available = note_right - (x + 20) - 16
original = note
while note and self.fonts.measure(note, FontRole.SEMI_BOLD, size).width > available:
original = original[:-1].rstrip()
note = original + '…' if original else ''
measured = self.fonts.measure(note, FontRole.SEMI_BOLD, size)
if note:
gap = (x + 20, x + 20 + measured.width + 16)
gaps.append(gap)
self.fonts.draw(note, FontRole.SEMI_BOLD, size, gap[0] + 8, y + BORDER / 2 - measured.height / 2, border)
outline(x, y, width, height, border, gaps)
shown = alerts[:MAX_ROWS]
band_size, frequency_size = 36, 28
band_width = max(self.fonts.measure(item['band'], FontRole.SEMI_BOLD, band_size).width for item in shown)
frequency_x = 24 + max(64, band_width + 18)
arrows = data.get('model') == 'R8'
arrow_x = width - 24 - 25 # room for the two side arrows, which sit either side of this
bars_x = (arrow_x - 25 - 18 if arrows else width - 24) - 8 * 11 + 3
for row, item in enumerate(shown):
cy = PAD + ROW * row + ROW / 2
faded = item['muted'] and muted < len(alerts)
tone = rl.Color(255, 91, 101, 255) if item['band'] in ('KA', 'LASER') else rl.Color(255, 186, 78, 255)
if faded:
tone = rl.Color(round(tone.r * .55), round(tone.g * .55), round(tone.b * .55), 255)
band = self.fonts.measure(item['band'], FontRole.SEMI_BOLD, band_size)
label(item['band'], band_size, 24, cy - band.height / 2, tone)
if item['frequency'] is not None or item['band'] != 'LASER':
frequency = f"{item['frequency']:.3f} GHz" if item['frequency'] is not None else 'Gatso'
measured = self.fonts.measure(frequency, FontRole.SEMI_BOLD, frequency_size)
label(frequency, frequency_size, frequency_x, cy - measured.height / 2, dim if faded else text)
for i in range(8):
bar_height = 8 + i * 3
lit = i < item['strength']
fill = signal_color(item['strength'], i) if lit else rl.Color(53, 67, 77, 255)
if lit and faded:
fill = rl.Color(round(fill.r * .55), round(fill.g * .55), round(fill.b * .55), 255)
rl.draw_rectangle(int(x + bars_x + i * 11), int(y + cy + 15 - bar_height), 8, bar_height, fill)
if arrows:
direction_arrows(x + arrow_x, y + cy, item['direction'], tone, 15)
def touch(self, kind, x, y, state):
p, data = self.placement(state), self.feed.snapshot()
config = {**data.get('config', {}), **(p or {})}
shown = shown_alerts(data.get('alerts', []), data.get('config', {}))
valid = (p is not None and time.monotonic() < self.visible_until and data.get('connected') and
data.get('can_mute') and bool(shown))
scale = card_scale(config)
width, height = (side * scale for side in card_size(shown))
inside = valid and p['x'] <= x <= p['x'] + width and p['y'] <= y <= p['y'] + height
key = (data.get('address'), alert_key(data.get('alerts', [])))
if kind == 'down':
self.pressed = (key, x, y, time.monotonic()) if inside else None
self.held = False
claimed = self.pressed is not None
if kind in ('move', 'up') and self.pressed:
old, px, py, _ = self.pressed
if not inside or old != key or (px - x) ** 2 + (py - y) ** 2 > 36 ** 2:
self.pressed = None
elif kind == 'up' and not self.held:
self.feed.mute(data)
if kind in ('up', 'cancel'):
self.pressed, self.held = None, False
return claimed
def _state(self, mode):
return self.session.snapshot(mode).onroad if mode == ShellMode.ONROAD else None
def press(self, mode, x, y):
session = self.session
self.claimed = bool(mode == ShellMode.ONROAD and not session.favorites.is_open and self.touch('down', x, y, self._state(mode)))
if self.claimed:
session.input.cancel()
return self.claimed
def move(self, mode, x, y):
if self.claimed:
self.touch('move', x, y, self._state(mode))
return self.claimed
def release(self, mode, x, y):
claimed, self.claimed = self.claimed, False
if claimed:
self.touch('up', x, y, self._state(mode))
return claimed
def cancel(self):
self.claimed = False
self.touch('cancel', 0, 0, None)
def close(self):
self.feed.close()
+32
View File
@@ -105,6 +105,7 @@ from openpilot.system.ui.widgets import Widget
from openpilot.system.ui.widgets.list_view import button_item, text_item, toggle_item
from openpilot.starpilot.ui.compact_settings_page import StarCompactSettings as StarCompactSettings
DETECTOR_CHECK_S = 5.
NATIVE_SETTINGS_PANELS = (Destination.DEVICE, Destination.SOFTWARE, Destination.BLUETOOTH, Destination.TOGGLES, Destination.DEVELOPER)
_FEATURE_SETTINGS_PANES = {
Destination.DRIVING_CONTROLS: ("features", "feature", "features"),
@@ -159,6 +160,10 @@ def visual_border_state(state: OnroadState, signals: Signals) -> OnroadState:
class StarShellSession(TeslaSpeedActions):
"""Own native shell resources and one request/router boundary per app."""
uniden = None
detector_feed = None
_detector_checked_at = -DETECTOR_CHECK_S
_detector_configured = False
def __init__(self, profile: Profile, camera_owner: Any, *, network_layer: Any = None, settings_layer: Any = None):
font_dir = os.environ.get("STARPILOT_UI_FONT_DIR")
@@ -323,12 +328,29 @@ class StarShellSession(TeslaSpeedActions):
pass # Car-screen speed-limit taps stay unavailable without affecting the native UI.
self.onroad_map = self.onroad_jetlink = None
if profile == Profile.LARGE:
self.uniden = self.view.onroad.uniden.activate(self)
from openpilot.starpilot.ui.onroad_map_layer import NativeMapLayer
self.onroad_map = NativeMapLayer(self.fonts, ui_state)
self.view.onroad.map_layer = self.onroad_map.render
from openpilot.starpilot.ui.onroad_jetlink_layer import NativeJetlinkLayer
self.onroad_jetlink = NativeJetlinkLayer(self.view.onroad.jetlink_status, ui_state)
self.view.onroad.jetlink_status = self.onroad_jetlink
from openpilot.starpilot.uniden.feed import DetectorFeed
# Poll the detector whenever onroad, with or without a widget.
self.detector_feed = self.uniden.feed if self.uniden else DetectorFeed()
def _poll_detector(self) -> None:
if not self.detector_feed:
return
now = time.monotonic()
if now - self._detector_checked_at >= DETECTOR_CHECK_S:
self._detector_checked_at = now
try:
config = ui_state.params.get('UnidenConfig')
except (TypeError, ValueError):
config = None
self._detector_configured = isinstance(config, dict) and config.get('enabled') is True and bool(config.get('address'))
self.detector_feed.set_enabled(self._detector_configured and bool(ui_state.started) and getattr(ui_state, 'replay_clock', None) is None)
def _favorite_authority(self, *, allow_personality_notice: bool = False) -> bool:
if getattr(ui_state, "replay_clock", None) is not None:
@@ -1744,6 +1766,8 @@ class StarShellSession(TeslaSpeedActions):
def press(self, mode: ShellMode, x: float, y: float) -> None:
self._request_emitted = False
self._mode = mode
if self.uniden and self.uniden.press(mode, x, y):
return
if mode == ShellMode.SETTINGS:
snapshot = self._settings_press_snapshot()
self.input.press(x, y, time.monotonic(), snapshot)
@@ -1775,6 +1799,8 @@ class StarShellSession(TeslaSpeedActions):
def move(self, mode: ShellMode, x: float, y: float, *, timestamp: float | None = None) -> None:
self._mode = mode
if self.uniden and self.uniden.move(mode, x, y):
return
if mode == ShellMode.SETTINGS:
if snapshot := self._settings_gesture_snapshot():
self.input.move(x, y, timestamp, snapshot)
@@ -1790,6 +1816,8 @@ class StarShellSession(TeslaSpeedActions):
def release(self, mode: ShellMode, x: float, y: float, *, timestamp: float | None = None) -> bool:
self._mode = mode
if self.uniden and self.uniden.release(mode, x, y):
return True
if mode == ShellMode.SETTINGS:
snapshot = self._settings_gesture_snapshot()
self._settings_touch = None
@@ -1810,6 +1838,8 @@ class StarShellSession(TeslaSpeedActions):
return self._request_emitted or getattr(self, '_onroad_claimed', False)
def cancel(self) -> None:
if self.uniden:
self.uniden.cancel()
if pending := getattr(self, "_aol_save", None):
pending.cancel.set()
self._settings_touch = None
@@ -1827,6 +1857,8 @@ class StarShellSession(TeslaSpeedActions):
def close(self) -> None:
if receiver := getattr(self, "rear_fog", None):
receiver.close()
if self.detector_feed:
self.detector_feed.close()
if layer := getattr(self, 'onroad_jetlink', None):
layer.close()
self.onroad_jetlink = None
@@ -185,7 +185,8 @@ def make_session(monkeypatch, request, profile, camera):
monkeypatch.setattr(runtime_app, 'ui_state', NS(params=object(), CP=None, sm={}))
monkeypatch.delenv('SP_ONROAD_VISUAL_PREVIEW', raising=False)
def view(*_, camera_layer, **__):
return NS(camera_layer=camera_layer, onroad=NS(unified_speed=NS(source_bounds=Mock()), compact_sidebar=NS(), jetlink_status=Mock()))
return NS(camera_layer=camera_layer, onroad=NS(unified_speed=NS(source_bounds=Mock()), compact_sidebar=NS(), jetlink_status=Mock(),
uniden=NS(activate=lambda session: None)))
monkeypatch.setattr(runtime_app, 'ShellView', view)
session = runtime_app.StarShellSession(profile, camera)
for owner in (session._projection_bookmarks, session._projection_slc, session.onroad_map, session.onroad_jetlink):
@@ -150,6 +150,7 @@ def test_renderer_dispatches_each_widget_in_saved_order(profile, viewport):
view.now_playing = NS(render=lambda state: seen.append('now_playing'))
view.jetlink_status = NS(render=lambda state: seen.append('jetlink_status'))
view.network_signal = NS(render=lambda state: seen.append('network_signal'))
view.uniden = NS(render=lambda state: seen.append('uniden_alerts'))
document['widgetOrder'] = {profile: order}
state = NS(customization=document, camera_available=True, viewport_width=1860, alert=NS(size='none'), stopped_duration_s=65,
appearance=NS(camera_view='road'))
@@ -4552,12 +4552,6 @@
"openpilot/starpilot/galaxy/web/js/install-app.js"
]
},
{
"source": "Download all logs",
"refs": [
"openpilot/starpilot/galaxy/web/js/logs.js"
]
},
{
"source": "Download all logs (.tar)",
"refs": [
@@ -8511,12 +8505,6 @@
"openpilot/starpilot/galaxy/web/js/vehicle-controls.js"
]
},
{
"source": "Log summaries remain available.",
"refs": [
"openpilot/starpilot/galaxy/web/js/logs.js"
]
},
{
"source": "Log uploads",
"refs": [
@@ -17441,12 +17429,6 @@
"openpilot/starpilot/galaxy/web/js/onroad-layout-template.js"
]
},
{
"source": "The last 20 connection sessions, newest first. The archive includes every session, a readable report for each, StarPort settings, the car view's renderer logs, and a snapshot of the device (Wi-Fi, Bluetooth and kernel logs, build, CPU load). Hardware addresses are masked.",
"refs": [
"openpilot/starpilot/galaxy/web/js/logs.js"
]
},
{
"source": "The last update was invalid.",
"refs": [
+69
View File
@@ -0,0 +1,69 @@
# Uniden R4/R8 integration
## Setup
Pair an R4/R8 in Galaxy → Bluetooth → Add a device → Search, then open the
**Uniden** tab, select it and choose **Use this detector**. The model is
inferred from the paired device name. The Uniden page (`#/bluetooth/uniden`)
shows connection status, **Change detector**, preferences, colors, frequency
rules and lockouts. Settings require the selected detector to remain paired;
edits require Park. Settings are stored in `UnidenConfig`. Widget size,
position, background transparency and *Hide when no alert* are in the theme
maker layout.
While the large driving UI is active, the feed polls every 100 ms after the
previous exchange completes when the integration is enabled (one second when
off), even with the widget hidden or covered by an openpilot alert. Leaving the
driving UI stops it. Both local Bluetooth and the StarPort owner run the same
exchange.
## Rules
- **Frequency rules.** Up to 32 rules with a label, X/K/KA band, frequency in GHz
and tolerance in MHz. For a 34.313 GHz head unit use KA / 34.313 / 0 MHz; 2 MHz
would match 34.311–34.315 GHz. Rules apply everywhere and cannot tell apart
transmitters on the same frequency. They are stored on the comma, not in the
detector's mute memory.
- **Mute delivery.** The detector has one general mute command (`BTreqMUTE:1`),
not a per-signal mute. Automatic mute (rules, lockouts, Quiet Ride, timed mute)
is sent in the same exchange as the snapshot, only when every active alert
qualifies, and retried at most every 500 ms. A write is never treated as
confirmation; only a later alert packet confirms a mute. Tap-to-mute requires
a fresh snapshot of the same alerts.
- **Hold to lock out.** Holding a live alert for about a second locks it out
within 300 m of where you are (at the pass point if the car just passed it).
Remove lockouts under Uniden → Lockouts, including while driving.
- **Learned lockouts** (off by default). A pass of a fixed source (the R8's
front → side → rear flip, or an R4's strength peak) passed again on separate
trips at least 10 minutes apart becomes a lockout: 3 passes for X and K, 5 for
Ka and Laser, for the chosen bands. Drive-bys where the signal is missing count
as misses; a source is learned only if misses are at most half its passes, and
a learned lockout whose misses outnumber its passes is removed. A signal more
than two levels stronger than any seen there still alerts. Unseen learned
lockouts expire after 90 days.
- **Quiet Ride** (off by default). Mutes the chosen bands while at or under the
posted limit plus a margin. Needs a fresh GPS fix and a valid limit. A signal
that appears at strength 5 or more is never quieted.
- **Timed mute** (off by default). Each new X, K or Ka signal beeps for its
band's delay, then is muted. Laser and suddenly strong signals are not. If the
signal reaches the band's warn-again strength it stays loud until it clears,
and StarPilot sends `BTreqMUTE:0` to undo a mute the timer sent (never the
driver's own), at most three times per set of alerts. *Never* keeps it muted.
- **Full-screen warning.** A segmented line inside the engagement border, with
optional chevrons toward the signal, glow and veil, for live alerts in the
chosen bands (Ka and Laser by default), each in its own color. Muted alerts dim
it to the chosen brightness.
- **Offline badge.** If the selected detector is not connected for 10 seconds
while driving, a DETECTOR OFFLINE badge replaces the card, or shows at the top
of the view when the widget is off or covered.
Lockouts and learned sources stay on the comma in
`/data/starpilot/uniden/locks.json`. Nothing goes into route logs or cereal;
cloudlog records only failures, never positions.
## Checks
- `./dev pytest openpilot/starpilot/uniden/tests openpilot/starpilot/galaxy/tests/test_uniden_http.py -q`
- `node --test openpilot/starpilot/galaxy/tests/test_uniden.mjs`
- `node openpilot/starpilot/galaxy/tests/browser/uniden.cjs` (Playwright; supports
`PLAYWRIGHT_MODULE` and `PLAYWRIGHT_EXECUTABLE_PATH` overrides).
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Aegis "P.R Aigis"
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+1
View File
@@ -0,0 +1 @@
"""Uniden detector alerts, independent of driving radar and vehicle controls."""
+167
View File
@@ -0,0 +1,167 @@
"""Bounded polling and mute delivery off the rendering thread; no queued command replay."""
import threading
import time
from typing import Any
from openpilot.common.swaglog import cloudlog
from openpilot.starpilot.uniden.protocol import alert_key
ENDPOINT = '/api/bluetooth/uniden'
OFFLINE_S = 10
NOTICE_S = 2.5
HOLD_S = .75 # a failed or empty read this soon after alerts keeps them, so one bad poll does not blink the card and frame
FAILURES = (AttributeError, ImportError, OSError, RuntimeError, TypeError, ValueError)
def drive_context():
"""Position, speed and posted limit from the live services; None until there is a fix."""
import capnp
from openpilot.cereal import messaging
services = (messaging.IpcError, capnp.KjException)
try:
sm = messaging.SubMaster(['gpsLocationExternal', 'carState', 'slcState'])
except services as error:
raise OSError(str(error)) from error
fix = {}
def read():
try:
sm.update(0)
return current()
except services as error:
raise OSError(str(error)) from error
def current():
if sm.updated['gpsLocationExternal'] and sm['gpsLocationExternal'].hasFix:
gps = sm['gpsLocationExternal']
fix.update(lat=gps.latitude, lon=gps.longitude, heading=gps.bearingDeg, speed=gps.speed, at=time.monotonic())
if not fix or not sm.alive['gpsLocationExternal']:
return None
limit = sm['slcState']
return {**fix, 'speed': sm['carState'].vEgo if sm.alive['carState'] else fix['speed'],
'limit': limit.speedLimit if sm.alive['slcState'] and limit.observationKind == 'valid' and limit.speedLimit > 0 else None}
return read
class DetectorFeed:
def __init__(self, call=None, clock=time.monotonic, context=None):
self.call, self.clock, self.context = call, clock, context
self.lock = threading.Lock()
self.stop = threading.Event()
self.thread = None
self.enabled = False
self.requested_at = 0
self.live_at = 0
self.alerts_at = None
self.state: dict[str, Any] = {}
self.pending = None
self.notice = ('', 0)
self.logged = None
def set_enabled(self, enabled):
with self.lock:
if enabled and not self.enabled:
self.live_at = self.clock()
self.enabled = enabled
self.requested_at = self.clock()
if not enabled:
self.state, self.pending = {}, None
if enabled and self.thread is None:
self.thread = threading.Thread(target=self.run, name='uniden-display', daemon=True)
self.thread.start()
def snapshot(self) -> dict[str, Any]:
with self.lock:
state: dict[str, Any] = self.state
notice, live_at = self.notice, self.live_at
at = state.get('observed_at', -1e9)
if state.get('connected') and not 0 <= self.clock() - at < 3:
state = {**state, 'connected': False, 'alerts': [], 'error': 'Detector data unavailable'}
if self.clock() < notice[1]:
state = {**state, 'notice': notice[0]}
if state.get('config', {}).get('enabled') and not state.get('connected') and self.enabled and self.clock() - live_at >= OFFLINE_S:
state = {**state, 'offline': True}
return state
def mute(self, state):
with self.lock:
if self.enabled and self.pending is None and state.get('connected') and state.get('can_mute') and state.get('alerts'):
self.pending = self.request('mute', state)
def lock_here(self, state):
with self.lock:
if self.enabled and self.pending is None and state.get('connected') and state.get('can_mute') and state.get('alerts'):
self.pending = self.request('lock', state)
@staticmethod
def request(operation, state):
return {'operation': operation, 'address': state['address'], 'observed_at': state['observed_at'], 'alerts': alert_key(state['alerts'])}
def _log(self, where, error):
if self.logged != (where, str(error)):
self.logged = (where, str(error))
cloudlog.exception(f'uniden feed: {where} failed')
def drive(self):
if self.context is None:
try:
self.context = drive_context()
except FAILURES as error:
self._log('drive context', error)
self.context = lambda: None
try:
return self.context()
except FAILURES as error:
self._log('drive context', error)
return None
def poll(self):
with self.lock:
if not self.enabled or self.clock() - self.requested_at > 1:
self.state, self.pending = {}, None
return
payload, self.pending = self.pending, None
if payload is None:
payload = {'operation': 'status'}
if (context := self.drive()) is not None:
payload['context'] = context
try:
if self.call is None:
from openpilot.starpilot.galaxy_bluetooth.phone_ui import galaxy_call
self.call = galaxy_call()
status, result = self.call('POST', ENDPOINT, payload)
if status != 200:
raise RuntimeError(result.get('error', 'Detector unavailable'))
except FAILURES as error:
self._log(payload['operation'], error)
result = {'connected': False, 'alerts': [], 'error': str(error)[:100]}
if payload['operation'] == 'lock':
with self.lock:
self.notice = (str(error)[:40] or 'Could not lock out', self.clock() + NOTICE_S)
return
if payload['operation'] == 'lock':
with self.lock:
self.notice = (f"Locked out here ({result.get('locked', 0)})", self.clock() + NOTICE_S)
return
with self.lock:
if self.enabled:
if result.get('connected') and result.get('alerts'):
self.alerts_at = self.clock()
elif self.alerts_at is not None and self.clock() - self.alerts_at < HOLD_S and self.state.get('alerts'):
return
else:
self.alerts_at = None
self.state = {**result, 'config': result.get('config', self.state.get('config', {}))}
if result.get('connected'):
self.live_at = self.clock()
def run(self):
while not self.stop.is_set():
self.poll()
self.stop.wait(0.1 if self.state.get('config', {}).get('enabled') else 1.0)
def close(self):
self.set_enabled(False)
self.stop.set()
if self.thread is not None:
self.thread.join(timeout=1)
+234
View File
@@ -0,0 +1,234 @@
"""Place-based lockouts and their learning. Local to the device and never part of the route logs."""
import json
import math
import os
import stat
import uuid
from pathlib import Path
from openpilot.common.swaglog import cloudlog
from openpilot.starpilot.uniden.protocol import LOCK_BANDS, RULE_BOUNDS
ROOT = Path('/data/starpilot/uniden')
MAX_LOCKS, MAX_CANDIDATES = 256, 200
MERGE_M, REPEAT_S, EXPIRE_S = 150, 600, 90 * 86400
VISIT_M, MIN_SPEED = 150, 3.0
LEARN_COUNT = {'X': 3, 'K': 3, 'KA': 5, 'LASER': 5}
LOCK_KEYS = {'id', 'source', 'enabled', 'band', 'frequency', 'tolerance_mhz', 'lat', 'lon', 'radius_m', 'heading',
'heading_tolerance', 'max_strength', 'created', 'seen', 'count', 'misses'}
CANDIDATE_KEYS = {'id', 'band', 'frequency', 'lat', 'lon', 'count', 'misses', 'last', 'max_strength'}
MAX_BYTES = 1 << 20
def distance_m(lat1, lon1, lat2, lon2):
x = math.radians(lon2 - lon1) * math.cos(math.radians((lat1 + lat2) / 2))
return 6371000 * math.hypot(x, math.radians(lat2 - lat1))
def heading_gap(a, b):
return abs((a - b + 180) % 360 - 180)
def number(value, low, high):
return type(value) in (int, float) and math.isfinite(value) and low <= value <= high
def normalize_lock(lock):
if type(lock) is not dict or set(lock) != LOCK_KEYS:
raise ValueError('Invalid lockout')
band = lock['band']
if band not in LOCK_BANDS or lock['source'] not in ('tap', 'auto') or type(lock['enabled']) is not bool or type(lock['id']) is not str:
raise ValueError('Invalid lockout')
if band == 'LASER':
if lock['frequency'] is not None:
raise ValueError('Laser lockouts have no frequency')
elif not number(lock['frequency'], *RULE_BOUNDS[band]):
raise ValueError('Invalid lockout frequency')
if not (number(lock['tolerance_mhz'], 0, 10) and number(lock['lat'], -90, 90) and number(lock['lon'], -180, 180) and
number(lock['radius_m'], 50, 1000) and number(lock['max_strength'], 1, 8) and number(lock['created'], 0, 1e12) and
number(lock['seen'], 0, 1e12) and type(lock['count']) is int and lock['count'] >= 1 and
type(lock['misses']) is int and lock['misses'] >= 0):
raise ValueError('Invalid lockout')
if lock['heading'] is not None and not (number(lock['heading'], 0, 360) and number(lock['heading_tolerance'], 10, 180)):
raise ValueError('Invalid lockout heading')
return dict(lock)
def normalize_candidate(candidate):
if type(candidate) is not dict:
raise ValueError('Invalid learning candidate')
candidate = {'misses': 0, 'id': uuid.uuid4().hex[:12], **candidate}
band = candidate.get('band')
if set(candidate) != CANDIDATE_KEYS or type(candidate['id']) is not str or band not in LOCK_BANDS:
raise ValueError('Invalid learning candidate')
if not ((candidate['frequency'] is None) if band == 'LASER' else number(candidate['frequency'], *RULE_BOUNDS[band])):
raise ValueError('Invalid learning candidate')
if not (number(candidate['lat'], -90, 90) and number(candidate['lon'], -180, 180) and number(candidate['last'], 0, 1e12) and
number(candidate['max_strength'], 1, 8) and type(candidate['count']) is int and candidate['count'] >= 1 and
type(candidate['misses']) is int and candidate['misses'] >= 0):
raise ValueError('Invalid learning candidate')
return candidate
def valid_entries(normalize, items):
result = []
for item in items if type(items) is list else []:
try:
result.append(normalize(item))
except (TypeError, ValueError):
continue
return result
def read_store(path):
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
try:
if not stat.S_ISREG(os.fstat(fd).st_mode):
raise ValueError('Lockout store is not a regular file')
raw = os.read(fd, MAX_BYTES + 1)
finally:
os.close(fd)
if len(raw) > MAX_BYTES:
raise ValueError('Lockout store is too large')
data = json.loads(raw)
return data if type(data) is dict else {}
def new_lock(source, event, now, **fields):
lock = {'id': uuid.uuid4().hex[:12], 'source': source, 'enabled': True, 'band': event['band'], 'frequency': event['frequency'],
'tolerance_mhz': 0 if event['band'] == 'LASER' else 3, 'lat': event['lat'], 'lon': event['lon'], 'radius_m': 300,
'heading': None, 'heading_tolerance': 60, 'max_strength': 8, 'created': int(now), 'seen': int(now), 'count': 1, 'misses': 0}
lock.update(fields)
return normalize_lock(lock)
def matches_lock(alert, lock, context):
if context is None or not lock['enabled'] or alert['band'] != lock['band']:
return False
if lock['band'] != 'LASER':
frequency = alert.get('frequency')
if frequency is None or abs(frequency - lock['frequency']) > lock['tolerance_mhz'] / 1000 + 1e-9:
return False
# A signal stronger than any seen here is not the known source.
if alert['strength'] > lock['max_strength'] + 2:
return False
if distance_m(context['lat'], context['lon'], lock['lat'], lock['lon']) > lock['radius_m']:
return False
return lock['heading'] is None or (context.get('heading') is not None and
heading_gap(context['heading'], lock['heading']) <= lock['heading_tolerance'])
def same_signal(a, b):
if a['band'] != b['band']:
return False
if a['frequency'] is None or b['frequency'] is None:
return a['frequency'] is b['frequency'] or a['frequency'] == b['frequency']
return abs(a['frequency'] - b['frequency']) <= .003 + 1e-9
class LockStore:
def __init__(self, root=ROOT):
self.path = Path(root) / 'locks.json'
self.visits = {}
try:
data = read_store(self.path)
except FileNotFoundError:
data = {}
except (OSError, ValueError):
cloudlog.exception('uniden: unreadable lockout store')
data = {}
self.locks = valid_entries(normalize_lock, data.get('locks'))[:MAX_LOCKS]
self.candidates = valid_entries(normalize_candidate, data.get('candidates'))[:MAX_CANDIDATES]
def save(self, locks=None):
self.path.parent.mkdir(parents=True, exist_ok=True)
temporary = self.path.with_suffix('.tmp')
temporary.write_text(json.dumps({'locks': self.locks if locks is None else locks, 'candidates': self.candidates}))
os.replace(temporary, self.path)
def active(self):
return [dict(lock) for lock in self.locks if lock['enabled']]
def add(self, lock):
if len(self.locks) >= MAX_LOCKS:
raise ValueError('Remove a lockout before adding another')
locks = [*self.locks, lock]
self.save(locks)
self.locks = locks
def remove(self, lock_id):
kept = [lock for lock in self.locks if lock['id'] != lock_id]
if len(kept) == len(self.locks):
raise ValueError('Unknown lockout')
self.save(kept)
self.locks = kept
def prune(self, now):
self.locks = [lock for lock in self.locks if lock['source'] == 'tap' or now - lock['seen'] < EXPIRE_S]
self.candidates = sorted((c for c in self.candidates if now - c['last'] < EXPIRE_S), key=lambda c: -c['last'])[:MAX_CANDIDATES]
def observe(self, event, *, learn, bands):
"""A confirmed pass of a fixed source. Returns the lockout it just earned, if any."""
now = event['at']
self.prune(now)
for lock in self.locks:
if same_signal(lock, event) and distance_m(event['lat'], event['lon'], lock['lat'], lock['lon']) <= lock['radius_m']:
self.visits[lock['id']] = True
if now - lock['seen'] >= REPEAT_S:
lock['seen'], lock['count'] = int(now), lock['count'] + 1
if lock['source'] == 'auto':
lock['max_strength'] = max(lock['max_strength'], event['strength'])
self.save()
return None
candidate = next((c for c in self.candidates if same_signal(c, event) and
distance_m(event['lat'], event['lon'], c['lat'], c['lon']) <= MERGE_M), None)
if candidate is None:
new_id = uuid.uuid4().hex[:12]
self.visits[new_id] = True
self.candidates.append({'id': new_id, 'band': event['band'], 'frequency': event['frequency'], 'lat': event['lat'],
'lon': event['lon'], 'count': 1, 'misses': 0, 'last': now, 'max_strength': event['strength']})
self.save()
return None
self.visits[candidate['id']] = True
if now - candidate['last'] < REPEAT_S:
return None
count = candidate['count']
candidate['lat'] = (candidate['lat'] * count + event['lat']) / (count + 1)
candidate['lon'] = (candidate['lon'] * count + event['lon']) / (count + 1)
candidate.update(count=count + 1, last=now, max_strength=max(candidate['max_strength'], event['strength']))
lock = None
if (learn and event['band'] in bands and candidate['count'] >= LEARN_COUNT[event['band']] and
candidate['misses'] * 2 <= candidate['count'] and len(self.locks) < MAX_LOCKS):
lock = new_lock('auto', candidate, now, count=candidate['count'],
max_strength=min(8, candidate['max_strength']))
self.locks.append(lock)
self.visits[lock['id']] = True
self.candidates.remove(candidate)
self.save()
return lock
def recentre(self, event, now, window):
"""A lockout held on approach moves to where the source really is once the car has passed it."""
moved = False
for lock in self.locks:
if lock['source'] == 'tap' and now - lock['created'] < window and same_signal(lock, event):
lock['lat'], lock['lon'], moved = event['lat'], event['lon'], True
if moved:
self.save()
def visit(self, alerts, context):
"""Counts each drive-by of a known place where the signal never appeared; a regular patrol spot is not a fixed source."""
if context is None or context['speed'] < MIN_SPEED:
return
changed = False
for item in [*self.candidates, *(lock for lock in self.locks if lock['source'] == 'auto')]:
near = distance_m(context['lat'], context['lon'], item['lat'], item['lon']) <= VISIT_M
if near:
self.visits[item['id']] = self.visits.get(item['id'], False) or any(same_signal(item, alert) for alert in alerts)
elif item['id'] in self.visits and not self.visits.pop(item['id']):
item['misses'] += 1
changed = True
if changed:
self.candidates = [c for c in self.candidates if c['misses'] <= c['count']]
self.locks = [lock for lock in self.locks if lock['source'] == 'tap' or lock['misses'] <= lock['count']]
self.save()
+42
View File
@@ -0,0 +1,42 @@
"""Decides which alerts are locked out, quiet for the posted limit, or sudden."""
from openpilot.starpilot.uniden.locks import matches_lock
from openpilot.starpilot.uniden.protocol import FREQUENCY_BANDS, matches_rule
INSTANT_STRENGTH = 5
CONTEXT_AGE_S = 1.0
def fresh_context(context, now):
return context if context is not None and 0 <= now - context['at'] < CONTEXT_AGE_S else None
def apply(alerts, rules, situation, previous, now):
"""Marks each alert filtered (ruled or locked), quiet and instant_on. Returns the state to pass in on the next read."""
context = fresh_context(situation.get('context'), now)
quiet = situation.get('quiet')
locks = situation.get('locks', [])
timed = situation.get('timed')
known = previous[1] if previous is not None and 0 <= now - previous[0] < CONTEXT_AGE_S else None
seen = {}
within = (quiet is not None and context is not None and context['limit'] is not None and
context['speed'] <= context['limit'] + quiet['margin'])
for alert in alerts:
key = (alert['band'], alert['frequency'])
entry = seen.get(key) or (known or {}).get(key)
if entry is None:
entry = {'instant': known is not None and alert['band'] in FREQUENCY_BANDS and alert['strength'] >= INSTANT_STRENGTH,
'since': now, 'loud': False}
chosen = bool(timed and alert['band'] in timed['bands'])
timing = timed.get('settings', {}).get(alert['band'], timed) if timed else {}
# Once a signal reaches the strength it stays loud until it clears, so it cannot flap at the threshold.
# A strength of 0 means never warn again: the signal stays muted however strong it gets.
seen[key] = entry = {**entry, 'loud': entry['loud'] or (chosen and timing['strength'] > 0 and alert['strength'] >= timing['strength'])}
instant = entry['instant']
alert['instant_on'] = instant
alert['timed'] = chosen and not instant and not entry['loud'] and now - entry['since'] >= timing['seconds']
alert['breakthrough'] = chosen and entry['loud']
alert['ruled'] = matches_rule(alert, rules)
alert['locked'] = any(matches_lock(alert, lock, context) for lock in locks)
alert['filtered'] = alert['ruled'] or alert['locked']
alert['quiet'] = bool(within and alert['band'] in quiet['bands'] and not instant)
return now, seen
+185
View File
@@ -0,0 +1,185 @@
"""R-series alert snapshots based on AegisX86/UnidenR8wlink PROTOCOL.md (MIT)."""
import math
import re
from typing import Any, NotRequired, TypedDict
ALERT_UUID = '6eb675ab-8bd1-1b9a-7444-621e52ec6823'
WRITE_UUID = '2c86686a-53dc-25b3-0c4a-f0e10c8dee20'
GATT = 'org.bluez.GattCharacteristic1'
FREQUENCY_BANDS = {'X', 'K', 'KA', 'K POP', 'KA POP'}
BANDS = {'X', 'K', 'KA', 'LASER', 'MRCD', 'MRCT', 'RT3', 'RT4', 'K POP', 'KA POP'}
LOCK_BANDS = ('X', 'K', 'KA', 'LASER')
BORDER_BANDS = ('K', 'KA', 'LASER')
TIMED_BANDS = ('X', 'K', 'KA')
BORDER_SWATCHES = {'amber': '#FFBA4E', 'coral': '#FF5B65', 'magenta': '#FF1FCE', 'ice': '#9FE8FF', 'lime': '#A6FF00',
'white': '#FFFFFF', 'ultraviolet': '#7A1FFF'}
LEGACY_COLORS = {'purple': 'ultraviolet', 'violet': 'ultraviolet', 'yellow': 'lime'}
LEGACY_KEYS = ('transparency', 'hide_when_no_alert', 'border_styles', 'unmute_on_breakthrough')
EDGE_PARTS = ('line', 'dashes', 'glow', 'veil', 'chevrons')
RULE_BOUNDS = {'X': (10.0, 11.0), 'K': (23.0, 25.0), 'KA': (33.0, 36.0)}
DEFAULT_CONFIG: dict[str, Any] = {'enabled': False, 'address': '', 'model': 'R8',
'auto_mute': False, 'hide_filtered': False, 'hide_below_limit': False, 'hide_q_ride': False, 'hide_mute_memory': False,
'frequency_rules': [],
'quiet_ride': False, 'quiet_margin': 0, 'quiet_bands': ['X', 'K'],
'auto_learn': False, 'learn_bands': ['X', 'K'], 'border_bands': ['KA', 'LASER'],
'border_colors': {'KA': 'coral', 'K': 'amber', 'LASER': 'coral'},
'border_edge': {'line': True, 'dashes': True, 'glow': False, 'veil': False, 'chevrons': True},
'border_muted_percent': 50,
'timed_mute': False, 'timed_mute_seconds': 5, 'timed_mute_strength': 6, 'timed_mute_bands': ['X', 'K', 'KA'],
'timed_mute_settings': {}}
OPTIONAL_KEYS = set(DEFAULT_CONFIG) - {'enabled', 'address', 'model'}
# Mute mode, field 7 per PROTOCOL.md.
MUTE_MODES = {'1': '', '2': 'manual', '3': 'memory', '4': 'auto_memory', '5': 'blocked', '6': 'quiet_ride'}
class Alert(TypedDict):
band: str
strength: int
frequency: float | None
direction: str
muted: bool
mute_mode: str
instant_on: NotRequired[bool]
timed: NotRequired[bool]
breakthrough: NotRequired[bool]
ruled: NotRequired[bool]
locked: NotRequired[bool]
filtered: NotRequired[bool]
quiet: NotRequired[bool]
def model_for_name(name):
match = re.search(r'(?:^|[^A-Z0-9])(R[48])W?(?=$|[^A-Z0-9])', str(name).upper())
return match[1] if match else None
def migrate_config(value):
"""Strips retired keys and maps retired colors before validation."""
if type(value) is not dict:
return value
config = {key: item for key, item in value.items() if key not in LEGACY_KEYS}
if type(colors := config.get('border_colors')) is dict:
config['border_colors'] = {band: LEGACY_COLORS.get(name, name) if type(name) is str else name for band, name in colors.items()}
return config
def normalize_config(value):
value = migrate_config(value)
if type(value) is not dict or set(value) - set(DEFAULT_CONFIG) or not (set(DEFAULT_CONFIG) - OPTIONAL_KEYS) <= set(value):
raise ValueError('Invalid detector configuration')
config = {**DEFAULT_CONFIG, **value}
if type(config['enabled']) is not bool or config['model'] not in ('R4', 'R8'):
raise ValueError('Choose R4 or R8')
if type(config['address']) is not str or (config['address'] and not re.fullmatch(r'(?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}', config['address'])):
raise ValueError('Invalid detector address')
if config['enabled'] and not config['address']:
raise ValueError('Choose a paired detector')
for key in ('auto_mute', 'hide_filtered', 'hide_below_limit', 'hide_q_ride', 'hide_mute_memory'):
if type(config[key]) is not bool:
raise ValueError('Filter toggles must be boolean')
config['frequency_rules'] = normalize_rules(config['frequency_rules'])
for key in ('quiet_ride', 'auto_learn'):
if type(config[key]) is not bool:
raise ValueError('Quiet Ride and learning toggles must be boolean')
if type(config['quiet_margin']) is not int or not 0 <= config['quiet_margin'] <= 15:
raise ValueError('Quiet Ride margin must be 0–15')
if type(config['timed_mute']) is not bool:
raise ValueError('Timed mute toggles must be boolean')
for key, low, high, message in (('timed_mute_seconds', 1, 60, 'Mute delay must be 1–60 seconds'),
('timed_mute_strength', 2, 8, 'Warn again at strength 2–8, or never')):
# 0 for the strength means never warn again.
if type(config[key]) is not int or not (low <= config[key] <= high or (key == 'timed_mute_strength' and config[key] == 0)):
raise ValueError(message)
settings = config['timed_mute_settings']
if type(settings) is not dict or set(settings) - set(TIMED_BANDS):
raise ValueError('Choose timed mute settings for X, K or Ka')
normalized = {}
for band in TIMED_BANDS:
item = settings.get(band, {'seconds': config['timed_mute_seconds'], 'strength': config['timed_mute_strength']})
if type(item) is not dict or set(item) != {'seconds', 'strength'}:
raise ValueError('Each band needs a mute delay and warning strength')
if type(item['seconds']) is not int or not 1 <= item['seconds'] <= 60:
raise ValueError('Mute delay must be 1–60 seconds')
if type(item['strength']) is not int or item['strength'] not in (0, 2, 3, 4, 5, 6, 7, 8):
raise ValueError('Warn again at strength 2–8, or never')
normalized[band] = dict(item)
config['timed_mute_settings'] = normalized
for key, allowed in (('quiet_bands', LOCK_BANDS), ('learn_bands', LOCK_BANDS), ('border_bands', BORDER_BANDS),
('timed_mute_bands', TIMED_BANDS)):
config[key] = normalize_bands(config[key], allowed)
colors = config['border_colors']
if type(colors) is not dict or set(colors) != set(BORDER_BANDS) or any(type(v) is not str or v not in BORDER_SWATCHES for v in colors.values()):
raise ValueError('Choose a border color from the list')
edge = config['border_edge']
if type(edge) is not dict or set(edge) != set(EDGE_PARTS) or any(type(v) is not bool for v in edge.values()):
raise ValueError('Edge parts must be on or off')
if type(config['border_muted_percent']) is not int or not 0 <= config['border_muted_percent'] <= 100:
raise ValueError('Muted brightness must be 0–100%')
config['border_edge'] = dict(edge)
config['address'] = config['address'].upper()
return config
def normalize_bands(bands, allowed):
if type(bands) is not list or any(type(band) is not str or band not in allowed for band in bands):
raise ValueError('Choose from ' + ', '.join(allowed))
return [band for band in allowed if band in bands]
def parse_alerts(payload, model='R8'):
text = bytes(payload).decode('ascii').strip('\x00\r\n ')
if not text or len(text) > 4096:
raise ValueError('Empty or oversized alert snapshot')
alerts: list[Alert] = []
for segment in text.split('&'):
if segment == '0':
continue
f = segment.split(',')
if len(f) not in (8, 9) or f[0] != '1' or f[2].upper() not in BANDS:
raise ValueError('Unsupported alert packet')
strength = int(f[3])
if not 1 <= strength <= 8:
raise ValueError('Invalid signal strength')
band = f[2].upper()
frequency = None
if band in FREQUENCY_BANDS:
frequency = float(f[5])
if not math.isfinite(frequency) or not 0 < frequency < 100:
raise ValueError('Invalid frequency')
alerts.append({'band': band, 'strength': strength, 'frequency': frequency,
'direction': {'F': 'front', 'S': 'side', 'R': 'rear'}.get(f[6], '') if model == 'R8' else '',
'muted': f[7] in ('2', '3', '4', '5', '6'), 'mute_mode': MUTE_MODES.get(f[7], '')})
return sorted(alerts, key=lambda a: (a['band'] != 'LASER', -a['strength']))
def alert_key(alerts):
"""Stable across strength changes; never use the detector's usually-zero alert ID."""
return sorted([[a['band'], a['frequency'], a['direction']] for a in alerts], key=str)
def normalize_rules(rules):
if type(rules) is not list or len(rules) > 32:
raise ValueError('Use at most 32 frequency rules')
result = []
for rule in rules:
if type(rule) is not dict or set(rule) != {'enabled', 'label', 'band', 'frequency', 'tolerance_mhz'}:
raise ValueError('Invalid frequency rule')
if type(rule['enabled']) is not bool or type(rule['label']) is not str or len(rule['label']) > 60:
raise ValueError('Use a label of at most 60 characters')
bounds = RULE_BOUNDS
band = rule['band']
if type(band) is not str or band not in bounds:
raise ValueError('Choose X, K or KA band')
frequency, tolerance = rule['frequency'], rule['tolerance_mhz']
if type(frequency) not in (int, float) or not math.isfinite(frequency) or not bounds[band][0] <= frequency <= bounds[band][1]:
raise ValueError('Frequency must be in the selected band, in GHz')
if type(tolerance) not in (int, float) or not math.isfinite(tolerance) or not 0 <= tolerance <= 10:
raise ValueError('Tolerance must be 0–10 MHz')
result.append(dict(rule))
return result
def matches_rule(alert, rules):
frequency = alert.get('frequency')
return frequency is not None and any(rule['enabled'] and alert['band'] == rule['band'] and
abs(frequency - rule['frequency']) <= rule['tolerance_mhz'] / 1000 + 1e-9 for rule in rules)
+173
View File
@@ -0,0 +1,173 @@
"""Configuration and request admission shared by Galaxy and both onroad displays."""
import math
import threading
import time
from datetime import UTC, datetime
from openpilot.common.swaglog import cloudlog
from openpilot.starpilot.bluetooth.owner import BluetoothRejected, BluetoothUnavailable
from openpilot.starpilot.uniden.locks import LEARN_COUNT, LockStore, distance_m, matches_lock, new_lock, same_signal
from openpilot.starpilot.uniden.policy import fresh_context
from openpilot.starpilot.uniden.protocol import DEFAULT_CONFIG, LOCK_BANDS, alert_key, normalize_config
from openpilot.starpilot.uniden.tracker import PassTracker
CONTEXT_KEYS = {'lat', 'lon', 'heading', 'speed', 'limit', 'at'}
PASS_AGE_S = 120
NEAR_M = 2000
REQUIRED = {'configure': {'config'}, 'mute': {'address', 'observed_at', 'alerts'}, 'lock': {'address', 'observed_at', 'alerts'},
'unlock': {'id'}}
def clean_context(context):
if context is None:
return None
if type(context) is not dict or set(context) != CONTEXT_KEYS:
raise ValueError('Invalid location context')
def finite(value, low, high):
return type(value) in (int, float) and math.isfinite(value) and low <= value <= high
if not (finite(context['lat'], -90, 90) and finite(context['lon'], -180, 180) and finite(context['speed'], 0, 120) and
finite(context['at'], 0, 1e12) and (context['heading'] is None or finite(context['heading'], 0, 360)) and
(context['limit'] is None or finite(context['limit'], 0, 120))):
raise ValueError('Invalid location context')
return context
class DetectorService:
def __init__(self, params, parked, store=None, clock=time.monotonic, wall=lambda: datetime.now(UTC).timestamp()):
self.params, self.parked = params, parked
self.store, self.clock, self.wall = store or LockStore(), clock, wall
self.tracker, self.last, self.passes, self.recent = PassTracker(), None, [], None
self.lock = threading.Lock()
def config(self):
try:
return normalize_config(self.params.get('UnidenConfig') or DEFAULT_CONFIG)
except (TypeError, ValueError):
return dict(DEFAULT_CONFIG)
def metric(self):
try:
return self.params.get_bool('IsMetric') is True
except (AttributeError, TypeError, ValueError):
return False
def situation(self, config, context):
quiet = None
if config['quiet_ride']:
quiet = {'bands': config['quiet_bands'], 'margin': config['quiet_margin'] * (1 / 3.6 if self.metric() else .44704)}
here = fresh_context(context, self.clock())
near = [] if here is None else [lock for lock in self.store.active() if
distance_m(here['lat'], here['lon'], lock['lat'], lock['lon']) <= NEAR_M + lock['radius_m']]
timed = None
if config['timed_mute']:
timed = {'bands': config['timed_mute_bands'], 'seconds': config['timed_mute_seconds'],
'strength': config['timed_mute_strength'], 'settings': config['timed_mute_settings']}
return {'context': context, 'locks': near, 'quiet': quiet, 'timed': timed}
def observe(self, result, config, context):
"""Follow passes of fixed sources; this runs for every reader but only a distinct pass counts."""
if not result.get('connected'):
return
now, wall = self.clock(), self.wall()
self.last = {'address': config['address'], 'alerts': result['alerts'], 'observed_at': result.get('observed_at'),
'context': fresh_context(context, now)}
try:
for event in self.tracker.update(result['alerts'], context, now, wall):
self.passes = [p for p in self.passes if wall - p['at'] < PASS_AGE_S] + [event]
self.store.recentre(event, wall, PASS_AGE_S)
self.store.observe(event, learn=config['auto_learn'], bands=config['learn_bands'])
self.store.visit(result['alerts'], fresh_context(context, now))
except OSError:
cloudlog.exception('uniden: could not save lockout learning')
def listing(self):
# Sources still being learned, closest to a lockout first; position stays on the device.
learning = sorted(({'id': c['id'], 'band': c['band'], 'frequency': c['frequency'], 'count': c['count'],
'need': LEARN_COUNT[c['band']], 'misses': c['misses']} for c in self.store.candidates),
key=lambda c: (-c['count'] / c['need'], c['misses']))
return {'locks': [dict(lock) for lock in self.store.locks], 'candidates': len(self.store.candidates), 'learning': learning,
'metric': self.metric()}
def lock_here(self, payload, config):
last, now = self.last, self.clock()
if not config['enabled'] or last is None or payload['address'] != config['address'] or last['address'] != config['address']:
raise BluetoothRejected('Selected detector changed', code='changed')
at = payload['observed_at']
if type(at) not in (float, int) or not 0 <= now - at < 3 or payload['alerts'] != alert_key(last['alerts']):
raise BluetoothRejected('Alert changed; hold the current alert', code='changed')
context = last['context']
if context is None:
raise BluetoothRejected('Waiting for a GPS fix', code='no_fix')
wall, added = self.wall(), 0
for alert in last['alerts']:
if alert['band'] not in LOCK_BANDS or alert.get('filtered') or any(matches_lock(alert, lock, context) for lock in self.store.locks):
continue
signal = {'band': alert['band'], 'frequency': alert['frequency']}
near = next((p for p in reversed(self.passes) if same_signal(p, signal) and wall - p['at'] < PASS_AGE_S), None)
here = near or context
self.store.add(new_lock('tap', {**signal, 'lat': here['lat'], 'lon': here['lon']}, wall))
added += 1
if not added:
raise BluetoothRejected('Already locked out here', code='changed')
return {**self.listing(), 'locked': added}
def request(self, payload, exchange, *, valid=lambda: True):
if type(payload) is not dict or payload.get('operation') not in ('status', 'configure', 'mute', 'lock', 'locks', 'unlock'):
raise ValueError('Invalid detector request')
operation = payload['operation']
required, keys = REQUIRED.get(operation, set()), set(payload) - {'operation'}
if not required <= keys or keys - required - ({'context'} if operation == 'status' else set()):
raise ValueError('Invalid detector request fields')
context = clean_context(payload.get('context'))
if context is not None:
self.recent = context
elif operation in ('status', 'mute'):
context = fresh_context(self.recent, self.clock())
with self.lock:
if not valid():
raise BluetoothRejected('Session expired', code='session_expired')
config = self.config()
if operation == 'locks':
return self.listing()
if operation == 'unlock':
try:
self.store.remove(payload['id'])
except ValueError as error:
raise BluetoothRejected(str(error), code='changed') from None
return self.listing()
if operation == 'lock':
return self.lock_here(payload, config)
if operation == 'configure':
if not self.parked():
raise BluetoothRejected('Park before selecting a detector', code='park_required')
previous, config = config, normalize_config(payload['config'])
self.params.put('UnidenConfig', config)
if config['address'] != previous['address']:
self.tracker, self.last, self.passes = PassTracker(), None, []
return {'config': config, 'connected': False, 'alerts': []}
if not config['enabled']:
return {'config': config, 'connected': False, 'alerts': []}
if operation == 'mute' and payload['address'] != config['address']:
raise BluetoothRejected('Selected detector changed', code='changed')
try:
result = exchange(config, payload if operation == 'mute' else None, self.situation(config, context))
self.observe(result, config, context)
except (BluetoothRejected, BluetoothUnavailable, OSError, RuntimeError, ValueError) as error:
if operation == 'mute':
raise
code = getattr(error, 'code', 'unavailable')
if str(error) in ('org.bluez.Error.Failed', 'org.bluez.Error.InProgress', 'org.bluez.Error.NotReady'):
code = 'reconnecting'
elif str(error) in ('org.bluez.Error.NotAuthorized', 'org.bluez.Error.AuthenticationFailed'):
code = 'detector_pairing_required'
messages = {
'reconnecting': 'Reconnecting to detector',
'radio_off': 'Turn on Bluetooth to connect the detector',
'busy': 'Waiting for Bluetooth to become available',
'detector_pairing_required': 'Pair or select the detector in Bluetooth settings',
'session_expired': 'Sign in to Galaxy again',
}
result = {'connected': False, 'alerts': [], 'connection_state': code if code in messages else 'unavailable',
'error': messages.get(code, 'Unable to read detector alerts. Check the detector connection.')}
return {**result, 'config': config}
@@ -0,0 +1,703 @@
import json
import threading
import time
from unittest.mock import Mock, patch
import pytest
from openpilot.starpilot.bluetooth.owner import ADAPTER, DEVICE, BluetoothRejected
from openpilot.starpilot.system.starport.bluetooth_bridge import SharedBluetoothOwner
from openpilot.starpilot.uniden.feed import DetectorFeed, OFFLINE_S
from openpilot.starpilot.uniden.locks import LEARN_COUNT, REPEAT_S, LockStore, matches_lock, new_lock, normalize_lock
from openpilot.starpilot.uniden.policy import apply
from openpilot.starpilot.uniden.protocol import ALERT_UUID, DEFAULT_CONFIG, GATT, WRITE_UUID, alert_key, normalize_config, parse_alerts
from openpilot.starpilot.uniden.service import DetectorService
from openpilot.starpilot.uniden.tracker import PassTracker
from openpilot.starpilot.uniden.transport import exchange
ADDRESS = 'AA:BB:CC:DD:EE:FF'
ADAPTER_PATH = '/org/bluez/hci0'
PATH = ADAPTER_PATH + '/dev_AA_BB_CC_DD_EE_FF'
CONFIG = {**DEFAULT_CONFIG, 'enabled': True, 'address': ADDRESS}
def context(**fields):
return {'lat': 36.0, 'lon': -115.0, 'heading': 90.0, 'speed': 20.0, 'limit': 25.0, 'at': time.monotonic(), **fields}
def alerts(packet, model='R8'):
return parse_alerts(packet, model)
def event(**fields):
return {'band': 'K', 'frequency': 24.15, 'lat': 36.0, 'lon': -115.0, 'strength': 4, 'at': 1_000_000, **fields}
@pytest.fixture
def setup(tmp_path):
objects = {ADAPTER_PATH: {ADAPTER: {'Powered': True}}, PATH: {DEVICE: {
'Name': 'R8W@12', 'Address': ADDRESS, 'Paired': True, 'Connected': True, 'ServicesResolved': True}},
PATH + '/service/alert': {GATT: {'UUID': ALERT_UUID}}, PATH + '/service/write': {GATT: {'UUID': WRITE_UUID}}}
client = Mock()
client._objects.side_effect = lambda: objects
client.adapter_identity.side_effect = lambda: (ADAPTER_PATH, objects[ADAPTER_PATH][ADAPTER], ':1.5')
owner = SharedBluetoothOwner(lambda: False, session_valid=lambda s: s == ('live',),
bluez_factory=lambda: client, lock_path=tmp_path / 'owner.lock')
return owner, client
def writes(client):
return sum(call.args[2] == 'WriteValue' for call in client._call.call_args_list)
def test_lock_matches_only_near_the_place_and_signal():
lock = new_lock('tap', event(), 1)
alert = alerts(b'1,00,K,3,0,24.150,F,1')[0]
assert matches_lock(alert, lock, context())
assert not matches_lock(alert, lock, None)
assert not matches_lock(alert, lock, context(lat=36.01))
assert not matches_lock({**alert, 'frequency': 24.2}, lock, context())
assert not matches_lock({**alert, 'strength': 8}, {**lock, 'max_strength': 4}, context())
assert matches_lock({**alert, 'strength': 6}, {**lock, 'max_strength': 4}, context())
assert not matches_lock(alert, {**lock, 'enabled': False}, context())
def test_lock_heading_window():
lock = new_lock('tap', event(), 1, heading=90, heading_tolerance=45)
alert = alerts(b'1,00,K,3,0,24.150,F,1')[0]
assert matches_lock(alert, lock, context(heading=120))
assert not matches_lock(alert, lock, context(heading=270))
assert not matches_lock(alert, lock, context(heading=None))
def test_laser_lock_has_no_frequency_and_matches_by_place():
lock = new_lock('tap', event(band='LASER', frequency=None), 1)
laser = alerts(b'1,00,LASER,8,0,5,F,1')[0]
assert matches_lock(laser, lock, context())
assert not matches_lock(laser, lock, context(lon=-115.02))
with pytest.raises(ValueError):
normalize_lock({**lock, 'frequency': 24.15})
@pytest.mark.parametrize('change', [{'lat': 91}, {'radius_m': 10}, {'band': 'POP'}, {'source': 'x'}, {'frequency': 99.}, {'count': 0}])
def test_invalid_locks_rejected(change):
with pytest.raises(ValueError):
normalize_lock({**new_lock('tap', event(), 1), **change})
def test_learning_needs_separate_passes_and_stays_off_without_opt_in(tmp_path):
store = LockStore(tmp_path)
at = 1_000_000
for n in range(LEARN_COUNT['K']):
earned = store.observe(event(at=at + n * REPEAT_S), learn=False, bands=['K'])
assert earned is None and not store.locks
store = LockStore(tmp_path / 'on')
assert store.observe(event(at=at), learn=True, bands=['K']) is None
assert store.observe(event(at=at + 5), learn=True, bands=['K']) is None
assert store.candidates[0]['count'] == 1
assert store.observe(event(at=at + REPEAT_S), learn=True, bands=['K']) is None
lock = store.observe(event(at=at + 2 * REPEAT_S, strength=6), learn=True, bands=['K'])
assert lock['source'] == 'auto' and lock['band'] == 'K' and lock['max_strength'] == 6 and not store.candidates
assert LockStore(tmp_path / 'on').locks == [lock]
def test_learning_respects_band_choice_and_laser_needs_more_passes(tmp_path):
store = LockStore(tmp_path)
for n in range(LEARN_COUNT['KA']):
assert store.observe(event(band='KA', frequency=34.7, at=1_000_000 + n * REPEAT_S), learn=True, bands=['K']) is None
assert not store.locks and LEARN_COUNT['LASER'] > LEARN_COUNT['K']
def test_distant_or_different_signals_are_not_merged(tmp_path):
store = LockStore(tmp_path)
store.observe(event(), learn=True, bands=['K'])
store.observe(event(at=1_000_000 + REPEAT_S, lat=36.05), learn=True, bands=['K'])
store.observe(event(at=1_000_000 + REPEAT_S, frequency=24.2), learn=True, bands=['K'])
assert len(store.candidates) == 3
def test_store_survives_a_corrupt_file_and_unlock(tmp_path):
(tmp_path / 'locks.json').write_text('{broken')
store = LockStore(tmp_path)
assert store.locks == []
lock = new_lock('tap', event(), 1)
store.add(lock)
assert LockStore(tmp_path).locks == [lock]
store.remove(lock['id'])
assert LockStore(tmp_path).locks == []
with pytest.raises(ValueError):
store.remove('missing')
def run_pass(tracker, directions, model='R8', start=0.):
found = []
for n, direction in enumerate(directions):
now = start + n * .5
packet = f'1,00,K,{3 + n % 3},0,24.150,{direction},1'.encode()
found += tracker.update(alerts(packet, model), context(at=now, lon=-115 + n * .001), now, 1000 + now)
return found
def test_arrow_flip_pinpoints_a_fixed_source_once():
found = run_pass(PassTracker(), ['F', 'F', 'F', 'S', 'S', 'R', 'R'])
assert len(found) == 1 and found[0]['band'] == 'K' and found[0]['lon'] == pytest.approx(-115 + .003)
def test_moving_with_you_or_no_gps_never_pinpoints():
assert run_pass(PassTracker(), ['R', 'R', 'R', 'R']) == []
tracker = PassTracker()
found = [e for n in range(4) for e in tracker.update(alerts(f'1,00,K,3,0,24.150,{"FSRR"[n]},1'.encode()), None, n * .5, 1000)]
assert found == []
assert PassTracker().update(alerts(b'1,00,K,3,0,24.150,S,1'), context(speed=1., at=0.), 0., 1000) == []
def test_r4_strength_peak_marks_the_pass_when_the_alert_ends():
tracker, found = PassTracker(), []
for n, strength in enumerate([1, 3, 6, 4, 2]):
found += tracker.update(alerts(f'1,00,K,{strength},0,24.150,F,1'.encode(), 'R4'), context(at=n * .5, lon=-115 + n * .001), n * .5, 1000)
assert found == []
found = tracker.update([], context(at=5.), 5., 1000)
assert len(found) == 1 and found[0]['strength'] == 6 and found[0]['lon'] == pytest.approx(-115 + .002)
def situation(**fields):
return {'context': context(), 'locks': [], 'quiet': {'bands': ['X', 'K'], 'margin': 0}, **fields}
def test_quiet_only_at_or_under_the_limit_for_chosen_bands():
now = time.monotonic()
def run(sit, packet=b'1,00,K,3,0,24.150,F,1', previous=None):
items = alerts(packet)
apply(items, [], sit, previous, now)
return items[0]
assert run(situation(context=context(at=now)))['quiet']
assert not run(situation(context=context(at=now, speed=26.)))['quiet']
assert run(situation(context=context(at=now, speed=26.), quiet={'bands': ['K'], 'margin': 2}))['quiet']
assert not run(situation(context=context(at=now, limit=None)))['quiet']
assert not run(situation(context=context(at=now - 2)))['quiet']
assert not run(situation(context=None))['quiet']
assert not run(situation(context=context(at=now), quiet=None))['quiet']
assert not run(situation(context=context(at=now)), b'1,00,KA,3,0,34.7,F,1')['quiet']
assert run(situation(context=context(at=now), quiet={'bands': ['LASER'], 'margin': 0}), b'1,00,LASER,8,0,5,F,1')['quiet']
def test_sudden_strong_signal_is_never_quiet_but_a_steady_one_is():
now = time.monotonic()
first = alerts(b'1,00,K,2,0,24.150,F,1')
state = apply(first, [], situation(context=context(at=now)), None, now)
sudden = alerts(b'1,00,K,2,0,24.150,F,1&1,00,KA,6,0,34.7,F,1')
state = apply(sudden, [], situation(context=context(at=now + .1), quiet={'bands': ['K', 'KA'], 'margin': 0}), state, now + .1)
ka = next(a for a in sudden if a['band'] == 'KA')
assert ka['instant_on'] and not ka['quiet']
assert not next(a for a in sudden if a['band'] == 'K')['instant_on']
later = alerts(b'1,00,KA,7,0,34.7,F,1')
apply(later, [], situation(context=context(at=now + .2)), state, now + .2)
assert later[0]['instant_on']
def test_stale_previous_read_does_not_call_a_signal_sudden():
now = time.monotonic()
items = alerts(b'1,00,KA,7,0,34.7,F,1')
apply(items, [], situation(), (now - 5, {}), now)
assert not items[0]['instant_on']
def test_exchange_sends_mute_when_quiet_and_not_when_one_alert_is_loud(setup):
owner, client = setup
client._call.return_value = (b'1,00,K,3,0,24.150,F,1',)
result = exchange(owner, ADDRESS, 'R8', ('live',), situation=situation())
assert result['alerts'][0]['quiet'] and writes(client) == 1
owner.uniden.auto_mute = (None, 0.)
client._call.return_value = (b'1,00,K,3,0,24.150,F,1&1,00,KA,3,0,34.7,F,1',)
exchange(owner, ADDRESS, 'R8', ('live',), situation=situation())
assert writes(client) == 1
client._call.return_value = (b'1,00,K,3,0,24.150,F,1',)
exchange(owner, ADDRESS, 'R8', ('live',), situation=situation(context=context(speed=40.)))
assert writes(client) == 1
def test_exchange_lock_filters_and_mutes_only_with_auto_mute(setup):
owner, client = setup
client._call.return_value = (b'1,00,K,3,0,24.150,F,1',)
sit = situation(quiet=None, locks=[new_lock('tap', event(), 1)])
result = exchange(owner, ADDRESS, 'R8', ('live',), situation=sit)
assert result['alerts'][0]['filtered'] and writes(client) == 0
exchange(owner, ADDRESS, 'R8', ('live',), auto_mute=True, situation=sit)
assert writes(client) == 1
def make_service(tmp_path, config=CONFIG, now=None):
params = Mock()
params.get.return_value = config
params.get_bool.return_value = False
clock = [100.]
return DetectorService(params, lambda: False, LockStore(tmp_path), clock=lambda: clock[0], wall=lambda: 5_000_000.), params, clock
def reading(packet, at):
items = alerts(packet)
return {'connected': True, 'address': ADDRESS, 'model': 'R8', 'alerts': items, 'observed_at': at, 'can_mute': True, 'command': ''}
def test_service_builds_situation_from_config_and_converts_margin(tmp_path):
service, params, clock = make_service(tmp_path, {**CONFIG, 'quiet_ride': True, 'quiet_margin': 5})
seen = {}
def transport(config, mute, sit):
seen.update(sit)
return reading(b'1,00,K,3,0,24.150,F,1', 100.)
service.request({'operation': 'status', 'context': context(at=100.)}, transport)
assert seen['quiet']['bands'] == ['X', 'K'] and seen['quiet']['margin'] == pytest.approx(5 * .44704)
params.get_bool.return_value = True
service.request({'operation': 'status'}, transport)
assert seen['quiet']['margin'] == pytest.approx(5 / 3.6)
@pytest.mark.parametrize('bad', [{'lat': 1}, {**context(), 'lat': 100}, {**context(), 'speed': float('nan')}, {**context(), 'extra': 1}, 'x'])
def test_service_rejects_bad_context(tmp_path, bad):
service, _, _ = make_service(tmp_path)
with pytest.raises(ValueError):
service.request({'operation': 'status', 'context': bad}, Mock())
def test_service_rejects_context_on_other_operations_and_missing_fields(tmp_path):
service, _, _ = make_service(tmp_path)
for payload in ({'operation': 'locks', 'context': context()}, {'operation': 'unlock'}, {'operation': 'lock'},
{'operation': 'unlock', 'id': 'x', 'extra': 1}):
with pytest.raises(ValueError):
service.request(payload, Mock())
def test_hold_to_lock_uses_the_pinpointed_source_and_unlock_removes_it(tmp_path):
service, _, clock = make_service(tmp_path)
steps = [(b'1,00,K,3,0,24.150,F,1', 0), (b'1,00,K,4,0,24.150,F,1', .5), (b'1,00,K,5,0,24.150,S,1', 1.)]
for n, (packet, offset) in enumerate(steps):
clock[0] = 100. + offset
service.request({'operation': 'status', 'context': context(at=clock[0], lon=-115 + n * .001)},
lambda config, mute, sit, p=packet, o=clock[0]: reading(p, o))
current = service.last['alerts']
payload = {'operation': 'lock', 'address': ADDRESS, 'observed_at': 101., 'alerts': alert_key(current)}
result = service.request(payload, Mock())
assert result['locked'] == 1 and result['locks'][0]['lon'] == pytest.approx(-115 + .002) and result['locks'][0]['source'] == 'tap'
with pytest.raises(BluetoothRejected, match='Already locked'):
service.request(payload, Mock())
assert service.request({'operation': 'locks'}, Mock())['locks'][0]['band'] == 'K'
assert service.request({'operation': 'unlock', 'id': result['locks'][0]['id']}, Mock())['locks'] == []
def test_listing_shows_learning_progress_closest_first(tmp_path):
service, _, _ = make_service(tmp_path)
store = service.store
store.candidates = [
{'id': 'a', 'band': 'KA', 'frequency': 34.7, 'lat': 36., 'lon': -115., 'count': 2, 'misses': 0, 'last': 1., 'max_strength': 3},
{'id': 'b', 'band': 'K', 'frequency': 24.15, 'lat': 36., 'lon': -115., 'count': 2, 'misses': 1, 'last': 1., 'max_strength': 3},
{'id': 'c', 'band': 'X', 'frequency': 10.525, 'lat': 36., 'lon': -115., 'count': 2, 'misses': 0, 'last': 1., 'max_strength': 3},
]
listing = service.request({'operation': 'locks'}, Mock())
assert listing['candidates'] == 3
assert [(c['id'], c['count'], c['need']) for c in listing['learning']] == [('c', 2, 3), ('b', 2, 3), ('a', 2, 5)]
assert all('lat' not in c and 'lon' not in c for c in listing['learning']), 'only progress, no position'
def test_lock_is_rejected_for_a_changed_alert_stale_read_or_no_fix(tmp_path):
service, _, clock = make_service(tmp_path)
service.request({'operation': 'status', 'context': context(at=100.)}, lambda config, mute, sit: reading(b'1,00,K,3,0,24.150,F,1', 100.))
base = {'operation': 'lock', 'address': ADDRESS, 'observed_at': 100., 'alerts': alert_key(service.last['alerts'])}
for change in ({'alerts': []}, {'address': 'OTHER'}, {'observed_at': 90.}):
with pytest.raises(BluetoothRejected):
service.request({**base, **change}, Mock())
clock[0] = 102.
service.request({'operation': 'status'}, lambda config, mute, sit: reading(b'1,00,K,3,0,24.150,F,1', 102.))
with pytest.raises(BluetoothRejected, match='GPS'):
service.request(base, Mock())
def test_service_learns_from_passes_only_when_enabled(tmp_path):
def drive(config):
service, _, clock = make_service(tmp_path / str(config['auto_learn']), config)
for trip in range(LEARN_COUNT['K']):
for n, d in enumerate('FFSR'):
clock[0] = 100. + n * .5
service.wall = lambda trip=trip: 5_000_000. + trip * REPEAT_S
service.request({'operation': 'status', 'context': context(at=clock[0], lon=-115 + n * .001)},
lambda config, mute, sit, d=d, o=clock[0]: reading(f'1,00,K,4,0,24.150,{d},1'.encode(), o))
clock[0] += 5
service.request({'operation': 'status'}, lambda config, mute, sit, o=clock[0]: reading(b'0', o))
return service
assert drive({**CONFIG, 'auto_learn': False}).store.locks == []
locks = drive({**CONFIG, 'auto_learn': True}).store.locks
assert len(locks) == 1 and locks[0]['source'] == 'auto'
def test_config_defaults_and_validation():
assert normalize_config({'enabled': False, 'address': '', 'model': 'R8'}) == normalize_config(DEFAULT_CONFIG)
assert normalize_config({**CONFIG, 'quiet_bands': ['LASER', 'X']})['quiet_bands'] == ['X', 'LASER']
for change in ({'quiet_margin': 16}, {'quiet_margin': True}, {'quiet_bands': ['POP']}, {'border_bands': ['X']},
{'border_colors': {'KA': 'cyan', 'K': 'violet', 'LASER': 'white'}}, {'border_colors': {'KA': 'purple'}},
{'quiet_ride': 1}, {'auto_learn': 'yes'}):
with pytest.raises(ValueError):
normalize_config({**CONFIG, **change})
def test_a_saved_config_from_an_older_version_still_loads():
old = {**CONFIG, 'transparency': 40, 'hide_when_no_alert': False, 'unmute_on_breakthrough': True,
'border_styles': {'KA': 'chase', 'K': 'solid', 'LASER': 'pulse'}, 'border_colors': {'KA': 'purple', 'K': 'yellow', 'LASER': 'violet'}}
config = normalize_config(old)
assert config == normalize_config({**CONFIG, 'border_colors': {'KA': 'ultraviolet', 'K': 'lime', 'LASER': 'ultraviolet'}})
assert config['address'] == ADDRESS and config['enabled']
def test_feed_flags_offline_after_the_grace_period_and_clears_on_reconnect():
now = [0.]
state = {'config': CONFIG, 'connected': False, 'alerts': [], 'error': 'Reconnecting'}
call = Mock(return_value=(200, state))
feed = DetectorFeed(call, clock=lambda: now[0], context=lambda: None)
feed.set_enabled(True)
feed.poll()
assert not feed.snapshot().get('offline')
now[0] = OFFLINE_S + 1
feed.requested_at = now[0]
assert feed.snapshot()['offline']
call.return_value = (200, {**state, 'connected': True, 'observed_at': now[0]})
feed.poll()
assert not feed.snapshot().get('offline')
feed.set_enabled(False)
def test_feed_sends_fresh_context_and_a_lock_request_with_a_notice():
now = [10.]
state = {'config': CONFIG, 'connected': True, 'address': ADDRESS, 'observed_at': 10., 'alerts': alerts(b'1,00,K,3,0,24.150,F,1'), 'can_mute': True}
call = Mock(return_value=(200, state))
feed = DetectorFeed(call, clock=lambda: now[0], context=lambda: context())
feed.enabled, feed.requested_at = True, 10.
feed.poll()
assert 'context' in call.call_args.args[2]
feed.lock_here(feed.snapshot())
call.return_value = (200, {'locked': 1, 'locks': []})
feed.poll()
assert call.call_args.args[2]['operation'] == 'lock' and 'context' not in call.call_args.args[2]
assert feed.snapshot()['notice'].startswith('Locked out here') and feed.snapshot()['alerts']
now[0] = 14
feed.state['observed_at'] = 14.
assert 'notice' not in feed.snapshot()
feed.lock_here(feed.snapshot())
call.return_value = (409, {'error': 'Already locked out here'})
now[0] = 14.1
feed.requested_at = 14.1
feed.poll()
assert feed.snapshot()['notice'] == 'Already locked out here'
def test_only_nearby_locks_are_sent_and_none_without_a_fresh_fix(tmp_path):
service, _, clock = make_service(tmp_path)
service.store.locks = [new_lock('tap', event(lat=36.0 + n * .01), 1) for n in range(200)]
near = service.situation(CONFIG, context(at=100.))['locks']
assert 0 < len(near) < 40 and all(abs(lock['lat'] - 36.0) < .03 for lock in near)
assert service.situation(CONFIG, None)['locks'] == []
assert service.situation(CONFIG, context(at=90.))['locks'] == []
def test_a_poll_without_location_reuses_the_last_fresh_fix_but_not_a_stale_one(tmp_path):
service, _, clock = make_service(tmp_path)
seen = []
def transport(config, mute, sit):
seen.append(sit['context'])
return reading(b'1,00,K,3,0,24.150,F,1', clock[0])
service.request({'operation': 'status', 'context': context(at=100.)}, transport)
clock[0] = 100.4
service.request({'operation': 'status'}, transport)
assert seen[1] == seen[0] and service.last['context'] is not None
base = {'operation': 'lock', 'address': ADDRESS, 'observed_at': 100.4, 'alerts': alert_key(service.last['alerts'])}
assert service.request(base, Mock())['locked'] == 1
clock[0] = 102.
service.request({'operation': 'status'}, transport)
assert seen[2] is None and service.last['context'] is None
def test_a_tap_lock_held_on_approach_moves_to_the_pass_point(tmp_path):
service, _, clock = make_service(tmp_path)
def poll(n, direction):
clock[0] = 100. + n * .5
service.request({'operation': 'status', 'context': context(at=clock[0], lon=-115 + n * .001)},
lambda config, mute, sit: reading(f'1,00,K,4,0,24.150,{direction},1'.encode(), clock[0]))
poll(0, 'F')
service.request({'operation': 'lock', 'address': ADDRESS, 'observed_at': 100., 'alerts': alert_key(service.last['alerts'])}, Mock())
assert service.store.locks[0]['lon'] == pytest.approx(-115)
poll(1, 'F')
poll(2, 'S')
assert service.store.locks[0]['lon'] == pytest.approx(-115 + .002)
def test_a_sudden_strong_signal_is_never_pinpointed():
tracker, found = PassTracker(), []
for n, direction in enumerate('FFSR'):
items = alerts(f'1,00,K,7,0,24.150,{direction},1'.encode())
items[0]['instant_on'] = n == 0
found += tracker.update(items, context(at=n * .5, lon=-115 + n * .001), n * .5, 1000)
assert found == []
def drive_by(store, alerts_seen, lon=-115.0):
store.visit(alerts_seen, context(lon=lon))
store.visit(alerts_seen, context(lon=lon + .05))
def leave(store):
store.visit([], context(lon=-115.05))
def test_drive_bys_without_the_signal_block_learning_and_remove_learned_lockouts(tmp_path):
store = LockStore(tmp_path)
at = 1_000_000
store.observe(event(at=at), learn=True, bands=['K'])
store.observe(event(at=at + REPEAT_S), learn=True, bands=['K'])
leave(store)
for _ in range(2):
drive_by(store, [])
assert store.candidates[0]['misses'] == 2
store.observe(event(at=at + 2 * REPEAT_S), learn=True, bands=['K'])
assert store.candidates and not store.locks
store.observe(event(at=at + 3 * REPEAT_S), learn=True, bands=['K'])
lock = store.locks[0]
assert lock['source'] == 'auto' and lock['misses'] == 0
leave(store)
for _ in range(lock['count']):
drive_by(store, [])
assert store.locks
drive_by(store, [])
assert not store.locks
def test_the_pass_that_created_a_candidate_is_not_counted_as_a_miss(tmp_path):
store = LockStore(tmp_path)
store.observe(event(at=1_000_000), learn=True, bands=['K'])
drive_by(store, [])
assert store.candidates[0]['misses'] == 0
def test_tap_lockouts_and_slow_or_unlocated_cars_never_collect_misses(tmp_path):
store = LockStore(tmp_path)
store.add(new_lock('tap', event(), 1))
drive_by(store, [])
store.observe(event(lat=36.5, at=1_000_000), learn=True, bands=['K'])
store.visit([], context(lat=36.5, speed=1.))
store.visit([], context(lat=36.6, speed=1.))
store.visit([], None)
assert store.locks[0]['misses'] == 0 and store.candidates[0]['misses'] == 0
TIMED = {'bands': ['X', 'K', 'KA'], 'seconds': 5, 'strength': 6}
def timed_run(packet, previous, now, timed=TIMED):
items = alerts(packet)
return items, apply(items, [], {'context': None, 'locks': [], 'quiet': None, 'timed': timed}, previous, now)
def test_timed_mute_waits_for_the_delay_and_skips_unchosen_bands_and_laser():
items, state = timed_run(b'1,00,K,3,0,24.150,F,1', None, 100.)
assert not items[0]['timed']
items, state = timed_run(b'1,00,K,3,0,24.150,F,1', state, 100.5)
assert not items[0]['timed']
items, state = timed_run(b'1,00,K,3,0,24.150,F,1', (104.9, {k: {**v, 'since': 100.} for k, v in state[1].items()}), 105.)
assert items[0]['timed'] and not items[0]['breakthrough']
for packet, timed in ((b'1,00,LASER,3,0,5,F,1', TIMED), (b'1,00,KA,3,0,34.7,F,1', {**TIMED, 'bands': ['K']})):
_, state = timed_run(packet, None, 100., timed)
items, _ = timed_run(packet, (104.9, {k: {**v, 'since': 90.} for k, v in state[1].items()}), 105., timed)
assert not items[0]['timed']
items, _ = timed_run(b'1,00,K,3,0,24.150,F,1', None, 100., timed=None)
assert not items[0]['timed'] and not items[0]['breakthrough']
def test_a_strong_signal_stays_loud_until_it_clears_and_a_sudden_one_is_never_timed():
_, state = timed_run(b'1,00,K,3,0,24.150,F,1', None, 100.)
state = (104.9, {k: {**v, 'since': 90.} for k, v in state[1].items()})
items, state = timed_run(b'1,00,K,7,0,24.150,F,1', state, 105.)
assert items[0]['breakthrough'] and not items[0]['timed']
items, state = timed_run(b'1,00,K,3,0,24.150,F,1', state, 105.5)
assert items[0]['breakthrough'] and not items[0]['timed']
_, state = timed_run(b'0', state, 106.)
items, state = timed_run(b'1,00,K,3,0,24.150,F,1', state, 106.5)
assert not items[0]['breakthrough']
_, state = timed_run(b'0', None, 100.)
items, state = timed_run(b'1,00,KA,7,0,34.7,F,1', state, 100.5)
items, _ = timed_run(b'1,00,KA,7,0,34.7,F,1', (104.9, {k: {**v, 'since': 90.} for k, v in state[1].items()}), 105.)
assert items[0]['instant_on'] and not items[0]['timed']
def age(owner, seconds):
_, seen = owner.uniden.seen
owner.uniden.seen = (time.monotonic(), {k: {**v, 'since': v['since'] - seconds} for k, v in seen.items()})
def sent(client):
return [call.args[4][0] for call in client._call.call_args_list if call.args[2] == 'WriteValue']
def test_exchange_mutes_after_the_delay_then_unmutes_once_the_signal_is_strong(setup):
owner, client = setup
sit = {'context': None, 'locks': [], 'quiet': None, 'timed': TIMED}
def read(packet):
client._call.return_value = (packet,)
return exchange(owner, ADDRESS, 'R8', ('live',), situation=sit)
read(b'1,00,K,3,0,24.150,F,1')
assert sent(client) == []
age(owner, 6)
result = read(b'1,00,K,3,0,24.150,F,1')
assert result['alerts'][0]['timed'] and sent(client) == [b'BTreqMUTE:1'] and owner.uniden.timed_mute
read(b'1,00,K,4,0,24.150,F,2')
assert sent(client) == [b'BTreqMUTE:1']
result = read(b'1,00,K,6,0,24.150,F,2')
assert result['alerts'][0]['breakthrough'] and result['command'] == 'unmute_sent_unconfirmed'
assert sent(client)[-1] == b'BTreqMUTE:0'
read(b'1,00,K,6,0,24.150,F,2')
assert sent(client).count(b'BTreqMUTE:0') == 1
for _ in range(5):
owner.uniden.unmute = (owner.uniden.unmute[0], owner.uniden.unmute[1], 0)
read(b'1,00,K,6,0,24.150,F,2')
assert sent(client).count(b'BTreqMUTE:0') == 3
assert sent(client).count(b'BTreqMUTE:1') == 1
def test_unmute_needs_timed_mute_and_never_undoes_the_drivers_own_mute(setup):
owner, client = setup
def sit(timed=TIMED):
return {'context': None, 'locks': [], 'quiet': None, 'timed': timed}
client._call.return_value = (b'1,00,K,7,0,24.150,F,2',)
exchange(owner, ADDRESS, 'R8', ('live',), situation=sit())
assert sent(client) == []
owner.uniden.timed_mute = True
exchange(owner, ADDRESS, 'R8', ('live',), situation=sit(None))
assert sent(client) == []
client._call.return_value = (b'1,00,K,7,0,24.150,F,3',)
exchange(owner, ADDRESS, 'R8', ('live',), situation=sit())
assert sent(client) == []
client._call.return_value = (b'0',)
exchange(owner, ADDRESS, 'R8', ('live',), situation=sit())
assert not owner.uniden.timed_mute
def test_service_sends_the_timed_settings_and_validates_them(tmp_path):
service, _, _ = make_service(tmp_path, {**CONFIG, 'timed_mute': True, 'timed_mute_seconds': 8, 'timed_mute_strength': 5,
'timed_mute_bands': ['K'], 'unmute_on_breakthrough': False})
assert service.situation(service.config(), None)['timed'] == {'bands': ['K'], 'seconds': 8, 'strength': 5,
'settings': {band: {'seconds': 8, 'strength': 5} for band in ('X', 'K', 'KA')}}, 'a saved unmute_on_breakthrough still loads'
assert normalize_config({**CONFIG, 'timed_mute_strength': 0})['timed_mute_strength'] == 0, '0 is never warn again'
assert make_service(tmp_path)[0].situation(CONFIG, None)['timed'] is None
for change in ({'timed_mute_seconds': 0}, {'timed_mute_seconds': 61}, {'timed_mute_strength': 1}, {'timed_mute_strength': 9},
{'timed_mute_seconds': 5.5}, {'timed_mute_bands': ['LASER']}, {'timed_mute': 1}):
with pytest.raises(ValueError):
normalize_config({**CONFIG, **change})
def test_timed_mute_uses_each_bands_delay_and_strength():
timed = {**TIMED, 'settings': {'K': {'seconds': 2, 'strength': 0}, 'KA': {'seconds': 10, 'strength': 5}}}
packet = b'1,00,K,3,0,24.150,F,1&1,00,KA,3,0,34.7,F,1'
_, state = timed_run(packet, None, 100., timed)
state = (102.9, state[1])
items, state = timed_run(packet, state, 103., timed)
by_band = {a['band']: a for a in items}
assert by_band['K']['timed'] and not by_band['KA']['timed']
items, _ = timed_run(b'1,00,K,8,0,24.150,F,1&1,00,KA,5,0,34.7,F,1', state, 103.5, timed)
by_band = {a['band']: a for a in items}
assert by_band['K']['timed'] and not by_band['K']['breakthrough']
assert by_band['KA']['breakthrough'] and not by_band['KA']['timed']
def test_per_band_timed_settings_migrate_validate_and_round_trip():
legacy = {**CONFIG, 'timed_mute_seconds': 9, 'timed_mute_strength': 0}
migrated = normalize_config(legacy)
assert migrated['timed_mute_settings'] == {band: {'seconds': 9, 'strength': 0} for band in ('X', 'K', 'KA')}
migrated['timed_mute_settings']['KA'] = {'seconds': 20, 'strength': 7}
assert normalize_config(migrated) == migrated
assert migrated['timed_mute_settings']['K']['seconds'] == 9
for settings in (None, [], {'LASER': {'seconds': 5, 'strength': 6}}, {'K': {}},
{'K': {'seconds': True, 'strength': 6}}, {'K': {'seconds': 61, 'strength': 6}},
{'K': {'seconds': 5, 'strength': 1}}, {'K': {'seconds': 5, 'strength': False}}):
with pytest.raises(ValueError):
normalize_config({**legacy, 'timed_mute_settings': settings})
def test_store_drops_bad_entries_one_by_one_and_refuses_links_and_oversized_files(tmp_path):
from openpilot.starpilot.uniden import locks
good = new_lock('tap', event(), 1)
candidate = {'band': 'K', 'frequency': 24.15, 'lat': 36.0, 'lon': -115.0, 'count': 2, 'last': 1_000_000, 'max_strength': 4}
(tmp_path / 'locks.json').write_text(json.dumps({'locks': [good, {**good, 'lat': 91}, 'junk'],
'candidates': [candidate, {**candidate, 'band': 'POP'}, {**candidate, 'extra': 1}, 7]}))
store = LockStore(tmp_path)
assert store.locks == [good]
assert len(store.candidates) == 1 and store.candidates[0]['misses'] == 0 and type(store.candidates[0]['id']) is str
linked = tmp_path / 'linked'
linked.mkdir()
(linked / 'locks.json').symlink_to(tmp_path / 'locks.json')
assert LockStore(linked).locks == []
with patch.object(locks, 'MAX_BYTES', 64):
assert LockStore(tmp_path).locks == []
def test_lockout_write_failures_reach_the_request_and_learning_failures_are_logged(tmp_path):
service, _, clock = make_service(tmp_path)
service.store.add(new_lock('tap', event(), 1))
lock_id = service.store.locks[0]['id']
with patch.object(service.store, 'save', side_effect=OSError('read-only')), pytest.raises(OSError):
service.request({'operation': 'unlock', 'id': lock_id}, Mock())
assert [lock['id'] for lock in service.store.locks] == [lock_id], 'memory follows what was saved'
with patch.object(service.store, 'visit', side_effect=OSError('full')), patch('openpilot.starpilot.uniden.service.cloudlog') as log:
result = service.request({'operation': 'status'}, lambda config, mute, sit: reading(b'1,00,K,3,0,24.150,F,1', clock[0]))
assert result['connected'] and log.exception.call_count == 1
def test_choosing_another_detector_forgets_the_last_alerts_and_passes(tmp_path):
service, _, _ = make_service(tmp_path)
service.parked = lambda: True
service.last, service.passes, tracker = {'address': ADDRESS}, [{'at': 1}], service.tracker
service.request({'operation': 'configure', 'config': CONFIG}, Mock())
assert service.last is not None and service.tracker is tracker
service.request({'operation': 'configure', 'config': {**CONFIG, 'address': '11:22:33:44:55:66'}}, Mock())
assert service.last is None and service.passes == [] and service.tracker is not tracker
def test_detector_state_belongs_to_one_address_and_expires_when_unused(setup):
from openpilot.starpilot.uniden.transport import STALE_S, detector_state
owner, client = setup
client._call.return_value = (b'1,00,K,3,0,24.150,F,1',)
exchange(owner, ADDRESS, 'R8', ('live',), situation=situation())
state = owner.uniden
state.timed_mute = True
assert state.address == ADDRESS and state.seen is not None and detector_state(owner, ADDRESS) is state
other = detector_state(owner, '11:22:33:44:55:66')
assert other is not state and not other.timed_mute and other.seen is None
other.used_at -= STALE_S + 1
assert detector_state(owner, '11:22:33:44:55:66') is not other
def test_close_wakes_and_stops_the_worker_even_while_a_call_blocks():
entered, release, calls = threading.Event(), threading.Event(), []
def call(method, path, payload):
calls.append(payload)
entered.set()
release.wait(5)
return 200, {'config': CONFIG, 'connected': False, 'alerts': []}
feed = DetectorFeed(call, context=lambda: None)
feed.set_enabled(True)
assert entered.wait(2)
feed.close()
assert feed.stop.is_set() and not feed.enabled
release.set()
assert feed.thread is not None
feed.thread.join(2)
assert not feed.thread.is_alive() and len(calls) == 1
idle = DetectorFeed(Mock(return_value=(200, {'config': {'enabled': False}})), context=lambda: None)
idle.set_enabled(True)
time.sleep(.05)
started = time.monotonic()
idle.close()
assert idle.thread is not None and not idle.thread.is_alive() and time.monotonic() - started < .5, 'a sleeping worker is woken'
def test_learning_progress_survives_a_restart(tmp_path):
store = LockStore(tmp_path)
store.observe(event(), learn=True, bands=['K'])
store.observe(event(band='LASER', frequency=None), learn=True, bands=['K'])
store.observe(event(at=1_000_000 + REPEAT_S), learn=True, bands=['K'])
assert len(store.candidates) == 2 and store.candidates[0]['count'] == 2
assert LockStore(tmp_path).candidates == store.candidates
@@ -0,0 +1,329 @@
import threading
import time
from types import SimpleNamespace as NS
from unittest.mock import Mock
import pytest
from openpilot.starpilot.bluetooth.owner import ADAPTER, DEVICE, BluetoothOwner, BluetoothRejected
from openpilot.starpilot.system.starport.bluetooth_bridge import SharedBluetoothOwner
from openpilot.starpilot.uniden.protocol import ALERT_UUID, WRITE_UUID, GATT, DEFAULT_CONFIG, alert_key, normalize_config, parse_alerts
from openpilot.starpilot.uniden.transport import exchange
from openpilot.starpilot.uniden.service import DetectorService
from openpilot.starpilot.uniden.feed import DetectorFeed
ADDRESS = 'AA:BB:CC:DD:EE:FF'
ADAPTER_PATH = '/org/bluez/hci0'
PATH = ADAPTER_PATH + '/dev_AA_BB_CC_DD_EE_FF'
PACKET = b'1,00,KA,3,33,33.7850,R,1&1,00,K,4,45,24.1500,F,2&0&0'
CONFIG = {'enabled': True, 'address': ADDRESS, 'model': 'R8',
'auto_mute': False, 'hide_filtered': False, 'frequency_rules': []}
@pytest.fixture
def setup(tmp_path):
objects = {ADAPTER_PATH: {ADAPTER: {'Powered': True}}, PATH: {DEVICE: {
'Name': 'R8W@12', 'Address': ADDRESS, 'Paired': True, 'Connected': True, 'ServicesResolved': True}},
PATH + '/service/alert': {GATT: {'UUID': ALERT_UUID}}, PATH + '/service/write': {GATT: {'UUID': WRITE_UUID}}}
client = Mock()
client._objects.side_effect = lambda: objects
client.adapter_identity.side_effect = lambda: (ADAPTER_PATH, objects[ADAPTER_PATH][ADAPTER], ':1.5')
client._call.return_value = (PACKET,)
owner = SharedBluetoothOwner(lambda: False, session_valid=lambda s: s == ('live',),
bluez_factory=lambda: client, lock_path=tmp_path / 'owner.lock')
return owner, client, objects
def test_packets_and_r4():
alerts = parse_alerts(PACKET)
assert alerts[0]['band'] == 'K' and alerts[0]['muted']
assert alerts[1]['frequency'] == 33.785 and alerts[1]['direction'] == 'rear'
assert all(a['direction'] == '' for a in parse_alerts(PACKET, 'R4'))
assert parse_alerts(b'0&0&0&0') == []
assert parse_alerts(b'1,00,LASER,8,0,5,F,1')[0]['frequency'] is None
def test_photo_radar_has_no_frequency_and_unknown_mute_keeps_alert():
assert parse_alerts(b'1,00,MRCD,4,0,3,F,1')[0]['frequency'] is None
assert parse_alerts(b'1,00,MRCT,4,0,x,F,1')[0]['frequency'] is None
alert = parse_alerts(b'1,00,KA,3,0,33.785,F,8')[0]
assert alert['band'] == 'KA' and alert['frequency'] == 33.785 and not alert['muted']
@pytest.mark.parametrize('packet', [b'', b'1,00,KA,9,0,33,F,1', b'1,00,KA,3,0,nan,F,1', b'1,00,K,3',
b'0&broken', b'\xff'])
def test_bad_snapshots_rejected(packet):
with pytest.raises(ValueError):
parse_alerts(packet)
def test_read_and_mute_onroad(setup):
owner, client, _ = setup
state = exchange(owner, ADDRESS, 'R8', ('live',))
assert owner.admission_file is None and state['connected']
result = exchange(owner, ADDRESS, 'R8', ('live',), mute={'observed_at': state['observed_at'], 'alerts': alert_key(state['alerts'])})
assert result['command'] == 'sent_unconfirmed'
assert not result['alerts'][1]['muted'] # Never fabricate acknowledgment.
assert client._call.call_args.args[2:] == ('WriteValue', 'aya{sv}', (b'BTreqMUTE:1', {'type': ('s', 'command')}))
@pytest.mark.parametrize('change', ['unpaired', 'wrong_model', 'unresolved', 'missing_characteristic', 'discovering', 'pairing', 'expired'])
def test_invalid_device_never_writes(setup, change):
owner, client, objects = setup
session = ('live',)
if change == 'unpaired':
objects[PATH][DEVICE]['Paired'] = False
if change == 'wrong_model':
objects[PATH][DEVICE]['Name'] = 'Phone'
if change == 'unresolved':
objects[PATH][DEVICE]['ServicesResolved'] = False
if change == 'missing_characteristic':
del objects[PATH + '/service/alert']
if change == 'discovering':
objects[ADAPTER_PATH][ADAPTER]['Discovering'] = True
if change == 'pairing':
owner.pairing = NS(done=threading.Event())
if change == 'expired':
session = ('old',)
with pytest.raises(BluetoothRejected):
exchange(owner, ADDRESS, 'R8', session, mute={'observed_at': time.monotonic(), 'alerts': alert_key(parse_alerts(PACKET))})
assert not any(c.args[2] == 'WriteValue' for c in client._call.call_args_list)
def test_cross_process_pairing_lock_is_respected(setup):
owner, client, _ = setup
other = BluetoothOwner(lambda: True, admission_lock=owner.admission_lock)
other._admission_enter()
try:
with pytest.raises(BluetoothRejected):
exchange(owner, ADDRESS, 'R8', ('live',))
client._call.assert_not_called()
finally:
other._admission_leave()
def lease():
return NS(session=None, released=False, enabled=lambda: True, selected_receiver=lambda: '11:22:33:44:55:66',
receiver='11:22:33:44:55:66', adapter_path=ADAPTER_PATH, bluez_sender=':1.5')
def test_aa_lease_permits_only_bonded_detector_io_without_radio_mutation(setup):
owner, client, _ = setup
owner.phone_lease = lease()
owner._admission_enter = Mock(side_effect=AssertionError('must reuse lease'))
assert exchange(owner, ADDRESS, 'R8', ('live',))['connected']
assert all(c.args[2] == 'ReadValue' for c in client._call.call_args_list)
client.operation.assert_not_called()
@pytest.mark.parametrize('change', ['pairing', 'released', 'receiver', 'adapter', 'revoked_during_read'])
def test_aa_lease_changes_reject(setup, change):
owner, client, _ = setup
owner.phone_lease = lease()
if change == 'pairing':
owner.phone_lease.session = ('live',)
if change == 'released':
owner.phone_lease.released = True
if change == 'receiver':
owner.phone_lease.receiver = ADDRESS
if change == 'adapter':
owner.phone_lease.bluez_sender = ':1.6'
if change == 'revoked_during_read':
def read(*args, **kwargs):
owner.phone_lease.released = True
return (PACKET,)
client._call.side_effect = read
with pytest.raises(BluetoothRejected):
exchange(owner, ADDRESS, 'R8', ('live',), mute={'observed_at': time.monotonic(), 'alerts': alert_key(parse_alerts(PACKET))})
assert not any(c.args[2] == 'WriteValue' for c in client._call.call_args_list)
@pytest.mark.parametrize('age,key', [(4, None), (-1, None), (0, [] )])
def test_mute_expiry_and_changed_alert(setup, age, key):
owner, client, _ = setup
with pytest.raises(BluetoothRejected):
exchange(owner, ADDRESS, 'R8', ('live',), mute={'observed_at': time.monotonic() - age,
'alerts': alert_key(parse_alerts(PACKET)) if key is None else key})
assert not any(c.args[2] == 'WriteValue' for c in client._call.call_args_list)
def test_reconnect_bounded_and_never_replays_mute(setup):
owner, client, objects = setup
objects[PATH][DEVICE]['Connected'] = False
for _ in range(2):
with pytest.raises(BluetoothRejected):
exchange(owner, ADDRESS, 'R8', ('live',))
assert sum(c.args[2] == 'Connect' for c in client._call.call_args_list) == 1
with pytest.raises(BluetoothRejected):
exchange(owner, ADDRESS, 'R8', ('live',), mute={})
assert sum(c.args[2] == 'Connect' for c in client._call.call_args_list) == 1
def test_service_defaults_configure_authority_and_selected_device():
params = Mock()
params.get.return_value = None
service = DetectorService(params, lambda: False)
transport = Mock()
assert service.request({'operation': 'status'}, transport)['config'] == normalize_config(DEFAULT_CONFIG)
transport.assert_not_called()
with pytest.raises(BluetoothRejected):
service.request({'operation': 'configure', 'config': CONFIG}, transport)
params.put.assert_not_called()
params.get.return_value = CONFIG
with pytest.raises(BluetoothRejected):
service.request({'operation': 'mute', 'address': 'old', 'alerts': [], 'observed_at': 0}, transport)
transport.side_effect = BluetoothRejected('Pairing busy')
result = service.request({'operation': 'status'}, transport)
assert result['config'] == normalize_config({**DEFAULT_CONFIG, **CONFIG}) and not result['connected'] and result['alerts'] == []
def test_feed_stale_and_hidden_and_failed_mute_not_replayed():
now = [10.]
state = {'config': CONFIG, 'connected': True, 'address': ADDRESS, 'observed_at': 10., 'alerts': parse_alerts(PACKET), 'can_mute': True}
call = Mock(return_value=(200, state))
feed = DetectorFeed(call, clock=lambda: now[0])
feed.enabled, feed.requested_at = True, 10.
feed.poll()
feed.mute(feed.snapshot())
call.return_value = (503, {'error': 'Lost connection'})
feed.poll()
assert call.call_args.args[2]['operation'] == 'mute' and feed.snapshot()['alerts'], 'one failed read does not blink the alerts'
now[0] = 10.8
feed.poll()
assert call.call_args.args[2]['operation'] == 'status' and feed.snapshot()['alerts'] == [], 'a lasting failure clears them'
now[0] = 10
feed.state = state
now[0] = 14
assert not feed.snapshot()['connected']
call.reset_mock()
feed.poll()
call.assert_not_called()
def test_daemon_requires_proof_but_mute_does_not_require_park():
from unittest.mock import patch
from openpilot.starpilot.system.starport import daemon
host = Mock()
host.uniden_exchange.return_value = {'connected': True}
verifier = Mock()
verifier.valid.return_value = True
request = {'command': 'uniden', 'source': 'proof', 'address': ADDRESS, 'model': 'R8', 'mute': None}
with patch('openpilot.common.params.Params') as params:
params.return_value.get_bool.return_value = True
assert daemon.handle(host, request, verifier, parked=lambda: False)['handled']
host.bind_source_session.assert_not_called()
verifier.valid.return_value = False
with pytest.raises(RuntimeError):
daemon.handle(host, request, verifier)
assert host.uniden_exchange.call_count == 1
def test_expired_session_cannot_save_detector_configuration():
params = Mock()
service = DetectorService(params, lambda: True)
with pytest.raises(BluetoothRejected):
service.request({'operation': 'configure', 'config': CONFIG}, Mock(), valid=lambda: False)
params.put.assert_not_called()
def test_older_detector_configuration_gains_defaults_and_drops_display_settings():
from openpilot.starpilot.uniden.protocol import normalize_config
old = {'enabled': True, 'address': ADDRESS, 'model': 'R8'}
assert normalize_config(old) == normalize_config({**DEFAULT_CONFIG, **CONFIG})
for value in (100, -1, True, 'false'):
config = normalize_config({**CONFIG, 'transparency': value, 'hide_when_no_alert': value})
assert 'transparency' not in config and 'hide_when_no_alert' not in config, 'display settings live in the layout'
RULE = {'enabled': True, 'label': 'Head unit', 'band': 'KA', 'frequency': 34.313, 'tolerance_mhz': 0}
def test_auto_mute_in_first_exchange_and_bounded_retry(setup):
owner, client, _ = setup
client._call.return_value = (b'1,00,KA,3,0,34.313,F,1',)
result = exchange(owner, ADDRESS, 'R8', ('live',), auto_mute=True, frequency_rules=[RULE])
assert result['alerts'][0]['filtered'] and not result['alerts'][0]['muted']
assert result['command'] == 'sent_unconfirmed'
assert [c.args[2] for c in client._call.call_args_list] == ['ReadValue', 'WriteValue']
exchange(owner, ADDRESS, 'R8', ('live',), auto_mute=True, frequency_rules=[RULE])
assert sum(c.args[2] == 'WriteValue' for c in client._call.call_args_list) == 1
owner.uniden.auto_mute = (owner.uniden.auto_mute[0], time.monotonic() - 1)
exchange(owner, ADDRESS, 'R8', ('live',), auto_mute=True, frequency_rules=[RULE])
assert sum(c.args[2] == 'WriteValue' for c in client._call.call_args_list) == 2
@pytest.mark.parametrize('packet', [b'0', b'1,00,KA,3,0,34.314,F,1', b'1,00,KA,3,0,34.313,F,2',
b'1,00,KA,3,0,34.313,F,1&1,00,KA,3,0,34.7,R,1',
b'1,00,KA,3,0,34.313,F,1&1,00,LASER,8,0,5,F,1'])
def test_auto_mute_preserves_unmatched_or_already_muted_signals(setup, packet):
owner, client, _ = setup
client._call.return_value = (packet,)
exchange(owner, ADDRESS, 'R8', ('live',), auto_mute=True, frequency_rules=[RULE])
assert not any(c.args[2] == 'WriteValue' for c in client._call.call_args_list)
def test_matching_does_not_require_auto_mute_and_absent_write_supported(setup):
owner, client, objects = setup
client._call.return_value = (b'1,00,KA,3,0,34.313,F,1',)
result = exchange(owner, ADDRESS, 'R8', ('live',), frequency_rules=[RULE])
assert result['alerts'][0]['filtered'] and not result['command']
del objects[PATH + '/service/write']
result = exchange(owner, ADDRESS, 'R8', ('live',), auto_mute=True, frequency_rules=[RULE])
assert not result['can_mute'] and not result['command']
assert not any(c.args[2] == 'WriteValue' for c in client._call.call_args_list)
def test_rule_tolerance_band_and_enabled():
from openpilot.starpilot.uniden.protocol import matches_rule
rule = {**RULE, 'tolerance_mhz': 2}
assert matches_rule({'band': 'KA', 'frequency': 34.315}, [rule])
assert not matches_rule({'band': 'KA', 'frequency': 34.316}, [rule])
assert not matches_rule({'band': 'K', 'frequency': 34.313}, [rule])
assert not matches_rule({'band': 'KA', 'frequency': 34.313}, [{**rule, 'enabled': False}])
@pytest.mark.parametrize('change', [{'frequency': float('nan')}, {'frequency': True}, {'frequency': 24.15},
{'tolerance_mhz': -1}, {'tolerance_mhz': 11}, {'tolerance_mhz': float('inf')}, {'band': 'LASER'},
{'band': []}, {'enabled': 1}, {'label': 'x' * 61}])
def test_invalid_frequency_rule_rejected(change):
from openpilot.starpilot.uniden.protocol import normalize_config
with pytest.raises(ValueError):
normalize_config({**CONFIG, 'frequency_rules': [{**RULE, **change}]})
def test_legacy_config_gains_independent_rule_lists():
from openpilot.starpilot.uniden.protocol import normalize_config
legacy = {key: value for key, value in CONFIG.items() if key not in ('auto_mute', 'hide_filtered', 'frequency_rules')}
first, second = normalize_config(legacy), normalize_config(legacy)
first['frequency_rules'].append(RULE)
assert second['frequency_rules'] == [] and not second['auto_mute']
def test_failed_connect_and_retry_delay_have_same_status(setup):
owner, client, objects = setup
objects[PATH][DEVICE]['Connected'] = False
client._call.side_effect = BluetoothRejected('org.bluez.Error.Failed')
params = Mock()
params.get.return_value = CONFIG
service = DetectorService(params, lambda: True)
results = [service.request({'operation': 'status'}, lambda config, mute, situation=None: exchange(owner, ADDRESS, 'R8', ('live',))) for _ in range(2)]
assert all(result['connection_state'] == 'reconnecting' for result in results)
assert results[0]['error'] == results[1]['error'] == 'Reconnecting to detector'
assert not any(result['connected'] or result['alerts'] for result in results)
assert sum(call.args[2] == 'Connect' for call in client._call.call_args_list) == 1
@pytest.mark.parametrize('error,expected', [
(BluetoothRejected('org.bluez.Error.Failed'), 'reconnecting'),
(BluetoothRejected('org.bluez.Error.NotAuthorized'), 'detector_pairing_required'),
(BluetoothRejected('off', code='radio_off'), 'radio_off'),
(BluetoothRejected('pairing', code='busy'), 'busy'),
(ValueError('Unsupported alert packet'), 'unavailable'),
])
def test_connection_errors_are_friendly_and_keep_alerts_unavailable(error, expected):
params = Mock()
params.get.return_value = CONFIG
result = DetectorService(params, lambda: True).request({'operation': 'status'}, Mock(side_effect=error))
assert result['connection_state'] == expected
assert 'org.bluez' not in result['error']
assert not result['connected'] and result['alerts'] == []
@@ -0,0 +1,667 @@
import time
import pytest
from types import SimpleNamespace as NS
from typing import Any, cast
from unittest.mock import Mock, patch
from openpilot.starpilot.ui.onroad_uniden import UnidenWidget
from openpilot.starpilot.uniden.protocol import parse_alerts
@pytest.fixture(autouse=True)
def outline_guard(monkeypatch):
outline = Mock()
monkeypatch.setattr('openpilot.starpilot.ui.onroad_uniden.outline', outline)
return outline
def fonts_mock():
fonts = Mock()
fonts.measure.side_effect = lambda text, role, size: NS(width=len(text) * size * .55, height=size * 1.2)
return fonts
def test_touch_requires_visible_fresh_card_and_cancels_drag_or_changed_alert():
feed = Mock()
data = {'connected': True, 'can_mute': True, 'address': 'detector', 'alerts': parse_alerts(b'1,00,KA,3,0,33.785,R,1')}
feed.snapshot.return_value = data
widget = UnidenWidget(Mock(), feed)
state = NS(alert=NS(size='none'), customization={'layouts': {'large': {'uniden_alerts': {'enabled': True, 'x': 30, 'y': 50}}}})
assert not widget.touch('down', 40, 60, state)
widget.visible_until = time.monotonic() + 10
assert widget.touch('down', 40, 60, state)
assert widget.touch('up', 42, 62, state)
feed.mute.assert_called_once_with(data)
feed.mute.reset_mock()
widget.touch('down', 40, 60, state)
widget.touch('move', 200, 60, state)
widget.touch('up', 40, 60, state)
feed.mute.assert_not_called()
widget.touch('down', 40, 60, state)
feed.snapshot.return_value = {**data, 'address': 'another'}
widget.touch('up', 40, 60, state)
feed.mute.assert_not_called()
feed.snapshot.return_value = data
widget.touch('down', 40, 60, state)
state.alert.size = 'full'
widget.touch('up', 40, 60, state)
feed.mute.assert_not_called()
def test_preview_does_not_start_detector_io_and_r4_has_no_arrows():
feed, fonts = Mock(), fonts_mock()
feed.snapshot.return_value = {'config': {'enabled': True}, 'connected': True, 'model': 'R4',
'alerts': parse_alerts(b'1,00,K,3,0,24.150,F,1', 'R4')}
widget = UnidenWidget(fonts, feed)
state = NS(alert=NS(size='none'), customization={'layouts': {'large': {'uniden_alerts': {'enabled': True, 'x': 30, 'y': 50}}}})
with patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_rectangle_rounded'), \
patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_rectangle'), \
patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_triangle') as arrows:
widget.render(state)
feed.set_enabled.assert_called_once_with(False)
arrows.assert_not_called()
feed.snapshot.return_value['model'] = 'R8'
feed.snapshot.return_value['alerts'][0]['direction'] = 'front'
widget.render(state)
assert arrows.call_count == 1
def test_transparency_only_changes_background_and_quiet_toggle_controls_visibility():
feed, fonts = Mock(), fonts_mock()
widget = UnidenWidget(fonts, feed)
data = {'config': {'enabled': True, 'transparency': 100, 'hide_when_no_alert': True}, 'connected': True, 'model': 'R8',
'alerts': parse_alerts(b'1,00,KA,3,0,33.785,R,1'), 'can_mute': True}
feed.snapshot.return_value = data
state = NS(alert=NS(size='none'), customization={'layouts': {'large': {'uniden_alerts': {'enabled': True, 'x': 30, 'y': 50}}}})
with patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_rectangle_rounded') as rounded, \
patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_rectangle'), \
patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_triangle') as arrows:
for transparency, alpha in ((0, 255), (50, 128), (100, 0)):
rounded.reset_mock()
data['config']['transparency'] = transparency
widget.render(state)
assert rounded.call_args_list[0].args[-1].a == alpha
assert all(call.args[-1].a == 255 for call in fonts.draw.call_args_list)
assert all(call.args[-1].a == 255 for call in arrows.call_args_list)
data['alerts'] = []
for connected in (True, False):
data['connected'] = connected
for hide in (True, False):
data['config']['hide_when_no_alert'] = hide
fonts.reset_mock()
rounded.reset_mock()
widget.render(state)
if hide:
fonts.draw.assert_not_called()
rounded.assert_not_called()
assert widget.visible_until == 0
else:
labels = [call.args[0] for call in fonts.draw.call_args_list]
assert ('Detector ready' if connected else 'Detector disconnected') in labels
assert not widget.touch('down', 40, 60, state)
feed.mute.assert_not_called()
def test_one_row_per_threat_overflow_arrows_and_touch_bounds():
from openpilot.starpilot.ui.onroad_uniden import card_size
feed, fonts = Mock(), fonts_mock()
alerts = parse_alerts(b'1,00,KA,6,0,35.500,R,1&1,00,K,3,0,24.150,F,2')
data = {'config': {'enabled': True}, 'connected': True, 'can_mute': True, 'model': 'R8', 'alerts': alerts}
feed.snapshot.return_value = data
widget = UnidenWidget(fonts, feed)
state = NS(alert=NS(size='none'), customization={'layouts': {'large': {'uniden_alerts': {'enabled': True, 'x': 30, 'y': 50}}}})
assert card_size(alerts[:1]) == (460, 76), 'a single threat is one slim row'
with patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_rectangle_rounded'), \
patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_rectangle'), \
patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_triangle') as arrows:
widget.render(state)
draws = {call.args[0]: call.args for call in fonts.draw.call_args_list}
assert '35.500 GHz' in draws and '24.150 GHz' in draws
assert '1 Manual mute' in draws and not any('THREATS' in text or 'Tap' in text for text in draws)
assert draws['1 Manual mute'][4] < 50 + 2, 'the mute note sits in the top edge of the card'
band, frequency = draws['KA'], draws['35.500 GHz']
assert abs((band[4] + 36 * .6) - (frequency[4] + 28 * .6)) < 1, 'band and frequency share one centre line'
assert arrows.call_count == 2
assert widget.touch('down', 480, 170, state)
assert widget.touch('up', 480, 170, state)
feed.mute.assert_called_once_with(data)
assert not widget.touch('down', 480, 190, state)
data['alerts'] = alerts * 3
fonts.reset_mock()
widget.render(state)
labels = [call.args[0] for call in fonts.draw.call_args_list]
assert any(label.startswith('3 Manual mute') for label in labels)
assert '3 MUTED' in labels
assert labels.count('35.500 GHz') == 2
assert card_size(data['alerts']) == (460, 256)
data['model'] = 'R4'
arrows.reset_mock()
widget.render(state)
arrows.assert_not_called()
def test_all_muted_says_so_in_the_outline(outline_guard):
feed, fonts = Mock(), fonts_mock()
data = {'config': {'enabled': True}, 'connected': True, 'model': 'R8', 'alerts': parse_alerts(b'1,00,KA,3,0,33.785,R,2')}
feed.snapshot.return_value = data
widget = UnidenWidget(fonts, feed)
state = NS(alert=NS(size='none'), customization={'layouts': {'large': {'uniden_alerts': {'enabled': True, 'x': 30, 'y': 50}}}})
with patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_rectangle_rounded'), \
patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_rectangle'), \
patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_triangle'):
widget.render(state)
assert 'Manual mute' in [call.args[0] for call in fonts.draw.call_args_list]
gap = outline_guard.call_args.args[5][1]
assert gap[0] < 30 + 24 < gap[1], 'the outline opens around the note'
data['alerts'] = parse_alerts(b'1,00,KA,3,0,33.785,R,1')
fonts.reset_mock()
widget.render(state)
assert 'MUTED' not in [call.args[0] for call in fonts.draw.call_args_list]
assert outline_guard.call_args.args[5] == []
def test_theme_display_settings_override_legacy_bluetooth_settings():
feed, fonts = Mock(), Mock()
feed.snapshot.return_value = {'config': {'enabled': True, 'transparency': 0, 'hide_when_no_alert': True},
'connected': True, 'alerts': []}
widget = UnidenWidget(fonts, feed)
placement = {'enabled': True, 'x': 30, 'y': 50, 'transparency': 75, 'hide_when_no_alert': False}
state = NS(alert=NS(size='none'), customization={'layouts': {'large': {'uniden_alerts': placement}}})
with patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_rectangle_rounded') as rounded:
widget.render(state)
assert rounded.call_args_list[0].args[-1].a == 64
assert 'Detector ready' in [call.args[0] for call in fonts.draw.call_args_list]
placement['hide_when_no_alert'] = True
rounded.reset_mock()
widget.render(state)
rounded.assert_not_called()
def test_theme_settings_roundtrip_migration_and_projection_isolation():
import pytest
from openpilot.starpilot.ui.onroad_customization import default_document, validate_document
from openpilot.starpilot.system.starport.projection_layout import (
default_layout_for_viewport, validate_layout_for_viewport, projection_customization)
native = default_document()
pos = native['layouts']['large']['uniden_alerts']
pos.update(transparency=41, hide_when_no_alert=False)
assert validate_document(native)['layouts']['large']['uniden_alerts'] == pos
viewport = (1860, 1080)
projected = default_layout_for_viewport(viewport)
other = projected['widgets']['uniden_alerts']
other.update(transparency=82, hide_when_no_alert=True)
saved = validate_layout_for_viewport(projected, viewport)
assert projection_customization(saved, native)['layouts']['large']['uniden_alerts']['transparency'] == 82
assert native['layouts']['large']['uniden_alerts']['transparency'] == 41
for document, placement, validate in ((native, pos, validate_document),
(projected, other, lambda value: validate_layout_for_viewport(value, viewport))):
for field, invalid in (('transparency', True), ('transparency', 101), ('hide_when_no_alert', 1),
('scale', 49), ('scale', 151), ('scale', 1.0)):
old = placement[field]
placement[field] = invalid
with pytest.raises(ValueError):
validate(document)
placement[field] = old
for field in ('transparency', 'hide_when_no_alert', 'scale'):
placement.pop(field)
placement.update(hide_quiet_ride=True, hide_mute_memory=False)
result = validate(document)
migrated = result['widgets']['uniden_alerts'] if 'widgets' in result else result['layouts']['large']['uniden_alerts']
assert (migrated['transparency'], migrated['hide_when_no_alert'], migrated['scale']) == (8, True, 100)
assert 'hide_quiet_ride' not in migrated and 'hide_mute_memory' not in migrated, 'retired fields in old layouts are dropped'
@pytest.mark.parametrize(('direction', 'count'), [('front', 1), ('rear', 1), ('side', 2), ('', 0)])
def test_only_active_direction_arrows_are_drawn(direction, count):
from openpilot.starpilot.ui.onroad_uniden import direction_arrows
with patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_triangle') as arrows:
direction_arrows(100, 100, direction, 'accent', 18)
assert arrows.call_count == count
assert all(call.args[-1] == 'accent' for call in arrows.call_args_list)
def test_quiet_ride_and_mute_memory_alerts_can_be_left_off_the_card():
from openpilot.starpilot.ui.onroad_uniden import shown_alerts
alerts = parse_alerts(b'1,00,KA,6,0,35.500,F,1&1,00,K,3,0,24.150,F,6&1,00,K,2,0,24.125,R,3&1,00,X,2,0,10.525,S,4&1,00,K,4,0,24.200,F,2')
assert sorted(a['mute_mode'] for a in alerts) == ['', 'auto_memory', 'manual', 'memory', 'quiet_ride']
assert shown_alerts(alerts, {}) == alerts
assert {a['mute_mode'] for a in shown_alerts(alerts, {'hide_q_ride': True})} == {'', 'memory', 'auto_memory', 'manual'}
assert {a['mute_mode'] for a in shown_alerts(alerts, {'hide_mute_memory': True})} == {'', 'quiet_ride', 'manual'}
feed, fonts = Mock(), fonts_mock()
quiet = parse_alerts(b'1,00,K,3,0,24.150,F,6')
data = {'config': {'enabled': True, 'hide_q_ride': True}, 'connected': True, 'can_mute': True, 'model': 'R8', 'alerts': quiet}
feed.snapshot.return_value = data
widget = UnidenWidget(fonts, feed)
placement = {'enabled': True, 'x': 30, 'y': 50, 'hide_when_no_alert': True}
state = NS(alert=NS(size='none'), customization={'layouts': {'large': {'uniden_alerts': placement}}})
with patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_rectangle_rounded') as rounded:
widget.render(state)
rounded.assert_not_called()
assert widget.visible_until == 0 and not widget.touch('down', 40, 60, state), 'a hidden Quiet Ride alert takes no taps'
placement['hide_when_no_alert'] = False
widget.render(state)
assert 'No active alerts' in [call.args[0] for call in fonts.draw.call_args_list]
def test_scale_grows_the_card_and_its_touch_area():
from openpilot.starpilot.ui.onroad_uniden import card_scale
assert (card_scale({}), card_scale({'scale': 150}), card_scale({'scale': 500}), card_scale({'scale': 'big'})) == (1., 1.5, 1.5, 1.)
feed, fonts = Mock(), fonts_mock()
data = {'config': {'enabled': True}, 'connected': True, 'can_mute': True, 'model': 'R8',
'alerts': parse_alerts(b'1,00,KA,6,0,35.500,F,1')}
feed.snapshot.return_value = data
widget = UnidenWidget(fonts, feed)
placement = {'enabled': True, 'x': 30, 'y': 50, 'scale': 150}
state = NS(alert=NS(size='none'), customization={'layouts': {'large': {'uniden_alerts': placement}}})
with patch('openpilot.starpilot.ui.onroad_uniden.rl') as rl:
widget.render(state)
rl.rl_translatef.assert_called_once_with(30, 50, 0)
rl.rl_scalef.assert_called_once_with(1.5, 1.5, 1)
assert rl.rl_pop_matrix.call_count == 1
assert widget.touch('down', 30 + 460 * 1.5 - 5, 50 + 76 * 1.5 - 5, state)
widget.touch('cancel', 0, 0, state)
placement['scale'] = 100
assert not widget.touch('down', 30 + 460 * 1.5 - 5, 50 + 76 * 1.5 - 5, state)
def test_mute_note_names_quiet_ride_and_mute_memory():
from openpilot.starpilot.ui.onroad_uniden import mute_note
assert mute_note(parse_alerts(b'1,00,K,3,0,24.150,F,6')) == 'Q-Ride'
assert mute_note(parse_alerts(b'1,00,K,3,0,24.150,F,3')) == 'Mute Memory'
assert mute_note(parse_alerts(b'1,00,K,3,0,24.150,F,3&1,00,X,2,0,10.525,S,4')) == 'Mute Memory', 'learned and saved are both mute memory'
assert mute_note(parse_alerts(b'1,00,K,3,0,24.150,F,2')) == 'Manual mute'
assert mute_note(parse_alerts(b'1,00,K,3,0,24.150,F,6&1,00,X,2,0,10.525,S,3')) == 'Muted', 'mixed reasons read as plain muted'
assert mute_note(parse_alerts(b'1,00,KA,6,0,35.500,F,1&1,00,K,3,0,24.150,F,6')) == '1 Q-Ride'
assert mute_note(parse_alerts(b'1,00,KA,6,0,35.500,F,1')) == ''
def test_custom_filters_hide_only_matching_rows():
from openpilot.starpilot.ui.onroad_uniden import shown_alerts
alerts = parse_alerts(b'1,00,KA,3,0,34.313,F,1&1,00,KA,3,0,34.7,R,1')
alerts[0]['filtered'] = True
assert shown_alerts(alerts, {'hide_filtered': True}) == alerts[1:]
assert shown_alerts(alerts, {'hide_filtered': False}) == alerts
def test_hidden_widget_keeps_runtime_feed_active():
feed = Mock()
widget = UnidenWidget(Mock(), feed)
widget.runtime_active = True
state = NS(alert=NS(size='full'), customization={'layouts': {'large': {}}})
widget.render(state)
feed.set_enabled.assert_called_once_with(True)
def test_activated_widget_leaves_the_feed_to_the_shell():
feed = Mock()
widget = UnidenWidget(Mock(), feed).activate(Mock())
widget.render(NS(alert=NS(size='full'), customization={'layouts': {'large': {}}}))
feed.set_enabled.assert_not_called()
@pytest.fixture
def detector_shell(monkeypatch):
from openpilot.starpilot.ui import runtime_app
saved = {'UnidenConfig': {'enabled': True, 'address': 'E0:00:00:00:0B:4D'}}
state = NS(started=True, replay_clock=None, params=NS(get=lambda key: saved.get(key)))
clock = [100.]
monkeypatch.setattr(runtime_app, 'ui_state', state)
monkeypatch.setattr(runtime_app.time, 'monotonic', lambda: clock[0])
shell = NS(detector_feed=Mock(), _detector_checked_at=-runtime_app.DETECTOR_CHECK_S, _detector_configured=False)
return lambda: runtime_app.StarShellSession._poll_detector(shell), shell, state, saved, clock
def test_detector_polls_whenever_onroad_even_with_the_screen_off(detector_shell):
poll, shell, state, _, _ = detector_shell
poll()
shell.detector_feed.set_enabled.assert_called_with(True)
state.started = False
poll()
shell.detector_feed.set_enabled.assert_called_with(False)
state.started, state.replay_clock = True, object()
poll()
shell.detector_feed.set_enabled.assert_called_with(False)
@pytest.mark.parametrize('config', [None, {'enabled': False, 'address': 'E0:00:00:00:0B:4D'}, {'enabled': True, 'address': ''}, 'bad'])
def test_detector_stays_off_until_enabled_and_configured(detector_shell, config):
poll, shell, _, saved, clock = detector_shell
saved['UnidenConfig'] = config
poll()
shell.detector_feed.set_enabled.assert_called_with(False)
saved['UnidenConfig'] = {'enabled': True, 'address': 'E0:00:00:00:0B:4D'}
poll()
shell.detector_feed.set_enabled.assert_called_with(False) # settings are re-read on a slow cadence
clock[0] += 5
poll()
shell.detector_feed.set_enabled.assert_called_with(True)
def border_state(**customization):
return NS(alert=NS(size='full'), customization=customization)
def border_data(packet, **config):
return {'config': {'enabled': True, 'border_bands': ['KA', 'LASER'], **config}, 'connected': True,
'alerts': parse_alerts(packet)}
def test_warning_ignores_unchosen_absent_locked_out_and_quiet_alerts_and_prefers_laser():
for packet, bands in ((b'1,00,K,3,0,24.150,F,1', ['KA', 'LASER']), (b'0', ['KA', 'K', 'LASER'])):
_, drawn = edge_run(packet, bands=bands)
assert not any(drawn.values())
for flag, hide in (('filtered', 'hide_filtered'), ('quiet', 'hide_below_limit')):
_, drawn = edge_run(b'1,00,K,3,0,24.150,F,1', flags={flag: True}, config={hide: True})
assert not any(drawn.values()), flag
_, shown = edge_run(b'1,00,K,3,0,24.150,F,1', flags={flag: True}, reduce_motion=True)
assert shown['line'] and shown['line'][0][2].a == round(255 * .85 * .5 * 1.1), f'{flag} but not hidden: shown at the muted brightness'
for mode, hide in ((b'6', 'hide_q_ride'), (b'3', 'hide_mute_memory')):
_, drawn = edge_run(b'1,00,K,3,0,24.150,F,' + mode, config={hide: True})
assert not any(drawn.values()), hide
_, drawn = edge_run(b'1,00,K,3,0,24.150,F,1&1,00,LASER,8,0,5,F,1')
assert all((c.r, c.g) == (0xFF, 0x5B) for _, c in drawn['rect']), 'laser wins, in its coral'
def test_holding_an_alert_locks_it_out_once_and_a_tap_still_mutes():
feed = Mock()
data = {'config': {'enabled': True}, 'connected': True, 'can_mute': True, 'address': 'detector', 'model': 'R8',
'alerts': parse_alerts(b'1,00,KA,3,0,33.785,R,1')}
feed.snapshot.return_value = data
widget = UnidenWidget(fonts_mock(), feed)
state = NS(alert=NS(size='none'), customization={'layouts': {'large': {'uniden_alerts': {'enabled': True, 'x': 30, 'y': 50}}}})
widget.visible_until = time.monotonic() + 10
with patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_rectangle_rounded'), patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_rectangle'), \
patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_triangle'):
widget.touch('down', 40, 60, state)
widget.render(state)
feed.lock_here.assert_not_called()
pressed = widget.pressed
assert pressed is not None
widget.pressed = (pressed[0], pressed[1], pressed[2], time.monotonic() - 1)
widget.render(state)
widget.render(state)
feed.lock_here.assert_called_once_with(data)
widget.touch('up', 40, 60, state)
feed.mute.assert_not_called()
widget.touch('down', 40, 60, state)
widget.touch('up', 40, 60, state)
feed.mute.assert_called_once_with(data)
def test_offline_detector_shows_a_badge_even_when_idle_and_notices_replace_the_note():
feed, fonts = Mock(), fonts_mock()
data = {'config': {'enabled': True, 'hide_when_no_alert': True}, 'connected': False, 'alerts': [], 'offline': True}
feed.snapshot.return_value = data
widget = UnidenWidget(fonts, feed)
state = NS(alert=NS(size='none'), customization={'layouts': {'large': {'uniden_alerts': {'enabled': True, 'x': 30, 'y': 50}}}})
with patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_rectangle_rounded'), patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_rectangle'), \
patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_triangle'):
widget.render(state)
assert [call.args[0] for call in fonts.draw.call_args_list] == ['DETECTOR OFFLINE']
fonts.reset_mock()
feed.snapshot.return_value = {**data, 'offline': False, 'connected': True, 'model': 'R8', 'can_mute': True, 'notice': 'Locked out here (1)',
'alerts': parse_alerts(b'1,00,KA,3,0,33.785,R,1')}
widget.render(state)
assert 'Locked out here (1)' in [call.args[0] for call in fonts.draw.call_args_list]
fonts.reset_mock()
quiet = parse_alerts(b'1,00,K,3,0,24.150,F,1')
quiet[0]['quiet'] = True
feed.snapshot.return_value = {**data, 'offline': False, 'connected': True, 'model': 'R8', 'alerts': quiet}
widget.render(state)
assert 'Below limit' in [call.args[0] for call in fonts.draw.call_args_list]
def test_offline_badge_moves_to_the_top_of_the_view_when_the_widget_is_off_or_covered():
feed, fonts = Mock(), fonts_mock()
feed.snapshot.return_value = {'config': {'enabled': True}, 'connected': False, 'alerts': [], 'offline': True}
widget = UnidenWidget(fonts, feed)
covered = NS(alert=NS(size='full'), customization={'layouts': {'large': {'uniden_alerts': {'enabled': True, 'x': 30, 'y': 50}}}})
with patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_rectangle_rounded'), patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_rectangle'):
widget.render_border(covered, 1860, 1080)
assert [call.args[0] for call in fonts.draw.call_args_list] == ['DETECTOR OFFLINE']
assert fonts.draw.call_args.args[3] == (1860 - 330) / 2 + 24
fonts.reset_mock()
shown = NS(alert=NS(size='none'), customization=covered.customization)
widget.render_border(shown, 1860, 1080)
fonts.draw.assert_not_called()
def test_onroad_view_draws_the_border_after_the_rest_of_the_frame():
from openpilot.starpilot.ui.onroad import OnroadView
from openpilot.starpilot.ui.presentation import Profile
order = []
view = cast(Any, object.__new__(OnroadView))
view.uniden = Mock(runtime_active=False)
view.uniden.render_border.side_effect = lambda *args: order.append(('border', args))
view.fonts, view.camera_layer, view.projection_viewport = NS(profile=Profile.LARGE), None, (1500, 1000)
view._large = lambda state: order.append('large')
view.render(NS(camera_available=False, viewport_width=1860))
assert order[0] == 'large' and order[1][0] == 'border' and order[1][1][1:] == (1500, 1000)
def test_a_mute_silences_the_detector_but_keeps_the_frame_while_the_signal_lasts():
from openpilot.starpilot.ui.onroad_uniden import threat
alert = parse_alerts(b'1,00,K,7,0,24.150,F,2')[0]
assert alert['muted']
assert threat([alert], ['K']) is alert
assert threat([{**alert, 'timed': True}], ['K'])
assert threat([{**alert, 'breakthrough': True}], ['K'])
assert threat([{**alert, 'quiet': True}], ['K']), 'hiding is up to the shared on-screen rules, not threat()'
def test_card_note_names_timed_mute_and_strong_signals():
feed, fonts = Mock(), fonts_mock()
widget = UnidenWidget(fonts, feed)
state = NS(alert=NS(size='none'), customization={'layouts': {'large': {'uniden_alerts': {'enabled': True, 'x': 30, 'y': 50}}}})
def notes(**flags):
items = parse_alerts(b'1,00,K,3,0,24.150,F,2')
items[0].update(flags)
feed.snapshot.return_value = {'config': {'enabled': True}, 'connected': True, 'model': 'R8', 'alerts': items}
fonts.reset_mock()
widget.render(state)
return [call.args[0] for call in fonts.draw.call_args_list]
with patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_rectangle_rounded'), patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_rectangle'), \
patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_triangle'):
assert 'Timed mute' in notes(timed=True)
assert 'Strong signal' in notes(breakthrough=True, timed=False)
@pytest.mark.parametrize('flags', [{}, {'breakthrough': True}, {'quiet': True, 'muted': False},
{'timed': True, 'muted': False}, {'locked': True}, {'filtered': True}])
def test_mute_status_stays_red_on_the_right_with_strength_notices_and_long_notes(flags, outline_guard):
fonts, feed = fonts_mock(), Mock()
alerts = [{**parse_alerts(b'1,00,K,8,0,24.150,F,2')[0], **flags}]
data = {'connected': True, 'model': 'R8', 'alerts': alerts}
widget = UnidenWidget(fonts, feed)
state = NS(customization={})
with patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_rectangle_rounded'), \
patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_rectangle'), \
patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_triangle'):
for notice in ('', 'Locked out here (1)', 'A very long notice that must leave room for mute status'):
fonts.reset_mock()
widget._card(state, {**data, 'notice': notice}, alerts, {}, 30, 50)
draws = {call.args[0]: call.args for call in fonts.draw.call_args_list}
status = draws['MUTED']
assert status[3] > 30 + 460 / 2
assert (status[-1].r, status[-1].g, status[-1].b, status[-1].a) == (255, 91, 101, 255)
if flags.get('breakthrough') and not notice:
assert 'Strong signal' in draws
gaps = sorted(outline_guard.call_args.args[5])
assert len(gaps) == 2 and gaps[0][1] + 12 <= gaps[1][0]
assert gaps[1][0] < status[3] < gaps[1][1]
def edge_run(packet, *, parts=None, muted_percent=50, moments=(5.,), model='R8', speed_x=640, reduce_motion=False,
bands=('KA', 'K', 'LASER'), flags=None, config=None):
"""Render the Edge style and collect what it drew: rounded strokes, straight pieces, rings and chevron lines."""
from openpilot.starpilot.uniden.protocol import DEFAULT_CONFIG
feed = Mock()
data = border_data(packet, border_bands=list(bands),
border_edge={**DEFAULT_CONFIG['border_edge'], **(parts or {})}, border_muted_percent=muted_percent, **(config or {}))
data['alerts'] = [{**alert, **(flags or {})} for alert in parse_alerts(packet, model)]
feed.snapshot.return_value = data
widget = UnidenWidget(Mock(), feed)
drawn = {'band': [], 'rect': [], 'ring': [], 'line': [], 'gradient': []}
customization = {'reduceMotion': reduce_motion, 'layouts': {'large': {'current_speed': {'x': speed_x, 'y': 30}}}}
with patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_rectangle_rounded_lines_ex', side_effect=lambda r, k, n, t, c: drawn['band'].append((r, t, c))), \
patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_rectangle_rec', side_effect=lambda r, c: drawn['rect'].append((r, c))), \
patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_ring', side_effect=lambda *a: drawn['ring'].append(a)), \
patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_line_ex', side_effect=lambda a, b, t, c: drawn['line'].append((a, b, c))), \
patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_rectangle_gradient_v', side_effect=lambda *a: drawn['gradient'].append(a)), \
patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_rectangle_gradient_h', side_effect=lambda *a: drawn['gradient'].append(a)), \
patch('openpilot.starpilot.ui.onroad_uniden.offset', return_value=(speed_x - 640, 0)), \
patch('openpilot.starpilot.ui.onroad_uniden.time.monotonic', side_effect=list(moments)):
for _ in moments:
widget.render_border(NS(alert=NS(size='none'), customization=customization), 1860, 1080)
return widget, drawn
def test_edge_draws_a_segmented_line_that_follows_the_rounded_corners_and_chevrons_by_strength():
_, drawn = edge_run(b'1,00,K,8,0,24.150,F,1')
assert drawn['rect'] and drawn['ring'], 'dashes along the straight sides and around the corners'
assert min(r.x for r, _ in drawn['rect']) >= 30 + 12 and all(c.r == 0xFF and c.g == 0xBA for _, c in drawn['rect'])
assert not drawn['band'] and not drawn['gradient'], 'no glow or veil unless chosen'
assert len(drawn['line']) == 2 * 4 * 2, 'strength 8 is four chevrons in each of the two sets beside the speed'
for strength, count in ((1, 1), (2, 1), (3, 2), (5, 3), (7, 4)):
_, drawn = edge_run(f'1,00,K,{strength},0,24.150,F,1'.encode())
assert len(drawn['line']) == 2 * count * 2
def test_edge_chevrons_flank_the_speed_ahead_and_for_the_r4_and_point_toward_the_signal():
_, ahead = edge_run(b'1,00,K,2,0,24.150,F,1', speed_x=700)
apexes = sorted(round(b.x) for a, b, c in ahead['line'][::2])
assert apexes == [930 + 60 - 300, 930 + 60 + 300], 'one set each side of the moved speed'
assert all(b.y < a.y for a, b, _ in ahead['line'][::2]), 'pointing up, ahead'
_, r4 = edge_run(b'1,00,K,2,0,24.150,F,1', model='R4')
assert sorted(round(b.x) for a, b, c in r4['line'][::2]) == [630, 1230]
_, rear = edge_run(b'1,00,K,2,0,24.150,R,1')
assert [round(b.x) for a, b, c in rear['line'][::2]] == [930] and all(b.y > a.y for a, b, _ in rear['line'][::2])
_, beside = edge_run(b'1,00,K,2,0,24.150,S,1')
assert sorted(round(b.y) for a, b, c in beside['line'][::2]) == [540, 540]
def test_edge_parts_can_be_switched_and_muted_alerts_use_the_chosen_brightness():
_, drawn = edge_run(b'1,00,K,4,0,24.150,F,1', parts={'line': False, 'chevrons': False, 'glow': True, 'veil': True})
assert drawn['band'] and not drawn['rect'] and not drawn['line']
assert any(c.r == 0 and c.g == 0 and c.b == 0 for _, _, c in drawn['band']), 'the veil is black'
_, solid = edge_run(b'1,00,K,4,0,24.150,F,1', parts={'dashes': False, 'chevrons': False})
assert len(solid['band']) == 1 and not solid['rect'], 'an unbroken line is one rounded stroke'
_, loud = edge_run(b'1,00,K,4,0,24.150,F,1', reduce_motion=True)
_, half = edge_run(b'1,00,K,4,0,24.150,F,2', reduce_motion=True)
_, hidden = edge_run(b'1,00,K,4,0,24.150,F,2', muted_percent=0)
assert loud['line'][0][2].a == round(255 * .85 * 1.1) and half['line'][0][2].a == round(255 * .85 * .5 * 1.1)
assert not any(hidden.values()), '0% hides the frame while muted'
def test_edge_pulses_on_a_new_alert_and_a_two_bar_jump_and_fades_out():
from openpilot.starpilot.ui.onroad_uniden import EdgeMotion
motion = EdgeMotion()
alert = parse_alerts(b'1,00,K,3,0,24.150,F,1')[0]
motion.update(alert, 10., False)
assert [p[1] for p in motion.pulses] == [2] and motion.boost(10.15) > .9
motion.update({**alert, 'strength': 4}, 11., False)
assert motion.boost(11.1) == 0, 'one bar is not worth a pulse'
motion.update({**alert, 'strength': 5}, 12., False)
assert motion.boost(12.15) > .9, 'two bars over the last pulse is'
motion.update({**alert, 'band': 'LASER', 'frequency': None}, 13., False)
assert motion.pulses[-1][1] == 3, 'laser gets three'
motion.update(None, 14., False)
assert motion.fading(14.25)[1] == pytest.approx(.5) and motion.fading(14.6) is None
still = EdgeMotion()
still.update(alert, 10., True)
assert not still.pulses
def test_old_saved_colors_map_to_current_ones_and_styles_are_dropped():
from openpilot.starpilot.uniden.protocol import DEFAULT_CONFIG, normalize_config
old = {**DEFAULT_CONFIG, 'border_colors': {'KA': 'white', 'K': 'purple', 'LASER': 'yellow'},
'border_styles': {'KA': 'direction', 'K': 'chase', 'LASER': 'pulse'}}
del old['border_edge'], old['border_muted_percent']
config = normalize_config(old)
assert 'border_styles' not in config and config['border_muted_percent'] == 50
assert config['border_colors'] == {'KA': 'white', 'K': 'ultraviolet', 'LASER': 'lime'}
for change in ({'border_edge': {'line': True}}, {'border_edge': {**DEFAULT_CONFIG['border_edge'], 'line': 1}},
{'border_muted_percent': 101}, {'border_muted_percent': True}):
with pytest.raises(ValueError):
normalize_config({**DEFAULT_CONFIG, **change})
def test_mute_note_says_why_starpilot_or_the_detector_muted():
from openpilot.starpilot.ui.onroad_uniden import mute_note
def note(**flags):
alert = parse_alerts(b'1,00,K,3,0,24.150,F,2')[0] # the detector reports our own mutes as manual
return mute_note([{**alert, **flags}])
assert note(locked=True, filtered=True) == 'Lockout'
assert note(ruled=True, filtered=True) == 'Frequency rule'
assert note(quiet=True) == 'Below limit'
assert note(timed=True) == 'Timed mute'
assert note() == 'Manual mute'
quiet = parse_alerts(b'1,00,K,3,0,24.150,F,1')[0]
assert mute_note([{**quiet, 'quiet': True}]) == 'Below limit', 'quieted before the detector confirms the mute'
def test_never_warn_again_keeps_a_strong_signal_muted():
from openpilot.starpilot.uniden.policy import apply
def run(strength_setting):
timed = {'bands': ['K'], 'seconds': 5, 'strength': strength_setting}
state = None
for step in range(13): # read every half second, as the feed does, for six seconds
alerts = parse_alerts(b'1,00,K,8,0,24.150,F,2')
state = apply(alerts, [], {'timed': timed}, state, step * .5)
return alerts[0]
assert run(6)['breakthrough'] and not run(6)['timed']
assert not run(0)['breakthrough'] and run(0)['timed'], 'never: a strength-8 signal stays on its timed mute'
def test_card_and_warning_share_the_on_screen_rules_and_work_without_each_other():
feed, fonts = Mock(), fonts_mock()
data = {'config': {'enabled': True, 'border_bands': ['K'], 'hide_below_limit': True}, 'connected': True, 'model': 'R8',
'alerts': [{**parse_alerts(b'1,00,K,3,0,24.150,F,1')[0], 'quiet': True}]}
feed.snapshot.return_value = data
widget = UnidenWidget(fonts, feed)
state = NS(alert=NS(size='none'), customization={'layouts': {'large': {}}}) # no card in this layout
with patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_rectangle_rec') as dashes, \
patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_ring'), patch('openpilot.starpilot.ui.onroad_uniden.rl.draw_line_ex'):
widget.render_border(state, 1860, 1080)
dashes.assert_not_called()
data['config']['hide_below_limit'] = False
widget.render_border(state, 1860, 1080)
assert dashes.called, 'the warning works with no card on screen'
def test_shell_routes_a_claimed_touch_to_the_card_and_always_ends_it():
from openpilot.starpilot.ui.shell import ShellMode
widget = UnidenWidget(Mock(), Mock())
session = NS(favorites=NS(is_open=False), input=Mock(), snapshot=Mock(return_value=NS(onroad='state')))
assert widget.activate(session) is widget and widget.runtime_active
widget.touch = Mock(return_value=True)
assert widget.press(ShellMode.ONROAD, 1, 2)
widget.touch.assert_called_with('down', 1, 2, 'state')
session.input.cancel.assert_called_once()
assert widget.move(ShellMode.SETTINGS, 3, 4)
widget.touch.assert_called_with('move', 3, 4, None)
assert widget.release(ShellMode.ONROAD, 5, 6) and not widget.claimed
widget.touch.assert_called_with('up', 5, 6, 'state')
assert not widget.release(ShellMode.ONROAD, 5, 6) and not widget.move(ShellMode.ONROAD, 5, 6)
session.favorites.is_open = True
widget.touch.reset_mock()
session.snapshot.reset_mock()
assert not widget.press(ShellMode.ONROAD, 1, 2) and not widget.touch.called and not session.snapshot.called
session.favorites.is_open = False
assert not widget.press(ShellMode.SETTINGS, 1, 2)
widget.claimed = True
widget.cancel()
assert not widget.claimed
widget.touch.assert_called_with('cancel', 0, 0, None)
def test_sizes_and_signal_colors_round_half_up_like_the_editor():
from openpilot.starpilot.ui.onroad_customization import scaled_size
from openpilot.starpilot.ui.onroad_uniden import signal_color
assert scaled_size(460, 150, 50) == (230, 75)
assert scaled_size(5, 3, 50) == (3, 2), '2.5 and 1.5 both round up, as Math.round does'
assert scaled_size(229, 1, 50) == (115, 1)
assert scaled_size(460, 260, 101) == (465, 263)
color = signal_color(5, 1)
assert (color.r, color.g, color.b) == (97, 203, 238), 'Math.round(202.5) is 203'
+48
View File
@@ -0,0 +1,48 @@
"""Finds where a fixed source is from how an alert behaves as the car passes it."""
GAP_S, MAX_S, MIN_SPEED = 2.0, 90.0, 3.0
class PassTracker:
def __init__(self):
self.tracks = {}
def update(self, alerts, context, now, wall):
"""Returns pass events: a fixed source was abeam of the car at the reported position."""
events = []
current = {}
for alert in alerts:
key = (alert['band'], alert['frequency'])
if key not in current or alert['strength'] > current[key]['strength']:
current[key] = alert
for key in [k for k, t in self.tracks.items() if k not in current and now - t['last'] >= GAP_S]:
events += self.finish(key, self.tracks.pop(key), wall)
for key, alert in current.items():
track = self.tracks.setdefault(key, {'start': now, 'first_dir': alert['direction'], 'fired': False, 'peak': None,
'sudden': bool(alert.get('instant_on'))})
track['last'], track['strength'] = now, alert['strength']
here = self.position(context, now)
if here and (track['peak'] is None or alert['strength'] > track['peak']['strength']):
track['peak'] = {**here, 'strength': alert['strength']}
if (here and not track['fired'] and not track['sudden'] and track['first_dir'] == 'front' and alert['direction'] in ('side', 'rear')
and now - track['start'] <= MAX_S):
track['fired'] = True
events.append(self.event(key, here, alert['strength'], wall))
return events
@staticmethod
def position(context, now):
if context is None or context['speed'] < MIN_SPEED or not 0 <= now - context['at'] < 1:
return None
return {'lat': context['lat'], 'lon': context['lon']}
def finish(self, key, track, wall):
# Without direction, a rise then a fall in strength marks the closest approach.
peak = track['peak']
if track['fired'] or track['sudden'] or track['first_dir'] or peak is None or peak['strength'] < 2 or track['strength'] > peak['strength'] - 2:
return []
return [self.event(key, peak, peak['strength'], wall)]
@staticmethod
def event(key, here, strength, wall):
return {'band': key[0], 'frequency': key[1], 'lat': here['lat'], 'lon': here['lon'], 'strength': strength, 'at': wall}
+150
View File
@@ -0,0 +1,150 @@
"""GATT operations admitted by the existing Bluetooth owner, including its AA lease."""
import time
from openpilot.starpilot.bluetooth.owner import DEVICE, BluetoothOwner, BluetoothRejected
from openpilot.starpilot.uniden.locks import normalize_lock
from openpilot.starpilot.uniden.policy import apply
from openpilot.starpilot.uniden.protocol import ALERT_UUID, WRITE_UUID, GATT, alert_key, model_for_name, parse_alerts, normalize_rules
STALE_S = 5
class DetectorState:
"""Per-detector exchange memory shared by both displays; replaced when the detector changes or goes unused."""
def __init__(self, address, now):
self.address, self.used_at = address, now
self.retry_at = 0.
self.seen = None
self.auto_mute = (None, 0.)
self.timed_mute = False
self.unmute = (None, 0, 0.)
def detector_state(owner, address):
now, state = time.monotonic(), getattr(owner, 'uniden', None)
if state is None or state.address != address or now - state.used_at > STALE_S:
state = owner.uniden = DetectorState(address, now)
state.used_at = now
return state
def exchange(owner, address, model, session, *, mute=None, auto_mute=False, frequency_rules=None, situation=None):
rules = normalize_rules([] if frequency_rules is None else frequency_rules)
situation = {**(situation or {})}
situation['locks'] = [normalize_lock(lock) for lock in situation.get('locks', [])]
if type(auto_mute) is not bool:
raise ValueError('Invalid automatic mute setting')
if model not in ('R4', 'R8'):
raise ValueError('Unsupported detector model')
if not owner.lock.acquire(blocking=False):
raise BluetoothRejected('Bluetooth is busy', code='busy')
admitted = False
try:
lease = getattr(owner, 'phone_lease', None)
def validate():
if not owner.session_valid(session):
raise BluetoothRejected('Session expired', code='session_expired')
if BluetoothOwner._admission_busy(owner):
raise BluetoothRejected('Finish Bluetooth discovery or pairing first', code='busy')
if lease is not None and (owner.phone_lease is not lease or lease.released or lease.session is not None or
lease.enabled is None or not lease.enabled() or lease.selected_receiver is None or
lease.selected_receiver().upper() != lease.receiver or address == lease.receiver):
raise BluetoothRejected('Android Auto Bluetooth owner changed', code='busy')
validate()
if lease is None:
owner._admission_enter()
admitted = True
client = owner._client()
adapter, props, sender = client.adapter_identity()
if props.get('Powered') is not True:
raise BluetoothRejected('Turn on Bluetooth to connect the detector', code='radio_off')
if props.get('Discovering') is True:
raise BluetoothRejected('Finish Bluetooth discovery before connecting the detector', code='busy')
if lease is not None and (adapter, sender) != (lease.adapter_path, lease.bluez_sender):
raise BluetoothRejected('Android Auto adapter changed', code='changed')
objects = client._objects()
device = next(((p, i[DEVICE]) for p, i in objects.items() if DEVICE in i and
i[DEVICE].get('Address', '').upper() == address and p.startswith(adapter + '/')), None)
if device is None:
raise BluetoothRejected('Pair the selected detector first', code='detector_pairing_required')
path, props = device
if props.get('Paired') is not True or props.get('Blocked') is True or model_for_name(props.get('Name')) != model:
raise BluetoothRejected('Choose a paired detector with the matching model', code='detector_pairing_required')
state = detector_state(owner, address)
if props.get('Connected') is not True:
if mute is not None:
raise BluetoothRejected('Detector disconnected; mute was not sent', code='changed')
if time.monotonic() < state.retry_at:
raise BluetoothRejected('Reconnecting to detector', code='reconnecting')
state.retry_at = time.monotonic() + 15
validate()
try:
client._call(path, DEVICE, 'Connect', timeout=3.0)
except (BluetoothRejected, OSError) as error:
if str(error) in ('org.bluez.Error.NotAuthorized', 'org.bluez.Error.AuthenticationFailed'):
raise BluetoothRejected('Pair the detector again in Bluetooth settings', code='detector_pairing_required') from error
raise BluetoothRejected('Reconnecting to detector', code='reconnecting') from error
raise BluetoothRejected('Reconnecting to detector', code='reconnecting')
if props.get('ServicesResolved') is not True:
raise BluetoothRejected('Reconnecting to detector', code='reconnecting')
paths = {p[GATT].get('UUID', '').lower(): name for name, p in objects.items() if name.startswith(path + '/') and GATT in p}
if ALERT_UUID not in paths:
raise BluetoothRejected('Detector alert characteristic is unavailable', code='changed')
def read():
return parse_alerts(client._call(paths[ALERT_UUID], GATT, 'ReadValue', 'a{sv}', ({},), timeout=2.0)[0], model)
alerts = read()
observed_at = time.monotonic()
validate()
current_adapter, current_props, current_sender = client.adapter_identity()
if (current_adapter, current_sender) != (adapter, sender) or current_props.get('Powered') is not True:
raise BluetoothRejected('Bluetooth adapter changed', code='changed')
current = client._objects().get(path, {}).get(DEVICE, {})
if current.get('Paired') is not True or current.get('Connected') is not True:
raise BluetoothRejected('Detector connection changed', code='changed')
state.seen = apply(alerts, rules, situation, state.seen, observed_at)
automatic = bool(alerts) and all((auto_mute and a['filtered']) or a['quiet'] or a['timed'] for a in alerts)
if not alerts:
state.timed_mute = False
# Retry an unacknowledged write at most twice per second, across both displays.
key = (address, alert_key(alerts))
last_key, last_at = state.auto_mute
if not automatic:
state.auto_mute = (None, 0.)
automatic = automatic and (key != last_key or observed_at - last_at >= .5)
command = ''
if mute is not None:
at = mute.get('observed_at')
if type(at) not in (float, int) or not 0 <= time.monotonic() - at < 3 or not alerts or alert_key(alerts) != mute.get('alerts'):
raise BluetoothRejected('Alert changed; tap the current alert', code='changed')
if WRITE_UUID not in paths:
raise BluetoothRejected('Detector mute characteristic is unavailable', code='changed')
if mute is not None or (automatic and WRITE_UUID in paths):
if not all(a['muted'] for a in alerts):
validate()
client._call(paths[WRITE_UUID], GATT, 'WriteValue', 'aya{sv}',
(b'BTreqMUTE:1', {'type': ('s', 'command')}), timeout=2.0)
if mute is None:
state.auto_mute = (key, observed_at)
if any(a['timed'] for a in alerts):
state.timed_mute = True
command = 'sent_unconfirmed'
if state.unmute[0] == key and not any(a['muted'] for a in alerts):
state.timed_mute = False
if (situation.get('timed') and mute is None and not command and WRITE_UUID in paths and state.timed_mute and
any(a['breakthrough'] and a['muted'] and a['mute_mode'] == 'manual' for a in alerts)):
# Undoes only a timer's mute, capped per alert set.
last_key, attempts, last_at = state.unmute
attempts = attempts if last_key == key else 0
if attempts < 3 and (last_key != key or observed_at - last_at >= 1):
validate()
client._call(paths[WRITE_UUID], GATT, 'WriteValue', 'aya{sv}',
(b'BTreqMUTE:0', {'type': ('s', 'command')}), timeout=2.0)
state.unmute = (key, attempts + 1, observed_at)
command = 'unmute_sent_unconfirmed'
return {'connected': True, 'address': address, 'model': model, 'alerts': alerts,
'observed_at': observed_at, 'can_mute': WRITE_UUID in paths, 'command': command}
finally:
if admitted:
owner._admission_leave()
owner.lock.release()
@@ -167,12 +167,13 @@ def test_ui_poll_precedes_every_frame_including_wake(frame, monkeypatch, awake):
preview = SimpleNamespace(poll=lambda: events.append("preview"))
star = SimpleNamespace(_poll_projection_bookmark=lambda now: events.append("bookmark"),
_poll_projection_slc=lambda now: events.append("slc"),
_poll_wheel=lambda now: events.append("wheel"))
_poll_wheel=lambda now: events.append("wheel"),
_poll_detector=lambda: events.append("detector"))
app._nav_stack_ticks = [lambda: events.append("transition")]
app._nav_stack[0].render.side_effect = lambda _: events.append("draw")
loop = app.render(before_frame=lambda: ui.update_frame(preview, controllers, star))
assert next(loop)[0] is awake
assert events == ["messages", "bookmark", "slc"] + ([] if awake else ["wheel"]) + ["controls", "preview"] + (
assert events == ["messages", "bookmark", "slc"] + ([] if awake else ["wheel"]) + ["detector", "controls", "preview"] + (
["transition", "draw"] if awake else [])
with pytest.raises(StopIteration):
next(loop)
@@ -210,7 +211,8 @@ def test_projection_bookmark_is_saved_once_without_rendering_starpilot(frame, mo
path = Path(directory) / 'bookmark.sock'
receiver, sender = BookmarkReceiver(path), BookmarkSender(path)
publish = Mock()
star = SimpleNamespace(_projection_bookmarks=receiver, _publish_bookmark=publish, _poll_projection_slc=Mock(), _poll_wheel=Mock())
star = SimpleNamespace(_projection_bookmarks=receiver, _publish_bookmark=publish, _poll_projection_slc=Mock(), _poll_wheel=Mock(),
_poll_detector=Mock())
star._poll_projection_bookmark = lambda now: namespace['_poll_projection_bookmark'](star, now)
loop = app.render(before_frame=lambda: ui.update_frame(star=star))
try:
+1 -1
View File
@@ -1 +1 @@
{"protected_inventory_sha256": "039faa7282d73968f6a428d4ca05524da23c1c86519a26383fd10e3f59f321e4", "schema_version": 1}
{"protected_inventory_sha256": "6262152bd1c80355e15ebd9dcaa12721fd688fde5823a6b5c724bd8a5d0e8f1a", "schema_version": 1}
+1
View File
@@ -13,6 +13,7 @@ LARGE_TEXT_FILES = frozenset((
'openpilot/selfdrive/ui/translations/app_ja.po',
'openpilot/selfdrive/ui/translations/app_ko.po',
'openpilot/selfdrive/ui/translations/app_vi.po',
'openpilot/selfdrive/ui/translations/app_zh-CHS.po',
'openpilot/starpilot/ui/translation_messages.json',
# shortcut: these existing modules bypass 120 KiB; split when their responsibilities warrant it.
'openpilot/selfdrive/selfdrived/selfdrived.py',
@@ -40,6 +40,7 @@ class LargeFilePolicyTest(unittest.TestCase):
'openpilot/selfdrive/ui/translations/app_ja.po',
'openpilot/selfdrive/ui/translations/app_ko.po',
'openpilot/selfdrive/ui/translations/app_vi.po',
'openpilot/selfdrive/ui/translations/app_zh-CHS.po',
'openpilot/starpilot/ui/translation_messages.json',
):
self.assertEqual(self.check(name, 1000000), 0)