From 00be4586e272a02ae894ba06137ff6cd5df77f95 Mon Sep 17 00:00:00 2001 From: Danny Date: Mon, 23 Nov 2026 07:22:32 -0800 Subject: [PATCH 1/2] StarPort: Add wired hands-free toggle for cars that need it, and remove the Fit fix --- openpilot/starpilot/galaxy/device_settings.py | 12 +++ .../starpilot/galaxy/setting_descriptions.py | 2 + .../tests/description-key-inventory.json | 1 + .../galaxy/tests/test_device_settings.py | 20 ++++- .../system/starport/bluetooth_bridge.py | 4 + .../starpilot/system/starport/bluez_phone.py | 7 ++ openpilot/starpilot/system/starport/daemon.py | 2 + .../system/starport/head_unit_fixes.py | 11 +-- .../starpilot/system/starport/identity.py | 2 + .../starpilot/system/starport/session.py | 25 ++++-- .../starpilot/system/starport/supervisor.py | 72 +++++++++++++++-- .../starport/tests/test_head_unit_fixes.py | 13 ---- .../tests/test_head_unit_fixes_session.py | 29 ++++++- .../starport/tests/test_wired_handsfree.py | 78 +++++++++++++++++++ 14 files changed, 239 insertions(+), 39 deletions(-) create mode 100644 openpilot/starpilot/system/starport/tests/test_wired_handsfree.py diff --git a/openpilot/starpilot/galaxy/device_settings.py b/openpilot/starpilot/galaxy/device_settings.py index 3f5a8bbae4..0ebbc06bae 100644 --- a/openpilot/starpilot/galaxy/device_settings.py +++ b/openpilot/starpilot/galaxy/device_settings.py @@ -29,6 +29,11 @@ STARPORT_UNACKED_VIDEO_DESCRIPTION = ("Experimental. For a car that shows video "and reconnects every few seconds. Sends video without waiting for acknowledgments, on " + "H.264 or H.265. Applies from the next StarPort connection.") STARPORT_PATIENT_TCP_KEY = "StarPortPatientConnect" +STARPORT_WIRED_HANDSFREE_KEY = "StarPortWiredHandsFree" +STARPORT_WIRED_HANDSFREE_DESCRIPTION = ("Experimental. For a car that stays on its own screen over USB, or shows Bluetooth connecting. " + + "Connects hands-free to the car and sends the Bluetooth pairing request before asking for the " + + "screen, as a phone does. Pair the comma in the car's Bluetooth menu first. It may take the " + + "car's hands-free link from your phone. Applies from the next StarPort connection.") STARPORT_PATIENT_TCP_DESCRIPTION = ("Experimental. For a wireless adapter that hands over its Wi-Fi but then refuses the connection, " + "as if it is still starting up. Keeps trying for up to a minute instead of about 15 seconds. " + "Applies from the next StarPort connection.") @@ -85,6 +90,11 @@ class DeviceSettingsOwner: b"1" if patient_tcp else b"0", ("Off", "On"), available=parked, reason=STARPORT_PATIENT_TCP_DESCRIPTION if parked else held, default_value="Off")) + wired_handsfree = bool(status.get("wired_handsfree")) + rows.append(FeatureRow(STARPORT_WIRED_HANDSFREE_KEY, "Wired hands-free", "On" if wired_handsfree else "Off", + b"1" if wired_handsfree else b"0", + ("Off", "On"), available=parked, reason=STARPORT_WIRED_HANDSFREE_DESCRIPTION if parked else held, + default_value="Off")) experiments = bool(status.get("head_unit_experiments")) chosen = set(status.get("head_unit_experiment_rules") or ()) rows.append(FeatureRow(STARPORT_EXPERIMENTS_KEY, "Try experimental fixes", "On" if experiments else "Off", @@ -177,6 +187,8 @@ class DeviceSettingsOwner: return self._apply_starport(request, "unacked_video", "set_unacked_video") if request.key == STARPORT_PATIENT_TCP_KEY: return self._apply_starport(request, "patient_tcp", "set_patient_tcp") + if request.key == STARPORT_WIRED_HANDSFREE_KEY: + return self._apply_starport(request, "wired_handsfree", "set_wired_handsfree") if request.key == STARPORT_EXPERIMENTS_KEY: return self._apply_starport(request, "head_unit_experiments", "set_head_unit_experiments") if request.key.startswith(STARPORT_EXPERIMENT_PREFIX): diff --git a/openpilot/starpilot/galaxy/setting_descriptions.py b/openpilot/starpilot/galaxy/setting_descriptions.py index 2d573034ad..8725f07990 100644 --- a/openpilot/starpilot/galaxy/setting_descriptions.py +++ b/openpilot/starpilot/galaxy/setting_descriptions.py @@ -127,6 +127,7 @@ DESCRIPTIONS = { 'StarPortTallHevc': 'Uses the car\'s 1080x1920 H.265 screen mode instead of 720x1280, to diagnose H.265-only cars. Needs Allow H.265 video on.', 'StarPortUnackedVideo': 'Sends video without waiting for the car\'s acknowledgments, on H.264 or H.265, for cars that show video but never acknowledge it.', 'StarPortPatientConnect': 'Keeps trying for up to a minute when a wireless adapter hands over its Wi-Fi but refuses the connection.', + 'StarPortWiredHandsFree': 'Over USB, connects hands-free to the car and sends the Bluetooth pairing request before asking for the screen, as a phone does.', 'StarPortHeadUnitExperiments': 'Shows experimental fixes for specific cars and dongles, each with its own switch. Off is the standard connection.', 'StarPortDedicatedWifi': "Joins the car's Wi-Fi on a second interface so the comma stays on its home Wi-Fi or phone hotspot.", 'TeslaWakeOnCAN': 'Wakes comma when the Tesla wakes up, before you press the brake.', @@ -203,6 +204,7 @@ INITIALIZATION = { 'StarPortTallHevc': 'Applies from the next StarPort connection.', 'StarPortUnackedVideo': 'Applies from the next StarPort connection.', 'StarPortPatientConnect': 'Applies from the next StarPort connection.', + 'StarPortWiredHandsFree': 'Applies from the next StarPort connection.', 'StarPortHeadUnitExperiments': 'Applies from the next StarPort connection.', 'StarPortDedicatedWifi': 'Applies from the next StarPort connection.', 'LateralControllerSelection': ('Applies when driving processes next start: the controller class, vehicle policy and ' + diff --git a/openpilot/starpilot/galaxy/tests/description-key-inventory.json b/openpilot/starpilot/galaxy/tests/description-key-inventory.json index 06a4a18e32..5653b654b7 100644 --- a/openpilot/starpilot/galaxy/tests/description-key-inventory.json +++ b/openpilot/starpilot/galaxy/tests/description-key-inventory.json @@ -123,6 +123,7 @@ "StarPortPatientConnect", "StarPortTallHevc", "StarPortUnackedVideo", + "StarPortWiredHandsFree", "SteerFriction", "SteerLatAccel", "StockConfidenceBallWidget", diff --git a/openpilot/starpilot/galaxy/tests/test_device_settings.py b/openpilot/starpilot/galaxy/tests/test_device_settings.py index 5cd44d0d2f..651df49406 100644 --- a/openpilot/starpilot/galaxy/tests/test_device_settings.py +++ b/openpilot/starpilot/galaxy/tests/test_device_settings.py @@ -12,6 +12,7 @@ from openpilot.starpilot.galaxy.device_settings import (CALIBRATION_RESET, DRIVE STARPORT_EXPERIMENTS_KEY, STARPORT_HEVC_KEY, STARPORT_KEYFRAME_TEST_KEY, STARPORT_TALL_HEVC_KEY, STARPORT_UNACKED_VIDEO_KEY, STARPORT_PATIENT_TCP_KEY, + STARPORT_WIRED_HANDSFREE_KEY, STARPORT_WIFI_KEY, DeviceSettingsOwner) from openpilot.starpilot.galaxy.settings import AuthorityContext, ContextSource, SettingsChanged, SettingsGateway, PAGES from openpilot.starpilot.longitudinal.voacc import KEY, selected @@ -45,7 +46,7 @@ class FileParams: class FakeStarPort: def __init__(self, enabled=False, running=True): self.enabled, self.running, self.hevc = enabled, running, False - self.keyframe_test = self.tall_hevc = self.unacked_video = self.patient_tcp = False + self.keyframe_test = self.tall_hevc = self.unacked_video = self.patient_tcp = self.wired_handsfree = False self.experiments, self.rules = False, [] def call(self, command, **payload): @@ -66,6 +67,9 @@ class FakeStarPort: if command == "set_patient_tcp": self.patient_tcp = payload["enabled"] return {"ok": True} + if command == "set_wired_handsfree": + self.wired_handsfree = payload["enabled"] + return {"ok": True} if command == "set_unacked_video": self.unacked_video = payload["enabled"] return {"ok": True} @@ -77,6 +81,7 @@ class FakeStarPort: return {"ok": True, "changed": True} return {"ok": True, "status": {"dedicated_wifi_interface": self.enabled, "allow_hevc": self.hevc, "keyframe_test": self.keyframe_test, "tall_hevc": self.tall_hevc, "unacked_video": self.unacked_video, "patient_tcp": self.patient_tcp, + "wired_handsfree": self.wired_handsfree, "head_unit_experiments": self.experiments, "head_unit_experiment_rules": self.rules}} @@ -348,6 +353,17 @@ class DeviceSettingsTest(unittest.TestCase): self.assertTrue(service.patient_tcp) self.assertFalse(service.unacked_video) + def test_wired_handsfree_defaults_off_and_follows_the_daemon(self): + service = FakeStarPort() + owner = DeviceSettingsOwner(self.params, lambda: self.parked, starport=lambda: service) + rows = owner.snapshot("starport_options").rows + keys = [row.key for row in rows] + row = rows[keys.index(STARPORT_WIRED_HANDSFREE_KEY)] + self.assertEqual((row.value, row.default_value, row.available), ("Off", "Off", True)) + self.assertTrue(owner.apply(FeatureSettingsRequest(STARPORT_WIRED_HANDSFREE_KEY, row.source, "On"))) + self.assertTrue(service.wired_handsfree) + self.assertFalse(service.unacked_video or service.experiments) + def test_try_experimental_fixes_defaults_off_and_is_the_only_master_switch(self): service = FakeStarPort() owner = DeviceSettingsOwner(self.params, lambda: self.parked, starport=lambda: service) @@ -372,7 +388,7 @@ class DeviceSettingsTest(unittest.TestCase): keys = [row.key for row in rows] self.assertEqual(keys[keys.index(STARPORT_EXPERIMENTS_KEY) + 1:], [STARPORT_EXPERIMENT_PREFIX + "gm_mychevrolet_w28e", STARPORT_EXPERIMENT_PREFIX + "polestar_ps2_aar_301433653", - STARPORT_EXPERIMENT_PREFIX + "honda_fit_t5a_83_01d", STARPORT_EXPERIMENT_PREFIX + "phone_ping"]) + STARPORT_EXPERIMENT_PREFIX + "phone_ping"]) rule_key = STARPORT_EXPERIMENT_PREFIX + "gm_mychevrolet_w28e" row = rows[keys.index(rule_key)] self.assertEqual((row.value, row.default_value, row.available), ("Off", "Off", True)) diff --git a/openpilot/starpilot/system/starport/bluetooth_bridge.py b/openpilot/starpilot/system/starport/bluetooth_bridge.py index 0b5814686e..1e6a1006a0 100644 --- a/openpilot/starpilot/system/starport/bluetooth_bridge.py +++ b/openpilot/starpilot/system/starport/bluetooth_bridge.py @@ -879,6 +879,10 @@ class LeaseAwarePhone: self._require_lease() self.phone.connect_device(address) + def connect_handsfree(self, address): + self._require_lease() + self.phone.connect_handsfree(address) + def disconnect_stray_link(self): self._require_lease() return self.phone.disconnect_stray_link() diff --git a/openpilot/starpilot/system/starport/bluez_phone.py b/openpilot/starpilot/system/starport/bluez_phone.py index bc692d323a..42461b7c2e 100644 --- a/openpilot/starpilot/system/starport/bluez_phone.py +++ b/openpilot/starpilot/system/starport/bluez_phone.py @@ -186,6 +186,13 @@ class BluezPhone: # raw SDP/RFCOMM socket needs is created on demand anyway. self.log("device_connect_warning", error=str(error)) + def connect_handsfree(self, address: str, timeout: float = 10.0) -> None: + """Open only the hands-free link, even when the car is already connected for something else.""" + info = self.device(address) + if info is None: + raise RuntimeError(f"{address} is not known to Bluetooth; pair the car first") + self._call(info["path"], DEVICE_IFACE, "ConnectProfile", "s", (HFP_HF_UUID,), timeout=timeout) + # ---------------------------------------------------------- phone identity def acquire(self, phone_class: bool = True) -> None: diff --git a/openpilot/starpilot/system/starport/daemon.py b/openpilot/starpilot/system/starport/daemon.py index bc144e501b..9b89b2f5c0 100644 --- a/openpilot/starpilot/system/starport/daemon.py +++ b/openpilot/starpilot/system/starport/daemon.py @@ -128,6 +128,8 @@ def handle(supervisor: Supervisor, request: dict[str, Any], verifier: StarPortSo supervisor.set_unacked_video(request.get("enabled") is True) elif command == "set_patient_tcp": supervisor.set_patient_tcp(request.get("enabled") is True) + elif command == "set_wired_handsfree": + supervisor.set_wired_handsfree(request.get("enabled") is True) elif command == "set_head_unit_experiments": supervisor.set_head_unit_experiments(request.get("enabled") is True) elif command == "set_head_unit_experiment_rule": diff --git a/openpilot/starpilot/system/starport/head_unit_fixes.py b/openpilot/starpilot/system/starport/head_unit_fixes.py index 547c19401e..cdc3a1c36d 100644 --- a/openpilot/starpilot/system/starport/head_unit_fixes.py +++ b/openpilot/starpilot/system/starport/head_unit_fixes.py @@ -16,8 +16,7 @@ OPEN_SENSORS = "open_sensors" # open the car-data channel (driving OPEN_VENDOR = "open_vendor" # open the car's vendor channel; nothing is sent on it REQUEST_BT_PAIRING = "request_bt_pairing" # send the Bluetooth pairing request with this comma's own address UNACKED_VIDEO = "unacked_video" # send video without waiting for acknowledgments; the car's pings show it is there -OPEN_PHONE_SERVICES = "open_phone_services" # open the car-data and Bluetooth channels together, as a phone does -ACTIONS = (OPEN_BLUETOOTH, OPEN_PHONE_STATUS, OPEN_SENSORS, OPEN_VENDOR, REQUEST_BT_PAIRING, UNACKED_VIDEO, OPEN_PHONE_SERVICES) +ACTIONS = (OPEN_BLUETOOTH, OPEN_PHONE_STATUS, OPEN_SENSORS, OPEN_VENDOR, REQUEST_BT_PAIRING, UNACKED_VIDEO) # ServiceDiscoveryResponse field numbers (JSON turns them into strings). SDR_LABELS = {"2": "car_make", "3": "car_model", "4": "car_year", "7": "head_unit_make", "8": "head_unit_model", @@ -64,14 +63,6 @@ RULES: tuple[Rule, ...] = ( ("2026-11-16 sessions 1-15",)), ladder=(UNACKED_VIDEO,), summary="This car shows a still picture for a few seconds, then reconnects, over and over."), - Rule(id="honda_fit_t5a_83_01d", label="2018 Honda Fit (83.01D.00.B.1021 build)", - match={"car_make": "Honda", "car_model": "T5A", "car_year": "2018", "head_unit_make": "HONDA/06", - "head_unit_model": "39100-T5A-L313-M1", "head_unit_software_version": "83.01D.00.B.1021"}, - transports=(WIRED,), status=EXPERIMENTAL, - evidence=Evidence("The car answers the screen request with its own screen and stays silent when the Android Auto tile is tapped.", - ("2026-11-22 sessions 1, 6-9", "2026-11-22 after-tap sessions 1, 3")), - ladder=(OPEN_PHONE_SERVICES,), - summary="This car connects but never shows the Android Auto screen."), ) diff --git a/openpilot/starpilot/system/starport/identity.py b/openpilot/starpilot/system/starport/identity.py index 4f2c783ced..5c131542fd 100644 --- a/openpilot/starpilot/system/starport/identity.py +++ b/openpilot/starpilot/system/starport/identity.py @@ -153,6 +153,7 @@ DEFAULT_CONFIG = { "tall_hevc": False, # H.265 only: use the car's 1080x1920 mode when offered (Galaxy Developer > StarPort) "unacked_video": False, # any codec: send video without waiting for the car's acknowledgments (Galaxy Developer > StarPort) "patient_tcp": False, # wireless: keep retrying a refused projection connection for a minute (Galaxy Developer > StarPort) + "wired_handsfree": False, # wired: connect hands-free and send the pairing request before asking for the screen (Galaxy Developer > StarPort) "keyframe_test": False, # H.265 sessions only: every frame a keyframe, plus ack and frame logging (Galaxy Developer > StarPort) "device_name": "StarPilot", "version_status": 0, # WifiVersionResponse status (0 = success) for receivers that negotiate a version @@ -210,6 +211,7 @@ def load_config(path: Path | None = None) -> dict: config["tall_hevc"] = config["tall_hevc"] is True config["unacked_video"] = config["unacked_video"] is True config["patient_tcp"] = config["patient_tcp"] is True + config["wired_handsfree"] = config["wired_handsfree"] is True config["head_unit_experiments"] = config["head_unit_experiments"] is True config["head_unit_experiment_rules"] = sorted({str(rule)[:64] for rule in config["head_unit_experiment_rules"] if isinstance(rule, str)})[:16] diff --git a/openpilot/starpilot/system/starport/session.py b/openpilot/starpilot/system/starport/session.py index 217ec5b2e1..20ae9e54be 100644 --- a/openpilot/starpilot/system/starport/session.py +++ b/openpilot/starpilot/system/starport/session.py @@ -748,6 +748,8 @@ class ProjectionSession(Session): self.head_unit_info: dict = {} self.on_discovered: Callable[[dict], tuple[str, ...]] | None = None # set by the supervisor: the car-specific actions to run self.fix_actions: tuple[str, ...] = () + # set by the supervisor with the wired hands-free toggle: connects to the car's address, returns this comma's address or "" + self.connect_handsfree: Callable[[str], str] | None = None self.focus_requested_at: float | None = None self.focus_granted_at: float | None = None self.nav = None # NavStatus, attached by the supervisor when the head unit offers turn-by-turn @@ -776,7 +778,10 @@ class ProjectionSession(Session): self.event("fix_selection_failed", error=str(error)[:120]) self.open_video() self.open_input() - if self.phone_services: + if self.connect_handsfree is not None: + self._open_sensors() + self.link_handsfree() + elif self.phone_services: self.open_phone_services() if self.fix_actions: self.run_fix_actions() @@ -894,10 +899,6 @@ class ProjectionSession(Session): done = False if action == "open_bluetooth": done = self.bluetooth_channel is not None or self._open_bluetooth(pair=False) - elif action == "open_phone_services": - sensors = self.sensor_channel is not None or self._open_sensors() - bluetooth = self.bluetooth_channel is not None or self._open_bluetooth(pair=False) - done = sensors and bluetooth elif action == "open_phone_status": if self.phone_status_channel is None: self.phone_status_channel = self._open_service(PHONE_STATUS_SERVICE, "phone_status") @@ -917,6 +918,20 @@ class ProjectionSession(Session): done = True self.event("fix_action", action=action, done=done) + def link_handsfree(self) -> bool: + """Connect hands-free to the address the car reports, then send the pairing request, as a wired phone does.""" + if self.connect_handsfree is None or not (self.bluetooth_channel is not None or self._open_bluetooth(pair=False)): + return False + car_bt = next((ch for ch in self.channels if ch.get("id") == self.bluetooth_channel), {}).get("bluetooth") or {} + car_address = car_bt.get("car_address", "") + linked = self.connect_handsfree(car_address) if car_address else "" + sent = bool(linked) + if sent: + self.phone_address = linked + self._send_pairing_request(car_bt.get("pairing_methods") or []) + self.event("handsfree_link", has_car_address=bool(car_address), pairing_request_sent=sent) + return sent + def request_projection(self) -> None: """Ask for display focus; the Mazda donor needed this, DHU grants it unsolicited.""" assert self.mode is not None diff --git a/openpilot/starpilot/system/starport/supervisor.py b/openpilot/starpilot/system/starport/supervisor.py index 7b6da59156..82c5e6d8c2 100644 --- a/openpilot/starpilot/system/starport/supervisor.py +++ b/openpilot/starpilot/system/starport/supervisor.py @@ -74,6 +74,8 @@ HFP_FRESH = 3.0 # a hands-free link from the car this recent still COMMA_PAGE_WINDOW = 6.0 # a hands-free link this soon after we paged the car is ours; later is the car's RFCOMM_BUSY_WAITS = (1.0, 2.0) # the kernel can still hold the last session's channel for a moment CAR_FIRST_WAIT = 8.0 # at ignition, give the car this long to open hands-free before the comma pages it +WIRED_HFP_WAIT = 8.0 # wired hands-free: longest wait for the car to take the hands-free link +WIRED_HFP_SETTLE = 1.0 # the car finishes its hands-free setup before it is asked for the screen NO_STARPORT_WAIT = 8.0 # a paired device must offer wireless projection within this long USB_HANDSHAKE_WAIT = 10.0 # the car connected but sent no AOA START this long -> present as an accessory directly USB_CONFIGURE_WAIT = 15.0 # slower receivers need time to enumerate after the AOA switch @@ -84,7 +86,7 @@ STALL_CAPTURE_S = 20.0 # device logs kept from before a shared-radio stall REPORTED_SETTINGS = ("connection", "usb_mode", "view", "encoder", "fps", "bitrate_kbps", "rate_control", "gpu_nv12", "async_readback", "wifi_interface", "dedicated_wifi_interface", "verify_head_unit", "version_status", "rfcomm_channel", "phone_class", "auto_connect", "allow_hevc", "keyframe_test", "tall_hevc", - "unacked_video", "patient_tcp", "head_unit_experiments", "head_unit_experiment_rules") + "unacked_video", "patient_tcp", "wired_handsfree", "head_unit_experiments", "head_unit_experiment_rules") def _open_projection(ip: str, ports: list[int], advertised: int, local_ip: str, log) -> socket.socket: @@ -394,6 +396,7 @@ class Supervisor: _pairing_note = "" # why a paired car was not chosen, kept after the pairing window closes _reset_note: dict | None = None # a handshake reset waiting for a session log to be written to _no_starport_since = 0.0 + _wired_car = "" # the car's Bluetooth address while a wired session holds hands-free def __init__(self, bluez_factory=None, lease_factory=None, bluetooth_client=None, frame_path: str | None = None, synthetic: bool = False, car_frame_path: str = CAR_FRAME_PATH, touch_path: str = DEFAULT_TOUCH_SOCKET, control_path: str = DEFAULT_CONTROL_SOCKET, renderer_command: list[str] | None = None, onroad=_is_onroad, @@ -490,6 +493,7 @@ class Supervisor: status["tall_hevc"] = bool(self.config["tall_hevc"]) status["unacked_video"] = bool(self.config["unacked_video"]) status["patient_tcp"] = bool(self.config["patient_tcp"]) + status["wired_handsfree"] = bool(self.config["wired_handsfree"]) status["head_unit_experiments"] = bool(self.config["head_unit_experiments"]) status["head_unit_experiment_rules"] = list(self.config["head_unit_experiment_rules"]) status["experimental_fixes"] = head_unit_fixes.experimental_entries() @@ -559,6 +563,13 @@ class Supervisor: identity_store.save_config(self.config) self.log("patient_tcp_selected", enabled=bool(enabled)) + def set_wired_handsfree(self, enabled: bool) -> None: + """Wired sessions connect hands-free to the car and send the pairing request before asking for the screen; from the next session.""" + with self._lock: + self.config["wired_handsfree"] = bool(enabled) + identity_store.save_config(self.config) + self.log("wired_handsfree_selected", enabled=bool(enabled)) + def set_head_unit_experiments(self, enabled: bool) -> None: """The master switch for car and dongle fixes; off gives the standard connection to every car from the next session.""" with self._lock: @@ -1171,7 +1182,7 @@ class Supervisor: from openpilot.starpilot.system.starport.bluetooth_bridge import LeaseAwarePhone bluez = LeaseAwarePhone(self._shared_bluetooth_owner, self._source_session, self.log, enabled=self._projection_enabled, - selected_receiver=lambda: self.config['receiver_address']) + selected_receiver=self._selected_receiver) else: raise RuntimeError('Shared StarPilot Bluetooth owner is required for wireless Android Auto') bluez.accepts = self._hfp_accepts @@ -1186,8 +1197,11 @@ class Supervisor: thread = self._thread return thread is not None and thread.is_alive() + def _selected_receiver(self) -> str: + return self._wired_car or self.config["receiver_address"] + def _hfp_accepts(self, address: str) -> bool: - receiver = self.config["receiver_address"] + receiver = self._selected_receiver() if self._pairing_active() and self._source_session is not None and self._shared_bluetooth_owner is not None: lease = self._shared_bluetooth_owner.phone_lease return bool(lease is not None and not lease.released and @@ -1303,7 +1317,7 @@ class Supervisor: raise error def _hfp_connected(self, address: str) -> None: - if address.upper() in (self.config["receiver_address"].upper(), self.config.get("companion_address", "").upper()): + if address.upper() in (self._selected_receiver().upper(), self.config.get("companion_address", "").upper()): now = time.monotonic() since_page = now - self._paged_at self.log("hfp_initiator", initiator="comma" if since_page < COMMA_PAGE_WINDOW else "car", since_page_s=round(since_page, 1)) @@ -1785,7 +1799,53 @@ class Supervisor: failed = True raise finally: - self._release_usb(gadget, bridge, listener, failed) + try: + self._release_usb(gadget, bridge, listener, failed) + finally: + self._end_wired_handsfree() + + def _end_wired_handsfree(self) -> None: + if not self._wired_car: + return + self._wired_car = "" + try: + self._release_phone() + except Exception as error: + self.log("wired_handsfree_release_failed", kind=type(error).__name__, error=str(error)[:120]) + + def _wired_handsfree(self, car_address: str) -> str: + """Some cars give the screen only to a phone on hands-free. Returns this comma's address once linked, else "".""" + address = car_address.upper() + started = time.monotonic() + try: + bluez = self._phone() + ready, device = bluez.snapshot(address) + if not (ready and device and device["paired"]): + # last octet only: shows whether the car's Android Auto address differs from the one it paired with + paired = [item["address"][-2:] for item in bluez.devices() if item.get("paired")] if ready else [] + self.log("wired_handsfree", outcome="not_paired" if ready else "bluetooth_off", car_tail=address[-2:], paired_tails=paired) + return "" + self._wired_car = address + self._hfp_link.clear() + bluez.acquire() + try: + bluez.connect_handsfree(address) + except RuntimeError as error: + self.log("wired_handsfree_connect_warning", error=str(error)[:120]) + linked = self._hfp_link.wait(WIRED_HFP_WAIT) + if linked: + time.sleep(WIRED_HFP_SETTLE) + connected = bool((bluez.snapshot(address)[1] or {}).get("connected")) + self.log("wired_handsfree", outcome="linked" if linked else "no_link", waited_s=round(time.monotonic() - started, 1), + car_connected=connected) + phone = self._adapter_address() if linked else "" + if not phone: + self._end_wired_handsfree() + return phone + except Exception as error: + self.log("wired_handsfree", outcome="failed", kind=type(error).__name__, error=str(error)[:120]) + self._end_wired_handsfree() + return "" def _attempt_headunitpad(self) -> None: """HeadunitPad or Open Headunit: the tablet, on the Galaxy hotspot or the same LAN, finds this port and connects like a head unit.""" @@ -2047,6 +2107,8 @@ class Supervisor: self._stage("negotiating") self._fix_context = None session.on_discovered = self._choose_fixes + if config["connection"] == "wired" and config["wired_handsfree"]: + session.connect_handsfree = self._wired_handsfree session.touch_units = dict(config.get("touch_units_cache", {})) session.on_touch_units = self._remember_touch_units mode = session.start(config["device_name"], "comma.ai") diff --git a/openpilot/starpilot/system/starport/tests/test_head_unit_fixes.py b/openpilot/starpilot/system/starport/tests/test_head_unit_fixes.py index ecc2b0bdeb..fafed21f0f 100644 --- a/openpilot/starpilot/system/starport/tests/test_head_unit_fixes.py +++ b/openpilot/starpilot/system/starport/tests/test_head_unit_fixes.py @@ -97,19 +97,6 @@ def test_gates_block_selection(kwargs): assert pick(CFG_ON, **kwargs) is None -FIT = {"car_make": "Honda", "car_model": "T5A", "car_year": "2018", "head_unit_make": "HONDA/06", - "head_unit_model": "39100-T5A-L313-M1", "head_unit_software_version": "83.01D.00.B.1021"} -FIT_ON = {"head_unit_experiments": True, "head_unit_experiment_rules": ["honda_fit_t5a_83_01d"]} - - -def test_fit_rule_opens_phone_services_on_wired_only(): - selection = pick(FIT_ON, FIT, transport="wired", key="usb:fit") - assert selection is not None and selection.actions == (hf.OPEN_PHONE_SERVICES,) - assert pick(FIT_ON, FIT, transport="wireless") is None - assert pick(FIT_ON, {**FIT, "head_unit_software_version": "83.01E.00.B.1021"}, transport="wired", key="usb:fit") is None - assert pick({"head_unit_experiments": True}, FIT, transport="wired", key="usb:fit") is None - - def test_wired_selection_with_key(): assert pick(CFG_ON, transport="wired", key="usb:x") is not None diff --git a/openpilot/starpilot/system/starport/tests/test_head_unit_fixes_session.py b/openpilot/starpilot/system/starport/tests/test_head_unit_fixes_session.py index 1b6343e021..037ac11465 100644 --- a/openpilot/starpilot/system/starport/tests/test_head_unit_fixes_session.py +++ b/openpilot/starpilot/system/starport/tests/test_head_unit_fixes_session.py @@ -74,10 +74,13 @@ def test_ladder_adds_one_channel_per_level(identity, tmp_path): assert VENDOR_CHANNEL in hu.opened and hu.pairing_requests == [] -def test_phone_services_action_opens_sensors_and_bluetooth_without_pairing(identity, tmp_path): +def handsfree_session(identity, answer, preloaded=""): hu = FakeHeadUnit(identity, bolt=True) session = connect(hu, identity) - session.on_discovered = lambda info: (hf.OPEN_PHONE_SERVICES,) + session.phone_services = bool(preloaded) + session.phone_address = preloaded + asked = [] + session.connect_handsfree = lambda car: asked.append(car) or answer session.authenticate() session.start("StarPilot", "comma.ai") pump_until(session, lambda: session.focused, timeout=8.0) @@ -85,8 +88,26 @@ def test_phone_services_action_opens_sensors_and_bluetooth_without_pairing(ident session.peer.close() hu.thread.join(5) assert hu.error is None, hu.error - assert sorted(hu.opened) == [1, 3, SENSOR_CHANNEL, BLUETOOTH_CHANNEL] - assert hu.sensor_requests and hu.pairing_requests == [] + return hu, asked + + +def test_wired_handsfree_sends_pairing_request_with_the_linked_address(identity): + hu, asked = handsfree_session(identity, "39:90:21:64:07:00") + assert asked == ["F8:36:9B:0A:7D:C8"] + assert SENSOR_CHANNEL in hu.opened and BLUETOOTH_CHANNEL in hu.opened + assert hu.pairing_requests == [("39:90:21:64:07:00", 2)] + + +def test_wired_handsfree_without_a_link_sends_no_pairing_request(identity): + hu, asked = handsfree_session(identity, "") + assert asked == ["F8:36:9B:0A:7D:C8"] and hu.pairing_requests == [] + + +def test_wired_handsfree_ignores_a_preloaded_profile_address(identity): + hu, _ = handsfree_session(identity, "", preloaded="11:22:33:44:55:66") + assert hu.pairing_requests == [] + hu, _ = handsfree_session(identity, "39:90:21:64:07:00", preloaded="11:22:33:44:55:66") + assert hu.pairing_requests == [("39:90:21:64:07:00", 2)] def test_pairing_request_only_at_the_last_level(identity, tmp_path): diff --git a/openpilot/starpilot/system/starport/tests/test_wired_handsfree.py b/openpilot/starpilot/system/starport/tests/test_wired_handsfree.py new file mode 100644 index 0000000000..e6cc9183fd --- /dev/null +++ b/openpilot/starpilot/system/starport/tests/test_wired_handsfree.py @@ -0,0 +1,78 @@ +from unittest.mock import Mock + +from openpilot.starpilot.system.starport import supervisor as supervisor_module +from openpilot.starpilot.system.starport.supervisor import Supervisor + +CAR = "F8:36:9B:0A:7D:C8" + + +def fixture(monkeypatch, *, paired=True, links=True): + monkeypatch.setattr(supervisor_module, "WIRED_HFP_WAIT", 0.2) + monkeypatch.setattr(supervisor_module, "WIRED_HFP_SETTLE", 0.0) + unit = Supervisor.__new__(Supervisor) + unit.config = {"receiver_address": "", "companion_address": "", "connection": "wired"} + unit._wired_car = "" + unit._pairing_until = 0.0 + unit._shared_bluetooth_owner = None + unit._hfp_link = supervisor_module.threading.Event() + unit.log = Mock() + phone = Mock() + phone.snapshot.return_value = True, {"paired": paired, "connected": False} + phone.devices.return_value = [{"address": "AA:BB:CC:DD:EE:01", "paired": True}] + phone.connect_handsfree.side_effect = lambda address: unit._hfp_link.set() if links else None + unit._phone = Mock(return_value=phone) + unit._adapter_address = Mock(return_value="39:90:21:64:07:00") + unit._release_phone = Mock() + return unit, phone + + +def test_linked_car_returns_this_comma_address(monkeypatch): + unit, phone = fixture(monkeypatch) + assert unit._wired_handsfree(CAR.lower()) == "39:90:21:64:07:00" + phone.acquire.assert_called_once() + phone.connect_handsfree.assert_called_once_with(CAR) + assert unit._selected_receiver() == CAR and unit._hfp_accepts(CAR) + unit._release_phone.assert_not_called() + + +def test_unpaired_car_is_left_alone(monkeypatch): + unit, phone = fixture(monkeypatch, paired=False) + assert unit._wired_handsfree(CAR) == "" + phone.acquire.assert_not_called() + assert unit._wired_car == "" + assert unit.log.call_args.kwargs == {"outcome": "not_paired", "car_tail": "C8", "paired_tails": ["01"]} + + +def test_no_link_sends_nothing_and_gives_back_bluetooth(monkeypatch): + unit, phone = fixture(monkeypatch, links=False) + assert unit._wired_handsfree(CAR) == "" + unit._release_phone.assert_called_once() + assert unit._selected_receiver() == "" + + +def test_lease_failure_gives_back_bluetooth(monkeypatch): + unit, phone = fixture(monkeypatch) + phone.acquire.side_effect = RuntimeError("Bluetooth pairing is busy") + assert unit._wired_handsfree(CAR) == "" + unit._release_phone.assert_called_once() + assert unit._wired_car == "" + + +def test_usb_cleanup_error_still_clears_the_wired_car(monkeypatch): + from openpilot.starpilot.system.starport import usb_accessory + unit, _ = fixture(monkeypatch) + unit.config["usb_mode"] = "auto" + unit._wired_car = CAR + gadget = Mock() + gadget.prepare.side_effect = RuntimeError("session ended") + monkeypatch.setattr(supervisor_module, "wired_blocker", lambda: "") + monkeypatch.setattr(supervisor_module.identity_store, "load_identity", lambda: None) + monkeypatch.setattr(usb_accessory, "AccessoryGadget", lambda log: gadget) + monkeypatch.setattr(usb_accessory, "UeventListener", Mock) + unit._release_usb = Mock(side_effect=OSError("gadget busy")) + try: + unit._attempt_usb() + except OSError: + pass + assert unit._wired_car == "" and unit._selected_receiver() == "" + unit._release_phone.assert_called_once() From 16786b6517fbf794a0e9dbe0d36fbd1d9a3e6d60 Mon Sep 17 00:00:00 2001 From: Danny Date: Mon, 23 Nov 2026 07:23:21 -0800 Subject: [PATCH 2/2] Build --- prebuilt.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/prebuilt.json b/prebuilt.json index 2510e91ce9..111aee91d0 100644 --- a/prebuilt.json +++ b/prebuilt.json @@ -1 +1 @@ -{"protected_inventory_sha256": "71389942e929c125081252a9e4f8185861a5e722e8008d1be825ba5c5a669325", "schema_version": 1} +{"protected_inventory_sha256": "3a0ff9916bb6e9671afde0ffd73685e5e06560537d0bcc793106cfeed4ca93a0", "schema_version": 1}