mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-12-02 01:13:39 +08:00
Merge pull request #324 from dirwin31/NetworkJetlinkWidgets
Widgets: Connections widget and Big model widget
This commit is contained in:
@@ -11,7 +11,7 @@ from openpilot.starpilot.system.starport.display_profile import (
|
||||
SCREEN_PATH, MAX_BYTES as SCREEN_MAX_BYTES, record_screen, validate_screen,
|
||||
)
|
||||
from openpilot.starpilot.system.starport.projection_layout import (
|
||||
DOCUMENT_KEY, JETLINK_WIDGET, MAX_BYTES, ProjectionLayoutSource, comma_display, decode_layout, default_layout, layout_metadata, validate_layout,
|
||||
DOCUMENT_KEY, MAX_BYTES, ProjectionLayoutSource, comma_display, decode_layout, default_layout, layout_metadata, validate_layout,
|
||||
)
|
||||
from openpilot.starpilot.ui.appearance_preferences import onroad_appearance
|
||||
from openpilot.starpilot.ui.onroad_customization import read_customization
|
||||
@@ -83,9 +83,6 @@ class ProjectionLayoutOwner:
|
||||
'Saved projection layout is unavailable' if not readable else None)
|
||||
base = read_customization(self.params)
|
||||
metadata = layout_metadata(screen) if screen is not None else None
|
||||
if metadata is not None:
|
||||
mode = self.params.get('JetlinkMode')
|
||||
metadata['widgets'][JETLINK_WIDGET]['available'] = type(mode) is int and mode in (1, 2)
|
||||
return {'version': 1, 'document': document, 'defaults': defaults,
|
||||
'metadata': metadata,
|
||||
'screen': screen, 'revision': _revision(screen_raw, raw),
|
||||
|
||||
@@ -61,19 +61,11 @@ class TestProjectionLayoutOwner(unittest.TestCase):
|
||||
self.assertIsNone(value['defaults'])
|
||||
self.assertIn('actual screen', value['reason'])
|
||||
|
||||
def test_jetlink_widget_available_when_selected_and_placement_retained_when_off(self):
|
||||
def test_big_model_widget_available_without_jetlink_or_chestnut(self):
|
||||
self.screen()
|
||||
self.assertFalse(self.owner.snapshot()['metadata']['widgets']['jetlink_status']['available'])
|
||||
for mode in (1, 2):
|
||||
for mode in (0, 1, 2):
|
||||
self.params.jetlink_mode = mode
|
||||
self.assertTrue(self.owner.snapshot()['metadata']['widgets']['jetlink_status']['available'])
|
||||
payload = self.payload()
|
||||
payload['document']['widgets']['jetlink_status'].update(enabled=True, x=700, y=500)
|
||||
self.owner.save(payload, session_valid=lambda: True)
|
||||
self.params.jetlink_mode = 0
|
||||
snapshot = self.owner.snapshot()
|
||||
self.assertFalse(snapshot['metadata']['widgets']['jetlink_status']['available'])
|
||||
self.assertEqual(snapshot['document'], payload['document'])
|
||||
self.assertNotIn('available', self.owner.snapshot()['metadata']['widgets']['jetlink_status'])
|
||||
|
||||
def test_defaults_valid_false_then_exact_saved_document(self):
|
||||
self.screen()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { compile } from "../web/vendor/vue/vue.esm-browser.js"
|
||||
import assert from "node:assert/strict"
|
||||
import { execFileSync } from "node:child_process"
|
||||
import { OnroadLayoutPage, validSnapshot, validDocument, widgetSize, clampPlacement } from "../web/js/onroad-layout.js"
|
||||
import { LayoutWidgetPreview, OnroadLayoutPage, validSnapshot, validDocument, widgetSize, clampPlacement } from "../web/js/onroad-layout.js"
|
||||
|
||||
// Use the server's real registry so a UI gate cannot silently reject a newly exposed widget.
|
||||
const data = JSON.parse(execFileSync(process.env.PYTHON || "python3", ["-c", `
|
||||
@@ -10,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)
|
||||
@@ -121,6 +137,42 @@ assert.equal(validDocument(beyondNewPromptWidth, data.metadata), false)
|
||||
Object.assign(vm.layout.speed_limit_actions, {x:600, y:500})
|
||||
vm.setSpeedSources("speedSources", false)
|
||||
assert.deepEqual([vm.layout.speed_limit_actions.x, vm.layout.speed_limit_actions.y], [600, 500])
|
||||
const signal = vm.profile.widgets.network_signal, signalBounds = signal.bounds || vm.profile.bounds
|
||||
assert.equal(signal.label, "Connections")
|
||||
vm.layout.network_signal.enabled = true
|
||||
vm.state.selected = "network_signal"
|
||||
vm.setWidgetSize("horizontal")
|
||||
assert.deepEqual(widgetSize(signal, vm.layout.network_signal), signal.sizes.horizontal)
|
||||
assert.ok(vm.layout.network_signal.x + signal.sizes.horizontal[0] <= signalBounds.x + signalBounds.width)
|
||||
assert.equal(validDocument(vm.state.draft, data.metadata), true)
|
||||
vm.setWidgetSize("vertical")
|
||||
assert.deepEqual(widgetSize(signal, vm.layout.network_signal), signal.sizes.vertical)
|
||||
// Every style shrinks from full size down to 30%; growing back pulls it inside the screen.
|
||||
assert.deepEqual(signal.scale, {min: 30, max: 100, default: 100})
|
||||
assert.equal(vm.layout.network_signal.scale, 100)
|
||||
assert.equal(vm.layout.network_signal.bluetooth, true)
|
||||
vm.setWidgetToggle("bluetooth", "Off")
|
||||
assert.equal(vm.layout.network_signal.bluetooth, false)
|
||||
vm.setWidgetToggle("bluetooth", "On")
|
||||
assert.equal(vm.layout.network_signal.bluetooth, true)
|
||||
for (const style of ["ring", "horizontal", "vertical"]) {
|
||||
vm.setWidgetSize(style)
|
||||
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]
|
||||
vm.scaleInput({ target: { value: "100" } })
|
||||
assert.ok(vm.layout.network_signal.x + signal.sizes.vertical[0] <= signalBounds.x + signalBounds.width)
|
||||
assert.equal(validDocument(vm.state.draft, data.metadata), true)
|
||||
const badScale = JSON.parse(JSON.stringify(vm.state.draft))
|
||||
badScale.layouts.large.network_signal.scale = 20
|
||||
assert.equal(validDocument(badScale, data.metadata), false)
|
||||
vm.state.profile = "compact"
|
||||
vm.add("stopped_timer")
|
||||
assert.equal(vm.layout.stopped_timer.enabled, true)
|
||||
@@ -137,3 +189,20 @@ assert.equal(compact.document.layouts.compact.nav_card.enabled, true)
|
||||
compact.document.layouts.compact.nav_card.enabled = false
|
||||
assert.equal(validDocument(compact.document, compact.metadata), true)
|
||||
assert.equal(compact.document.layouts.large.nav_card.enabled, true)
|
||||
|
||||
// Exercise the rendered fallback, not just the stored toggle value.
|
||||
const renderSignal = compile(LayoutWidgetPreview.template, { decodeEntities: value => value.replaceAll("&", "&") })
|
||||
function previewText(node) {
|
||||
if (!node || typeof node !== "object") return ""
|
||||
if (Array.isArray(node)) return node.map(previewText).join(" ")
|
||||
return typeof node.children === "string" ? node.children : previewText(node.children)
|
||||
}
|
||||
for (const size of ["ring", "horizontal", "vertical"]) {
|
||||
for (const bluetooth of [true, false]) {
|
||||
const tree = renderSignal({ widget: { kind: "network_signal", size, width: 268, height: 196, bluetooth },
|
||||
palette: {}, profile: "large", scene: "engaged", native: false, art: null }, [])
|
||||
const text = previewText(tree)
|
||||
assert.equal(text.includes("iPhone 15"), bluetooth, `${size} Bluetooth preview follows the toggle`)
|
||||
if (!bluetooth) assert(!text.includes("Connected") && !text.includes("AirPods"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,7 +42,12 @@ export const withAlpha = (color, factor) => color.slice(0, 7) + Math.floor(parse
|
||||
// Steering wheels resize as a square ("size"); box widgets such as the Android Auto map take a width and height.
|
||||
export function widgetSize(widget, position) {
|
||||
if (widget.iconSize && position?.display === "icons") return [widget.iconSize, widget.iconSize]
|
||||
if (widget.sizes && Array.isArray(widget.sizes[position?.size])) return [...widget.sizes[position.size]]
|
||||
if (widget.sizes && Array.isArray(widget.sizes[position?.size])) {
|
||||
// A widget with a size percentage (the signal widget) shrinks its chosen style.
|
||||
const scale = widget.scale && Number.isInteger(position?.scale) ? position.scale / 100 : 1
|
||||
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.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]
|
||||
@@ -109,8 +114,10 @@ export function overlapsReserved(profile, id, x, y, layout = null) {
|
||||
if ((id !== owner && id !== key) || !positions[key]?.enabled) return false
|
||||
const [width, height] = widgetSize(profile.widgets[key], positions[key])
|
||||
const obstacle = profile.widgets[key].confirmationObstacle || { x: 0, y: 0, width, height }
|
||||
return overlaps(panel, { x: (id === key ? x : positions[key].x) + obstacle.x,
|
||||
y: (id === key ? y : positions[key].y) + obstacle.y, width: obstacle.width, height: obstacle.height })
|
||||
return overlaps(panel, {
|
||||
x: (id === key ? x : positions[key].x) + obstacle.x,
|
||||
y: (id === key ? y : positions[key].y) + obstacle.y, width: obstacle.width, height: obstacle.height
|
||||
})
|
||||
})) return true
|
||||
}
|
||||
if (widget.layer === "underlay") return false
|
||||
@@ -182,11 +189,14 @@ export function validDocument(document, metadata) {
|
||||
const widget = profile.widgets[id], limits = placementLimits(profile, id, layout)
|
||||
const resizable = widget.resizable, box = widget.box, opacity = widget.opacity
|
||||
return keysEqual(position, ["x", "y", "enabled", ...(resizable ? ["size"] : []), ...(box ? ["width", "height"] : []),
|
||||
...(opacity ? ["opacity"] : []), ...(widget.iconSize ? ["display"] : []), ...(widget.backgroundToggle ? ["background"] : []), ...(widget.collapseToggle ? ["collapse"] : []), ...(widget.sizes ? ["size"] : [])]) &&
|
||||
...(opacity ? ["opacity"] : []), ...(widget.iconSize ? ["display"] : []), ...(widget.backgroundToggle ? ["background"] : []), ...(widget.collapseToggle ? ["collapse"] : []), ...(widget.bluetoothToggle ? ["bluetooth"] : []), ...(widget.wifiNameHeight ? ["wifiName"] : []), ...(widget.sizes ? ["size"] : []), ...(widget.scale ? ["scale"] : [])]) &&
|
||||
(!widget.iconSize || ["words", "icons"].includes(position.display)) &&
|
||||
(!widget.backgroundToggle || typeof position.background === "boolean") &&
|
||||
(!widget.collapseToggle || typeof position.collapse === "boolean") &&
|
||||
(!widget.bluetoothToggle || typeof position.bluetooth === "boolean") &&
|
||||
(!widget.wifiNameHeight || typeof position.wifiName === "boolean") &&
|
||||
(!widget.sizes || Object.hasOwn(widget.sizes, position.size)) &&
|
||||
(!widget.scale || (Number.isInteger(position.scale) && position.scale >= widget.scale.min && position.scale <= widget.scale.max)) &&
|
||||
(!opacity || (Number.isInteger(position.opacity) && position.opacity >= opacity.min && position.opacity <= opacity.max)) &&
|
||||
(!resizable || (Number.isInteger(position.size) && position.size >= resizable.min && position.size <= resizable.max)) &&
|
||||
(!box || (Number.isInteger(position.width) && position.width >= box.minWidth && position.width <= box.maxWidth &&
|
||||
@@ -265,14 +275,19 @@ export function validSnapshot(data) {
|
||||
widget.box.minHeight > widget.box.maxHeight || widget.box.maxWidth > area.width || widget.box.maxHeight > area.height)) return false
|
||||
if (widget.aspectRatio != null && (!projection || !widget.box || !["nav_card", "pip_camera"].includes(widget.kind) ||
|
||||
!positive(widget.aspectRatio) || widget.aspectRatio !== widget.width / widget.height)) return false
|
||||
if (widget.opacity && (!(["nav_map", "jetlink_status"].includes(widget.kind) || projection && ["nav_home", "nav_work", "bookmark", "car_exit", "cruise_limits", "now_playing"].includes(widget.kind)) ||
|
||||
if (widget.opacity && (!(["nav_map", "jetlink_status", "network_signal"].includes(widget.kind) || projection && ["nav_home", "nav_work", "bookmark", "car_exit", "cruise_limits", "now_playing"].includes(widget.kind)) ||
|
||||
!object(widget.opacity) || ![widget.opacity.min, widget.opacity.max, widget.opacity.default].every(Number.isInteger) ||
|
||||
widget.opacity.min < 0 || widget.opacity.max > 100 || widget.opacity.min > widget.opacity.default ||
|
||||
widget.opacity.default > widget.opacity.max)) return false
|
||||
if (widget.collapseToggle != null && (!projection || widget.kind !== "now_playing" || widget.collapseToggle !== true)) return false
|
||||
if (widget.sizes != null && (!projection || widget.kind !== "now_playing" || !object(widget.sizes) ||
|
||||
if (widget.bluetoothToggle != null && (widget.kind !== "network_signal" || widget.bluetoothToggle !== true)) return false
|
||||
if (widget.wifiNameHeight != null && (widget.kind !== "network_signal" || !positive(widget.wifiNameHeight))) return false
|
||||
if (widget.sizes != null && (!(projection && widget.kind === "now_playing" || widget.kind === "network_signal") || !object(widget.sizes) ||
|
||||
!Object.values(widget.sizes).every(size => Array.isArray(size) && size.length === 2 && size.every(positive) &&
|
||||
size[0] <= area.width && size[1] <= area.height))) return false
|
||||
if (widget.scale != null && (widget.kind !== "network_signal" || !widget.sizes || !object(widget.scale) ||
|
||||
![widget.scale.min, widget.scale.max, widget.scale.default].every(Number.isInteger) || widget.scale.min < 10 ||
|
||||
widget.scale.max > 100 || widget.scale.min > widget.scale.default || widget.scale.default > widget.scale.max)) return false
|
||||
if (widget.backgroundToggle != null && (!projection || !["nav_home", "nav_work", "bookmark", "car_exit"].includes(widget.kind) ||
|
||||
widget.backgroundToggle !== true || !widget.opacity)) return false
|
||||
if (widget.resizable && (!["steering_wheel", "driver_monitor"].includes(widget.kind) || !Number.isInteger(widget.resizable.min) ||
|
||||
|
||||
@@ -252,23 +252,32 @@ export const ONROAD_LAYOUT_TEMPLATE = `
|
||||
<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.opacity">
|
||||
<label for="layout-widget-opacity">{{ selectedWidget.box ? 'Map opacity' : ['cruise_limits', 'jetlink_status'].includes(selectedWidget.kind) ? 'Background opacity' : 'Opacity' }} · {{ selectedPosition.opacity }}%</label>
|
||||
<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"
|
||||
:value="selectedPosition.opacity" :disabled="!editAvailable || !!state.drag || !!state.layerDrag" @input="opacityInput($event)" @change="finishColorEdit" @blur="finishColorEdit">
|
||||
</template>
|
||||
<GalaxySettingRow feedback="draft" v-if="selectedWidget.backgroundToggle" :row="switchRow('Show background', selectedPosition.background === true)" :index="0"
|
||||
:disabled="!editAvailable || !!state.drag || !!state.layerDrag" :save-value="(index, value) => setWidgetBackground(value)" />
|
||||
<div v-if="projection && selectedWidget.sizes" class="gx-layout__favorite-display">
|
||||
<span>Size</span>
|
||||
<div class="gx-segment" role="group" :aria-label="selectedWidget.label + ' size'">
|
||||
<button v-for="size in ['big', 'small']" :key="size" class="gx-btn" type="button"
|
||||
<div v-if="selectedWidget.sizes" class="gx-layout__favorite-display">
|
||||
<span>{{ sizeChoice.label }}</span>
|
||||
<div class="gx-segment" role="group" :aria-label="selectedWidget.label + ' ' + sizeChoice.label.toLowerCase()">
|
||||
<button v-for="size in sizeChoice.options" :key="size" class="gx-btn" type="button"
|
||||
:class="selectedPosition.size === size ? 'gx-btn--primary' : 'gx-btn--tonal'"
|
||||
:aria-pressed="selectedPosition.size === size" :disabled="!editAvailable || !!state.drag || !!state.layerDrag"
|
||||
@click="setWidgetSize(size)">{{ size === 'big' ? 'Big' : 'Small' }}</button>
|
||||
@click="setWidgetSize(size)">{{ size[0].toUpperCase() + size.slice(1) }}</button>
|
||||
</div>
|
||||
</div>
|
||||
<template v-if="selectedWidget.scale">
|
||||
<label for="layout-widget-scale">Size · {{ selectedPosition.scale }}%</label>
|
||||
<input id="layout-widget-scale" class="gx-slider" type="range" step="5" :min="selectedWidget.scale.min" :max="selectedWidget.scale.max"
|
||||
:value="selectedPosition.scale" :disabled="!editAvailable || !!state.drag || !!state.layerDrag" @input="scaleInput($event)" @change="finishColorEdit" @blur="finishColorEdit">
|
||||
</template>
|
||||
<GalaxySettingRow v-if="selectedWidget.collapseToggle" :row="switchRow('Collapse when paused', selectedPosition.collapse === true)" :index="0"
|
||||
:disabled="!editAvailable || !!state.drag || !!state.layerDrag" :save-value="(index, value) => setWidgetCollapse(value)" />
|
||||
<GalaxySettingRow feedback="draft" v-if="selectedWidget.bluetoothToggle" :row="switchRow('Show Bluetooth connections', selectedPosition.bluetooth !== false)" :index="0"
|
||||
:disabled="!editAvailable || !!state.drag || !!state.layerDrag" :save-value="(index, value) => setWidgetToggle('bluetooth', value)" />
|
||||
<GalaxySettingRow feedback="draft" v-if="selectedWidget.wifiNameHeight" :row="switchRow('Show Wi-Fi network name', selectedPosition.wifiName === true)" :index="0"
|
||||
:disabled="!editAvailable || !!state.drag || !!state.layerDrag" :save-value="(index, value) => setWidgetToggle('wifiName', value)" />
|
||||
<p v-if="selectedWidget.defaultAnchor === 'driver_side'" class="gx-note">The default position follows the driver’s side. A moved position stays where you place it.</p>
|
||||
<p v-if="selectedWidget.note" class="gx-note">{{ selectedWidget.note }}</p>
|
||||
<div v-if="selectedWidget.kind === 'clock'" class="gx-row"><div class="gx-row__info"><span class="gx-row__label">Use 24-hour time</span></div>
|
||||
|
||||
@@ -263,13 +263,102 @@ export const LayoutWidgetPreview = {
|
||||
<path d="M0 7 V-11 H8 V-7.8 H2.6 V7" /><circle cx="-3" cy="7" r="5" />
|
||||
</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 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="widget.height / 2" :cy="widget.height / 2" r="9" fill="#46c86e" />
|
||||
<text :x="widget.height - 6" y="38" font-size="28" font-weight="600" fill="#f5f2fc">Link up</text>
|
||||
<text :x="widget.height - 6" y="66" font-size="22" fill="#b8b2c8">Jetlink • iPhone</text>
|
||||
<text :x="widget.width - 70" :y="widget.height / 2 + 12" text-anchor="end" font-size="34" font-weight="600" fill="#f5f2fc">24.6</text>
|
||||
<text :x="widget.width - 30" :y="widget.height / 2 + 12" text-anchor="end" font-size="22" fill="#b8b2c8">ms</text>
|
||||
<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>
|
||||
<template v-else-if="widget.kind === 'speed_limit'">
|
||||
<text x="0" y="10" font-size="24" font-weight="500">LIMIT</text>
|
||||
@@ -313,14 +402,6 @@ export const LayoutWidgetPreview = {
|
||||
<path d="M38 48 H78 M67 37 L78 48 L67 59" />
|
||||
</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="widget.height / 2" :cy="widget.height / 2" r="9" fill="#46c86e" />
|
||||
<text :x="widget.height - 6" y="40" font-size="28" font-weight="600" fill="#f5f2fc">Link up</text>
|
||||
<text :x="widget.height - 6" y="68" font-size="22" fill="#b8b2c8">Jetlink • iPhone</text>
|
||||
<text :x="widget.width - 70" y="52" text-anchor="end" font-size="34" font-weight="600" fill="#f5f2fc">24.6</text>
|
||||
<text :x="widget.width - 30" y="52" text-anchor="end" font-size="22" fill="#b8b2c8">ms</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" />
|
||||
@@ -630,7 +711,10 @@ export const OnroadLayoutPage = {
|
||||
...(widget.opacity ? { opacity: this.layout[widget.id].opacity } : {}),
|
||||
...(widget.backgroundToggle ? { background: this.layout[widget.id].background } : {}),
|
||||
...(widget.collapseToggle ? { collapse: this.layout[widget.id].collapse } : {}),
|
||||
...(widget.sizes ? { size: this.layout[widget.id].size } : {})
|
||||
...(widget.bluetoothToggle ? { bluetooth: this.layout[widget.id].bluetooth } : {}),
|
||||
...(widget.wifiNameHeight ? { wifiName: this.layout[widget.id].wifiName } : {}),
|
||||
...(widget.sizes ? { size: this.layout[widget.id].size } : {}),
|
||||
...(widget.scale ? { scale: this.layout[widget.id].scale } : {})
|
||||
}
|
||||
})
|
||||
},
|
||||
@@ -638,6 +722,10 @@ export const OnroadLayoutPage = {
|
||||
(!this.layout[id].enabled || (this.state.drag?.fromTray && this.state.drag.id === id))) },
|
||||
availableProfiles() { return this.state.data?.supportedProfiles || (this.state.data?.activeProfile ? [this.state.data.activeProfile] : []) },
|
||||
selectedWidget() { return this.profile?.widgets[this.state.selected] },
|
||||
sizeChoice() {
|
||||
const signal = this.selectedWidget?.kind === 'network_signal'
|
||||
return { label: signal ? 'Style' : 'Size', options: signal ? Object.keys(this.selectedWidget.sizes) : ['big', 'small'] }
|
||||
},
|
||||
selectedPosition() { return this.layout?.[this.state.selected] },
|
||||
selectedSize() { return this.selectedWidget ? widgetSize(this.selectedWidget, this.selectedPosition) : [0, 0] },
|
||||
// A finger covers the preview chip, so touch drags show the alignment in the sticky save bar.
|
||||
@@ -1341,6 +1429,17 @@ export const OnroadLayoutPage = {
|
||||
axis === "height" ? number : this.selectedPosition.height)
|
||||
event.target.value = this.selectedPosition[axis]
|
||||
},
|
||||
scaleInput(event) {
|
||||
const value = Number(event.target.value), range = this.selectedWidget?.scale
|
||||
if (!this.editable || this.state.drag || this.state.layerDrag || !range || !Number.isInteger(value) || value < range.min || value > range.max) return
|
||||
const before = clone(this.state.draft)
|
||||
this.selectedPosition.scale = value
|
||||
// Growing back toward full size may overhang the screen edge; pull it back in.
|
||||
Object.assign(this.selectedPosition, clampPlacement(this.limitProfile, this.state.selected,
|
||||
this.selectedPosition.x, this.selectedPosition.y, this.layout))
|
||||
this.recordChange(before, this.state.profile + ":" + this.state.selected + ":scale")
|
||||
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
|
||||
@@ -1375,6 +1474,17 @@ export const OnroadLayoutPage = {
|
||||
this.recordChange(before)
|
||||
this.state.notice = ""
|
||||
},
|
||||
setWidgetToggle(field, value) {
|
||||
const flag = { bluetooth: 'bluetoothToggle', wifiName: 'wifiNameHeight' }[field]
|
||||
if (!this.editable || this.state.drag || this.state.layerDrag || !flag || !this.selectedWidget?.[flag]) return
|
||||
this.finishColorEdit()
|
||||
const before = clone(this.state.draft)
|
||||
this.selectedPosition[field] = value === 'On'
|
||||
Object.assign(this.selectedPosition, clampPlacement(this.limitProfile, this.state.selected,
|
||||
this.selectedPosition.x, this.selectedPosition.y, this.layout))
|
||||
this.recordChange(before)
|
||||
this.state.notice = ""
|
||||
},
|
||||
moveDrag(event) {
|
||||
const pending = this._pendingTouch
|
||||
if (pending?.pointerId === event.pointerId) {
|
||||
|
||||
@@ -13,6 +13,8 @@ STALE_NS = 2_500_000_000
|
||||
LATENCY_RECORD = "/dev/shm/jetlink/starpilot_latency.json"
|
||||
LATENCY_FRESH_S = 3.
|
||||
RUNNING = {'ready': 'ready', 'joining': 'connecting', 'retrying': 'connecting'}
|
||||
# progress codes (jetlink.openpilot.status.PROGRESS_CODES) while the big model is fetched or built
|
||||
BUILDING = ('downloading', 'download', 'upload', 'patch', 'parse', 'convert', 'compile', 'build')
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -21,6 +23,9 @@ class JetlinkStatus:
|
||||
state: str = 'off' # off, disconnected, connected, connecting, ready, active, unavailable
|
||||
latency_ms: float | None = None
|
||||
port: str | None = None # jetlink's port_state: 'connected' (host on the link), 'device' (plugged in), else None
|
||||
offer: bool = False # joined in modeld and ready: re-engage to switch
|
||||
building: bool = False # the picked model is downloading or building
|
||||
model: str = '' # active or selected big model name on the link
|
||||
|
||||
|
||||
def _write_latency(model, path) -> None:
|
||||
@@ -70,13 +75,18 @@ def read_status() -> JetlinkStatus:
|
||||
return JetlinkStatus() # a Chestnut is fitted
|
||||
device = 'iPhone' if status.mode == 'ios' else 'Computer'
|
||||
port = status.port_state if status.port_state in ('connected', 'device') else None
|
||||
raw_model = getattr(status, 'active_model', None) or getattr(status, 'model', None)
|
||||
model = raw_model if isinstance(raw_model, str) else ''
|
||||
if not status.present:
|
||||
return JetlinkStatus(device, 'disconnected', port=port)
|
||||
return JetlinkStatus(device, 'disconnected', port=port, model=model)
|
||||
if status.active:
|
||||
return JetlinkStatus(device, 'active', read_latency(), port)
|
||||
return JetlinkStatus(device, 'active', read_latency(), port, model=model)
|
||||
if status.reason:
|
||||
return JetlinkStatus(device, 'unavailable', port=port)
|
||||
return JetlinkStatus(device, RUNNING.get(status.running, 'ready' if status.ready else 'connected'), port=port)
|
||||
return JetlinkStatus(device, 'unavailable', port=port, model=model)
|
||||
progress = status.progress if isinstance(status.progress, dict) else {} # only while provisioning or joining
|
||||
return JetlinkStatus(device, RUNNING.get(status.running, 'ready' if status.ready else 'connected'), port=port,
|
||||
offer=status.running == 'ready', building=not status.ready and progress.get('code') in BUILDING,
|
||||
model=model)
|
||||
|
||||
|
||||
class JetlinkStatusFeed:
|
||||
|
||||
@@ -12,7 +12,8 @@ from openpilot.starpilot.models.jetlink_status import JetlinkStatus, JetlinkStat
|
||||
|
||||
|
||||
def status(**kw):
|
||||
base = {'enabled': True, 'mode': 'usb', 'present': True, 'port_state': 'connected', 'active': False, 'reason': None, 'running': None, 'ready': False}
|
||||
base = {'enabled': True, 'mode': 'usb', 'present': True, 'port_state': 'connected', 'active': False, 'reason': None, 'running': None, 'ready': False,
|
||||
'progress': None}
|
||||
return NS(**{**base, **kw})
|
||||
|
||||
|
||||
@@ -31,7 +32,10 @@ def test_off_reads_nothing_of_jetlink():
|
||||
|
||||
@pytest.mark.parametrize('kw,expected', [
|
||||
({'active': True, 'running': 'running'}, JetlinkStatus('Computer', 'active', 24.6, 'connected')),
|
||||
({'running': 'ready'}, JetlinkStatus('Computer', 'ready', port='connected')),
|
||||
({'running': 'ready'}, JetlinkStatus('Computer', 'ready', port='connected', offer=True)),
|
||||
({'running': None, 'ready': True}, JetlinkStatus('Computer', 'ready', port='connected')),
|
||||
({'progress': {'stage': 'build', 'frac': .4, 'code': 'build'}}, JetlinkStatus('Computer', 'connected', port='connected', building=True)),
|
||||
({'progress': {'stage': 'joining', 'frac': 0, 'code': 'connecting'}}, JetlinkStatus('Computer', 'connected', port='connected')),
|
||||
({'running': 'joining'}, JetlinkStatus('Computer', 'connecting', port='connected')),
|
||||
({'running': 'retrying'}, JetlinkStatus('Computer', 'connecting', port='connected')),
|
||||
({'running': None, 'ready': False}, JetlinkStatus('Computer', 'connected', port='connected')),
|
||||
@@ -40,6 +44,11 @@ def test_off_reads_nothing_of_jetlink():
|
||||
({'present': False, 'port_state': 'empty'}, JetlinkStatus('Computer', 'disconnected')),
|
||||
({'present': False, 'port_state': None}, JetlinkStatus('Computer', 'disconnected')),
|
||||
({'mode': 'ios', 'active': True}, JetlinkStatus('iPhone', 'active', 24.6, 'connected')),
|
||||
({'active': True, 'active_model': 'Cinque v3'}, JetlinkStatus('Computer', 'active', 24.6, 'connected', model='Cinque v3')),
|
||||
({'running': 'ready', 'model': 'ResFit', 'active_model': 'Cinque v3'},
|
||||
JetlinkStatus('Computer', 'ready', port='connected', offer=True, model='Cinque v3')),
|
||||
({'running': 'ready', 'model': 'ResFit', 'active_model': None},
|
||||
JetlinkStatus('Computer', 'ready', port='connected', offer=True, model='ResFit')),
|
||||
({'enabled': False}, JetlinkStatus()),
|
||||
])
|
||||
def test_states(kw, expected):
|
||||
@@ -83,10 +92,11 @@ def test_feed_polls_off_thread_expires_and_disables():
|
||||
|
||||
|
||||
def test_feed_stale_and_failed_reads_drop_latency_and_port():
|
||||
feed = JetlinkStatusFeed(read=lambda: JetlinkStatus('iPhone', 'active', 24.6, 'connected'))
|
||||
feed = JetlinkStatusFeed(read=lambda: JetlinkStatus('iPhone', 'active', 24.6, 'connected', model='Cinque v3'))
|
||||
feed._enabled = True
|
||||
feed.poll()
|
||||
assert feed.snapshot().port == 'connected'
|
||||
assert feed.snapshot().model == 'Cinque v3'
|
||||
feed._read_at = 0
|
||||
assert feed.snapshot() == JetlinkStatus('iPhone', 'unavailable')
|
||||
feed.read = lambda: 1 / 0
|
||||
|
||||
@@ -6,9 +6,11 @@ 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,
|
||||
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,
|
||||
STOPPED_TIMER_WIDGET, WEATHER_WIDGET, CEM_GAUGE_FRAME, CEM_GAUGE_INSET, MAP_MIN_SIZE, NAV_CARD_SIZE,
|
||||
SPEED_ALIGNMENTS, customization_metadata, validate_map_box, validate_widget_order)
|
||||
SPEED_ALIGNMENTS, customization_metadata, signal_size, valid_signal_scale,
|
||||
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
|
||||
from openpilot.starpilot.ui.onroad_customization import (SPEED_LAYOUT_V7, migrate_speed_layout, migrate_large_sign_layout, migrate_attached_actions_gap,
|
||||
@@ -36,12 +38,13 @@ NOW_PLAYING_WIDGET = 'now_playing'
|
||||
NOW_PLAYING_SIZE = (520, 96)
|
||||
NOW_PLAYING_SIZES = {'small': NOW_PLAYING_SIZE, 'big': (640, 264)}
|
||||
NOW_PLAYING_OPACITY = (0, 100, 85)
|
||||
JETLINK_SIZE = (420, 84)
|
||||
JETLINK_SIZE = (420, 100)
|
||||
JETLINK_OPACITY = (0, 100, 85)
|
||||
CARD_WIDGETS = {NOW_PLAYING_WIDGET: NOW_PLAYING_OPACITY, JETLINK_WIDGET: JETLINK_OPACITY}
|
||||
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, CAR_EXIT)
|
||||
PROJECTION_WIDGETS = (NAV_CARD, NAV_MAP, *DISPLAY_WIDGETS, STOPPED_TIMER_WIDGET, NOW_PLAYING_WIDGET, JETLINK_WIDGET, CAR_EXIT, 'following_distance')
|
||||
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,
|
||||
'following_distance')
|
||||
|
||||
|
||||
class ProjectionLayoutSource:
|
||||
@@ -82,6 +85,7 @@ def layout_metadata_for_viewport(viewport):
|
||||
widgets[MODE_WIDGET]['default']['x'] += (width - 1860) / 2
|
||||
widgets[CLOCK_WIDGET]['default']['x'] += (width - 1860) / 2
|
||||
widgets['steering_wheel']['default']['x'] += width - 1860
|
||||
widgets[SIGNAL_WIDGET]['default']['x'] += width - 1860
|
||||
widgets['driver_monitor']['default']['y'] += height - 1080
|
||||
widgets['following_distance']['default']['y'] += height - 1080
|
||||
x, y, w, h = maximum_footprint(30, 30, width - 60, height - 60, width)
|
||||
@@ -127,9 +131,9 @@ def layout_metadata_for_viewport(viewport):
|
||||
'collapseToggle': True, 'sizes': {name: list(size) for name, size in NOW_PLAYING_SIZES.items()},
|
||||
'default': {'x': width - 30 - NOW_PLAYING_SIZE[0], 'y': height - 30 - NOW_PLAYING_SIZE[1],
|
||||
'enabled': True, 'opacity': NOW_PLAYING_OPACITY[2], 'collapse': False, 'size': 'small'}}
|
||||
widgets[JETLINK_WIDGET] = {'label': 'Jetlink status', 'kind': JETLINK_WIDGET,
|
||||
widgets[JETLINK_WIDGET] = {'label': 'Big model', 'kind': JETLINK_WIDGET,
|
||||
'width': JETLINK_SIZE[0], 'height': JETLINK_SIZE[1], 'colors': {},
|
||||
'note': 'Shown while Jetlink is on: connection, device and host processing time. Opacity sets the card background.',
|
||||
'note': "Big or small model driving, and Jetlink's or the Chestnut's state (else Disconnected). Opacity sets the card background.",
|
||||
'opacity': {'min': JETLINK_OPACITY[0], 'max': JETLINK_OPACITY[1], 'default': JETLINK_OPACITY[2]},
|
||||
'default': {'x': 30, 'y': 650, 'enabled': False, 'opacity': JETLINK_OPACITY[2]}}
|
||||
exit_w, exit_h = CAR_EXIT_SIZE
|
||||
@@ -210,6 +214,8 @@ def now_playing_size(placement):
|
||||
def placement_size(key, widget, placement):
|
||||
if key == NOW_PLAYING_WIDGET:
|
||||
return now_playing_size(placement)
|
||||
if key == SIGNAL_WIDGET:
|
||||
return signal_size(placement)
|
||||
if key in DISPLAY_WIDGETS and placement.get('display') == 'icons':
|
||||
return FAVORITE_ICON_SIZE, FAVORITE_ICON_SIZE
|
||||
if widget.get('resizable'):
|
||||
@@ -283,6 +289,11 @@ def validate_layout_for_viewport(value, viewport, *, _legacy_geometry=False):
|
||||
if key == NOW_PLAYING_WIDGET and type(placement) is dict:
|
||||
placement.setdefault('collapse', False)
|
||||
placement.setdefault('size', 'small')
|
||||
if key == SIGNAL_WIDGET and type(placement) is dict:
|
||||
placement.setdefault('size', 'ring')
|
||||
placement.setdefault('scale', SIGNAL_SCALE_RANGE[2])
|
||||
placement.setdefault('bluetooth', True)
|
||||
placement.setdefault('wifiName', False)
|
||||
if key == 'driver_monitor' and type(placement) is dict and 'size' not in placement:
|
||||
for axis in ('x', 'y'):
|
||||
if type(placement.get(axis)) in (int, float):
|
||||
@@ -299,6 +310,7 @@ def validate_layout_for_viewport(value, viewport, *, _legacy_geometry=False):
|
||||
({'opacity', 'background'} if key in ACTION_WIDGETS else set()) |
|
||||
({'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()) |
|
||||
({'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:
|
||||
@@ -319,6 +331,14 @@ def validate_layout_for_viewport(value, viewport, *, _legacy_geometry=False):
|
||||
raise ValueError('Invalid now playing collapse setting')
|
||||
if key == NOW_PLAYING_WIDGET and (type(placement['size']) is not str or placement['size'] not in NOW_PLAYING_SIZES):
|
||||
raise ValueError('Invalid now playing size')
|
||||
if key == SIGNAL_WIDGET and (type(placement['size']) is not str or placement['size'] not in SIGNAL_SIZES):
|
||||
raise ValueError('Invalid signal style')
|
||||
if key == SIGNAL_WIDGET and not valid_signal_scale(placement):
|
||||
raise ValueError('Invalid signal scale')
|
||||
if key == SIGNAL_WIDGET and type(placement['bluetooth']) is not bool:
|
||||
raise ValueError('Invalid signal bluetooth setting')
|
||||
if key == SIGNAL_WIDGET and type(placement['wifiName']) is not bool:
|
||||
raise ValueError('Invalid signal Wi-Fi name setting')
|
||||
if key == CAR_EXIT and placement['opacity'] < CAR_EXIT_MIN_OPACITY:
|
||||
raise ValueError('Exit to car opacity must be at least 25%')
|
||||
if widget.get('resizable'):
|
||||
@@ -352,8 +372,8 @@ 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 == NOW_PLAYING_WIDGET:
|
||||
# A larger card size may overhang a saved spot; pull it back in.
|
||||
if key in (NOW_PLAYING_WIDGET, SIGNAL_WIDGET, JETLINK_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]):
|
||||
placement[axis] = min(placement[axis], bounds[axis] + bounds[extent] - dimension)
|
||||
|
||||
@@ -93,6 +93,7 @@ def native_dependencies():
|
||||
from openpilot.starpilot.system.starport.projection_now_playing import ProjectionNowPlayingFeed
|
||||
from openpilot.starpilot.system.starport.media_audio import music_control
|
||||
from openpilot.starpilot.models.jetlink_status import JetlinkStatusFeed
|
||||
from openpilot.starpilot.ui.onroad_jetlink import gpu_inputs
|
||||
|
||||
class ProjectionRoadCamera(AugmentedRoadView):
|
||||
"""Current native calibrated camera/model without stock action widgets."""
|
||||
@@ -151,7 +152,7 @@ def native_dependencies():
|
||||
pip_rect=Rect, pip_widgets=CAMERA_WIDGETS, placement=placement, widget_size=widget_size,
|
||||
alert=OnroadAlert, alert_size=AlertSize, map_overlay=live_overlay, map_feed=MapFeed,
|
||||
favorites=ProjectionFavorites, standby_logo=standby_logo, now_playing_feed=ProjectionNowPlayingFeed,
|
||||
now_playing_control=music_control, jetlink_feed=JetlinkStatusFeed)
|
||||
now_playing_control=music_control, jetlink_feed=JetlinkStatusFeed, gpu_inputs=gpu_inputs)
|
||||
|
||||
|
||||
class ProjectionOnroad:
|
||||
@@ -366,6 +367,8 @@ class ProjectionOnroad:
|
||||
placed = (self.customization or {}).get('widgets', {}).get('jetlink_status', {})
|
||||
self.jetlink_feed.set_enabled(bool(placed.get('enabled') and self.native.ui_state.started))
|
||||
self.onroad.jetlink_status.status = self.jetlink_feed.snapshot()
|
||||
if (gpu_inputs := getattr(self.native, 'gpu_inputs', None)) is not None:
|
||||
self.onroad.jetlink_status.gpu, self.onroad.jetlink_status.chestnut = gpu_inputs(self.native.ui_state)
|
||||
if self.favorites is not None:
|
||||
self.favorites.refresh()
|
||||
self.onroad.navigation_favorites.document = self.favorites.document
|
||||
|
||||
@@ -18,27 +18,38 @@ def _clock_ns() -> int:
|
||||
return time.clock_gettime_ns(boot) if boot is not None else time.monotonic_ns()
|
||||
|
||||
|
||||
def read_bluetooth_state() -> str:
|
||||
"""One BlueZ object listing: the adapter's power and whether any of its devices is connected."""
|
||||
def read_bluetooth_details() -> tuple[str, tuple[str, ...]]:
|
||||
"""One BlueZ object listing: adapter state ('off', 'on', 'connected') and connected device names."""
|
||||
try:
|
||||
result = subprocess.run(("busctl", "--system", "--timeout=1", "call", "org.bluez", "/", "org.freedesktop.DBus.ObjectManager",
|
||||
"GetManagedObjects", "--json=short"), capture_output=True, text=True, timeout=1.5, check=False)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return "off"
|
||||
return "off", ()
|
||||
if result.returncode != 0:
|
||||
return "off"
|
||||
return "off", ()
|
||||
try:
|
||||
objects = json.loads(result.stdout)["data"][0]
|
||||
|
||||
def prop(path, interface, name):
|
||||
return objects.get(path, {}).get(interface, {}).get(name, {}).get("data")
|
||||
if prop("/org/bluez/hci0", "org.bluez.Adapter1", "Powered") is not True:
|
||||
return "off"
|
||||
connected = any(path.startswith("/org/bluez/hci0/dev_") and prop(path, "org.bluez.Device1", "Connected") is True
|
||||
for path in objects)
|
||||
return "off", ()
|
||||
devices = []
|
||||
for path in objects:
|
||||
if path.startswith("/org/bluez/hci0/dev_") and prop(path, "org.bluez.Device1", "Connected") is True:
|
||||
name = prop(path, "org.bluez.Device1", "Name")
|
||||
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"
|
||||
devices.append(label)
|
||||
except (ValueError, KeyError, IndexError, TypeError, AttributeError):
|
||||
return "off"
|
||||
return "connected" if connected else "on"
|
||||
return "off", ()
|
||||
return ("connected", tuple(devices)) if devices else ("on", ())
|
||||
|
||||
|
||||
def read_bluetooth_state() -> str:
|
||||
"""One BlueZ object listing: the adapter's power and whether any of its devices is connected."""
|
||||
return read_bluetooth_details()[0]
|
||||
|
||||
|
||||
class BluetoothStatusSource:
|
||||
|
||||
@@ -237,7 +237,9 @@ class _Canvas:
|
||||
self.view.map_layer = self._render_map
|
||||
from openpilot.starpilot.models.jetlink_status import JetlinkStatus
|
||||
from openpilot.starpilot.ui.onroad_jetlink import JetlinkStatusWidget
|
||||
cast(JetlinkStatusWidget, self.view.jetlink_status).status = JetlinkStatus('iPhone', 'active', 24.6, 'connected')
|
||||
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.monitor = _DriverMonitorArt(profile)
|
||||
self.view.driver_monitor_layer = self._render_driver_monitor
|
||||
self.view.preview_pip_layer = self._render_preview_pip
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
"""Cellular and Wi-Fi strength read together; deviceState only carries the link in use. Read-only."""
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from typing import NamedTuple
|
||||
|
||||
TECH = {'nr': '5G', 'lte': 'LTE', 'utran': '3G', 'umts': '3G', 'gsm': '2G'}
|
||||
WANTED_S = 5.
|
||||
STALE_S = 10.
|
||||
|
||||
|
||||
class Signal(NamedTuple):
|
||||
cell: int | None = None # 1 to 4, None when not connected
|
||||
wifi: int | None = None
|
||||
active: str | None = None # 'cell' or 'wifi': the link carrying data
|
||||
tech: str = 'LTE'
|
||||
bt: str = 'off' # 'off', 'on', or 'connected'
|
||||
bt_devices: tuple[str, ...] = ()
|
||||
wifi_name: str = '' # the joined network's SSID, empty when unknown
|
||||
|
||||
|
||||
def ssid_text(value: str) -> str:
|
||||
"""Undoes wpa_supplicant's escaping (\\xNN, \\n, \\\\ and the like) and decodes the SSID bytes as UTF-8."""
|
||||
def unescape(match):
|
||||
code = match[1]
|
||||
return bytes([int(code[1:], 16)]) if code[:1] == b'x' else {b'n': b'\n', b'r': b'\r', b't': b'\t', b'e': b'\x1b'}.get(code, code)
|
||||
return re.sub(rb'\\(x[0-9a-fA-F]{2}|.)', unescape, value.encode('utf-8', 'replace')).decode('utf-8', 'replace').strip()
|
||||
|
||||
|
||||
def read_signal() -> Signal:
|
||||
from openpilot.common.hardware.comma.hardware import HardwareComma, NetworkType, get_default_route_iface, wpa_supplicant_cmd
|
||||
from openpilot.starpilot.ui.bluetooth_status import read_bluetooth_details
|
||||
hardware = HardwareComma()
|
||||
cell = active = iface = None
|
||||
wifi_name = ''
|
||||
tech = 'LTE'
|
||||
modem = hardware.get_modem_state()
|
||||
quality = modem.get('signal_quality', 0)
|
||||
if modem.get('connected') and type(quality) in (int, float):
|
||||
cell = int(hardware.parse_strength(quality))
|
||||
tech = TECH.get(modem.get('network_type'), tech)
|
||||
wifi = int(hardware.get_network_strength(NetworkType.wifi)) or None
|
||||
if wifi:
|
||||
try:
|
||||
status = wpa_supplicant_cmd('STATUS')
|
||||
except OSError:
|
||||
status = {}
|
||||
if status.get('wpa_state') == 'COMPLETED':
|
||||
wifi_name = ssid_text(status.get('ssid', ''))[:64]
|
||||
try:
|
||||
iface = get_default_route_iface()
|
||||
except (OSError, ValueError, IndexError):
|
||||
pass
|
||||
bt, bt_devices = read_bluetooth_details()
|
||||
if iface and iface.startswith('wlan'):
|
||||
active = 'wifi' if wifi else None
|
||||
elif cell and not (iface and iface.startswith('eth')):
|
||||
active = 'cell'
|
||||
return Signal(cell, wifi, active, tech, bt, bt_devices, wifi_name)
|
||||
|
||||
|
||||
class SignalFeed:
|
||||
"""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):
|
||||
try:
|
||||
signal = self.read()
|
||||
except Exception:
|
||||
signal = Signal()
|
||||
with self._lock:
|
||||
self._signal, self._read_at = signal, time.monotonic()
|
||||
|
||||
def snapshot(self) -> Signal:
|
||||
now = time.monotonic()
|
||||
with self._lock:
|
||||
self._wanted_at = now
|
||||
signal, fresh = self._signal, now - self._read_at <= STALE_S
|
||||
if self._thread is None:
|
||||
self._thread = threading.Thread(target=self._run, name='network-signal', daemon=True)
|
||||
self._thread.start()
|
||||
return signal if fresh else Signal()
|
||||
|
||||
def _run(self):
|
||||
while not self._stop.is_set():
|
||||
with self._lock:
|
||||
wanted = time.monotonic() - self._wanted_at <= WANTED_S
|
||||
if wanted:
|
||||
self.poll()
|
||||
self._stop.wait(self.period)
|
||||
|
||||
def close(self):
|
||||
self._stop.set()
|
||||
if self._thread is not None:
|
||||
self._thread.join(timeout=2)
|
||||
@@ -163,6 +163,8 @@ class OnroadView:
|
||||
self.steering_wheel = SteeringWheelWidget(asset_directory)
|
||||
from openpilot.starpilot.ui.onroad_jetlink import JetlinkStatusWidget
|
||||
self.jetlink_status = JetlinkStatusWidget(fonts)
|
||||
from openpilot.starpilot.ui.onroad_signal import SignalWidget
|
||||
self.network_signal = SignalWidget(fonts)
|
||||
else:
|
||||
self.compact_hud = CompactHudRenderer(fonts, asset_directory)
|
||||
self.compact_sidebar = MiciSidebarWidgets(fonts)
|
||||
@@ -322,6 +324,9 @@ class OnroadView:
|
||||
if "jetlink_status" in state.customization["layouts"]["large"]:
|
||||
if jetlink := getattr(self, "jetlink_status", None):
|
||||
submit("jetlink_status", lambda: jetlink.render(state))
|
||||
if "network_signal" in state.customization["layouts"]["large"]:
|
||||
if signal := getattr(self, "network_signal", None):
|
||||
submit("network_signal", lambda: signal.render(state))
|
||||
if "car_exit" in state.customization["layouts"]["large"]:
|
||||
if exit_layer := getattr(self, "projection_exit_layer", None):
|
||||
submit("car_exit", lambda: exit_layer(state))
|
||||
@@ -443,6 +448,8 @@ class OnroadView:
|
||||
now_playing.render(state)
|
||||
if jetlink := getattr(self, "jetlink_status", None):
|
||||
jetlink.render(state)
|
||||
if signal := getattr(self, "network_signal", None):
|
||||
signal.render(state)
|
||||
self._driving_mode(state, right_shift / 2)
|
||||
self._clock(state, right_shift / 2)
|
||||
self._weather(state, right_shift / 2)
|
||||
@@ -603,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()
|
||||
|
||||
@@ -6,7 +6,7 @@ import json
|
||||
import math
|
||||
import re
|
||||
from functools import lru_cache
|
||||
from typing import Any, NotRequired, TypedDict
|
||||
from typing import Any, NotRequired, TypedDict, cast
|
||||
|
||||
from openpilot.starpilot.saved_source import read_saved
|
||||
from openpilot.starpilot.ui.onroad_torque_geometry import maximum_footprint
|
||||
@@ -39,10 +39,13 @@ class WidgetPlacement(TypedDict):
|
||||
x: float
|
||||
y: float
|
||||
enabled: bool
|
||||
size: NotRequired[int]
|
||||
size: NotRequired[int | str]
|
||||
width: NotRequired[int]
|
||||
height: NotRequired[int]
|
||||
opacity: NotRequired[int]
|
||||
bluetooth: NotRequired[bool]
|
||||
wifiName: NotRequired[bool]
|
||||
scale: NotRequired[int]
|
||||
|
||||
|
||||
class Widget(TypedDict):
|
||||
@@ -64,6 +67,10 @@ class Widget(TypedDict):
|
||||
confirmationObstacle: NotRequired[Bounds]
|
||||
box: NotRequired[dict[str, int]]
|
||||
opacity: NotRequired[dict[str, int]]
|
||||
sizes: NotRequired[dict[str, list[int]]]
|
||||
scale: NotRequired[dict[str, int]]
|
||||
bluetoothToggle: NotRequired[bool]
|
||||
wifiNameHeight: NotRequired[int]
|
||||
anchorShift: NotRequired[float]
|
||||
expandable: NotRequired[bool]
|
||||
hidden: NotRequired[bool]
|
||||
@@ -207,13 +214,52 @@ _nav_map["note"] = ("Road lines and your route over the camera. Drag the corner
|
||||
PROFILES["large"]["widgets"][NAV_MAP_WIDGET] = _nav_map
|
||||
|
||||
JETLINK_WIDGET = "jetlink_status"
|
||||
JETLINK_SIZE = (420, 84)
|
||||
JETLINK_SIZE = (420, 100)
|
||||
JETLINK_OPACITY = (0, 100, 85) # percent: min, max, default
|
||||
_jetlink = _widget("Jetlink status", JETLINK_WIDGET, *JETLINK_SIZE, 30, 650)
|
||||
_jetlink = _widget("Big model", JETLINK_WIDGET, *JETLINK_SIZE, 30, 650)
|
||||
_jetlink["default"].update(enabled=False, opacity=JETLINK_OPACITY[2])
|
||||
_jetlink["opacity"] = dict(zip(("min", "max", "default"), JETLINK_OPACITY, strict=True))
|
||||
_jetlink["note"] = "Shown while Jetlink is on: connection, device and host processing time. Opacity sets the card background."
|
||||
_jetlink["note"] = "Big or small model driving, and Jetlink's or the Chestnut's state (else Disconnected). Opacity sets the card background."
|
||||
PROFILES["large"]["widgets"][JETLINK_WIDGET] = _jetlink
|
||||
|
||||
SIGNAL_WIDGET = "network_signal"
|
||||
SIGNAL_SCALE = 120 / 88 # drawn on an 88 px grid
|
||||
SIGNAL_GRIDS = {"ring": (112, 140), "horizontal": (268, 112), "vertical": (112, 196)}
|
||||
SIGNAL_SIZES = {style: (round(w * SIGNAL_SCALE), round(h * SIGNAL_SCALE)) for style, (w, h) in SIGNAL_GRIDS.items()}
|
||||
SIGNAL_LEGACY_GRIDS = {"ring": (88, 88), "horizontal": (268, 84), "vertical": (96, 160)} # before the Bluetooth row
|
||||
SIGNAL_SIZE = SIGNAL_SIZES["ring"]
|
||||
SIGNAL_WIFI_NAME_GRID = 22 # header row for the Wi-Fi network name, on the 88 px grid
|
||||
SIGNAL_WIFI_NAME_HEIGHT = round(SIGNAL_WIFI_NAME_GRID * SIGNAL_SCALE)
|
||||
SIGNAL_OPACITY = (0, 100, 85) # percent: min, max, default
|
||||
SIGNAL_SCALE_RANGE = (30, 100, 100) # percent of the style's size: min, max, default
|
||||
_signal = _widget("Connections", SIGNAL_WIDGET, *SIGNAL_SIZE, 1624, 290)
|
||||
_signal["default"].update(enabled=False, opacity=SIGNAL_OPACITY[2], size="ring", scale=SIGNAL_SCALE_RANGE[2], bluetooth=True,
|
||||
wifiName=False)
|
||||
_signal["opacity"] = dict(zip(("min", "max", "default"), SIGNAL_OPACITY, strict=True))
|
||||
_signal["scale"] = dict(zip(("min", "max", "default"), SIGNAL_SCALE_RANGE, strict=True))
|
||||
_signal["sizes"] = {style: list(size) for style, size in SIGNAL_SIZES.items()}
|
||||
_signal["bluetoothToggle"] = True
|
||||
_signal["wifiNameHeight"] = SIGNAL_WIFI_NAME_HEIGHT
|
||||
|
||||
|
||||
def valid_signal_scale(placement: dict) -> bool:
|
||||
return type(placement.get("scale")) is int and SIGNAL_SCALE_RANGE[0] <= placement["scale"] <= SIGNAL_SCALE_RANGE[1]
|
||||
|
||||
|
||||
def signal_scale(placement: dict | None) -> float:
|
||||
"""The chosen fraction of the style's full size; a missing or bad value draws full size."""
|
||||
return placement["scale"] / 100 if placement and valid_signal_scale(placement) else 1.
|
||||
|
||||
|
||||
def signal_size(placement: dict | None) -> tuple[int, int]:
|
||||
width, height = SIGNAL_SIZES.get((placement or {}).get("size"), SIGNAL_SIZE)
|
||||
if (placement or {}).get("wifiName") is True:
|
||||
height += SIGNAL_WIFI_NAME_HEIGHT
|
||||
scale = signal_scale(placement)
|
||||
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
|
||||
# Restore the Dom road graphic in the gap between the speed card and main speed.
|
||||
# Center the road gauge above the driver monitor, below the speed-limit controls.
|
||||
# It has no background and appears only with a current selected source.
|
||||
@@ -240,7 +286,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, "rear_fog"})
|
||||
NAV_CARD_WIDGET, NAV_MAP_WIDGET, JETLINK_WIDGET, SIGNAL_WIDGET, "rear_fog"})
|
||||
|
||||
# The torque arc grows when the developer sidebar closes; protect both road widths.
|
||||
_torque = PROFILES['large']['widgets']['torque_bar']
|
||||
@@ -289,11 +335,25 @@ WIDGET_COLORS = {
|
||||
}
|
||||
|
||||
|
||||
def _fit_legacy_signal(placement: dict, bounds: Bounds) -> None:
|
||||
"""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
|
||||
old = [round(round(side * SIGNAL_SCALE) * placement["scale"] / 100) for side in grid]
|
||||
new = signal_size(placement)
|
||||
axes = (("x", "width"), ("y", "height"))
|
||||
if all(type(placement.get(axis)) in (int, float) and math.isfinite(placement[axis]) and
|
||||
bounds[axis] <= placement[axis] <= bounds[axis] + bounds[extent] - size for (axis, extent), size in zip(axes, old, strict=True)):
|
||||
for (axis, extent), size in zip(axes, new, strict=True):
|
||||
placement[axis] = max(bounds[axis], min(placement[axis], bounds[axis] + bounds[extent] - size))
|
||||
|
||||
|
||||
# Back-to-front order used when a layout first opts into custom layers.
|
||||
DEFAULT_WIDGET_ORDER = {
|
||||
"large": (NAV_MAP_WIDGET, "cruise_limits", "speed_limit_actions", 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, "rear_fog", "pip_left", "pip_right"),
|
||||
STOPPED_TIMER_WIDGET, NAV_CARD_WIDGET, JETLINK_WIDGET, SIGNAL_WIDGET, "rear_fog", "pip_left", "pip_right"),
|
||||
"compact": ("speed_limit", "max_speed", "steering_wheel", "torque_bar",
|
||||
"speed_limit_actions", "driver_monitor", *RAIL_WIDGETS, MODE_WIDGET, CLOCK_WIDGET, WEATHER_WIDGET,
|
||||
STOPPED_TIMER_WIDGET, NAV_CARD_WIDGET, "rear_fog", "pip_left", "pip_right"),
|
||||
@@ -654,15 +714,33 @@ def validate_document(value):
|
||||
raise ValueError("Invalid widget IDs")
|
||||
for key, widget in data["widgets"].items():
|
||||
placement = layout[key]
|
||||
legacy_signal = key == SIGNAL_WIDGET and type(placement) is dict and 'bluetooth' not in placement
|
||||
if key == SIGNAL_WIDGET and type(placement) is dict and any(field not in placement for field in ('size', 'scale', 'bluetooth', 'wifiName')):
|
||||
placement = dict(placement)
|
||||
placement.setdefault('size', 'ring')
|
||||
placement.setdefault('scale', SIGNAL_SCALE_RANGE[2])
|
||||
placement.setdefault('bluetooth', True)
|
||||
placement.setdefault('wifiName', False)
|
||||
layout[key] = placement
|
||||
bounds = widget_bounds(profile, key)
|
||||
if value['version'] < 8 and key in SPEED_LAYOUT_V7[profile]:
|
||||
bounds = data['bounds']
|
||||
if legacy_signal:
|
||||
_fit_legacy_signal(placement, bounds)
|
||||
if (key == JETLINK_WIDGET and type(placement) is dict and type(placement.get('y')) in (int, float) and
|
||||
math.isfinite(placement['y']) and
|
||||
bounds['y'] + bounds['height'] - JETLINK_SIZE[1] < placement['y'] <= bounds['y'] + bounds['height'] - 84):
|
||||
placement['y'] = bounds['y'] + bounds['height'] - JETLINK_SIZE[1]
|
||||
scalable = key == 'driver_monitor' or key == 'steering_wheel' and value['version'] >= 4
|
||||
expected = {"x", "y", "enabled"} | ({"size"} if scalable else set())
|
||||
if widget.get("box"):
|
||||
expected |= {"width", "height", "opacity"}
|
||||
elif widget.get("opacity"):
|
||||
expected.add("opacity")
|
||||
if widget.get("sizes"):
|
||||
expected.add("size")
|
||||
if key == SIGNAL_WIDGET:
|
||||
expected |= {"scale", "bluetooth", "wifiName"}
|
||||
if type(placement) is not dict or set(placement) != expected or type(placement["enabled"]) is not bool:
|
||||
raise ValueError("Invalid widget placement")
|
||||
if widget.get("box"):
|
||||
@@ -671,12 +749,20 @@ def validate_document(value):
|
||||
low, high = widget["opacity"]["min"], widget["opacity"]["max"]
|
||||
if type(placement["opacity"]) is not int or not low <= placement["opacity"] <= high:
|
||||
raise ValueError("Invalid widget opacity")
|
||||
if widget.get("sizes") and (type(placement["size"]) is not str or placement["size"] not in widget["sizes"]):
|
||||
raise ValueError("Invalid widget style")
|
||||
if key == SIGNAL_WIDGET and not valid_signal_scale(placement):
|
||||
raise ValueError("Invalid widget scale")
|
||||
if key == SIGNAL_WIDGET and type(placement["bluetooth"]) is not bool:
|
||||
raise ValueError("Invalid widget bluetooth setting")
|
||||
if key == SIGNAL_WIDGET and type(placement["wifiName"]) is not bool:
|
||||
raise ValueError("Invalid widget Wi-Fi name setting")
|
||||
size = WHEEL_SIZES[profile][1]
|
||||
if scalable:
|
||||
size = placement["size"]
|
||||
minimum, _, maximum = WIDGET_SIZES[key][profile]
|
||||
if type(size) is not int or not minimum <= size <= maximum:
|
||||
if type(placement["size"]) is not int or not minimum <= cast(int, placement["size"]) <= maximum:
|
||||
raise ValueError("Invalid widget size")
|
||||
size = cast(int, placement["size"])
|
||||
# Only a gauge the saved layout actually placed moves; one filled in from defaults is already in the new box.
|
||||
saved_layout = value.get("layouts", {}).get(profile) if type(value.get("layouts")) is dict else None
|
||||
old_gauge = key == CEM_GAUGE_WIDGET and value["version"] < 7 and type(saved_layout) is dict and key in saved_layout
|
||||
@@ -702,7 +788,9 @@ def validate_document(value):
|
||||
if not current_default:
|
||||
dimensions = (576, 148) if profile == 'large' else (348, 54)
|
||||
dimension = (dimensions[0 if axis == 'x' else 1] if dimensions else
|
||||
size if key in WIDGET_SIZES else placement[extent] if widget.get("box") else widget[extent])
|
||||
size if key in WIDGET_SIZES else placement[extent] if widget.get("box") else
|
||||
signal_size(placement)[0 if axis == 'x' else 1] if key == SIGNAL_WIDGET else
|
||||
widget["sizes"][str(placement["size"])][0 if axis == 'x' else 1] if widget.get("sizes") else widget[extent])
|
||||
if old_gauge:
|
||||
dimension = CEM_GAUGE_FRAME[0 if axis == 'x' else 1]
|
||||
if type(number) not in (int, float) or not math.isfinite(number) or not bounds[axis] <= number <= bounds[axis] + bounds[extent] - dimension:
|
||||
@@ -851,6 +939,8 @@ def widget_size(document, profile, widget):
|
||||
return default["width"], default["height"] + sources_extent(document)
|
||||
if default.get("box"):
|
||||
return position["width"], position["height"]
|
||||
if widget == SIGNAL_WIDGET:
|
||||
return signal_size(position)
|
||||
return (position.get("size", WIDGET_SIZES[widget][str(profile)][1]),) * 2 if widget in WIDGET_SIZES else (default["width"], default["height"])
|
||||
|
||||
|
||||
|
||||
@@ -1,25 +1,168 @@
|
||||
"""Jetlink status card shared by the native and Android Auto screens."""
|
||||
"""Big model card for native and Android Auto screens."""
|
||||
import re
|
||||
import time
|
||||
from typing import NamedTuple
|
||||
|
||||
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.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
|
||||
from openpilot.starpilot.ui.presentation import FontRole
|
||||
|
||||
LABELS = {'active': 'Link up', 'connected': 'Host connected', 'ready': 'Ready to switch',
|
||||
'connecting': 'Connecting', 'disconnected': 'Disconnected', 'unavailable': 'Unavailable'}
|
||||
GREEN = rl.Color(70, 200, 110, 255)
|
||||
ORANGE = rl.Color(255, 150, 60, 255)
|
||||
ACCENT = rl.Color(199, 174, 247, 255)
|
||||
GRAY = rl.Color(140, 136, 152, 255)
|
||||
TEXT = rl.Color(245, 242, 252, 255)
|
||||
MUTED = rl.Color(184, 178, 200, 255)
|
||||
DOT = {'active': GREEN, 'ready': GREEN, 'unavailable': ORANGE, 'disconnected': GRAY}
|
||||
MUTED = rl.Color(214, 210, 224, 255)
|
||||
BIG, SMALL = 'Big model', 'Small model'
|
||||
# 20 Hz frames: a host this close to 50 ms is about to fall behind
|
||||
SLOW_MS = 40.
|
||||
SCROLL_SPEED = 40
|
||||
SCROLL_GAP = 60
|
||||
SCROLL_PAUSE = 2.0
|
||||
MODEL_TTL = 1.0
|
||||
_TRAILING_DATE = re.compile(r' \([A-Za-z]+ \d{1,2}, \d{4}\)$')
|
||||
ABBREVIATIONS = (
|
||||
('Regret Driven Framework', 'RDF'),
|
||||
('Terrific Super Fantastic', 'TSF'),
|
||||
('Vegetarian-Filet-O-Fish', 'V-Filet-O-Fish'),
|
||||
)
|
||||
JETLINK_DETAIL = {'ready': ('Jetlink ready', ACCENT), 'connecting': ('Jetlink connecting', ACCENT),
|
||||
'connected': ('Jetlink connected', ACCENT), 'disconnected': ('Jetlink offline', GRAY),
|
||||
'unavailable': ('Jetlink error', ORANGE)}
|
||||
CHESTNUT_DETAIL = {'loading': ('Chestnut loading', ACCENT), 'ready': ('Chestnut ready', ACCENT),
|
||||
'uncompiled': ('Chestnut not built', ACCENT)}
|
||||
|
||||
_model_cache: tuple[float, tuple[str, str]] | None = None
|
||||
|
||||
|
||||
def abbreviate_model_name(name: str) -> str:
|
||||
"""Normalize and shorten catalog/Jetlink model names for the ASCII bitmap atlas and 420px card."""
|
||||
if '/' in name:
|
||||
return ' / '.join(part for p in name.split('/') if (part := abbreviate_model_name(p)))
|
||||
text = model_display_text(name)
|
||||
text = _TRAILING_DATE.sub('', text)
|
||||
for old in ('•', '·', '—', '–'):
|
||||
text = text.replace(old, '-')
|
||||
if text.endswith(' Model'):
|
||||
text = text[:-6].rstrip()
|
||||
for full, short in ABBREVIATIONS:
|
||||
text = text.replace(full, short)
|
||||
return text.strip()
|
||||
|
||||
|
||||
def scroll_offset(text_width: float, width: float, seconds: float) -> float:
|
||||
"""Pause, then scroll long text until its repeat reaches the start."""
|
||||
if text_width <= width:
|
||||
return 0.0
|
||||
travel = text_width + SCROLL_GAP
|
||||
elapsed = max(0.0, seconds)
|
||||
return min(travel, max(0.0, elapsed % (SCROLL_PAUSE + travel / SCROLL_SPEED) - SCROLL_PAUSE) * SCROLL_SPEED)
|
||||
|
||||
|
||||
def _entry_name(entries: dict, model_id: str, variant: ModelVariant | None = None) -> str:
|
||||
if not model_id:
|
||||
return ''
|
||||
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) 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]
|
||||
try:
|
||||
result = _read_model_names()
|
||||
except Exception:
|
||||
result = ('', '')
|
||||
_model_cache = (ts, result)
|
||||
return result
|
||||
|
||||
|
||||
class Card(NamedTuple):
|
||||
title: str
|
||||
detail: str
|
||||
dot: rl.Color
|
||||
latency_ms: float | None = None
|
||||
|
||||
@property
|
||||
def tier(self) -> str:
|
||||
is_green = self.dot is GREEN or (self.dot.r, self.dot.g, self.dot.b) == (GREEN.r, GREEN.g, GREEN.b)
|
||||
return 'BIG' if is_green and self.detail in ('Jetlink', 'Chestnut') else 'SMALL'
|
||||
|
||||
|
||||
def big_model_card(jetlink: JetlinkStatus, gpu: str | None = None, chestnut: bool = False,
|
||||
*, small: str = '', big: str = '') -> Card:
|
||||
"""`gpu` is UIState.chestnut_state's value or None; `chestnut` is whether one is fitted."""
|
||||
small_name = abbreviate_model_name(small) or SMALL
|
||||
jetlink_big = abbreviate_model_name(jetlink.model or big) or BIG
|
||||
chestnut_big = abbreviate_model_name(big) or BIG
|
||||
if jetlink.state != 'off':
|
||||
if jetlink.state == 'active':
|
||||
return Card(jetlink_big, 'Jetlink', GREEN, jetlink.latency_ms)
|
||||
if jetlink.offer:
|
||||
return Card(small_name, 'Re-engage to switch', ORANGE if gpu == 'failed' else ACCENT)
|
||||
if gpu == 'failed' and jetlink.state not in ('disconnected', 'unavailable'):
|
||||
return Card(small_name, 'Fell back', ORANGE)
|
||||
if jetlink.state == 'connected' and jetlink.building:
|
||||
return Card(small_name, 'Jetlink building', ACCENT)
|
||||
return Card(small_name, *JETLINK_DETAIL.get(jetlink.state, JETLINK_DETAIL['unavailable']))
|
||||
if not chestnut:
|
||||
return Card(small_name, '', GREEN)
|
||||
if gpu == 'active':
|
||||
return Card(chestnut_big, 'Chestnut', GREEN)
|
||||
if gpu == 'failed':
|
||||
return Card(small_name, 'Fell back', ORANGE)
|
||||
return Card(small_name, *CHESTNUT_DETAIL.get(gpu, ('Chestnut', ACCENT)))
|
||||
|
||||
|
||||
def gpu_inputs(ui) -> tuple[str | None, bool]:
|
||||
"""(UIState.chestnut_state's value, a Chestnut is fitted) for big_model_card."""
|
||||
if getattr(ui, 'projection_read_only', False):
|
||||
ui._update_chestnut_state()
|
||||
return ui.chestnut_state.value, bool(ui.sm["deviceState"].chestnutPresent)
|
||||
|
||||
|
||||
class JetlinkStatusWidget:
|
||||
def __init__(self, fonts):
|
||||
def __init__(self, fonts, ticks=time.monotonic, models=local_model_names):
|
||||
self.fonts = fonts
|
||||
self.ticks = ticks
|
||||
self.models = models
|
||||
self.status = JetlinkStatus()
|
||||
self.gpu: str | None = None
|
||||
self.chestnut = False
|
||||
self.small = ''
|
||||
self.big = ''
|
||||
self._scroll: tuple[str, float] | None = None
|
||||
|
||||
def _fit(self, text, role, size, width):
|
||||
measured = self.fonts.measure(text, role, size)
|
||||
@@ -27,25 +170,51 @@ class JetlinkStatusWidget:
|
||||
|
||||
def render(self, state):
|
||||
placed = state.customization['layouts']['large'].get(JETLINK_WIDGET)
|
||||
status = self.status
|
||||
if not placed or not placed['enabled'] or status.state == 'off' or state.alert.size != 'none':
|
||||
if not placed or not placed['enabled'] or state.alert.size != 'none':
|
||||
return
|
||||
small, big = (self.small, self.big) if (self.small or self.big) else self.models()
|
||||
card = big_model_card(self.status, self.gpu, self.chestnut, small=small, big=big)
|
||||
rect = rl.Rectangle(placed['x'], placed['y'], *JETLINK_SIZE)
|
||||
h = rect.height
|
||||
rl.draw_rectangle_rounded(rect, 1.0, 16, rl.Color(15, 13, 23, round(235 * placed.get('opacity', 85) / 100)))
|
||||
rl.draw_circle_v(rl.Vector2(rect.x + h / 2, rect.y + h / 2), 9, DOT.get(status.state, ACCENT))
|
||||
right = rect.x + rect.width - 30
|
||||
if status.state == 'active' and status.latency_ms is not None:
|
||||
value, unit = f'{status.latency_ms:.1f}', 'ms'
|
||||
unit_w = self.fonts.measure(unit, FontRole.NORMAL, 22).width
|
||||
value_w = self.fonts.measure(value, FontRole.SEMI_BOLD, 34).width
|
||||
self.fonts.draw(unit, FontRole.NORMAL, 22, right - unit_w, rect.y + h / 2 - 6, MUTED)
|
||||
right -= unit_w + 8
|
||||
self.fonts.draw(value, FontRole.SEMI_BOLD, 34, right - value_w, rect.y + h / 2 - 18, TEXT)
|
||||
right -= value_w + 16
|
||||
left = rect.x + h - 6
|
||||
width = right - left
|
||||
title = LABELS.get(status.state, 'Unavailable')
|
||||
detail = f'Jetlink • {status.device}' if status.device else 'Jetlink'
|
||||
self.fonts.draw(title, FontRole.SEMI_BOLD, self._fit(title, FontRole.SEMI_BOLD, 28, width), left, rect.y + 12, TEXT)
|
||||
self.fonts.draw(detail, FontRole.NORMAL, self._fit(detail, FontRole.NORMAL, 22, width), left, rect.y + 46, MUTED)
|
||||
rl.draw_circle_v(rl.Vector2(rect.x + 40, rect.y + 30), 7.5, card.dot)
|
||||
right = rect.x + rect.width - 32
|
||||
if card.latency_ms is not None:
|
||||
value, unit = f'{card.latency_ms:.1f}', 'ms'
|
||||
unit_w = self.fonts.measure(unit, FontRole.NORMAL, 18).width
|
||||
value_w = self.fonts.measure(value, FontRole.SEMI_BOLD, 24).width
|
||||
self.fonts.draw(unit, FontRole.NORMAL, 18, right - unit_w, rect.y + 18, MUTED)
|
||||
right -= unit_w + 6
|
||||
self.fonts.draw(value, FontRole.SEMI_BOLD, 24, right - value_w, rect.y + 13,
|
||||
ORANGE if card.latency_ms >= SLOW_MS else TEXT)
|
||||
right -= value_w + 12
|
||||
tier_x = rect.x + 58
|
||||
if not card.detail:
|
||||
self.fonts.draw('DRIVING MODEL', FontRole.SEMI_BOLD, 20, tier_x, rect.y + 17, MUTED)
|
||||
else:
|
||||
tier = card.tier
|
||||
tier_w = self.fonts.measure(tier, FontRole.SEMI_BOLD, 20).width
|
||||
self.fonts.draw(tier, FontRole.SEMI_BOLD, 20, tier_x, rect.y + 17, MUTED)
|
||||
dot_x = tier_x + tier_w + 10
|
||||
rl.draw_circle_v(rl.Vector2(dot_x, rect.y + 30), 2.8, MUTED)
|
||||
detail_x = dot_x + 10
|
||||
detail = card.detail.upper()
|
||||
detail_size = self._fit(detail, FontRole.SEMI_BOLD, 20, max(40, right - detail_x))
|
||||
self.fonts.draw(detail, FontRole.SEMI_BOLD, detail_size, detail_x, rect.y + 17, MUTED)
|
||||
left = rect.x + 32
|
||||
width = rect.width - 64
|
||||
title_w = self.fonts.measure(card.title, FontRole.SEMI_BOLD, 28).width
|
||||
if title_w <= width:
|
||||
self._scroll = None
|
||||
self.fonts.draw(card.title, FontRole.SEMI_BOLD, 28, left, rect.y + 47, TEXT)
|
||||
return
|
||||
now = self.ticks()
|
||||
if self._scroll is None or self._scroll[0] != card.title:
|
||||
self._scroll = (card.title, now)
|
||||
offset = scroll_offset(title_w, width, now - self._scroll[1])
|
||||
clip.begin_scissor_mode(left, rect.y + 45, width, 44)
|
||||
try:
|
||||
for start in (left - offset, left - offset + title_w + SCROLL_GAP):
|
||||
if start < left + width:
|
||||
self.fonts.draw(card.title, FontRole.SEMI_BOLD, 28, start, rect.y + 47, TEXT)
|
||||
finally:
|
||||
clip.end_scissor_mode()
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"""Keeps Jetlink's status polled for the native large screen only while its widget is showing."""
|
||||
"""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
|
||||
from openpilot.starpilot.ui.onroad_jetlink import gpu_inputs
|
||||
from openpilot.system.ui.lib.application import gui_app
|
||||
|
||||
|
||||
@@ -28,6 +29,7 @@ class NativeJetlinkLayer:
|
||||
return
|
||||
self.pending = state
|
||||
self.widget.status = self.feed.snapshot()
|
||||
self.widget.gpu, self.widget.chestnut = gpu_inputs(self.ui)
|
||||
self.widget.render(state)
|
||||
|
||||
def close(self):
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
"""All connections: cellular and Wi-Fi strength plus Bluetooth status and device name."""
|
||||
from openpilot.starpilot.ui.raylib import rl
|
||||
|
||||
from openpilot.starpilot.ui.network_signal import Signal, SignalFeed
|
||||
from openpilot.starpilot.ui.onroad_customization import SIGNAL_GRIDS, SIGNAL_SCALE, SIGNAL_WIDGET, SIGNAL_WIFI_NAME_GRID, signal_scale
|
||||
from openpilot.starpilot.ui.presentation import FontRole
|
||||
|
||||
ACCENT = rl.Color(164, 128, 242, 255)
|
||||
BT_BLUE = rl.Color(110, 175, 255, 255)
|
||||
ORANGE = rl.Color(255, 150, 60, 255)
|
||||
GRAY = rl.Color(140, 136, 152, 255)
|
||||
TEXT = rl.Color(245, 242, 252, 255)
|
||||
MUTED = rl.Color(184, 178, 200, 255)
|
||||
DIM = rl.Color(255, 255, 255, 43)
|
||||
DIM_BACK = rl.Color(15, 13, 23, 130)
|
||||
SHADOW = rl.Color(8, 6, 14, 175)
|
||||
|
||||
|
||||
def lit(signal: Signal, radio: str) -> rl.Color:
|
||||
strength = getattr(signal, radio)
|
||||
if not strength:
|
||||
return GRAY
|
||||
if strength <= 1:
|
||||
return ORANGE
|
||||
return ACCENT if signal.active == radio else TEXT
|
||||
|
||||
|
||||
def _bt_color(signal: Signal) -> rl.Color:
|
||||
if signal.bt == 'connected':
|
||||
return BT_BLUE
|
||||
return MUTED if signal.bt == 'on' else GRAY
|
||||
|
||||
|
||||
def _arc(cx, cy, radius, width, start, end, color, s=1.0):
|
||||
dy = max(1.0, 1.5 * s)
|
||||
if color == DIM:
|
||||
rl.draw_ring(rl.Vector2(cx, cy), radius - width / 2, radius + width / 2, min(start, end), max(start, end), 24, DIM_BACK)
|
||||
else:
|
||||
rl.draw_ring(rl.Vector2(cx, cy + dy), radius - width / 2, radius + width / 2, min(start, end), max(start, end), 24, SHADOW)
|
||||
rl.draw_ring(rl.Vector2(cx, cy), radius - width / 2, radius + width / 2, min(start, end), max(start, end), 24, color)
|
||||
|
||||
|
||||
def _pill(x, y, width, height, color, roundness=1.0, shadow=True, s=1.0):
|
||||
if shadow:
|
||||
if color == DIM:
|
||||
rl.draw_rectangle_rounded(rl.Rectangle(x, y, width, height), roundness, 12, DIM_BACK)
|
||||
else:
|
||||
rl.draw_rectangle_rounded(rl.Rectangle(x, y + max(1.0, 1.5 * s), width, height), roundness, 12, SHADOW)
|
||||
rl.draw_rectangle_rounded(rl.Rectangle(x, y, width, height), roundness, 12, color)
|
||||
|
||||
|
||||
def _dot(cx, cy, radius, color, s=1.0):
|
||||
if color == DIM:
|
||||
rl.draw_circle_v(rl.Vector2(cx, cy), radius, DIM_BACK)
|
||||
else:
|
||||
rl.draw_circle_v(rl.Vector2(cx, cy + max(1.0, 1.5 * s)), radius, SHADOW)
|
||||
rl.draw_circle_v(rl.Vector2(cx, cy), radius, color)
|
||||
|
||||
|
||||
def _cell_icon(x, y, s, color):
|
||||
dy = max(1.0, 1.5 * s)
|
||||
for c, off in ((SHADOW, dy), (color, 0.0)):
|
||||
for i in range(4):
|
||||
h = (4 + 4 * i) * s
|
||||
rl.draw_rectangle_rec(rl.Rectangle(x + i * 4.5 * s, y + off + 16 * s - h, 3 * s, h), c)
|
||||
|
||||
|
||||
def _wifi_icon(x, y, s, color):
|
||||
dy = max(1.0, 1.5 * s)
|
||||
cx, cy = x + 9 * s, y + 14 * s
|
||||
rl.draw_circle_v(rl.Vector2(cx, cy + dy), 2 * s, SHADOW)
|
||||
for radius in (6.5, 11.5):
|
||||
rl.draw_ring(rl.Vector2(cx, cy + dy), radius * s - 1.2 * s, radius * s + 1.2 * s, 222, 318, 24, SHADOW)
|
||||
rl.draw_circle_v(rl.Vector2(cx, cy), 2 * s, color)
|
||||
for radius in (6.5, 11.5):
|
||||
rl.draw_ring(rl.Vector2(cx, cy), radius * s - 1.2 * s, radius * s + 1.2 * s, 222, 318, 24, color)
|
||||
|
||||
|
||||
def _bt_icon(x, y, s, color, off=False):
|
||||
t = max(1.0, 1.8 * s)
|
||||
dy = max(1.0, 1.5 * s)
|
||||
segments = (
|
||||
((6, 1), (6, 15)),
|
||||
((6, 1), (10.5, 4.5)),
|
||||
((10.5, 4.5), (1.5, 11)),
|
||||
((1.5, 5), (10.5, 11.5)),
|
||||
((10.5, 11.5), (6, 15)),
|
||||
) + ((((-2, 0), (14, 16)),) if off else ())
|
||||
for c, shift in ((SHADOW, dy), (color, 0.0)):
|
||||
for (x1, y1), (x2, y2) in segments:
|
||||
rl.draw_line_ex(rl.Vector2(x + x1 * s, y + shift + y1 * s), rl.Vector2(x + x2 * s, y + shift + y2 * s), t, c)
|
||||
|
||||
|
||||
def _icon(radio, x, y, s, color):
|
||||
(_cell_icon if radio == 'cell' else _wifi_icon)(x, y, s, color)
|
||||
|
||||
|
||||
class SignalWidget:
|
||||
def __init__(self, fonts, feed=None):
|
||||
self.fonts = fonts
|
||||
self.feed = feed or SignalFeed()
|
||||
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
|
||||
top, bottom = self.fonts.vertical_ink(text, FontRole.SEMI_BOLD, size)
|
||||
if align == 'center':
|
||||
x -= self.fonts.measure(text, FontRole.SEMI_BOLD, size).width / 2
|
||||
y = cy - (top + bottom) / 2
|
||||
self.fonts.draw(text, FontRole.SEMI_BOLD, size, x, y + max(1.0, 1.5 * self.s), SHADOW)
|
||||
self.fonts.draw(text, FontRole.SEMI_BOLD, size, x, y, color)
|
||||
|
||||
def _fit(self, text, size, max_width):
|
||||
limit = max_width * self.s
|
||||
px_size = size * self.s
|
||||
if self.fonts.measure(text, FontRole.SEMI_BOLD, px_size).width <= limit:
|
||||
return text
|
||||
trimmed = text
|
||||
while len(trimmed) > 1 and self.fonts.measure(f"{trimmed}…", FontRole.SEMI_BOLD, px_size).width > limit:
|
||||
trimmed = trimmed[:-1].rstrip()
|
||||
return f"{trimmed}…" if trimmed else "…"
|
||||
|
||||
def _fit_count(self, text, extra, size, max_width):
|
||||
"""Shows the name with "+N" for extra devices, or just the count when both don't fit."""
|
||||
if not extra:
|
||||
return self._fit(text, size, max_width)
|
||||
full = f"{text} +{extra}"
|
||||
if self.fonts.measure(full, FontRole.SEMI_BOLD, size * self.s).width <= max_width * self.s:
|
||||
return full
|
||||
return f"+{extra + 1} more"
|
||||
|
||||
def render(self, state):
|
||||
placed = state.customization['layouts']['large'].get(SIGNAL_WIDGET)
|
||||
if not placed or not placed['enabled'] or state.alert.size != 'none':
|
||||
return
|
||||
signal = self.preview or self.feed.snapshot()
|
||||
style = placed.get('size', 'ring')
|
||||
style = style if style in SIGNAL_GRIDS else 'ring'
|
||||
self.s = S = SIGNAL_SCALE * signal_scale(placed)
|
||||
background = rl.Color(15, 13, 23, round(235 * placed.get('opacity', 85) / 100))
|
||||
radios = [radio for radio in ('cell', 'wifi') if getattr(signal, radio)]
|
||||
x, y = placed['x'], placed['y']
|
||||
show_bt = placed.get('bluetooth', True)
|
||||
header = SIGNAL_WIFI_NAME_GRID if placed.get('wifiName') is True else 0
|
||||
if style == 'ring':
|
||||
self._ring(signal, radios, x, y, background, show_bt, header)
|
||||
return
|
||||
width, height = SIGNAL_GRIDS[style]
|
||||
radius = 28 if style == 'horizontal' else 24
|
||||
rl.draw_rectangle_rounded(rl.Rectangle(x, y, width * S, (height + header) * S), radius * 2 / min(width, height + header), 24, background)
|
||||
if header:
|
||||
self._wifi_name(signal, x, y, width, style == 'horizontal')
|
||||
(self._lines if style == 'horizontal' else self._columns)(signal, radios, x, y + header * S, show_bt)
|
||||
|
||||
def _wifi_name(self, signal, x, y, width, left=False):
|
||||
"""The joined Wi-Fi network's name in a row above the rest of the widget."""
|
||||
size = 16 if left else 15
|
||||
name = signal.wifi_name if signal.wifi else ''
|
||||
text = self._fit(name, size, width - (48 if left else 12)) if name else ('Wi-Fi' if signal.wifi else 'No Wi-Fi')
|
||||
color = (TEXT if signal.active == 'wifi' else MUTED) if signal.wifi else GRAY
|
||||
if left:
|
||||
self._text(text, x + 24 * self.s, y + 17 * self.s, size, color, 'left')
|
||||
else:
|
||||
self._text(text, x + width / 2 * self.s, y + 16 * self.s, size, color)
|
||||
|
||||
def _label(self, signal, radio):
|
||||
if radio == 'cell':
|
||||
return signal.tech if signal.cell else 'Cell'
|
||||
return 'Wi-Fi'
|
||||
|
||||
def _bt_device_label(self, signal, size, max_width):
|
||||
if signal.bt == 'connected':
|
||||
if signal.bt_devices:
|
||||
joined = ', '.join(signal.bt_devices)
|
||||
if self.fonts.measure(joined, FontRole.SEMI_BOLD, size * self.s).width <= max_width * self.s:
|
||||
return joined
|
||||
if len(signal.bt_devices) > 1:
|
||||
suffix = f" +{len(signal.bt_devices) - 1}"
|
||||
suffix_w = self.fonts.measure(suffix, FontRole.SEMI_BOLD, size * self.s).width / self.s
|
||||
if max_width > suffix_w + 12:
|
||||
return f"{self._fit(signal.bt_devices[0], size, max_width - suffix_w)}{suffix}"
|
||||
return self._fit(signal.bt_devices[0], size, max_width)
|
||||
return 'Connected'
|
||||
return 'Bluetooth'
|
||||
|
||||
def _draw_bt_stack(self, signal, cx, icon_y, single_y, y1, y2, *, status_y=None):
|
||||
"""Draws the centered Bluetooth icon and up to two device rows below it."""
|
||||
S = self.s
|
||||
bt_color = _bt_color(signal)
|
||||
_bt_icon(cx - 6 * S, icon_y, 1.0 * S, bt_color, signal.bt == 'off')
|
||||
devices = (signal.bt_devices or ('Connected',)) if signal.bt == 'connected' else ()
|
||||
if devices:
|
||||
self._text(self._fit(devices[0], 15, 100), cx, y1 if len(devices) > 1 else single_y, 15, TEXT)
|
||||
if len(devices) > 1:
|
||||
self._text(self._fit_count(devices[1], len(devices) - 2, 15, 100), cx, y2, 15, TEXT)
|
||||
elif status_y is not None:
|
||||
self._text('BT On' if signal.bt == 'on' else 'BT Off', cx, status_y, 15, bt_color)
|
||||
|
||||
def _ring(self, signal, radios, x, y, background, show_bt=True, header=0):
|
||||
S = self.s
|
||||
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:
|
||||
self._wifi_name(signal, x, y, 112)
|
||||
y += header * S
|
||||
cx, cy = x + 56 * S, y + 56 * S
|
||||
radius, width = 45 * S, 7 * S
|
||||
for i in range(4):
|
||||
c_start = 150 + i * 29
|
||||
_arc(cx, cy, radius, width, c_start, c_start + 24, lit(signal, 'cell') if signal.cell and i < signal.cell else DIM, S)
|
||||
w_start = 30 - i * 29
|
||||
_arc(cx, cy, radius, width, w_start - 24, w_start, lit(signal, 'wifi') if signal.wifi and i < signal.wifi else DIM, S)
|
||||
|
||||
cell_color = lit(signal, 'cell') if signal.active == 'cell' else (MUTED if signal.cell else GRAY)
|
||||
wifi_color = lit(signal, 'wifi') if signal.active == 'wifi' else (MUTED if signal.wifi else GRAY)
|
||||
icon_y = y + (36 if show_bt else 44) * S
|
||||
_cell_icon(x + 34 * S, icon_y, 1.0 * S, cell_color)
|
||||
_wifi_icon(x + 60 * S, icon_y, 1.0 * S, wifi_color)
|
||||
|
||||
if not show_bt:
|
||||
primary = signal.active if signal.active in ('cell', 'wifi') else (radios[0] if radios else None)
|
||||
self._text(self._label(signal, primary) if primary else 'No link', cx, y + 80 * S, 14, TEXT if primary else GRAY)
|
||||
return
|
||||
|
||||
self._draw_bt_stack(signal, cx, y + 65 * S, y + 100 * S, y + 100 * S, y + 120 * S)
|
||||
|
||||
def _lines(self, signal, radios, x, y, show_bt=True):
|
||||
S = self.s
|
||||
|
||||
def row(radio, cy):
|
||||
strength = getattr(signal, radio) or 0
|
||||
active = signal.active == radio
|
||||
color = lit(signal, radio)
|
||||
icon_color = color if active else (MUTED if strength else GRAY)
|
||||
_icon(radio, x + 24 * S, y + (cy - 9) * S, 1.0 * S, icon_color)
|
||||
for i in range(4):
|
||||
_pill(x + (56 + i * 49) * S, y + (cy - 4) * S, 41 * S, 8 * S, color if i < strength else DIM, s=S)
|
||||
|
||||
row('cell', 26 if show_bt else 37)
|
||||
row('wifi', 56 if show_bt else 75)
|
||||
if not show_bt:
|
||||
return
|
||||
|
||||
bt_color = _bt_color(signal)
|
||||
_bt_icon(x + 27 * S, y + 78 * S, 1.0 * S, bt_color, signal.bt == 'off')
|
||||
name_color = TEXT if signal.bt == 'connected' else (MUTED if signal.bt == 'on' else GRAY)
|
||||
self._text(self._bt_device_label(signal, 16, 188), x + 56 * S, y + 86 * S, 16, name_color, 'left')
|
||||
|
||||
def _columns(self, signal, radios, x, y, show_bt=True):
|
||||
S = self.s
|
||||
top_off = 0 if show_bt else 32
|
||||
|
||||
def column(radio, cx):
|
||||
strength = getattr(signal, radio) or 0
|
||||
on = strength > 0
|
||||
active = on and signal.active == radio
|
||||
color = lit(signal, radio)
|
||||
for i in range(4):
|
||||
_dot(x + cx * S, y + (22 + top_off + (3 - i) * 21) * S, 8 * S, color if i < strength else DIM, S)
|
||||
icon_w = 16.5 if radio == 'cell' else 18
|
||||
_icon(radio, x + (cx - icon_w / 2) * S, y + (102 + top_off) * S, 1.0 * S, color if active else (MUTED if on else GRAY))
|
||||
|
||||
column('cell', 34)
|
||||
column('wifi', 78)
|
||||
if not show_bt:
|
||||
return
|
||||
rl.draw_line_ex(rl.Vector2(x + 14 * S, y + 128 * S), rl.Vector2(x + 98 * S, y + 128 * S), max(1.0, 1.5 * S), DIM)
|
||||
self._draw_bt_stack(signal, x + 56 * S, y + 134 * S, y + 168 * S, y + 162 * S, y + 181 * S, status_y=y + 168 * S)
|
||||
@@ -6,7 +6,7 @@ import subprocess
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from openpilot.starpilot.ui.bluetooth_status import BluetoothStatusSource, read_bluetooth_state
|
||||
from openpilot.starpilot.ui.bluetooth_status import BluetoothStatusSource, read_bluetooth_details, read_bluetooth_state
|
||||
|
||||
|
||||
class FakeExecutor:
|
||||
@@ -41,6 +41,34 @@ class TestBluetoothStatus(unittest.TestCase):
|
||||
side_effect=subprocess.TimeoutExpired(["busctl"], 1.5)):
|
||||
self.assertEqual(read_bluetooth_state(), "off")
|
||||
|
||||
def test_bluez_details_return_connected_device_names(self):
|
||||
data = {
|
||||
"/org/bluez/hci0": {"org.bluez.Adapter1": {"Powered": {"type": "b", "data": True}}},
|
||||
"/org/bluez/hci0/dev_AA": {"org.bluez.Device1": {"Connected": {"type": "b", "data": True},
|
||||
"Name": {"type": "s", "data": "iPhone 15"}}},
|
||||
"/org/bluez/hci0/dev_BB": {"org.bluez.Device1": {"Connected": {"type": "b", "data": True},
|
||||
"Alias": {"type": "s", "data": "AirPods"}}},
|
||||
"/org/bluez/hci0/dev_CC": {"org.bluez.Device1": {"Connected": {"type": "b", "data": False},
|
||||
"Name": {"type": "s", "data": "Old Phone"}}},
|
||||
}
|
||||
output = json.dumps({"type": "a{oa{sa{sv}}}", "data": [data]})
|
||||
with patch("openpilot.starpilot.ui.bluetooth_status.subprocess.run",
|
||||
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])
|
||||
|
||||
@@ -0,0 +1,313 @@
|
||||
import json
|
||||
import math
|
||||
import threading
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from openpilot.common.hardware.comma import hardware
|
||||
from openpilot.starpilot.ui import network_signal
|
||||
from openpilot.starpilot.ui.network_signal import Signal, SignalFeed, read_signal
|
||||
from openpilot.starpilot.ui.onroad_customization import SIGNAL_WIDGET, default_document, validate_document
|
||||
|
||||
|
||||
def read(tmp_path, modem, rssi, iface, bt=('off', ())):
|
||||
path = tmp_path / 'modem'
|
||||
if modem is not None:
|
||||
path.write_text(json.dumps(modem))
|
||||
poll = {'RSSI': str(rssi)} if rssi is not None else {}
|
||||
with patch.object(hardware, 'MODEM_STATE_PATH', str(path)), patch.object(hardware, 'wpa_supplicant_cmd', return_value=poll), \
|
||||
patch.object(hardware, 'get_default_route_iface', return_value=iface), \
|
||||
patch('openpilot.starpilot.ui.bluetooth_status.read_bluetooth_details', return_value=bt):
|
||||
return read_signal()
|
||||
|
||||
|
||||
def test_reads_both_radios_and_the_link_in_use(tmp_path):
|
||||
modem = {'connected': True, 'signal_quality': 60, 'network_type': 'nr'}
|
||||
assert read(tmp_path, modem, -45, 'wlan0', ('connected', ('iPhone 15',))) == Signal(3, 4, 'wifi', '5G', 'connected', ('iPhone 15',))
|
||||
assert read(tmp_path, modem, None, 'ppp0', ('on', ())) == Signal(3, None, 'cell', '5G', 'on', ())
|
||||
assert read(tmp_path, {'connected': False, 'signal_quality': 60}, -88, 'wlan0') == Signal(None, 2, 'wifi')
|
||||
assert read(tmp_path, None, None, None) == Signal()
|
||||
assert read(tmp_path, {'connected': True, 'signal_quality': '60'}, None, 'ppp0') == Signal()
|
||||
|
||||
|
||||
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():
|
||||
feed = SignalFeed(read=lambda: Signal(4, None, 'cell'), period=3600)
|
||||
feed._thread = threading.Thread(target=lambda: None) # never started: no background polling
|
||||
feed.poll()
|
||||
assert feed.snapshot() == Signal(4, None, 'cell')
|
||||
feed._read_at -= network_signal.STALE_S + 1
|
||||
assert feed.snapshot() == Signal()
|
||||
|
||||
|
||||
def test_signal_is_an_opt_in_big_widget_with_background_opacity():
|
||||
document = default_document()
|
||||
placed = document['layouts']['large'][SIGNAL_WIDGET]
|
||||
assert placed['enabled'] is False and placed['opacity'] == 85
|
||||
assert SIGNAL_WIDGET not in document['layouts']['compact']
|
||||
del document['layouts']['large'][SIGNAL_WIDGET]
|
||||
assert validate_document(document)['layouts']['large'][SIGNAL_WIDGET]['enabled'] is False
|
||||
|
||||
|
||||
def test_signal_style_picks_size_and_older_layouts_default_to_ring():
|
||||
from openpilot.starpilot.ui.onroad_customization import SIGNAL_SIZES, widget_size
|
||||
document = default_document()
|
||||
placed = document['layouts']['large'][SIGNAL_WIDGET]
|
||||
assert placed['size'] == 'ring'
|
||||
del placed['size']
|
||||
assert validate_document(document)['layouts']['large'][SIGNAL_WIDGET]['size'] == 'ring'
|
||||
placed.update(size='vertical')
|
||||
document = validate_document(document)
|
||||
assert widget_size(document, 'large', SIGNAL_WIDGET) == SIGNAL_SIZES['vertical']
|
||||
document['layouts']['large'][SIGNAL_WIDGET]['size'] = 'square'
|
||||
with pytest.raises(ValueError):
|
||||
validate_document(document)
|
||||
|
||||
|
||||
def test_starport_signal_style_is_validated_and_pulled_on_screen():
|
||||
from openpilot.starpilot.system.starport.projection_layout import default_layout_for_viewport, validate_layout_for_viewport
|
||||
from openpilot.starpilot.ui.onroad_customization import SIGNAL_SIZES
|
||||
layout = default_layout_for_viewport((1920, 1080))
|
||||
del layout['widgets'][SIGNAL_WIDGET]['size']
|
||||
assert validate_layout_for_viewport(layout, (1920, 1080))['widgets'][SIGNAL_WIDGET]['size'] == 'ring'
|
||||
layout['widgets'][SIGNAL_WIDGET].update(size='horizontal', x=1920 - 30 - SIGNAL_SIZES['ring'][0])
|
||||
placed = validate_layout_for_viewport(layout, (1920, 1080))['widgets'][SIGNAL_WIDGET]
|
||||
assert placed['x'] == 1920 - 30 - SIGNAL_SIZES['horizontal'][0]
|
||||
layout['widgets'][SIGNAL_WIDGET]['size'] = 'big'
|
||||
with pytest.raises(ValueError):
|
||||
validate_layout_for_viewport(layout, (1920, 1080))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('style', ['ring', 'horizontal', 'vertical'])
|
||||
@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=scale)
|
||||
document = validate_document(document)
|
||||
width, height = SIGNAL_SIZES[style]
|
||||
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):
|
||||
validate_document(document)
|
||||
|
||||
|
||||
def test_older_signal_layouts_default_to_full_size():
|
||||
document = default_document()
|
||||
del document['layouts']['large'][SIGNAL_WIDGET]['scale']
|
||||
assert validate_document(document)['layouts']['large'][SIGNAL_WIDGET]['scale'] == 100
|
||||
|
||||
|
||||
def test_starport_signal_scale_is_validated():
|
||||
from openpilot.starpilot.system.starport.projection_layout import default_layout_for_viewport, validate_layout_for_viewport
|
||||
from openpilot.starpilot.ui.onroad_customization import SIGNAL_SIZES
|
||||
layout = default_layout_for_viewport((1920, 1080))
|
||||
del layout['widgets'][SIGNAL_WIDGET]['scale']
|
||||
assert validate_layout_for_viewport(layout, (1920, 1080))['widgets'][SIGNAL_WIDGET]['scale'] == 100
|
||||
# At 30% the vertical card fits where the full-size one would not.
|
||||
layout['widgets'][SIGNAL_WIDGET].update(size='vertical', scale=30, y=1080 - 30 - round(SIGNAL_SIZES['vertical'][1] * .3))
|
||||
assert validate_layout_for_viewport(layout, (1920, 1080))['widgets'][SIGNAL_WIDGET]['y'] == layout['widgets'][SIGNAL_WIDGET]['y']
|
||||
layout['widgets'][SIGNAL_WIDGET]['scale'] = 20
|
||||
with pytest.raises(ValueError):
|
||||
validate_layout_for_viewport(layout, (1920, 1080))
|
||||
|
||||
|
||||
def test_signal_draws_at_its_size_percentage():
|
||||
from types import SimpleNamespace as NS
|
||||
from unittest.mock import MagicMock
|
||||
from openpilot.starpilot.ui.onroad_customization import SIGNAL_SCALE
|
||||
from openpilot.starpilot.ui import onroad_signal
|
||||
fonts = MagicMock()
|
||||
fonts.vertical_ink.return_value = (0, 10)
|
||||
fonts.measure.return_value = NS(width=20)
|
||||
widget = onroad_signal.SignalWidget(fonts)
|
||||
widget.preview = Signal(2, 4, 'wifi', 'LTE', 'connected', ('iPhone 15',))
|
||||
document = default_document()
|
||||
document['layouts']['large'][SIGNAL_WIDGET].update(enabled=True, scale=30)
|
||||
with patch.object(onroad_signal, 'rl') as rl:
|
||||
rl.Rectangle = lambda *args: args
|
||||
widget.render(NS(customization=document, alert=NS(size='none')))
|
||||
assert rl.draw_rectangle_rounded.call_args_list[0].args[0][2:] == pytest.approx((112 * SIGNAL_SCALE * .3, 122 * SIGNAL_SCALE * .3))
|
||||
assert all(call.args[2] == pytest.approx(15 * SIGNAL_SCALE * .3)
|
||||
for call in fonts.draw.call_args_list)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('style', ['ring', 'horizontal', 'vertical'])
|
||||
def test_all_styles_render_bluetooth_status_and_device_name(style):
|
||||
from types import SimpleNamespace as NS
|
||||
from unittest.mock import MagicMock
|
||||
from openpilot.starpilot.ui import onroad_signal
|
||||
fonts = MagicMock()
|
||||
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',))
|
||||
document = default_document()
|
||||
document['layouts']['large'][SIGNAL_WIDGET].update(enabled=True, size=style)
|
||||
with patch.object(onroad_signal, 'rl'):
|
||||
widget.render(NS(customization=document, alert=NS(size='none')))
|
||||
drawn = [call.args[0] for call in fonts.draw.call_args_list]
|
||||
assert 'iPhone 15' in drawn
|
||||
assert 'Connected' not in drawn
|
||||
|
||||
fonts.draw.reset_mock()
|
||||
widget.preview = Signal(2, 4, 'wifi', '5G', 'connected', ('iPhone 15', 'AirPods'))
|
||||
with patch.object(onroad_signal, 'rl'):
|
||||
widget.render(NS(customization=document, alert=NS(size='none')))
|
||||
drawn_multi = [call.args[0] for call in fonts.draw.call_args_list]
|
||||
assert any('iPhone' in text and ('AirPods' in text or '+1' in text) for text in drawn_multi) or ('iPhone 15' in drawn_multi and 'AirPods' in drawn_multi)
|
||||
|
||||
|
||||
def test_bluetooth_toggle_defaults_on_and_hides_bluetooth_when_off():
|
||||
from types import SimpleNamespace as NS
|
||||
from unittest.mock import MagicMock
|
||||
from openpilot.starpilot.system.starport.projection_layout import default_layout_for_viewport, validate_layout_for_viewport
|
||||
from openpilot.starpilot.ui import onroad_signal
|
||||
document = default_document()
|
||||
assert document['layouts']['large'][SIGNAL_WIDGET]['bluetooth'] is True
|
||||
del document['layouts']['large'][SIGNAL_WIDGET]['bluetooth']
|
||||
assert validate_document(document)['layouts']['large'][SIGNAL_WIDGET]['bluetooth'] is True
|
||||
document['layouts']['large'][SIGNAL_WIDGET]['bluetooth'] = 'yes'
|
||||
with pytest.raises(ValueError):
|
||||
validate_document(document)
|
||||
|
||||
layout = default_layout_for_viewport((1920, 1080))
|
||||
assert layout['widgets'][SIGNAL_WIDGET]['bluetooth'] is True
|
||||
del layout['widgets'][SIGNAL_WIDGET]['bluetooth']
|
||||
assert validate_layout_for_viewport(layout, (1920, 1080))['widgets'][SIGNAL_WIDGET]['bluetooth'] is True
|
||||
|
||||
fonts = MagicMock()
|
||||
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', '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') 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))])
|
||||
@pytest.mark.parametrize('scale', [30, 100])
|
||||
def test_legacy_signal_at_screen_edge_migrates_without_losing_layout(style, grid, scale):
|
||||
from openpilot.starpilot.ui.onroad_customization import SIGNAL_SCALE, signal_size, widget_bounds
|
||||
document = default_document()
|
||||
placed = document['layouts']['large'][SIGNAL_WIDGET]
|
||||
del placed['bluetooth']
|
||||
bounds = widget_bounds('large', SIGNAL_WIDGET)
|
||||
old_size = [round(round(d * SIGNAL_SCALE) * scale / 100) for d in grid]
|
||||
placed.update(size=style, scale=scale, enabled=True,
|
||||
x=bounds['x'] + bounds['width'] - old_size[0], y=bounds['y'] + bounds['height'] - old_size[1])
|
||||
migrated = validate_document(document)
|
||||
saved = migrated['layouts']['large'][SIGNAL_WIDGET]
|
||||
width, height = signal_size(saved)
|
||||
assert saved['x'] == bounds['x'] + bounds['width'] - width
|
||||
assert saved['y'] == bounds['y'] + bounds['height'] - height
|
||||
assert saved['enabled'] and saved['bluetooth']
|
||||
assert migrated['layouts']['compact'] == document['layouts']['compact']
|
||||
assert validate_document(migrated) == migrated
|
||||
placed['x'] += 1
|
||||
with pytest.raises(ValueError):
|
||||
validate_document(document)
|
||||
|
||||
|
||||
def test_horizontal_bluetooth_name_does_not_overlap_status():
|
||||
from types import SimpleNamespace as NS
|
||||
from unittest.mock import MagicMock
|
||||
from openpilot.starpilot.ui import onroad_signal
|
||||
fonts = MagicMock()
|
||||
fonts.vertical_ink.return_value = (0, 10)
|
||||
fonts.measure.side_effect = lambda text, _role, size: NS(width=len(text) * size * .6)
|
||||
widget = onroad_signal.SignalWidget(fonts)
|
||||
widget.preview = Signal(2, 4, 'wifi', 'LTE', 'connected', ('A very long phone name', 'Headphones'))
|
||||
document = default_document()
|
||||
placed = document['layouts']['large'][SIGNAL_WIDGET]
|
||||
placed.update(enabled=True, size='horizontal')
|
||||
with patch.object(onroad_signal, 'rl'):
|
||||
widget.render(NS(customization=document, alert=NS(size='none')))
|
||||
drawn = [call.args for call in fonts.draw.call_args_list]
|
||||
assert 'Connected' not in [args[0] for args in drawn]
|
||||
name = next(args for args in drawn if '+1' in args[0])
|
||||
name_right = name[3] + fonts.measure(name[0], name[1], name[2]).width
|
||||
assert name_right <= placed['x'] + 244 * widget.s
|
||||
|
||||
|
||||
def test_reads_the_joined_wifi_name(tmp_path):
|
||||
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'), \
|
||||
patch('openpilot.starpilot.ui.bluetooth_status.read_bluetooth_details', return_value=('off', ())):
|
||||
assert read_signal().wifi_name == 'Danny’s Café'
|
||||
replies['STATUS'] = {'wpa_state': 'ASSOCIATING', 'ssid': 'Home'}
|
||||
assert read_signal().wifi_name == ''
|
||||
|
||||
|
||||
def test_wifi_name_toggle_defaults_off_and_adds_a_header_row():
|
||||
from types import SimpleNamespace as NS
|
||||
from unittest.mock import MagicMock
|
||||
from openpilot.starpilot.system.starport.projection_layout import default_layout_for_viewport, validate_layout_for_viewport
|
||||
from openpilot.starpilot.ui import onroad_signal
|
||||
from openpilot.starpilot.ui.onroad_customization import SIGNAL_SIZES, SIGNAL_WIFI_NAME_HEIGHT, signal_size
|
||||
document = default_document()
|
||||
assert document['layouts']['large'][SIGNAL_WIDGET]['wifiName'] is False
|
||||
del document['layouts']['large'][SIGNAL_WIDGET]['wifiName']
|
||||
assert validate_document(document)['layouts']['large'][SIGNAL_WIDGET]['wifiName'] is False
|
||||
document['layouts']['large'][SIGNAL_WIDGET]['wifiName'] = 'yes'
|
||||
with pytest.raises(ValueError):
|
||||
validate_document(document)
|
||||
layout = default_layout_for_viewport((1920, 1080))
|
||||
del layout['widgets'][SIGNAL_WIDGET]['wifiName']
|
||||
assert validate_layout_for_viewport(layout, (1920, 1080))['widgets'][SIGNAL_WIDGET]['wifiName'] is False
|
||||
|
||||
for style, (width, height) in SIGNAL_SIZES.items():
|
||||
assert signal_size({'size': style, 'scale': 100, 'wifiName': True}) == (width, height + SIGNAL_WIFI_NAME_HEIGHT)
|
||||
|
||||
fonts = MagicMock()
|
||||
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)
|
||||
for style in ('ring', 'horizontal', 'vertical'):
|
||||
for signal, shown in ((Signal(2, 4, 'wifi', 'LTE', 'on', (), 'Home Wi-Fi'), 'Home Wi-Fi'), (Signal(2, None, 'cell'), 'No Wi-Fi')):
|
||||
widget.preview = signal
|
||||
for enabled in (False, True):
|
||||
fonts.draw.reset_mock()
|
||||
doc = default_document()
|
||||
doc['layouts']['large'][SIGNAL_WIDGET].update(enabled=True, size=style, wifiName=enabled)
|
||||
with patch.object(onroad_signal, 'rl'):
|
||||
widget.render(NS(customization=doc, alert=NS(size='none')))
|
||||
assert (shown in [call.args[0] for call in fonts.draw.call_args_list]) is enabled
|
||||
@@ -1,14 +1,25 @@
|
||||
from types import SimpleNamespace as NS
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from openpilot.starpilot.models.catalog import BUNDLED_CURRENT
|
||||
from openpilot.starpilot.models.jetlink_status import JetlinkStatus
|
||||
from openpilot.starpilot.models.status import ModelVariant
|
||||
from openpilot.starpilot.ui import onroad_jetlink
|
||||
from openpilot.starpilot.ui.onroad_customization import default_document
|
||||
from openpilot.starpilot.ui.onroad_jetlink import (
|
||||
ACCENT, GRAY, GREEN, ORANGE, TEXT, JetlinkStatusWidget, abbreviate_model_name, big_model_card, gpu_inputs,
|
||||
local_model_names, scroll_offset,
|
||||
)
|
||||
from openpilot.starpilot.ui.onroad_jetlink_layer import NativeJetlinkLayer
|
||||
from openpilot.starpilot.ui.presentation import FontRole, TextSize
|
||||
|
||||
|
||||
def test_native_jetlink_polls_only_while_its_widget_is_showing_onroad():
|
||||
with patch('openpilot.starpilot.ui.onroad_jetlink_layer.gui_app') as app, \
|
||||
patch('openpilot.starpilot.ui.onroad_jetlink_layer.JetlinkStatusFeed') as feed:
|
||||
widget, ui = Mock(), NS(started=True)
|
||||
widget, ui = Mock(), NS(started=True, chestnut_state=NS(value=None), sm={'deviceState': NS(chestnutPresent=False)})
|
||||
layer = NativeJetlinkLayer(widget, ui)
|
||||
state = NS(customization=default_document())
|
||||
app.add_render_prepare.assert_called_once_with(layer.prepare, layer.close)
|
||||
@@ -19,6 +30,7 @@ def test_native_jetlink_polls_only_while_its_widget_is_showing_onroad():
|
||||
state.customization['layouts']['large']['jetlink_status']['enabled'] = True
|
||||
layer.render(state)
|
||||
assert widget.status is feed.return_value.snapshot.return_value
|
||||
assert (widget.gpu, widget.chestnut) == (None, False) # nothing tracks the GPU on this fake UIState
|
||||
widget.render.assert_called_once_with(state)
|
||||
layer.prepare()
|
||||
feed.return_value.set_enabled.assert_called_with(True)
|
||||
@@ -31,3 +43,215 @@ def test_native_jetlink_polls_only_while_its_widget_is_showing_onroad():
|
||||
layer.close()
|
||||
app.remove_render_prepare.assert_called_once_with(layer.prepare)
|
||||
feed.return_value.close.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('jetlink,gpu,chestnut,expected', [
|
||||
(JetlinkStatus(), None, False, ('Small model', '', GREEN, None)),
|
||||
(JetlinkStatus(), 'disconnected', False, ('Small model', '', GREEN, None)),
|
||||
(JetlinkStatus('Computer', 'active', 24.6), 'active', False, ('Big model', 'Jetlink', GREEN, 24.6)),
|
||||
(JetlinkStatus('Computer', 'ready', offer=True), 'loading', False, ('Small model', 'Re-engage to switch', ACCENT, None)),
|
||||
(JetlinkStatus('Computer', 'ready', offer=True), 'failed', False, ('Small model', 'Re-engage to switch', ORANGE, None)),
|
||||
(JetlinkStatus('Computer', 'connecting'), 'failed', False, ('Small model', 'Fell back', ORANGE, None)),
|
||||
(JetlinkStatus('Computer', 'ready'), None, False, ('Small model', 'Jetlink ready', ACCENT, None)),
|
||||
(JetlinkStatus('Computer', 'connected', building=True), 'loading', False, ('Small model', 'Jetlink building', ACCENT, None)),
|
||||
(JetlinkStatus('Computer', 'disconnected'), 'failed', False, ('Small model', 'Jetlink offline', GRAY, None)),
|
||||
(JetlinkStatus(state='unavailable'), 'failed', False, ('Small model', 'Jetlink error', ORANGE, None)),
|
||||
(JetlinkStatus(), 'active', True, ('Big model', 'Chestnut', GREEN, None)),
|
||||
(JetlinkStatus(), 'failed', True, ('Small model', 'Fell back', ORANGE, None)),
|
||||
(JetlinkStatus(), 'loading', True, ('Small model', 'Chestnut loading', ACCENT, None)),
|
||||
])
|
||||
def test_big_model_card_says_which_model_drives_in_a_few_words(jetlink, gpu, chestnut, expected):
|
||||
assert tuple(big_model_card(jetlink, gpu, chestnut)) == expected
|
||||
|
||||
|
||||
def test_gpu_inputs_read_uistate():
|
||||
ui = NS(chestnut_state=NS(value='active'), sm={'deviceState': NS(chestnutPresent=True)})
|
||||
assert gpu_inputs(ui) == ('active', True)
|
||||
with pytest.raises(AttributeError):
|
||||
gpu_inputs(NS())
|
||||
|
||||
proj_ui = NS(
|
||||
projection_read_only=True,
|
||||
chestnut_state=NS(value='disconnected'),
|
||||
sm={'deviceState': NS(chestnutPresent=True)},
|
||||
_update_chestnut_state=lambda: setattr(proj_ui, 'chestnut_state', NS(value='active')),
|
||||
)
|
||||
assert gpu_inputs(proj_ui) == ('active', True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('raw,expected', [
|
||||
('Regret Driven Framework V4 👀📡', 'RDF V4'),
|
||||
('Terrific Super Fantastic Do Over 👀📡', 'TSF Do Over'),
|
||||
('Vegetarian-Filet-O-Fish 👀📡', 'V-Filet-O-Fish'),
|
||||
('Cinque v3 (September 17, 2026)', 'Cinque v3'),
|
||||
('Cinque v3 Model', 'Cinque v3'),
|
||||
('Regret Driven Framework V4 / Cinque v3', 'RDF V4 / Cinque v3'),
|
||||
('Alpha · Beta — Gamma', 'Alpha - Beta - Gamma'),
|
||||
])
|
||||
def test_abbreviate_model_name_strips_noise_and_shortens_long_series(raw, expected):
|
||||
assert abbreviate_model_name(raw) == expected
|
||||
|
||||
|
||||
def test_big_model_card_uses_abbreviated_model_names_and_tier():
|
||||
active_jl = big_model_card(
|
||||
JetlinkStatus('Computer', 'active', 24.6, model='Cinque v3 (September 17, 2026)'),
|
||||
'active',
|
||||
False,
|
||||
small='Regret Driven Framework V4 👀📡',
|
||||
big='ResFit',
|
||||
)
|
||||
assert (active_jl.title, active_jl.detail, active_jl.tier) == ('Cinque v3', 'Jetlink', 'BIG')
|
||||
|
||||
active_cn = big_model_card(
|
||||
JetlinkStatus(),
|
||||
'active',
|
||||
True,
|
||||
small='Regret Driven Framework V4 👀📡',
|
||||
big='ResFit Model',
|
||||
)
|
||||
assert (active_cn.title, active_cn.detail, active_cn.tier) == ('ResFit', 'Chestnut', 'BIG')
|
||||
|
||||
fallback = big_model_card(
|
||||
JetlinkStatus('Computer', 'connecting'),
|
||||
'failed',
|
||||
False,
|
||||
small='Regret Driven Framework V4 👀📡',
|
||||
big='Cinque v3',
|
||||
)
|
||||
assert (fallback.title, fallback.detail, fallback.tier) == ('RDF V4', 'Fell back', 'SMALL')
|
||||
|
||||
|
||||
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=pair), \
|
||||
patch.object(onroad_jetlink, 'process_start_ticks', return_value=456):
|
||||
assert local_model_names(now=10.0) == ('TR16 / Cinque v3', 'TR16 / Cinque v3')
|
||||
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
|
||||
|
||||
|
||||
@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', 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
|
||||
|
||||
|
||||
def _fake_fonts():
|
||||
def measure(text, role, size):
|
||||
return TextSize(len(text) * size * 0.55, size * 1.242)
|
||||
fonts = Mock()
|
||||
fonts.measure.side_effect = measure
|
||||
return fonts
|
||||
|
||||
|
||||
def _enabled_state():
|
||||
doc = default_document()
|
||||
doc['layouts']['large']['jetlink_status']['enabled'] = True
|
||||
return NS(customization=doc, alert=NS(size='none'))
|
||||
|
||||
|
||||
def test_widget_renders_option4_eyebrow_latency_and_scrolls_long_model_names():
|
||||
clock = [100.0]
|
||||
fonts = _fake_fonts()
|
||||
widget = JetlinkStatusWidget(fonts, ticks=lambda: clock[0], models=lambda: ('RDF V4', 'Cinque v3'))
|
||||
widget.status = JetlinkStatus('Computer', 'active', 43.8, model='Cinque v3')
|
||||
widget.gpu = 'active'
|
||||
state = _enabled_state()
|
||||
|
||||
with patch.object(onroad_jetlink.rl, 'draw_rectangle_rounded'), \
|
||||
patch.object(onroad_jetlink.rl, 'draw_circle_v') as circles, \
|
||||
patch.object(onroad_jetlink.clip, 'begin_scissor_mode') as begin_scissor, \
|
||||
patch.object(onroad_jetlink.clip, 'end_scissor_mode') as end_scissor:
|
||||
widget.render(state)
|
||||
|
||||
# Two circles: status dot (7.5) and eyebrow separator dot (2.8)
|
||||
assert [c.args[1] for c in circles.call_args_list] == [7.5, 2.8]
|
||||
begin_scissor.assert_not_called()
|
||||
end_scissor.assert_not_called()
|
||||
drawn = [(c.args[0], c.args[1], c.args[2], round(c.args[3], 1), c.args[5]) for c in fonts.draw.call_args_list]
|
||||
assert any(t == 'BIG' and sz == 20 for t, _, sz, _, _ in drawn)
|
||||
assert any(t == 'JETLINK' for t, _, _, _, _ in drawn)
|
||||
assert any(t == '43.8' and col is ORANGE for t, _, _, _, col in drawn)
|
||||
assert any(t == 'Cinque v3' and sz == 28 and col is TEXT for t, _, sz, _, col in drawn)
|
||||
|
||||
# Long model name (> 356px) pauses then scrolls horizontally inside a scissor clip.
|
||||
fonts.draw.reset_mock()
|
||||
long_name = 'Watermelon Indigo v10 / Cinque Divergence Mask'
|
||||
widget.status = JetlinkStatus('Computer', 'active', 24.6, model=long_name)
|
||||
with patch.object(onroad_jetlink.rl, 'draw_rectangle_rounded'), \
|
||||
patch.object(onroad_jetlink.rl, 'draw_circle_v'), \
|
||||
patch.object(onroad_jetlink.clip, 'begin_scissor_mode') as begin_scissor, \
|
||||
patch.object(onroad_jetlink.clip, 'end_scissor_mode') as end_scissor:
|
||||
widget.render(state)
|
||||
clock[0] = 103.0 # 1s past the 2s pause -> scrolled 40px left
|
||||
fonts.draw.reset_mock()
|
||||
widget.render(state)
|
||||
placed_x = state.customization['layouts']['large']['jetlink_status']['x'] + 32
|
||||
title_draws = [c.args for c in fonts.draw.call_args_list if c.args[0] == long_name]
|
||||
assert len(title_draws) == 1
|
||||
assert title_draws[0][3] == pytest.approx(placed_x - 40.0)
|
||||
|
||||
clock[0] = 113.0 # 11s past the 2s pause -> repeat copy enters the 356px clip
|
||||
fonts.draw.reset_mock()
|
||||
widget.render(state)
|
||||
|
||||
begin_scissor.assert_called()
|
||||
end_scissor.assert_called()
|
||||
title_draws = [c.args for c in fonts.draw.call_args_list if c.args[0] == long_name]
|
||||
assert len(title_draws) == 2
|
||||
expected_offset = scroll_offset(fonts.measure(long_name, FontRole.SEMI_BOLD, 28).width, 420 - 64, 13.0)
|
||||
assert expected_offset == pytest.approx(440.0)
|
||||
assert title_draws[0][3] == pytest.approx(placed_x - expected_offset)
|
||||
assert title_draws[1][3] > title_draws[0][3]
|
||||
|
||||
|
||||
def test_widget_shows_driving_model_only_when_jetlink_and_chestnut_are_off():
|
||||
fonts = _fake_fonts()
|
||||
widget = JetlinkStatusWidget(fonts, models=lambda: ('RDF V4', ''))
|
||||
state = _enabled_state()
|
||||
|
||||
card = big_model_card(JetlinkStatus(), None, False, small='Regret Driven Framework V4 👀📡')
|
||||
assert (card.title, card.detail, card.tier, card.dot is GREEN) == ('RDF V4', '', 'SMALL', True)
|
||||
|
||||
with patch.object(onroad_jetlink.rl, 'draw_rectangle_rounded'), \
|
||||
patch.object(onroad_jetlink.rl, 'draw_circle_v') as circles:
|
||||
widget.render(state)
|
||||
|
||||
# Single status circle (no separator bullet) and 'DRIVING MODEL' eyebrow
|
||||
assert len(circles.call_args_list) == 1
|
||||
assert circles.call_args_list[0].args[1] == 7.5
|
||||
assert circles.call_args_list[0].args[2] is GREEN
|
||||
drawn = [(c.args[0], c.args[2], c.args[5]) for c in fonts.draw.call_args_list]
|
||||
assert ('DRIVING MODEL', 20, onroad_jetlink.MUTED) in drawn
|
||||
assert ('RDF V4', 28, TEXT) in drawn
|
||||
|
||||
@@ -150,6 +150,7 @@ def test_renderer_dispatches_each_widget_in_saved_order(profile, viewport):
|
||||
view.projection_exit_layer = lambda state: seen.append(CAR_EXIT)
|
||||
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'))
|
||||
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'))
|
||||
|
||||
Reference in New Issue
Block a user