[MICI] ui: add Bluetooth settings panel

This commit is contained in:
Jason Wen
2026-11-25 01:50:53 -05:00
parent cb6b5d6913
commit 7d93cd16cd
4 changed files with 313 additions and 0 deletions
@@ -0,0 +1,86 @@
"""
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import time
from openpilot.selfdrive.ui.mici.widgets.button import BigButton, BigParamControl
from openpilot.selfdrive.ui.mici.widgets.dialog import BigConfirmationDialog
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.connect_phone import start_connect_phone
from openpilot.selfdrive.ui.ui_state import ui_state
from openpilot.sunnypilot.system.ble import grants
from openpilot.sunnypilot.system.connect_phone import write_request
from openpilot.system.ui.lib.application import gui_app
from openpilot.system.ui.lib.multilang import tr
from openpilot.system.ui.widgets.scroller import NavScroller
POLL_SECONDS = 1.0
def _phone_count(n: int) -> str:
return tr("none yet") if n == 0 else (tr("1 phone") if n == 1 else tr("{} phones").format(n))
class BluetoothLayoutMici(NavScroller):
def __init__(self):
super().__init__()
self._bluetooth_on = ui_state.params.get_bool("BluetoothAllowed")
def bluetooth_callback(checked: bool):
self._bluetooth_on = checked
self._bluetooth_toggle = BigParamControl(tr("bluetooth"), "BluetoothAllowed", toggle_callback=bluetooth_callback)
self._connect_phone_btn = BigButton(tr("connect phone"), "")
self._connect_phone_btn.set_click_callback(start_connect_phone)
self._connect_phone_btn.set_enabled(lambda: self._bluetooth_on)
self._phones_page = ConnectedPhonesMici()
self._phones_btn = BigButton(tr("connected phones"), "")
self._phones_btn.set_click_callback(lambda: gui_app.push_widget(self._phones_page))
self._phones_btn.set_visible(lambda: self._bluetooth_on)
self._last_poll = float("-inf")
self._scroller.add_widgets([self._bluetooth_toggle, self._connect_phone_btn, self._phones_btn])
def _update_state(self):
super()._update_state()
now = time.monotonic()
if now - self._last_poll >= POLL_SECONDS:
self._last_poll = now
self._phones_btn.set_value(_phone_count(len(grants.load(ui_state.params))))
class ConnectedPhonesMici(NavScroller):
def __init__(self):
super().__init__()
self._phone_items: list[BigButton] = []
self._grants: list[dict] | None = None
self._last_poll = float("-inf")
def _update_state(self):
super()._update_state()
now = time.monotonic()
if now - self._last_poll < POLL_SECONDS:
return
self._last_poll = now
phones = grants.load(ui_state.params)
if phones != self._grants:
self._grants = phones
for item in self._phone_items:
self._scroller._items.remove(item)
self._phone_items = [self._phone_item(phone) for phone in phones] or [BigButton(tr("no phones connected yet"), "")]
self._scroller.add_widgets(self._phone_items)
def _phone_item(self, phone: dict) -> BigButton:
spki = phone["spki"]
item = BigButton(phone["name"], tr("remove"))
item.set_click_callback(lambda: self._remove(spki))
return item
def _remove(self, spki: str) -> None:
icon = gui_app.texture("icons_mici/settings/network/new/trash.png", 54, 64)
gui_app.push_widget(BigConfirmationDialog(tr("slide to remove"), icon, lambda: write_request(ui_state.params, "remove", phone=spki), red=True))
@@ -0,0 +1,200 @@
"""
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import time
import pyray as rl
from openpilot.common.qrcode import make_texture
from openpilot.common.swaglog import cloudlog
from openpilot.selfdrive.ui.mici.widgets.dialog import BigConfirmationCircleButton, BigDialog
from openpilot.selfdrive.ui.ui_state import device, ui_state
from openpilot.sunnypilot.system.connect_phone import WINDOW_SECONDS, format_code, read_window, write_request
from openpilot.system.ui.lib.application import FontWeight, gui_app
from openpilot.system.ui.lib.multilang import tr
from openpilot.system.ui.mici_setup import GreyBigButton
from openpilot.system.ui.widgets.label import UnifiedLabel
from openpilot.system.ui.widgets.nav_widget import NavWidget
from openpilot.system.ui.widgets.scroller import NavScroller
POLL_SECONDS = 0.25
START_TIMEOUT = 15 # seconds from open to the first window for this request
LOST_SECONDS = 3 # the daemon restarted mid-window and no longer reports our seq
INTERACTIVE_TIMEOUT = WINDOW_SECONDS + 10 # the offroad idle timeout would pop the screen mid-window
def _closed_message(reason: str) -> str | None:
messages = {
"granted": tr("phone connected"),
"denied": tr("phone not connected"),
"no_answer": tr("allow not tapped in time"),
"phone_left": tr("phone disconnected"),
"wrong_codes": tr("too many wrong codes"),
"limit": tr("8 phones already connected"),
"timeout": tr("connect timed out"),
"bluetooth_off": tr("turn on bluetooth"),
"no_key": tr("device key unavailable"),
}
return messages.get(reason)
def start_connect_phone() -> None:
gui_app.push_widget(ConnectPhoneDialog())
class ConnectPhoneDialog(NavWidget):
def __init__(self):
super().__init__()
self._params = ui_state.params
self._seq = write_request(self._params, "open")
self._opened_at = time.monotonic()
self._next_poll = 0.0
self._was_open = False
self._lost_since: float | None = None
self._window: dict | None = None
self._closing = False
self._check_shown_for: float | None = None
self._qr_source = ""
self._qr_texture: rl.Texture | None = None
self._title = UnifiedLabel(tr("connect phone"), font_size=48, font_weight=FontWeight.BOLD,
text_color=rl.Color(255, 255, 255, int(255 * 0.9)), line_height=0.8)
self._status = UnifiedLabel("", font_size=36, font_weight=FontWeight.ROMAN,
text_color=rl.Color(255, 255, 255, int(255 * 0.65)))
self._code = UnifiedLabel("", font_size=48, font_weight=FontWeight.BOLD,
text_color=rl.Color(255, 255, 255, int(255 * 0.9)))
self.set_back_callback(self._cancel)
def show_event(self):
super().show_event()
device.set_override_interactive_timeout(INTERACTIVE_TIMEOUT)
def hide_event(self):
super().hide_event()
device.set_override_interactive_timeout(None)
if not self._closing:
self._cancel()
def _update_state(self):
super()._update_state()
if self._closing:
return
now = time.monotonic()
if now < self._next_poll:
return
self._next_poll = now + POLL_SECONDS
window = read_window(self._params)
# the request seq guards against a window left over from an earlier open
if window is None or window.get("seq") != self._seq:
self._window = None
if self._was_open:
# a daemon restart writes seq 0 and never reports our window again
if self._lost_since is None:
self._lost_since = now
if now - self._lost_since > LOST_SECONDS:
self._finish(None)
elif now - self._opened_at > START_TIMEOUT:
self._cancel()
self._finish(tr("bluetooth did not start"))
return
self._lost_since = None
self._window = window
prompt = window.get("prompt") or {}
if prompt.get("step") == "allow" and self._check_shown_for != prompt.get("until"):
self._check_shown_for = prompt.get("until")
gui_app.push_widget(ConnectPhoneCheckDialog(prompt.get("check", ""), self._params))
if window.get("state") == "closed":
self._finish(_closed_message(window.get("reason", "")))
elif window.get("state") == "open":
self._was_open = True
if not window.get("held") and now >= window["deadline"]:
self._finish(None)
def _cancel(self) -> None:
if not self._closing:
self._closing = True
write_request(self._params, "cancel")
def _finish(self, message: str | None) -> None:
self._closing = True
if message is None:
self.dismiss(lambda: None)
else:
self.dismiss(lambda: gui_app.push_widget(BigDialog(message, "")))
def _render(self, _):
window = self._window
held = window is not None and window.get("held", False)
show_code = window is not None and window.get("state") == "open" and not held
if show_code:
if window["qr"] != self._qr_source:
self._load_qr(window["qr"])
self._draw_qr()
label_x = self._rect.x + 8 + self._rect.height + 24 if show_code else self._rect.x + 20
max_width = int(self._rect.x + self._rect.width - label_x)
y = self._rect.y + 16
self._title.set_max_width(max_width)
self._title.set_position(label_x, y)
self._title.render()
y += self._title.get_content_height(max_width) + 16
if show_code:
remaining = max(0, int(window["deadline"] - time.monotonic()))
self._code.set_text(format_code(int(window["code"])))
self._code.set_max_width(max_width)
self._code.set_position(label_x, y)
self._code.render()
y += self._code.get_content_height(max_width) + 12
self._status.set_text(f"{tr('expires in')} {remaining // 60}:{remaining % 60:02d}")
elif held:
self._status.set_text(tr("connecting phone"))
else:
self._status.set_text("" if self._closing else tr("starting bluetooth"))
self._status._shimmer = not show_code and not self._closing
self._status.set_max_width(max_width)
self._status.set_position(label_x, y)
self._status.render()
def _load_qr(self, text: str) -> None:
self._unload_qr()
self._qr_source = text
try:
self._qr_texture = make_texture(text, inverted=True)
except Exception:
cloudlog.exception("connect phone QR generation failed")
self._qr_texture = None
def _draw_qr(self) -> None:
if self._qr_texture is None:
return
scale = self._rect.height / self._qr_texture.height
rl.draw_texture_ex(self._qr_texture, rl.Vector2(round(self._rect.x + 8), round(self._rect.y)), 0.0, scale, rl.WHITE)
def _unload_qr(self) -> None:
if self._qr_texture and self._qr_texture.id != 0:
rl.unload_texture(self._qr_texture)
self._qr_texture = None
def __del__(self):
self._unload_qr()
class ConnectPhoneCheckDialog(NavScroller):
def __init__(self, check: str, params):
super().__init__()
self._params = params
allow = BigConfirmationCircleButton(tr("allow\nthis phone"), gui_app.texture("icons_mici/setup/driver_monitoring/dm_check.png", 64, 64),
lambda: self._answer("allow"))
deny = BigConfirmationCircleButton(tr("deny"), gui_app.texture("icons_mici/setup/cancel.png", 64, 64), lambda: self._answer("deny"))
self._scroller.add_widgets([GreyBigButton(check, tr("same code on your phone?"), gui_app.texture("icons_mici/setup/green_info.png", 64, 64)),
allow, deny])
def _answer(self, action: str) -> None:
self.dismiss(lambda: write_request(self._params, action))
@@ -5,19 +5,38 @@ This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import math
import time
import pyray as rl
from openpilot.selfdrive.ui.mici.layouts.home import MiciHomeLayout
from openpilot.selfdrive.ui.ui_state import ui_state, ChestnutState
from openpilot.sunnypilot.system.connect_phone import phone_indicator, read_status
from openpilot.system.ui.lib.application import FontWeight
from openpilot.system.ui.widgets.icon_widget import IconWidget
from openpilot.system.ui.widgets.label import UnifiedLabel
BT_POLL_SECONDS = 1.0
BT_WAITING_OPACITY = 0.35
class MiciHomeLayoutSP(MiciHomeLayout):
def __init__(self):
super().__init__()
self._openpilot_label = UnifiedLabel("sunnypilot", font_size=88, font_weight=FontWeight.AUDIOWIDE, max_width=480, wrap_text=False)
self._bluetooth_icon = IconWidget("../../sunnypilot/selfdrive/assets/offroad/icon_bluetooth.png", (40, 40))
self._bluetooth_icon.set_visible(False)
self._bt_polled_at = float("-inf")
self._status_bar_layout.add_widget(self._bluetooth_icon)
def _update_state(self):
super()._update_state()
now = time.monotonic()
if now - self._bt_polled_at >= BT_POLL_SECONDS:
self._bt_polled_at = now
state = phone_indicator(read_status(ui_state.params))
self._bluetooth_icon.set_visible(state != "hidden")
self._bluetooth_icon.set_opacity(1.0 if state == "connected" else BT_WAITING_OPACITY)
def _set_chestnut_visibility(self):
usb_connected = ui_state.usb_connected
@@ -11,6 +11,7 @@ from openpilot.selfdrive.ui.mici.widgets.button import BigCircleButton
from openpilot.selfdrive.ui.mici.widgets.dialog import BigConfirmationDialog, BigDialog
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.sunnylink import SunnylinkLayoutMici
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.models import ModelsLayoutMici
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.bluetooth import BluetoothLayoutMici
from openpilot.selfdrive.ui.ui_state import ui_state
from openpilot.system.ui.lib.application import gui_app, FontWeight
from openpilot.system.ui.lib.multilang import tr
@@ -50,6 +51,12 @@ class SettingsLayoutSP(OP.SettingsLayout):
models_btn = SettingsBigButton(tr("models"), "", gui_app.texture("../../sunnypilot/selfdrive/assets/offroad/icon_models.png", ICON_SIZE, ICON_SIZE))
models_btn.set_click_callback(lambda: gui_app.push_widget(models_panel))
network_btn = self._scroller._items[1]
bluetooth_panel = BluetoothLayoutMici()
bluetooth_btn = SettingsBigButton(tr("bluetooth"), "",
gui_app.texture("../../sunnypilot/selfdrive/assets/offroad/icon_bluetooth.png", ICON_SIZE, ICON_SIZE))
bluetooth_btn.set_click_callback(lambda: gui_app.push_widget(bluetooth_panel))
# onroad: enable button sits at the front (left of toggles)
self._enable_offroad_btn_onroad = BigCircleButton(self.icon_offroad_enable, red=True)
self._enable_offroad_btn_onroad.set_click_callback(lambda: self._handle_always_offroad(True))
@@ -68,6 +75,7 @@ class SettingsLayoutSP(OP.SettingsLayout):
items.insert(1, models_btn)
items.insert(5, sunnylink_btn)
items.insert(items.index(network_btn) + 1, bluetooth_btn)
# front slots (only one ever visible at a time): exit-always-offroad, then enable-onroad
items.insert(0, self._enable_offroad_btn_onroad)