Qualify StarPort radio monitoring and Canadian map package

This commit is contained in:
Codex
2026-11-18 17:46:47 -06:00
committed by firestar5683
14 changed files with 325 additions and 84 deletions
+2 -2
View File
@@ -65,8 +65,8 @@ func BundledManagedRegions() ([]ManagedRegion, error) {
if err != nil {
return nil, err
}
result := make([]ManagedRegion, 0, 229)
for _, group := range []string{"nation", "us_state"} {
result := make([]ManagedRegion, 0, 242)
for _, group := range []string{"nation", "us_state", "ca_province"} {
for key, data := range menu[group] {
if key == "" || strings.Contains(key, ".") || data.FullName == "" {
return nil, errors.New("invalid bundled region")
+37 -3
View File
@@ -1,13 +1,17 @@
package maps
import "testing"
import (
"testing"
"pfeifer.dev/mapd/settings"
)
func TestBundledManagedRegionCoverage(t *testing.T) {
regions, err := BundledManagedRegions()
if err != nil {
t.Fatal(err)
}
if len(regions) != 229 {
if len(regions) != 242 {
t.Fatalf("bundled catalog changed: %d", len(regions))
}
available := 0
@@ -19,7 +23,7 @@ func TestBundledManagedRegionCoverage(t *testing.T) {
}
}
}
if available != 225 {
if available != 238 {
t.Fatalf("review supported-region count changed: %d", available)
}
for token, groups := range map[string]int{"us_state.CA": 36, "us_state.TX": 56, "us_state.IL": 12, "nation.CA": 765, "nation.JP": 72, "nation.US": 390} {
@@ -34,3 +38,33 @@ func TestBundledManagedRegionCoverage(t *testing.T) {
}
}
}
// Province coverage comes from the pinned Geofabrik extract envelopes. Every
// envelope must survive outward grid alignment without losing any edge.
func TestCanadianProvinceCoverage(t *testing.T) {
menu, err := settings.BundledDownloadMenu()
if err != nil {
t.Fatal(err)
}
if len(menu["ca_province"]) != 13 {
t.Fatal("expected ten provinces and three territories")
}
for key, data := range menu["ca_province"] {
region, err := ResolveManagedRegion("ca_province." + key)
if err != nil || !region.Available {
t.Fatalf("%s unavailable: %v", key, err)
}
b := data.BoundingBox
if region.Bounds[0] > b.MinLat || region.Bounds[1] > b.MinLon || region.Bounds[2] < b.MaxLat || region.Bounds[3] < b.MaxLon {
t.Fatalf("coverage clipped: %s", key)
}
if region.Groups >= 765 {
t.Fatalf("province not smaller than Canada: %s", key)
}
}
for _, token := range []string{"ca_province.CA", "ca_province.ON.extra", "ca_province."} {
if _, err := ResolveManagedRegion(token); err == nil {
t.Fatalf("unknown token accepted: %s", token)
}
}
}
+24
View File
@@ -0,0 +1,24 @@
# Canadian download regions
The `ca_province` catalog covers all ten provinces and three territories.
Bounds are the envelopes of Geofabrik's Canada subregion extract polygons,
retrieved from https://download.geofabrik.de/index-v1.json on 2026-11-18.
The index SHA-256 was `076fb6d5d0df3efae47af91a8e24ff69d84da05872107958f99341a16a04da22`.
These are deliberately conservative extract envelopes (including coastal
coverage), not claims of precise administrative borders. Mapd rounds them
outward onto its existing two-degree archive grid from
https://map-data.pfeifer.dev/offline/. This uses existing provider archives,
not Geofabrik PBF downloads. Availability in the catalog means bounded, valid
coverage; it does not guarantee every live archive is currently reachable.
`nation.CA` and its existing bounds are unchanged for saved-selection
compatibility. Its legacy northern extent is 73.23 degrees; northern territory
choices cover their own full extract envelopes beyond that legacy extent.
Existing downloaded generations are not removed or migrated by this change.
The usual parked, transfer-budget, verification and atomic selection rules
remain in force. A missing archive leaves the previous selection intact.
The new embedded catalog requires a rebuilt Mapd provider and manifest. The
Galaxy UI only presents province choices returned by that installed provider,
so an older package continues to present its old catalog without invented
or unusable province buttons.
+119
View File
@@ -2064,5 +2064,124 @@
"max_lat": -14.157381542325423
}
}
},
"ca_province": {
"AB": {
"full_name": "Alberta",
"bounding_box": {
"min_lon": -120.0043,
"min_lat": 48.99251,
"max_lon": -110.0018,
"max_lat": 60.00254
}
},
"BC": {
"full_name": "British Columbia",
"bounding_box": {
"min_lon": -141.7761,
"min_lat": 46.41459,
"max_lon": -114.049,
"max_lat": 60.00678
}
},
"MB": {
"full_name": "Manitoba",
"bounding_box": {
"min_lon": -102.014,
"min_lat": 48.99056,
"max_lon": -88.12183,
"max_lat": 60.00845
}
},
"NB": {
"full_name": "New Brunswick",
"bounding_box": {
"min_lon": -69.05975,
"min_lat": 44.19205,
"max_lon": -62.88575,
"max_lat": 48.38075
}
},
"NL": {
"full_name": "Newfoundland and Labrador",
"bounding_box": {
"min_lon": -67.87079,
"min_lat": 44.45787,
"max_lon": -44.17684,
"max_lat": 60.50864
}
},
"NT": {
"full_name": "Northwest Territories",
"bounding_box": {
"min_lon": -136.6974,
"min_lat": 59.9896,
"max_lon": -101.976,
"max_lat": 81.65483
}
},
"NS": {
"full_name": "Nova Scotia",
"bounding_box": {
"min_lon": -67.24728,
"min_lat": 42.10691,
"max_lon": -58.22593,
"max_lat": 47.89793
}
},
"NU": {
"full_name": "Nunavut",
"bounding_box": {
"min_lon": -120.737,
"min_lat": 51.1268,
"max_lon": -53.26943,
"max_lat": 84.95198
}
},
"ON": {
"full_name": "Ontario",
"bounding_box": {
"min_lon": -95.15965,
"min_lat": 41.66009,
"max_lon": -74.30998,
"max_lat": 57.50826
}
},
"PE": {
"full_name": "Prince Edward Island",
"bounding_box": {
"min_lon": -64.60236,
"min_lat": 45.82497,
"max_lon": -61.24878,
"max_lat": 47.68573
}
},
"QC": {
"full_name": "Quebec",
"bounding_box": {
"min_lon": -79.8404,
"min_lat": 44.98552,
"max_lon": -57.08908,
"max_lat": 62.6262
}
},
"SK": {
"full_name": "Saskatchewan",
"bounding_box": {
"min_lon": -110.0069,
"min_lat": 48.9876,
"max_lon": -101.3614,
"max_lat": 60.00052
}
},
"YT": {
"full_name": "Yukon",
"bounding_box": {
"min_lon": -141.2389,
"min_lat": 59.99739,
"max_lon": -123.8021,
"max_lat": 70.16293
}
}
}
}
@@ -178,3 +178,15 @@ await lateStart
assert.equal(expiredConflict.client.actionError, '')
assert.equal(expiredConflict.client.active, false)
console.log('Map operation conflicts: distinct reasons and expired response isolation passed')
// A new provider can expose provinces; an older provider remains valid.
const ontario = { ...region, token: 'ca_province.ON', name: 'Ontario', groups: 99 }
const provinceCatalog = { ...largeCatalog, regions: [...largeCatalog.regions, ontario] }
assert.equal(validCatalog(provinceCatalog), true)
assert.equal(validCatalog({ ...provinceCatalog, regions: [{ ...ontario, token: 'ca_province.ON.extra' }] }), false)
const findRegions = (search) => MapOperationsPanel.computed.regions.call({ search, catalog: provinceCatalog })
assert.equal(findRegions('Ontario').some((r) => r.token === 'ca_province.ON'), true)
assert.equal(findRegions('Canada').some((r) => r.token === 'ca_province.ON'), true)
assert.equal(MapOperationsPanel.computed.canadianRegions.call({ regions: findRegions('Canada') }).length, 1)
assert.equal(MapOperationsPanel.computed.otherRegions.call({ regions: findRegions('Canada') })[0].token, 'nation.CA')
assert.equal(MapOperationsPanel.computed.canadianRegions.call({ regions: largeCatalog.regions }).length, 0)
@@ -5,7 +5,7 @@ import { requestJson } from "./startup.js"
// One parked map operation belongs to the local owner, not to this browser tab.
const STATES = new Set(["idle", "transferring", "validating", "selecting", "completed", "canceled", "failed", "interrupted", "unavailable"])
const GENERATION = /^(?:|[0-9a-f]{64})$/
const TOKEN = /^(?:nation|us_state)\.[A-Za-z0-9_-]+$/
const TOKEN = /^(?:nation|us_state|ca_province)\.[A-Za-z0-9_-]+$/
const ERROR_LABELS = {
canceled: "Canceled", interrupted: "Interrupted", selection_changed: "The saved selection changed",
not_parked: "Parked availability was lost", package_unavailable: "The map package is unavailable",
@@ -290,8 +290,10 @@ export const MapOperationsPanel = {
regions() {
const query = this.search.trim().toLocaleLowerCase()
return (this.catalog?.regions || []).filter((item) => !query ||
`${item.name} ${item.token}`.toLocaleLowerCase().includes(query))
`${item.token.startsWith("ca_province.") ? "Canada " : ""}${item.name} ${item.token}`.toLocaleLowerCase().includes(query))
},
canadianRegions() { return this.regions.filter((item) => item.token.startsWith("ca_province.")) },
otherRegions() { return this.regions.filter((item) => !item.token.startsWith("ca_province.")) },
running() { return ["transferring", "validating", "selecting"].includes(this.operation?.state) },
},
methods: {
@@ -335,15 +337,23 @@ export const MapOperationsPanel = {
<button v-if="running" type="button" class="gx-btn gx-btn--tonal" @click="client.cancel()">Cancel operation</button>
</template>
<div class="gx-map-manager__picker"><label for="map-region-search">Search regions</label>
<input id="map-region-search" class="gx-field" type="search" v-model="search" placeholder="Country or US state"></div>
<input id="map-region-search" class="gx-field" type="search" v-model="search" placeholder="Country, province, territory or US state"></div>
<p v-if="!catalog && setup?.packageReady && !error" role="status">Loading map catalog…</p>
<template v-if="catalog"><p class="gx-note">{{ regions.length }} regions shown · Up to {{ formatBytes(catalog.maxTransferBytes) }} transfer · {{ formatBytes(catalog.maxNewDiskBytes) }} new storage.</p>
<div class="gx-map-manager__regions">
<div v-for="region in regions" :key="region.token" class="gx-map-manager__region">
<div><strong>{{ region.name }}</strong><small>{{ region.token }} · {{ region.groups }} groups</small>
<div v-for="region in otherRegions" :key="region.token" class="gx-map-manager__region">
<div><strong>{{ region.token === 'nation.CA' ? 'Canada — All Canada' : region.name }}</strong><small>{{ region.token }} · {{ region.groups }} groups</small>
<small v-if="!region.available">Unavailable: {{ region.unavailable.replaceAll('_', ' ') }}</small></div>
<button type="button" class="gx-btn gx-btn--tonal" :disabled="running || !region.available || !operation" @click="reviewRegion(region)">Review…</button>
</div>
<details v-if="canadianRegions.length" :open="search.trim() ? true : undefined">
<summary>Canada — Provinces and territories</summary>
<div v-for="region in canadianRegions" :key="region.token" class="gx-map-manager__region">
<div><strong>{{ region.name }}</strong><small>{{ region.groups }} groups</small>
<small v-if="!region.available">Unavailable: {{ region.unavailable.replaceAll('_', ' ') }}</small></div>
<button type="button" class="gx-btn gx-btn--tonal" :disabled="running || !region.available || !operation" @click="reviewRegion(region)">Review…</button>
</div>
</details>
</div></template>
</template>
</div>
+2 -2
View File
@@ -39,7 +39,7 @@ MAX_TRANSFER_BYTES = 8 * 1024**3
MAX_NEW_DISK_BYTES = 16 * 1024**3
OPERATION_DEADLINE_S = 30 * 60
GENERATION = re.compile(r'[0-9a-f]{64}\Z')
TOKEN = re.compile(r'(?:nation|us_state)\.[A-Za-z0-9_-]{1,64}\Z')
TOKEN = re.compile(r'(?:nation|us_state|ca_province)\.[A-Za-z0-9_-]{1,64}\Z')
ACTIVE = frozenset(('transferring', 'validating', 'selecting'))
STATES = frozenset(('idle', 'transferring', 'validating', 'selecting', 'completed',
'canceled', 'failed', 'interrupted', 'unavailable'))
@@ -283,7 +283,7 @@ def _catalog() -> list[dict]:
if len(completed.stdout) > MAX_CATALOG or len(completed.stderr) > MAX_STATUS:
raise ValueError('catalog output exceeds bound')
rows = json.loads(completed.stdout, object_pairs_hook=_unique_object)
if type(rows) is not list or len(rows) != 229:
if type(rows) is not list or len(rows) not in (229, 242):
raise ValueError('catalog shape invalid')
seen = set()
for row in rows:
@@ -1 +1 @@
{"binarySha256":"979ccc8d6512280b072fdc5ba8fb27cd3f6aa108eec545ff299e4bfa689a5e7b","goVersion":"go1.25.1","schemaVersion":1,"sourceDigest":"2707ec7f901fd10e348a45a9bec8b7bb01ca4671693963d237ec00ad38bab9a8","sourceRevision":"db3f6f61efd3a7411ddbf9f22813d78a4175d7cd","target":"linux-arm64-static","upstreamRevision":"7201c6b4b4ec1b0b9ea21daa8c05b80fdd7e01ee"}
{"binarySha256":"25b24f44ca2e109477ed863a4d22493dcf6ac38b8921c572487ff84c9f5900eb","goVersion":"go1.25.1","schemaVersion":1,"sourceDigest":"7ddd6ad351392c7522dd12f6617914a862e71010eccc355ef09c91cbd217be3d","sourceRevision":"afcd2179fca9a17a3ae87b3aa47f1a62e9dea840","target":"linux-arm64-static","upstreamRevision":"7201c6b4b4ec1b0b9ea21daa8c05b80fdd7e01ee"}
Binary file not shown.
@@ -253,6 +253,30 @@ class TestMapSnapshotOperationOwner(unittest.TestCase):
with self.assertRaises(ops.OperationError):
ops._catalog()
def test_canadian_province_tokens(self):
codes = ('AB', 'BC', 'MB', 'NB', 'NL', 'NS', 'NT', 'NU', 'ON', 'PE', 'QC', 'SK', 'YT')
for code in codes:
self.assertIsNotNone(ops.TOKEN.fullmatch(f'ca_province.{code}'))
self.assertIsNone(ops.TOKEN.fullmatch('ca_province.ON.extra'))
rows = [{**REGION, 'token': f'nation.region{i}'} for i in range(229)]
rows.extend({**REGION, 'token': f'ca_province.{code}'} for code in codes)
completed = subprocess.CompletedProcess([], 0, json.dumps(rows).encode(), b'')
with patch.object(ops.subprocess, 'run', return_value=completed):
self.assertEqual([row['token'] for row in ops._catalog()[229:]], [f'ca_province.{code}' for code in codes])
def test_catalog_rejects_incomplete_and_duplicate_regions(self):
for count in (0, 1, 228, 230, 241, 243):
with self.subTest(count=count):
rows = [{**REGION, 'token': f'nation.region{i}'} for i in range(count)]
completed = subprocess.CompletedProcess([], 0, json.dumps(rows).encode(), b'')
with patch.object(ops.subprocess, 'run', return_value=completed), self.assertRaises(ops.OperationError):
ops._catalog()
rows = [{**REGION, 'token': f'nation.region{i}'} for i in range(242)]
rows[-1] = rows[0]
completed = subprocess.CompletedProcess([], 0, json.dumps(rows).encode(), b'')
with patch.object(ops.subprocess, 'run', return_value=completed), self.assertRaises(ops.OperationError):
ops._catalog()
def test_boolean_version_is_not_v1(self):
owner = self.owner(lambda *args: GEN_A)
with self.assertRaises(ops.OperationError) as caught:
@@ -0,0 +1,79 @@
"""Shared-radio change monitoring for Android Auto projection."""
from __future__ import annotations
import threading
import time
from collections.abc import Callable
from pathlib import Path
RADIO_CHECK_INTERVAL = 0.5 # how often the comma's own Wi-Fi is checked for a join or roam (a sysfs read)
RADIO_CHANGE_WINDOW = 15.0 # a join or roam this recent can still stall the car (11-02: stall came 7.5 s after a roam)
class SharedRadioWatch:
"""Notices the comma's own Wi-Fi joining or roaming while the car is on aa0; both share one radio.
The link going down or up bumps carrier_changes, a plain sysfs read. The network's name is never read or logged.
"""
def __init__(self, log: Callable[..., None], interface: str = "wlan0", interval: float = RADIO_CHECK_INTERVAL,
counter: Path | None = None, carrier: Path | None = None, on_down: Callable[[], None] | None = None,
on_stall: Callable[[], None] | None = None):
self.log, self.interface, self.interval = log, interface, interval
self.counter = counter or Path(f"/sys/class/net/{interface}/carrier_changes")
self.carrier = carrier or Path(f"/sys/class/net/{interface}/carrier")
self.on_down = on_down # the other network was lost, not just roamed
self.on_stall = on_stall # the car's acks stopped after a change that has not connected yet
self.changed_at: float | None = None
self._stop = threading.Event()
self._thread = threading.Thread(target=self._run, name="aa_radio_watch", daemon=True)
def start(self) -> SharedRadioWatch:
self._thread.start()
return self
def stop(self) -> None:
self._stop.set()
def recent(self, now: float | None = None) -> bool:
"""Whether the other network joined or roamed within RADIO_CHANGE_WINDOW."""
changed_at = self.changed_at
now = time.monotonic() if now is None else now
return changed_at is not None and now - changed_at <= RADIO_CHANGE_WINDOW
def _read(self) -> str | None:
try:
return self.counter.read_text().strip()
except OSError:
return None
def _run(self) -> None:
last = self._read()
while not self._stop.wait(self.interval):
current = self._read()
if current is None or current == last:
continue
last = current
self.changed_at = time.monotonic()
self.log("other_wifi_changed", interface=self.interface)
if self.on_down is not None and not self._carrier():
try:
self.on_down()
except Exception as error:
self.log("other_wifi_hold_failed", error=str(error) or type(error).__name__)
def stalled(self) -> None:
# A join that already connected has only its address left. Stopping it there lost the hotspot and still
# dropped the car on 2026-11-16, while a joined hotspot then streamed alongside the car for minutes.
if self._carrier():
self.log("other_wifi_join_kept", interface=self.interface)
return
if self.on_stall is not None:
self.on_stall()
def _carrier(self) -> bool:
try:
return self.carrier.read_text().strip() == "1"
except OSError:
return False # reading carrier of a down interface fails with EINVAL
@@ -43,6 +43,8 @@ from openpilot.starpilot.system.starport.bugsink_report import PairingAttempt
from openpilot.starpilot.system.starport.frame_source import (DEFAULT_PATH as DEFAULT_FRAME_PATH, FLAG_ASYNC_READBACK, FLAG_NV12,
FORMAT_NV12, FrameRequest)
from openpilot.starpilot.system.starport.projection_control import DEFAULT_CONTROL_SOCKET, NATIVE_FOCUS
from openpilot.starpilot.system.starport.radio_watch import (RADIO_CHANGE_WINDOW as RADIO_CHANGE_WINDOW,
RADIO_CHECK_INTERVAL as RADIO_CHECK_INTERVAL, SharedRadioWatch)
from openpilot.starpilot.system.starport.touch import DEFAULT_TOUCH_SOCKET, TouchEvent
from openpilot.starpilot.system.starport.view import CAR_FRAME_PATH, ViewSource, renderer_available
from openpilot.starpilot.system.starport.session import CODEC_H265, AuthenticationRejected, PeerRequestedStop, ProjectionSession, SharedRadioStall
@@ -76,8 +78,6 @@ USB_CONFIGURE_WAIT = 15.0 # slower receivers need time to enumerate after the
LINK_CHECK_INTERVAL = 1.0 # how often the link watcher asks whether the car's Wi-Fi is still up
LINK_CHECK_SLOW = 1.0 # a link check slower than this is logged (NetworkManager answers over D-Bus)
STREAM_STALL_LOG = 1.0 # a streaming loop pass slower than this is logged
RADIO_CHECK_INTERVAL = 0.5 # how often the comma's own Wi-Fi is checked for a join or roam (a sysfs read)
RADIO_CHANGE_WINDOW = 15.0 # a join or roam this recent can still stall the car (11-02: stall came 7.5 s after a roam)
STALL_CAPTURE_S = 20.0 # device logs kept from before a shared-radio stall is reported
REPORTED_SETTINGS = ("connection", "usb_mode", "view", "encoder", "fps", "bitrate_kbps", "rate_control", "gpu_nv12",
"async_readback", "wifi_interface", "dedicated_wifi_interface", "verify_head_unit", "version_status",
@@ -276,74 +276,6 @@ class LinkWatch:
self._stop.wait(self.interval)
class SharedRadioWatch:
"""Notices the comma's own Wi-Fi joining or roaming while the car is on aa0; both share one radio.
The link going down or up bumps carrier_changes, a plain sysfs read. The network's name is never read or logged.
"""
def __init__(self, log: Callable[..., None], interface: str = "wlan0", interval: float = RADIO_CHECK_INTERVAL,
counter: Path | None = None, carrier: Path | None = None, on_down: Callable[[], None] | None = None,
on_stall: Callable[[], None] | None = None):
self.log, self.interface, self.interval = log, interface, interval
self.counter = counter or Path(f"/sys/class/net/{interface}/carrier_changes")
self.carrier = carrier or Path(f"/sys/class/net/{interface}/carrier")
self.on_down = on_down # the other network was lost, not just roamed
self.on_stall = on_stall # the car's acks stopped after a change that has not connected yet
self.changed_at: float | None = None
self._stop = threading.Event()
self._thread = threading.Thread(target=self._run, name="aa_radio_watch", daemon=True)
def start(self) -> SharedRadioWatch:
self._thread.start()
return self
def stop(self) -> None:
self._stop.set()
def recent(self, now: float | None = None) -> bool:
"""Whether the other network joined or roamed within RADIO_CHANGE_WINDOW."""
changed_at = self.changed_at
now = time.monotonic() if now is None else now
return changed_at is not None and now - changed_at <= RADIO_CHANGE_WINDOW
def _read(self) -> str | None:
try:
return self.counter.read_text().strip()
except OSError:
return None
def _run(self) -> None:
last = self._read()
while not self._stop.wait(self.interval):
current = self._read()
if current is None or current == last:
continue
last = current
self.changed_at = time.monotonic()
self.log("other_wifi_changed", interface=self.interface)
if self.on_down is not None and not self._carrier():
try:
self.on_down()
except Exception as error:
self.log("other_wifi_hold_failed", error=str(error) or type(error).__name__)
def stalled(self) -> None:
# A join that already connected has only its address left. Stopping it there lost the hotspot and still
# dropped the car on 2026-11-16, while a joined hotspot then streamed alongside the car for minutes.
if self._carrier():
self.log("other_wifi_join_kept", interface=self.interface)
return
if self.on_stall is not None:
self.on_stall()
def _carrier(self) -> bool:
try:
return self.carrier.read_text().strip() == "1"
except OSError:
return False # reading carrier of a down interface fails with EINVAL
class EventLog:
"""Sanitized JSONL session log under /data/starport/logs, plus the recent tail in memory.
@@ -0,0 +1,7 @@
from openpilot.starpilot.system.starport import radio_watch, supervisor
def test_supervisor_preserves_public_radio_watch_imports():
assert supervisor.SharedRadioWatch is radio_watch.SharedRadioWatch
assert supervisor.RADIO_CHECK_INTERVAL == radio_watch.RADIO_CHECK_INTERVAL == 0.5
assert supervisor.RADIO_CHANGE_WINDOW == radio_watch.RADIO_CHANGE_WINDOW == 15.0
+1 -1
View File
@@ -1 +1 @@
{"protected_inventory_sha256": "11655bea5af2f6565e54e4404db70b837ac372a2bab7173c818bb3715a3bf6c2", "schema_version": 1}
{"protected_inventory_sha256": "48ce18260232b938ce0d7998312f078f06e60cc9e57aee84e375f8dd5f92712b", "schema_version": 1}