StarPort: Log why an adapter has no car and name the car that tried to connect

This commit is contained in:
Danny
2026-11-23 14:08:52 -08:00
parent aafa97df61
commit e7f5d5fd4e
4 changed files with 145 additions and 5 deletions
@@ -114,6 +114,14 @@ def _tcp_failure_kind(error: OSError) -> str:
return "other"
HANDSFREE_UUID = "0000111e-0000-1000-8000-00805f9b34fb"
REFUSED_CAR_HINT_S = 120.0
def short_uuids(device: dict) -> list[str]:
return sorted(uuid[4:8] for uuid in device.get("uuids", []) if uuid.endswith("-0000-1000-8000-00805f9b34fb"))
def encoder_preference(configured: str) -> str:
return 'hardware' if COMMA_HARDWARE else configured
@@ -397,6 +405,8 @@ class Supervisor:
_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
_refused_car: tuple[str, str, float] = ("", "", 0.0) # adapter, car, when
_adapter_car_note: dict | None = None
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,
@@ -1207,8 +1217,11 @@ class Supervisor:
return bool(lease is not None and not lease.released and
(lease.receiver == address.upper() or lease.incoming is not None and
lease.incoming.approved_address == address.upper()))
return bool(receiver) and (address.upper() == receiver.upper() or
accepted = bool(receiver) and (address.upper() == receiver.upper() or
self._shared_bluetooth_owner is not None and self._shared_bluetooth_owner.companion_accepts(address))
if not accepted and self.config.get("car_type") == "adapter" and not self.config.get("companion_address"):
self._refused_car = (receiver.upper(), address.upper(), time.monotonic())
return accepted
def phone_window(self, operation: str, session: tuple, **arguments):
owner = self._shared_bluetooth_owner
@@ -1233,6 +1246,18 @@ class Supervisor:
return self._forget_selected_car(owner, address, session)
if operation == 'disconnect' and self.config['receiver_address'].upper() == address.upper():
return self._disconnect_selected_car(owner, address, session)
if operation != 'connect':
return self._companion_action(owner, operation, address, session)
try:
result = self._companion_action(owner, operation, address, session)
except Exception as error:
self.log("adapter_car_connect", tail=address[-2:], outcome="failed", error=str(error)[:120])
raise
if result is None:
self.log("adapter_car_connect", tail=address[-2:], outcome="not_holding_bluetooth")
return result
def _companion_action(self, owner, operation: str, address: str, session: tuple):
# select_receiver takes the supervisor lock before releasing an owner lease.
# Keep that same order through connection, save and admission pruning so an
# old adapter's successful action cannot save its car under a new adapter.
@@ -1253,10 +1278,13 @@ class Supervisor:
owner.phone_lease is not lease or lease.released or
not owner.session_valid(session) or not lease.enabled()):
raise RuntimeError('Selected car connection was not confirmed')
if '0000111e-0000-1000-8000-00805f9b34fb' not in device.get('uuids', []):
if HANDSFREE_UUID not in device.get('uuids', []):
self.log("adapter_car_connect", tail=address[-2:], outcome="not_handsfree", services=short_uuids(device))
return result # An accessory must never replace the dongle's selected car.
self.config.update(companion_address=device['address'], companion_name=device['name'])
identity_store.save_config(self.config)
self._refused_car = ("", "", 0.0)
self.log("adapter_car_connect", tail=address[-2:], outcome="saved")
for previous in list(owner.companion_devices):
if previous != device['address']:
owner.companion_devices.pop(previous, None)
@@ -1608,6 +1636,27 @@ class Supervisor:
text += " (set verify_head_unit false in config.json to test without verifying the car)"
return f"{STATE_LABELS.get(stage, stage)}: {text}"[:300]
def _missing_adapter_car(self, bluez, receiver: str) -> str:
receiver = receiver.upper()
adapter, refused, at = self._refused_car
if adapter != receiver or not 0 <= time.monotonic() - at <= REFUSED_CAR_HINT_S:
refused = ""
devices = bluez.devices()
paired = [item for item in devices if item.get("paired") and item["address"] != receiver]
connected = any(item["address"] == receiver and item["connected"] for item in devices)
cars = []
for item in paired:
services = short_uuids(item)
cars.append({"tail": item["address"][-2:], "handsfree": "111e" in services, "connected": item["connected"], "services": services})
note = {"paired": cars, "refused_tail": refused[-2:], "adapter_connected": connected}
if note != self._adapter_car_note:
self._adapter_car_note = note
self.log("adapter_car_missing", **note)
car = next((item for item in paired if item["address"] == refused), None)
if car is not None:
return f"Connect your paired car in Galaxy Bluetooth first: {car['name']} tried to connect, so tap Connect on it there"
return 'Connect your paired car in Galaxy Bluetooth first to select it for this Android Auto adapter'
def _attempt(self, lease) -> None:
if self.config["connection"] == "wired":
self._attempt_usb()
@@ -1633,10 +1682,10 @@ class Supervisor:
self._shared_bluetooth_owner.prepare_companion(companion, lambda: self.config.get('companion_address', ''), connect=True)
self._check_cancel()
self.log('companion_car_connected', address=companion)
elif device.get('starport') and '0000111e-0000-1000-8000-00805f9b34fb' not in device.get('uuids', []):
elif device.get('starport') and HANDSFREE_UUID not in device.get('uuids', []):
if car_profiles.tuning(config)["own_handsfree"]:
raise RuntimeError('Waiting for the adapter to finish starting up')
raise RuntimeError('Connect your paired car in Galaxy Bluetooth first to select it for this Android Auto adapter')
raise RuntimeError(self._missing_adapter_car(bluez, address))
if delay := car_profiles.tuning(config)["connect_delay_s"]:
self.log("car_profile_connect_delay", seconds=delay)
self._wait(delay)
@@ -237,6 +237,7 @@ def test_unofficial_dongle_turns_on_the_handshake_experiments_only_when_chosen()
def test_an_adapter_without_hands_free_yet_waits_or_asks_for_the_car(sup, profile, expected):
bluez = Mock()
bluez.device.return_value = {"address": ADAPTER, "paired": True, "starport": True, "uuids": []}
bluez.devices.return_value = [{**bluez.device.return_value, "connected": True}]
sup._phone = lambda: bluez
sup.config.update(connection="wireless", receiver_address=ADAPTER, receiver_name="AAWireless-4F2A", companion_address="",
car_type="adapter", car_profile_override=profile)
@@ -4,6 +4,8 @@ from types import SimpleNamespace
import unittest
from unittest.mock import Mock, patch
import pytest
from openpilot.starpilot.bluetooth.owner import BluetoothRejected as Rejected
from openpilot.starpilot.system.starport.bluetooth_bridge import SharedBluetoothOwner as OwnerMethods
from openpilot.starpilot.system.starport import daemon
@@ -79,6 +81,7 @@ class CompanionTests(unittest.TestCase):
self.devices[address]['connected'] = operation == 'connect'
self.client.operation = operation
host = Supervisor.__new__(Supervisor)
host.log = Mock()
host._lock = threading.RLock()
host.config = {'receiver_address': ADAPTER, 'companion_address': 'saved-car', 'companion_name': 'My car'}
host._shared_bluetooth_owner = self.owner
@@ -222,6 +225,7 @@ class CompanionTests(unittest.TestCase):
def test_manual_car_save_cannot_cross_receiver_change(self):
from openpilot.starpilot.system.starport.supervisor import Supervisor
host = Supervisor.__new__(Supervisor)
host.log = Mock()
host._lock = threading.RLock()
host._thread, host._bluez = None, None
host.config = {'receiver_address': ADAPTER, 'companion_address': '', 'companion_name': ''}
@@ -260,6 +264,7 @@ class CompanionTests(unittest.TestCase):
def test_manual_car_save_revalidates_source_after_action(self):
from openpilot.starpilot.system.starport.supervisor import Supervisor
host = Supervisor.__new__(Supervisor)
host.log = Mock()
host._lock = threading.RLock()
host.config = {'receiver_address': ADAPTER, 'companion_address': '', 'companion_name': ''}
host._shared_bluetooth_owner = self.owner
@@ -281,6 +286,7 @@ class CompanionTests(unittest.TestCase):
def test_forgetting_the_selected_car_stops_its_retry_then_deletes_it(self):
from openpilot.starpilot.system.starport.supervisor import Supervisor
host = Supervisor.__new__(Supervisor)
host.log = Mock()
host._lock = threading.RLock()
host.config = {'receiver_address': ADAPTER}
host._shared_bluetooth_owner = self.owner
@@ -302,6 +308,7 @@ class CompanionTests(unittest.TestCase):
def test_forgetting_the_selected_car_waits_out_pairing_and_expired_sessions(self):
from openpilot.starpilot.system.starport.supervisor import Supervisor
host = Supervisor.__new__(Supervisor)
host.log = Mock()
host.config = {'receiver_address': ADAPTER}
host._shared_bluetooth_owner = self.owner
host.stop = Mock()
@@ -405,3 +412,86 @@ class CompanionTests(unittest.TestCase):
if __name__ == '__main__':
unittest.main()
def adapter_host(car_uuids=(HFP,)):
from openpilot.starpilot.system.starport.supervisor import Supervisor
host = Supervisor.__new__(Supervisor)
host.config = {'receiver_address': ADAPTER, 'companion_address': '', 'car_type': 'adapter', 'connection': 'wireless'}
host._wired_car = ''
host._pairing_until = 0.0
host._shared_bluetooth_owner = Mock(companion_accepts=Mock(return_value=False))
host.log = Mock()
phone = Mock()
phone.devices.return_value = [
{'address': ADAPTER, 'name': 'Adapter', 'paired': True, 'connected': True, 'uuids': []},
{'address': CAR, 'name': 'HandsFreeLink', 'paired': True, 'connected': False, 'uuids': list(car_uuids)},
]
return host, phone
def test_refused_car_is_named_in_the_adapter_error():
host, phone = adapter_host()
assert not host._hfp_accepts(CAR.lower())
message = host._missing_adapter_car(phone, ADAPTER)
assert message.startswith('Connect your paired car in Galaxy Bluetooth first') and 'HandsFreeLink' in message
assert host.log.call_args.kwargs == {
'paired': [{'tail': '01', 'handsfree': True, 'connected': False, 'services': ['111e']}], 'refused_tail': '01',
'adapter_connected': True}
def test_adapter_car_note_is_logged_only_when_it_changes():
host, phone = adapter_host()
host._missing_adapter_car(phone, ADAPTER)
host._missing_adapter_car(phone, ADAPTER)
assert host.log.call_count == 1
phone.devices.return_value[0]['connected'] = False
host._missing_adapter_car(phone, ADAPTER)
assert host.log.call_count == 2 and host.log.call_args.kwargs['adapter_connected'] is False
def test_old_or_other_adapter_refusal_is_not_shown(monkeypatch):
from openpilot.starpilot.system.starport import supervisor
host, phone = adapter_host()
host._hfp_accepts(CAR)
monkeypatch.setattr(supervisor.time, 'monotonic', lambda: 10_000.0)
assert host._missing_adapter_car(phone, ADAPTER).endswith('for this Android Auto adapter')
host._refused_car = ('02:00:00:00:00:09', CAR, 10_000.0)
assert host._missing_adapter_car(phone, ADAPTER).endswith('for this Android Auto adapter')
def test_accessory_without_handsfree_keeps_the_usual_error():
host, phone = adapter_host(car_uuids=('0000110b-0000-1000-8000-00805f9b34fb',))
assert host._missing_adapter_car(phone, ADAPTER).endswith('for this Android Auto adapter')
assert host.log.call_args.kwargs['paired'][0]['services'] == ['110b']
def test_selected_car_or_builtin_setup_records_no_refusal():
host, _ = adapter_host()
host.config['companion_address'] = '02:00:00:00:00:03'
host._hfp_accepts(CAR)
host.config.update(companion_address='', car_type='builtin')
host._hfp_accepts(CAR)
assert host._refused_car[1] == ''
def test_device_list_failure_propagates():
host, phone = adapter_host()
phone.devices.side_effect = RuntimeError('BlueZ is not running')
with pytest.raises(RuntimeError, match='BlueZ'):
host._missing_adapter_car(phone, ADAPTER)
def test_adapter_car_connect_outcomes_are_logged():
host, _ = adapter_host()
host._companion_action = Mock(return_value=None)
assert host.companion_bluetooth_action('connect', CAR, SESSION) is None
assert host.log.call_args.kwargs == {'tail': '01', 'outcome': 'not_holding_bluetooth'}
host._companion_action.side_effect = RuntimeError('Selected car connection was not confirmed')
with pytest.raises(RuntimeError):
host.companion_bluetooth_action('connect', CAR, SESSION)
assert host.log.call_args.kwargs['outcome'] == 'failed'
host.log.reset_mock()
host._companion_action = Mock(return_value=None)
host.companion_bluetooth_action('disconnect', CAR, SESSION)
host.log.assert_not_called()
+1 -1
View File
@@ -1 +1 @@
{"protected_inventory_sha256": "54ae293c85263211df46d20813316601b733975008751b5f913793982fcb1a02", "schema_version": 1}
{"protected_inventory_sha256": "2420175288725834e14047e533a59d94e288236d7ef0b45b75feb2dfda0a595c", "schema_version": 1}