Refactor signal handling and improve widget scaling logic; enhance Bluetooth and network signal tests

This commit is contained in:
Prabhaav Pillai
2026-11-19 16:36:27 -05:00
parent cfe3a8f5ef
commit 45e696673c
12 changed files with 152 additions and 165 deletions
@@ -11,6 +11,21 @@ print(json.dumps(dict(document=default_document(), defaults=default_document(),
revision="native", editable=True, valid=True, activeProfile="large", supportedProfiles=["large"])))
`], { encoding: "utf8" }))
assert.equal(validSnapshot(data), true)
const signalEdges = JSON.parse(execFileSync(process.env.PYTHON || "python3", ["-c", `
import json
from openpilot.starpilot.ui.onroad_customization import SIGNAL_SIZES, default_document, signal_size, validate_document, widget_bounds
documents = []
for style in SIGNAL_SIZES:
document = default_document()
placed = document['layouts']['large']['network_signal']
placed.update(size=style, scale=50, enabled=True, wifiName=True)
bounds = widget_bounds('large', 'network_signal')
width, height = signal_size(placed)
placed.update(x=bounds['x'] + bounds['width'] - width, y=bounds['y'] + bounds['height'] - height)
documents.append(validate_document(document))
print(json.dumps(documents))
`], { encoding: "utf8" }))
for (const document of signalEdges) assert.equal(validDocument(document, data.metadata), true)
for (const version of [11, 12, 13, 14, 15]) {
assert.equal(validSnapshot({ ...data, document: { ...data.document, version } }), true)
assert.equal(validSnapshot({ ...data, defaults: { ...data.defaults, version } }), true)
@@ -142,10 +157,13 @@ vm.setWidgetToggle("bluetooth", "On")
assert.equal(vm.layout.network_signal.bluetooth, true)
for (const style of ["ring", "horizontal", "vertical"]) {
vm.setWidgetSize(style)
vm.scaleInput({ target: { value: "30" } })
assert.deepEqual(widgetSize(signal, vm.layout.network_signal), signal.sizes[style].map(side => Math.round(side * 0.3)))
assert.equal(validDocument(vm.state.draft, data.metadata), true)
for (const scale of [30, 50, 100]) {
vm.scaleInput({ target: { value: String(scale) } })
assert.deepEqual(widgetSize(signal, vm.layout.network_signal), signal.sizes[style].map(side => Math.round(side * scale / 100)))
assert.equal(validDocument(vm.state.draft, data.metadata), true)
}
}
vm.scaleInput({ target: { value: "30" } })
vm.scaleInput({ target: { value: "25" } })
assert.equal(vm.layout.network_signal.scale, 30)
vm.layout.network_signal.x = signalBounds.x + signalBounds.width - widgetSize(signal, vm.layout.network_signal)[0]
@@ -402,103 +402,6 @@ export const LayoutWidgetPreview = {
<path d="M38 48 H78 M67 37 L78 48 L67 59" />
</g>
</g>
<g v-else-if="widget.kind === 'network_signal' && !['horizontal', 'vertical'].includes(widget.size)" :transform="'scale(' + widget.width / 112 + ')'">
<rect width="112" :height="(widget.bluetooth === false ? 102 : 140) + (widget.wifiName ? 22 : 0)" rx="24" fill="#0f0d17" :fill-opacity="235 / 255 * (widget.opacity ?? 85) / 100" />
<text v-if="widget.wifiName" x="56" y="21" text-anchor="middle" font-size="15" font-weight="600" fill="#f5f2fc">Home Wi-Fi</text>
<g :transform="widget.wifiName ? 'translate(0 22)' : null">
<g>
<path d="M17.0 78.5A45 45 0 0 1 11.2 60.7" fill="none" stroke="#f5f2fc" stroke-width="7" />
<path d="M95.0 78.5A45 45 0 0 0 100.8 60.7" fill="none" stroke="#a480f2" stroke-width="7" />
<path d="M11.0 56.8A45 45 0 0 1 14.6 38.4" fill="none" stroke="#f5f2fc" stroke-width="7" />
<path d="M101.0 56.8A45 45 0 0 0 97.4 38.4" fill="none" stroke="#a480f2" stroke-width="7" />
<path d="M16.3 34.9A45 45 0 0 1 28.3 20.5" fill="none" stroke="#ffffff2b" stroke-width="7" />
<path d="M95.7 34.9A45 45 0 0 0 83.7 20.5" fill="none" stroke="#a480f2" stroke-width="7" />
<path d="M31.5 18.3A45 45 0 0 1 49.0 11.6" fill="none" stroke="#ffffff2b" stroke-width="7" />
<path d="M80.5 18.3A45 45 0 0 0 63.0 11.6" fill="none" stroke="#a480f2" stroke-width="7" />
</g>
<g :transform="widget.bluetooth === false ? 'translate(0 8)' : null">
<rect x="34.0" y="48" width="3" height="4" fill="#b8b2c8" />
<rect x="38.5" y="44" width="3" height="8" fill="#b8b2c8" />
<rect x="43.0" y="40" width="3" height="12" fill="#b8b2c8" />
<rect x="47.5" y="36" width="3" height="16" fill="#b8b2c8" />
<circle cx="69" cy="50" r="2" fill="#a480f2" />
<path d="M64.2 45.7A6.5 6.5 0 0 1 73.8 45.7" fill="none" stroke="#a480f2" stroke-width="2.4" />
<path d="M60.5 42.3A11.5 11.5 0 0 1 77.5 42.3" fill="none" stroke="#a480f2" stroke-width="2.4" />
</g>
<g v-if="widget.bluetooth !== false">
<path d="M56 66V80M56 66L60.5 69.5L51.5 76M51.5 70L60.5 76.5L56 80" fill="none" stroke="#6eafff" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" />
<text x="56" y="106" text-anchor="middle" font-size="15" font-weight="600" fill="#f5f2fc">iPhone 15</text>
<text x="56" y="126" text-anchor="middle" font-size="15" font-weight="600" fill="#f5f2fc">AirPods</text>
</g>
<text v-else x="56" y="84" text-anchor="middle" font-size="14" font-weight="600" fill="#f5f2fc">Wi-Fi</text>
</g>
</g>
<g v-else-if="widget.kind === 'network_signal' && widget.size === 'horizontal'" :transform="'scale(' + widget.width / 268 + ')'">
<rect width="268" :height="112 + (widget.wifiName ? 22 : 0)" rx="28" fill="#0f0d17" :fill-opacity="235 / 255 * (widget.opacity ?? 85) / 100" />
<text v-if="widget.wifiName" x="24" y="23" font-size="16" font-weight="600" fill="#f5f2fc">Home Wi-Fi</text>
<g :transform="widget.wifiName ? 'translate(0 22)' : null">
<g :transform="widget.bluetooth === false ? 'translate(0 11)' : null">
<rect x="24" y="29" width="3" height="4" fill="#b8b2c8" />
<rect x="28.5" y="25" width="3" height="8" fill="#b8b2c8" />
<rect x="33" y="21" width="3" height="12" fill="#b8b2c8" />
<rect x="37.5" y="17" width="3" height="16" fill="#b8b2c8" />
<rect x="56" y="22" width="41" height="8" rx="4" fill="#f5f2fc" />
<rect x="105" y="22" width="41" height="8" rx="4" fill="#f5f2fc" />
<rect x="154" y="22" width="41" height="8" rx="4" fill="#ffffff2b" />
<rect x="203" y="22" width="41" height="8" rx="4" fill="#ffffff2b" />
</g>
<g :transform="widget.bluetooth === false ? 'translate(0 19)' : null">
<circle cx="33" cy="61" r="2" fill="#a480f2" />
<path d="M28.17 56.65A6.5 6.5 0 0 1 37.83 56.65" fill="none" stroke="#a480f2" stroke-width="2.4" />
<path d="M24.45 53.30A11.5 11.5 0 0 1 41.55 53.30" fill="none" stroke="#a480f2" stroke-width="2.4" />
<rect x="56" y="52" width="41" height="8" rx="4" fill="#a480f2" />
<rect x="105" y="52" width="41" height="8" rx="4" fill="#a480f2" />
<rect x="154" y="52" width="41" height="8" rx="4" fill="#a480f2" />
<rect x="203" y="52" width="41" height="8" rx="4" fill="#a480f2" />
</g>
<g v-if="widget.bluetooth !== false">
<path d="M33 79V93M33 79L37.5 82.5L28.5 89M28.5 83L37.5 89.5L33 93" fill="none" stroke="#6eafff" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" />
<text x="56" y="92" font-size="16" font-weight="600" fill="#f5f2fc">iPhone 15, AirPods</text>
</g>
</g>
</g>
<g v-else-if="widget.kind === 'network_signal' && widget.size === 'vertical'" :transform="'scale(' + widget.width / 112 + ')'">
<rect width="112" :height="196 + (widget.wifiName ? 22 : 0)" rx="24" fill="#0f0d17" :fill-opacity="235 / 255 * (widget.opacity ?? 85) / 100" />
<text v-if="widget.wifiName" x="56" y="21" text-anchor="middle" font-size="15" font-weight="600" fill="#f5f2fc">Home Wi-Fi</text>
<g :transform="widget.wifiName ? 'translate(0 22)' : null">
<g :transform="widget.bluetooth === false ? 'translate(0 32)' : null">
<circle cx="34" cy="85" r="8" fill="#f5f2fc" />
<circle cx="34" cy="64" r="8" fill="#f5f2fc" />
<circle cx="34" cy="43" r="8" fill="#ffffff2b" />
<circle cx="34" cy="22" r="8" fill="#ffffff2b" />
<rect x="25.75" y="114" width="3" height="4" fill="#b8b2c8" />
<rect x="30.25" y="110" width="3" height="8" fill="#b8b2c8" />
<rect x="34.75" y="106" width="3" height="12" fill="#b8b2c8" />
<rect x="39.25" y="102" width="3" height="16" fill="#b8b2c8" />
<circle cx="78" cy="85" r="8" fill="#a480f2" />
<circle cx="78" cy="64" r="8" fill="#a480f2" />
<circle cx="78" cy="43" r="8" fill="#a480f2" />
<circle cx="78" cy="22" r="8" fill="#a480f2" />
<circle cx="78" cy="116" r="2" fill="#a480f2" />
<path d="M73.17 111.65A6.5 6.5 0 0 1 82.83 111.65" fill="none" stroke="#a480f2" stroke-width="2.4" />
<path d="M69.45 108.30A11.5 11.5 0 0 1 86.55 108.30" fill="none" stroke="#a480f2" stroke-width="2.4" />
</g>
<g v-if="widget.bluetooth !== false">
<line x1="14" y1="128" x2="98" y2="128" stroke="#ffffff2b" stroke-width="1.5" />
<path d="M56 135V149M56 135L60.5 138.5L51.5 145M51.5 139L60.5 145.5L56 149" fill="none" stroke="#6eafff" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" />
<text x="56" y="167" text-anchor="middle" font-size="15" font-weight="600" fill="#f5f2fc">iPhone 15</text>
<text x="56" y="186" text-anchor="middle" font-size="15" font-weight="600" fill="#f5f2fc">AirPods</text>
</g>
</g>
</g>
<g v-else-if="widget.kind === 'jetlink_status'">
<rect :width="widget.width" :height="widget.height" :rx="widget.height / 2" fill="#0f0d17" :fill-opacity="235 / 255 * (widget.opacity ?? 85) / 100" />
<circle cx="40" cy="30" r="7.5" fill="#46c86e" />
<text x="58" y="36" font-size="20" font-weight="700" letter-spacing="0.6" fill="#d6d2e0">BIG • JETLINK</text>
<text :x="widget.width - 62" y="37" text-anchor="end" font-size="24" font-weight="700" fill="#f5f2fc">24.6</text>
<text :x="widget.width - 32" y="37" text-anchor="end" font-size="18" fill="#d6d2e0">ms</text>
<text x="32" y="75" font-size="28" font-weight="600" fill="#f5f2fc">Cinque v3</text>
</g>
<g v-else-if="widget.kind === 'nav_card' && profile === 'compact'">
<rect x="1" y="1" :width="widget.width - 2" :height="widget.height - 2" rx="20" fill="#0f0d17" stroke="#a07edcbe" stroke-width="2" />
<path d="M42 78 V42 Q42 32 52 32 H78 M64 18 L78 32 L64 46" fill="none" stroke="white" stroke-width="7" stroke-linecap="round" stroke-linejoin="round" />
+1 -2
View File
@@ -41,8 +41,7 @@ def read_bluetooth_details() -> tuple[str, tuple[str, ...]]:
if not isinstance(name, str) or not name.strip():
name = prop(path, "org.bluez.Device1", "Alias")
label = name.strip() if isinstance(name, str) and name.strip() else "Bluetooth"
if label not in devices:
devices.append(label)
devices.append(label)
except (ValueError, KeyError, IndexError, TypeError, AttributeError):
return "off", ()
return ("connected", tuple(devices)) if devices else ("on", ())
+13 -4
View File
@@ -60,16 +60,20 @@ def read_signal() -> Signal:
class SignalFeed:
"""Polls in the background only while snapshot() keeps being asked; snapshot() never does IO."""
"""Poll off-thread while snapshots are requested."""
def __init__(self, read=read_signal, period=2.0):
self.read, self.period = read, period
self._lock = threading.Lock()
self._stop = threading.Event()
self._thread = None
self._signal = Signal()
self._read_at = self._wanted_at = 0.
def poll(self):
signal = self.read()
try:
signal = self.read()
except Exception:
signal = Signal()
with self._lock:
self._signal, self._read_at = signal, time.monotonic()
@@ -84,9 +88,14 @@ class SignalFeed:
return signal if fresh else Signal()
def _run(self):
while True:
while not self._stop.is_set():
with self._lock:
wanted = time.monotonic() - self._wanted_at <= WANTED_S
if wanted:
self.poll()
time.sleep(self.period)
self._stop.wait(self.period)
def close(self):
self._stop.set()
if self._thread is not None:
self._thread.join(timeout=2)
+2
View File
@@ -610,6 +610,8 @@ class OnroadView:
self.navigation.close()
if now_playing := getattr(self, "now_playing", None):
now_playing.close()
if signal := getattr(self, "network_signal", None):
signal.close()
if self.fonts.profile == Profile.LARGE:
self.unified_speed.close()
self.steering_wheel.close()
@@ -256,7 +256,7 @@ def signal_size(placement: dict | None) -> tuple[int, int]:
if (placement or {}).get("wifiName") is True:
height += SIGNAL_WIFI_NAME_HEIGHT
scale = signal_scale(placement)
return round(width * scale), round(height * scale)
return math.floor(width * scale + .5), math.floor(height * scale + .5)
_signal["note"] = ("Cellular and Wi-Fi strength with the active link highlighted, Bluetooth status and device name, " +
"and optionally the Wi-Fi network name on top. Opacity sets the background.")
PROFILES["large"]["widgets"][SIGNAL_WIDGET] = _signal
@@ -336,7 +336,7 @@ WIDGET_COLORS = {
def _fit_legacy_signal(placement: dict, bounds: Bounds) -> None:
"""A card saved before the Bluetooth row grew may now overhang its edge; pull it back in if it fit at its old size."""
"""Keep layouts saved before the Bluetooth row inside their bounds."""
grid = SIGNAL_LEGACY_GRIDS.get(placement.get("size"))
if grid is None or not valid_signal_scale(placement):
return
+30 -27
View File
@@ -1,4 +1,4 @@
"""Big model card shared by the native and Android Auto screens: which model drives, and the external GPU's state."""
"""Big model card for native and Android Auto screens."""
import re
import time
from typing import NamedTuple
@@ -7,9 +7,8 @@ from openpilot.starpilot.ui.raylib import rl
from openpilot.starpilot.models.catalog import BUNDLED_CURRENT, model_entries
from openpilot.starpilot.models.jetlink_status import JetlinkStatus
from openpilot.starpilot.models.manager import preferences
from openpilot.starpilot.models.receipt import read_pair_receipt, read_receipt
from openpilot.starpilot.models.status import ModelVariant
from openpilot.starpilot.models.receipt import process_start_ticks, read_pair_receipt, read_receipt
from openpilot.starpilot.models.status import LaboratoryLoad, ModelLoad, ModelVariant
from openpilot.starpilot.ui import clip
from openpilot.starpilot.ui.models_state import model_display_text
from openpilot.starpilot.ui.onroad_customization import JETLINK_SIZE, JETLINK_WIDGET
@@ -59,7 +58,7 @@ def abbreviate_model_name(name: str) -> str:
def scroll_offset(text_width: float, width: float, seconds: float) -> float:
"""How far a too-wide line has scrolled left: still for SCROLL_PAUSE, then one pass to where its repeat starts."""
"""Pause, then scroll long text until its repeat reaches the start."""
if text_width <= width:
return 0.0
travel = text_width + SCROLL_GAP
@@ -70,37 +69,41 @@ def scroll_offset(text_width: float, width: float, seconds: float) -> float:
def _entry_name(entries: dict, model_id: str, variant: ModelVariant | None = None) -> str:
if not model_id:
return ''
if model_id == BUNDLED_CURRENT:
return 'Cinque v2' if variant is ModelVariant.CHESTNUT else 'RDF V4'
if model_id == BUNDLED_CURRENT and variant is ModelVariant.CHESTNUT:
return ''
entry = entries.get(model_id)
return entry.name if entry is not None else model_id
def _live_load(load: ModelLoad | LaboratoryLoad | None) -> bool:
return (load is not None and load.process_start_ticks > 0 and process_start_ticks(load.pid) == load.process_start_ticks and
0 < load.loaded_mono_ns <= time.monotonic_ns())
def _read_model_names() -> tuple[str, str]:
entries = model_entries()
pair = read_pair_receipt()
if pair is not None and _live_load(pair):
names = (abbreviate_model_name(_entry_name(entries, mid)) for mid in (pair.lateral_id, pair.longitudinal_id))
name = ' / '.join(part for part in names if part)
return name, name
load = read_receipt()
if load is not None and _live_load(load):
name = abbreviate_model_name(_entry_name(entries, load.model_id, load.variant))
return ('', name) if load.variant is ModelVariant.CHESTNUT else (name, '')
return '', ''
def local_model_names(now: float | None = None) -> tuple[str, str]:
"""Cached (small, big) driving model names from modeld receipts and saved preferences."""
"""Cached (small, big) names from receipts belonging to a live modeld process."""
global _model_cache
ts = time.monotonic() if now is None else now
if _model_cache is not None and 0 <= ts - _model_cache[0] < MODEL_TTL:
return _model_cache[1]
entries = model_entries()
pair = read_pair_receipt()
if pair is not None:
lat = abbreviate_model_name(_entry_name(entries, pair.lateral_id))
lon = abbreviate_model_name(_entry_name(entries, pair.longitudinal_id))
pair_name = ' / '.join(part for part in (lat, lon) if part)
result = (pair_name, pair_name)
else:
prefs = preferences()
small = _entry_name(entries, prefs.get('small', ''), ModelVariant.SMALL)
big = _entry_name(entries, prefs.get('big', ''), ModelVariant.CHESTNUT)
load = read_receipt()
if load is not None:
loaded = _entry_name(entries, load.model_id, load.variant)
if load.variant is ModelVariant.CHESTNUT:
big = loaded or big
else:
small = loaded or small
result = (abbreviate_model_name(small), abbreviate_model_name(big))
try:
result = _read_model_names()
except Exception:
result = ('', '')
_model_cache = (ts, result)
return result
@@ -1,4 +1,4 @@
"""Keeps the big model card fed on the native large screen: Jetlink polled only while it is showing, and the GPU state."""
"""Keep the native Big model card fed while visible."""
from openpilot.starpilot.models.jetlink_status import JetlinkStatusFeed
from openpilot.starpilot.ui.onroad_customization import JETLINK_WIDGET
+4 -1
View File
@@ -102,6 +102,9 @@ class SignalWidget:
self.preview: Signal | None = None
self.s = SIGNAL_SCALE
def close(self):
self.feed.close()
def _text(self, text, x, cy, size, color, align='center'):
"""Draws text with its ink centered on cy; x is the centre, or the left edge with align='left'."""
size *= self.s
@@ -200,7 +203,7 @@ class SignalWidget:
def _ring(self, signal, radios, x, y, background, show_bt=True, header=0):
S = self.s
devices = (signal.bt_devices or ('Connected',)) if signal.bt == 'connected' else ()
devices = (signal.bt_devices or ('Connected',)) if show_bt and signal.bt == 'connected' else ()
height = 140 if len(devices) > 1 else 122 if devices and show_bt else 102
_pill(x, y, 112 * S, (height + header) * S, background, 24 / 56, shadow=False)
if header:
@@ -56,6 +56,19 @@ class TestBluetoothStatus(unittest.TestCase):
return_value=subprocess.CompletedProcess([], 0, output, "")):
self.assertEqual(read_bluetooth_details(), ("connected", ("iPhone 15", "AirPods")))
def test_bluez_details_count_distinct_devices_with_identical_names(self):
for name in ("Headphones", None):
props = {"Connected": {"data": True}, "Name": {"data": name}}
data = {
"/org/bluez/hci0": {"org.bluez.Adapter1": {"Powered": {"data": True}}},
"/org/bluez/hci0/dev_AA": {"org.bluez.Device1": props},
"/org/bluez/hci0/dev_BB": {"org.bluez.Device1": props},
}
output = json.dumps({"data": [data]})
with self.subTest(name=name), patch("openpilot.starpilot.ui.bluetooth_status.subprocess.run",
return_value=subprocess.CompletedProcess([], 0, output, "")):
self.assertEqual(read_bluetooth_details(), ("connected", (name or "Bluetooth",) * 2))
def test_pending_failure_and_stale_result_never_show_icon(self):
clock = [10_000_000_000]
source = BluetoothStatusSource(clock=lambda: clock[0])
@@ -1,4 +1,5 @@
import json
import math
import threading
from unittest.mock import patch
@@ -30,12 +31,26 @@ def test_reads_both_radios_and_the_link_in_use(tmp_path):
assert read(tmp_path, {'connected': True, 'signal_quality': '60'}, None, 'ppp0') == Signal()
def test_feed_lets_a_failed_read_propagate():
def fail():
raise RuntimeError('boom')
feed = SignalFeed(read=fail)
with pytest.raises(RuntimeError):
def test_feed_clears_a_failed_read_and_recovers():
signal = Signal(4, None, 'cell')
feed = SignalFeed(read=lambda: signal)
feed.poll()
with patch.object(feed, 'read', side_effect=OSError('modem temporarily unavailable')):
feed.poll()
assert feed._signal == Signal()
feed.poll()
assert feed._signal == signal
def test_feed_close_wakes_and_stops_the_worker():
polled = threading.Event()
feed = SignalFeed(read=lambda: polled.set() or Signal(), period=3600)
try:
feed.snapshot()
assert polled.wait(2)
finally:
feed.close()
assert feed._thread is not None and not feed._thread.is_alive()
def test_feed_goes_blank_when_the_reading_is_old():
@@ -86,15 +101,16 @@ def test_starport_signal_style_is_validated_and_pulled_on_screen():
@pytest.mark.parametrize('style', ['ring', 'horizontal', 'vertical'])
def test_every_signal_style_shrinks_to_30_percent(style):
@pytest.mark.parametrize('scale', [30, 50, 100])
def test_every_signal_style_scales_like_the_editor(style, scale):
from openpilot.starpilot.ui.onroad_customization import SIGNAL_SIZES, widget_size
document = default_document()
placed = document['layouts']['large'][SIGNAL_WIDGET]
assert placed['scale'] == 100
placed.update(size=style, scale=30)
placed.update(size=style, scale=scale)
document = validate_document(document)
width, height = SIGNAL_SIZES[style]
assert widget_size(document, 'large', SIGNAL_WIDGET) == (round(width * .3), round(height * .3))
assert widget_size(document, 'large', SIGNAL_WIDGET) == (math.floor(width * scale / 100 + .5), math.floor(height * scale / 100 + .5))
for bad in (29, 101, 50.0):
document['layouts']['large'][SIGNAL_WIDGET]['scale'] = bad
with pytest.raises(ValueError):
@@ -189,16 +205,20 @@ def test_bluetooth_toggle_defaults_on_and_hides_bluetooth_when_off():
fonts.vertical_ink.return_value = (0, 10)
fonts.measure.side_effect = lambda text, _role, size: NS(width=len(text) * size * 0.5)
widget = onroad_signal.SignalWidget(fonts)
widget.preview = Signal(2, 4, 'wifi', '5G', 'connected', ('iPhone 15',))
widget.preview = Signal(2, 4, 'wifi', '5G', 'connected', ('iPhone 15', 'AirPods'))
for style in ('ring', 'horizontal', 'vertical'):
fonts.draw.reset_mock()
doc = default_document()
doc['layouts']['large'][SIGNAL_WIDGET].update(enabled=True, size=style, bluetooth=False)
with patch.object(onroad_signal, 'rl'):
with patch.object(onroad_signal, 'rl') as rl:
rl.Rectangle = lambda *args: args
widget.render(NS(customization=doc, alert=NS(size='none')))
drawn = [call.args[0] for call in fonts.draw.call_args_list]
assert 'iPhone 15' not in drawn
assert 'Connected' not in drawn
if style == 'ring':
from openpilot.starpilot.ui.onroad_customization import SIGNAL_SCALE
assert rl.draw_rectangle_rounded.call_args_list[0].args[0][3] == pytest.approx(102 * SIGNAL_SCALE)
@pytest.mark.parametrize('style,grid', [('ring', (88, 88)), ('horizontal', (268, 84)), ('vertical', (96, 160))])
@@ -247,7 +267,7 @@ def test_horizontal_bluetooth_name_does_not_overlap_status():
def test_reads_the_joined_wifi_name(tmp_path):
replies = {'SIGNAL_POLL': {'RSSI': '-45'}, 'STATUS': {'wpa_state': 'COMPLETED', 'ssid': r'Danny\xe2\x80\x99s Caf\xc3\xa9'}}
replies = {'SIGNAL_POLL': {'RSSI': '-45'}, 'STATUS': {'wpa_state': 'COMPLETED', 'ssid': r'Danny\xe2\x80\x99s \x43\x61\x66\xc3\xa9'}}
with patch.object(hardware, 'MODEM_STATE_PATH', str(tmp_path / 'modem')), \
patch.object(hardware, 'wpa_supplicant_cmd', side_effect=lambda cmd: replies[cmd]), \
patch.object(hardware, 'get_default_route_iface', return_value='wlan0'), \
@@ -121,32 +121,49 @@ def test_big_model_card_uses_abbreviated_model_names_and_tier():
assert (fallback.title, fallback.detail, fallback.tier) == ('RDF V4', 'Fell back', 'SMALL')
def test_local_model_names_reads_receipts_caches_and_never_raises():
entries = {
'rdf43': NS(name='Regret Driven Framework V4 👀📡'),
'cinquev3': NS(name='Cinque v3 👀📡'),
'tr16223': NS(name='TR16 👀📡'),
}
def test_local_model_names_reads_live_receipts_and_caches():
entries = {'tr16223': NS(name='TR16'), 'cinquev3': NS(name='Cinque v3'), BUNDLED_CURRENT: NS(name='Cheddar')}
pair = NS(pid=123, process_start_ticks=456, loaded_mono_ns=1, lateral_id='tr16223', longitudinal_id='cinquev3')
onroad_jetlink._model_cache = None
with patch.object(onroad_jetlink, 'model_entries', return_value=entries), \
patch.object(onroad_jetlink, 'read_pair_receipt', return_value=NS(lateral_id='tr16223', longitudinal_id='cinquev3')), \
patch.object(onroad_jetlink, 'read_receipt', return_value=None), \
patch.object(onroad_jetlink, 'preferences', return_value={'small': 'rdf43', 'big': ''}):
patch.object(onroad_jetlink, 'read_pair_receipt', return_value=pair), \
patch.object(onroad_jetlink, 'process_start_ticks', return_value=456):
assert local_model_names(now=10.0) == ('TR16 / Cinque v3', 'TR16 / Cinque v3')
# Cached hit inside MODEL_TTL avoids re-reading even if inputs change.
with patch.object(onroad_jetlink, 'read_pair_receipt', side_effect=AssertionError('should use cache')):
assert local_model_names(now=10.5) == ('TR16 / Cinque v3', 'TR16 / Cinque v3')
for variant, expected in ((ModelVariant.SMALL, ('Cheddar', '')), (ModelVariant.CHESTNUT, ('', ''))):
onroad_jetlink._model_cache = None
load = NS(pid=123, process_start_ticks=456, loaded_mono_ns=1, model_id=BUNDLED_CURRENT, variant=variant)
with patch.object(onroad_jetlink, 'model_entries', return_value=entries), \
patch.object(onroad_jetlink, 'read_pair_receipt', return_value=None), \
patch.object(onroad_jetlink, 'read_receipt', return_value=load), \
patch.object(onroad_jetlink, 'process_start_ticks', return_value=456):
assert local_model_names(now=20.0) == expected
onroad_jetlink._model_cache = None
with patch.object(onroad_jetlink, 'model_entries', return_value=entries), \
patch.object(onroad_jetlink, 'read_pair_receipt', return_value=None), \
patch.object(onroad_jetlink, 'preferences', return_value={'small': 'rdf43', 'big': 'cinquev3'}), \
patch.object(onroad_jetlink, 'read_receipt', return_value=NS(model_id=BUNDLED_CURRENT, variant=ModelVariant.CHESTNUT)):
assert local_model_names(now=20.0) == ('RDF V4', 'Cinque v2')
@pytest.mark.parametrize('ticks', [0, 789])
def test_local_model_names_reject_stale_process_receipts(ticks):
load = NS(pid=123, process_start_ticks=456, loaded_mono_ns=1, model_id='tr16223', variant=ModelVariant.SMALL)
pair = NS(pid=123, process_start_ticks=456, loaded_mono_ns=1, lateral_id='tr16223', longitudinal_id='tr16223')
onroad_jetlink._model_cache = None
with patch.object(onroad_jetlink, 'model_entries', side_effect=RuntimeError('boom')), pytest.raises(RuntimeError):
local_model_names(now=30.0)
with patch.object(onroad_jetlink, 'model_entries', return_value={'tr16223': NS(name='TR16')}), \
patch.object(onroad_jetlink, 'read_pair_receipt', return_value=pair), \
patch.object(onroad_jetlink, 'read_receipt', return_value=load), \
patch.object(onroad_jetlink, 'process_start_ticks', return_value=ticks):
assert local_model_names(now=30.0) == ('', '')
onroad_jetlink._model_cache = None
def test_local_model_names_unavailable_does_not_guess_from_preferences():
onroad_jetlink._model_cache = None
with patch.object(onroad_jetlink, 'read_pair_receipt', return_value=None), \
patch.object(onroad_jetlink, 'read_receipt', return_value=None):
assert local_model_names(now=30.0) == ('', '')
onroad_jetlink._model_cache = None
with patch.object(onroad_jetlink, 'model_entries', side_effect=OSError('unavailable')):
assert local_model_names(now=30.0) == ('', '')
onroad_jetlink._model_cache = None