From f67edb6529cb138ee8da1f4395d448b330bba545 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 20:12:29 +0000 Subject: [PATCH] Tesla Model 3/Y: controls work with nothing saved, and three recovery fixes - The input worker never parsed its settings on an install where CarControlAssignments had never been saved, so no scroll, stalk press or nudge reached the comma until a Wheel Controls row was changed. It now starts from the defaults. - Saved assignments are used on either model: a Model 3 and a Model Y have the same controls. Before, a document saved on the other model gave no controls and locked every Wheel Controls row. - Speed sync no longer waits for the Tesla's own speed to change after unanswered requests once the comma's speed is on the other side of the Tesla's (the Tesla had been at its own lowest or highest set speed). - The UI restarts a stopped input worker after a wait that grows from 2 s to 30 s, instead of at most three times a drive. A first start that fails is retried on the same wait, not every frame. Co-Authored-By: Claude Fable 5.2 --- opendbc_repo/opendbc/car/tesla/speed_sync.py | 4 +- .../tesla/tests/test_speed_sync_handover.py | 20 +++++ .../tesla/tests/test_speed_sync_other_cars.py | 2 +- openpilot/starpilot/controllers/runtime.py | 3 +- .../controllers/tesla_input_worker.py | 11 ++- .../starpilot/controllers/tesla_receiver.py | 45 ++++++---- .../tests/test_slc_input_recovery.py | 87 +++++++++++++++---- .../tests/test_tesla_controls_v7.py | 22 ++++- .../controllers/tests/test_tesla_worker.py | 51 ++++++++++- .../starpilot/ui/tesla_controls_feature.py | 6 +- 10 files changed, 201 insertions(+), 50 deletions(-) diff --git a/opendbc_repo/opendbc/car/tesla/speed_sync.py b/opendbc_repo/opendbc/car/tesla/speed_sync.py index 3a694043d2..2bea38464a 100644 --- a/opendbc_repo/opendbc/car/tesla/speed_sync.py +++ b/opendbc_repo/opendbc/car/tesla/speed_sync.py @@ -626,7 +626,9 @@ class SpeedSynchronizer: retry = False if self.unanswered is not None: u = self.unanswered - if self.native_ns > u.sent_ns and self.native != u.before: + # The Tesla moved, or the comma now wants the other way (the Tesla was at its own limit in the old direction): + # the unanswered request says nothing about this one. + if (self.native_ns > u.sent_ns and self.native != u.before) or u.direction != (1 if target > native else -1): self.unanswered = None self.unanswered_count = 0 self.retry_refused = False diff --git a/opendbc_repo/opendbc/car/tesla/tests/test_speed_sync_handover.py b/opendbc_repo/opendbc/car/tesla/tests/test_speed_sync_handover.py index 8c8873a9e6..4493ab8793 100644 --- a/opendbc_repo/opendbc/car/tesla/tests/test_speed_sync_handover.py +++ b/opendbc_repo/opendbc/car/tesla/tests/test_speed_sync_handover.py @@ -181,6 +181,26 @@ def test_no_response_is_retried_a_few_times_then_waits_for_the_tesla(): assert any(r.tick() for _ in range(20)) +def test_an_unanswered_request_does_not_hold_back_the_other_direction(): + # The Tesla ignores scrolls one way (it is at its own lowest or highest set speed). A comma speed still on that side + # keeps waiting; once it is on the other side of the Tesla's, sync carries on without the Tesla changing first. + r = Rig() + r.tick() + for _ in range(100): + r.tick(dt=100_000_000) + assert r.sync.status == 'waiting_for_native_change' + sent = len(r.sent) + r.target = 55 # further the same way (the Tesla shows 45) + for _ in range(20): + assert r.tick() is None + assert r.sync.status == 'waiting_for_native_change' + r.target = 40 # now below the Tesla's + assert any(r.tick() for _ in range(20)) + assert len(r.sent) == sent + 1 and clicks(r.sent[-1][1]) == -1 + r.speed -= 1 # the Tesla follows: nothing is left of the old wait + assert any(r.tick() for _ in range(20)) and r.sync.unanswered is None + + def test_request_needs_a_new_physical_neutral_frame(): r = Rig() r.tick() diff --git a/openpilot/starpilot/car/tesla/tests/test_speed_sync_other_cars.py b/openpilot/starpilot/car/tesla/tests/test_speed_sync_other_cars.py index eaff0b7778..96f625b7b7 100644 --- a/openpilot/starpilot/car/tesla/tests/test_speed_sync_other_cars.py +++ b/openpilot/starpilot/car/tesla/tests/test_speed_sync_other_cars.py @@ -204,7 +204,7 @@ GATES = { 'openpilot/starpilot/controllers/tesla_input_worker.py': [ 'fingerprint = cp_fingerprint(cp) if vehicle_supported(cp) else None', 'provenance = bool(fingerprint) and speed_sync_selected(cp)', - 'bindings = (effective_bindings(doc, comma_speed=self.comma_speed(cp))', + 'bindings = effective_bindings(doc, comma_speed=self.comma_speed(cp)) if doc else {}', ], 'openpilot/starpilot/car/tesla_speed_sync_context.py': [ 'if controller is None or getattr(controller, "speed_sync", None) is None: return', diff --git a/openpilot/starpilot/controllers/runtime.py b/openpilot/starpilot/controllers/runtime.py index 324b520597..6fa8fabc42 100644 --- a/openpilot/starpilot/controllers/runtime.py +++ b/openpilot/starpilot/controllers/runtime.py @@ -37,8 +37,7 @@ class ControllerRuntime: self.tesla.poll() except Exception: LOGGER.exception('Tesla input stopped') - self.tesla.close() - self.tesla.next_start = time.monotonic() + 2. + self.tesla.fail() try: now = time.monotonic() if now >= self._next_warm: diff --git a/openpilot/starpilot/controllers/tesla_input_worker.py b/openpilot/starpilot/controllers/tesla_input_worker.py index 4f2b7bf35d..89d4058dc0 100644 --- a/openpilot/starpilot/controllers/tesla_input_worker.py +++ b/openpilot/starpilot/controllers/tesla_input_worker.py @@ -27,6 +27,9 @@ from openpilot.starpilot.controllers.tesla_controls import TeslaInputDecoder from openpilot.starpilot.controllers.tesla_input_protocol import MAX_AGE, READY, document_hash, drive_id, encode_event from openpilot.starpilot.controllers.wheel_actions import cp_fingerprint +# Nothing read yet. The first read is always parsed, also when it finds no saved file (read_saved gives None for that). +UNREAD = object() + class InputPump: def __init__(self, params, send, *, socket_factory, receive, clock=time.monotonic, boot_clock_ns=None): @@ -41,7 +44,7 @@ class InputPump: self.decoder: TeslaInputDecoder | None = None self.identity = None self.sequence = 0 - self.raw = None + self.raw = UNREAD self.document = None self.cp = None self.cp_hash = None @@ -73,9 +76,9 @@ class InputPump: self.raw = raw self.document = parse_assignments(raw) if readable else None doc = self.document if readable else None - # Nothing saved yet still has the fixed and default bindings (the right stalk hold and half press). - bindings = (effective_bindings(doc, comma_speed=self.comma_speed(cp)) - if doc and doc['vehicle'] in ('', cp.carFingerprint) else {}) + # Nothing saved yet still has the fixed and default bindings (the right stalk hold and half press). A saved document + # is a Model 3's or a Model Y's (parse_assignments); the two have the same controls, so either car uses it. + bindings = effective_bindings(doc, comma_speed=self.comma_speed(cp)) if doc else {} if not bindings: self.reset() return diff --git a/openpilot/starpilot/controllers/tesla_receiver.py b/openpilot/starpilot/controllers/tesla_receiver.py index 254683350a..712e27fe61 100644 --- a/openpilot/starpilot/controllers/tesla_receiver.py +++ b/openpilot/starpilot/controllers/tesla_receiver.py @@ -18,6 +18,11 @@ from openpilot.starpilot.controllers.tesla_input_protocol import ( # A Resume press during a short speed-limit dropout waits this long for the limit to come back, then runs once. RESUME_WAIT_SECONDS = 2. +# How long a stopped worker waits before it is started again: longer after each failure in a row, and the last wait +# repeats. A worker that then runs for RESTART_HEALTHY_SECONDS starts the waits from the beginning. It is never given +# up on: with Comma can set speed on Tesla dashboard on, the scroll wheel only sets the speed while the worker runs. +RESTART_WAIT_SECONDS = (2., 4., 8., 16., 30.) +RESTART_HEALTHY_SECONDS = 60. class WorkerChannel: @@ -75,8 +80,8 @@ class TeslaReceiver: # page (including the maps package), which took 2.3 s on a cold first press # and outlived MAX_AGE, so the press was dropped. self.keyed_actions = keyed_actions - self._restart_drive = None - self._restarts = 0 + self._restarts = 0 # failures in a row + self._started_at = None # when the current (or last) worker started self._diagnostic_at = 0. self.clock, self.messages, self.channel_factory = clock, messages, channel_factory self.channel = None @@ -94,12 +99,23 @@ class TeslaReceiver: try: self.channel = self.channel_factory() self._started = True + self._started_at = self.clock() self.sequence = 0 self.failed = False except (OSError, RuntimeError): LOGGER.exception('Tesla input worker could not start') - self.failed = True - self.next_start = self.clock() + 2. + self.fail() + + def fail(self): + """The worker stopped, could not start, or handling its input failed: close it and set when it may start again.""" + self.close() + now = self.clock() + if self._started_at is not None and now - self._started_at >= RESTART_HEALTHY_SECONDS: + self._restarts = 0 + self._started_at = None + self.failed = True + self.next_start = now + RESTART_WAIT_SECONDS[min(self._restarts, len(RESTART_WAIT_SECONDS) - 1)] + self._restarts += 1 def close(self): if self.channel is not None: @@ -128,16 +144,11 @@ class TeslaReceiver: self.close() return if self.channel is None: - if not self._started: - self._start() + if self.clock() < self.next_start: return - # Receive-only recovery is bounded per drive; a new worker must observe - # a fresh neutral gesture and exact current authority before dispatch. - drive = self.drive() - if drive != self._restart_drive and drive is not None: - self._restart_drive, self._restarts = drive, 0 - if self.clock() >= self.next_start and (self._offroad() or drive is not None and self._restarts < 3): - self._restarts += 1 + # The first start needs nothing more. A restart waits for a drive or a parked car that is known for certain; the + # new worker must observe a fresh neutral gesture and exact current authority before anything is dispatched. + if not self._started or self._offroad() or self.drive() is not None: self._start() return try: @@ -157,10 +168,8 @@ class TeslaReceiver: self._dispatch(raw) self._retry_resume() except (OSError, EOFError, RuntimeError): - LOGGER.exception('Tesla input worker stopped; bounded fresh-context recovery scheduled') - self.failed = True - self.close() - self.next_start = self.clock() + 2. + LOGGER.exception('Tesla input worker stopped; fresh-context recovery scheduled') + self.fail() def _dispatch(self, raw, *, retry=False): event = decode_event(raw, self.clock()) @@ -179,7 +188,7 @@ class TeslaReceiver: self._diagnostic('assignment_changed_or_unreadable', event) return doc = parse_assignments(current) - if not doc or doc['vehicle'] not in ('', cp.carFingerprint) or cp_fingerprint(cp) != event['vehicle']: + if not doc or cp_fingerprint(cp) != event['vehicle']: self._diagnostic('assignment_vehicle_identity_mismatch', event) return name = event['name'] diff --git a/openpilot/starpilot/controllers/tests/test_slc_input_recovery.py b/openpilot/starpilot/controllers/tests/test_slc_input_recovery.py index 2bfca03bca..446d9b42bb 100644 --- a/openpilot/starpilot/controllers/tests/test_slc_input_recovery.py +++ b/openpilot/starpilot/controllers/tests/test_slc_input_recovery.py @@ -1,5 +1,5 @@ """Tesla input failure paths: a failing receiver or worker never takes the other controllers down, never repeats an -input, and recovers a bounded number of times.""" +input, and is started again after a wait that grows with each failure in a row.""" import json from types import SimpleNamespace as NS from unittest.mock import Mock, patch @@ -11,6 +11,8 @@ from openpilot.starpilot.controllers import tesla_receiver from openpilot.starpilot.controllers.runtime import ControllerRuntime from openpilot.starpilot.controllers.tests.test_tesla_decoder import wheel from openpilot.starpilot.controllers.tests.tesla_worker_fixture import Channel, selected_rig +from openpilot.starpilot.tests.port_settings_fixture import Saved +from openpilot.starpilot.tests.tesla_set_speed_fixture import tesla @pytest.fixture @@ -23,7 +25,7 @@ def bare_runtime(presses=(), capture=None): vars(r).update(_closed=False, _next_warm=float('inf'), _warm_until=0, input_capture=lambda: capture, reader=NS(poll=lambda _: presses, devices=list, close=Mock()), owner=NS(set_devices=Mock(), tick=Mock(), feed=Mock()), - tesla=NS(poll=Mock(), close=Mock()), service=NS(poll=Mock(), close=Mock()), authority=NS(close=Mock())) + tesla=NS(poll=Mock(), close=Mock(), fail=Mock()), service=NS(poll=Mock(), close=Mock()), authority=NS(close=Mock())) return r @@ -31,8 +33,8 @@ def test_tesla_exception_without_button_press_does_not_close_all_controllers(): r = bare_runtime() r.tesla.poll.side_effect = ValueError('injected dispatch failure') r.poll() - assert not r._closed and r.tesla.next_start > 0 - r.tesla.close.assert_called_once() + assert not r._closed + r.tesla.fail.assert_called_once() r.service.poll.assert_called_once() r.reader.close.assert_not_called() @@ -115,28 +117,79 @@ def test_speed_input_does_not_build_unrelated_action_catalog(setup): s.receiver.actions.assert_not_called() -def test_worker_recovery_is_bounded_and_requires_fresh_drive(setup): - s = setup +def recovering(s): + """Swap in a channel factory that counts, and return (created channels, fail-and-time-the-restart).""" created = [] def factory(): created.append(Channel()) return created[-1] s.receiver.channel_factory = factory - s.receiver.close() - s.clock[0] += 3 + + def restart_after_failure(): + s.receiver.fail() + failed_at = s.clock[0] + assert s.receiver.channel is None and s.receiver.failed + while s.receiver.channel is None: + s.clock[0] += .5 + s.sm.refresh(s.clock[0]) + s.receiver.poll() + return s.clock[0] - failed_at + return created, restart_after_failure + + +def test_worker_recovery_waits_longer_each_time_and_never_gives_up(setup): + # With Comma can set speed on Tesla dashboard on, the scroll only sets the speed while the worker runs, so a drive + # never ends up without it: the wait grows to 30 s and then repeats. + s = setup + created, restart_after_failure = recovering(s) + assert [restart_after_failure() for _ in range(8)] == [2., 4., 8., 16., 30., 30., 30., 30.] + assert len(created) == 8 and s.receiver.channel is created[-1] and not s.receiver.failed + + +def test_a_worker_that_ran_for_a_minute_starts_the_waits_again(setup): + s = setup + created, restart_after_failure = recovering(s) + assert [restart_after_failure() for _ in range(3)] == [2., 4., 8.] + s.clock[0] += tesla_receiver.RESTART_HEALTHY_SECONDS - 1 + s.sm.refresh(s.clock[0]) + assert restart_after_failure() == 16., 'not yet a minute' + s.clock[0] += tesla_receiver.RESTART_HEALTHY_SECONDS + s.sm.refresh(s.clock[0]) + assert restart_after_failure() == 2. + + +def test_a_stopped_worker_is_restarted_through_the_same_wait(setup): + # A backlog (the screen stalled while the driver scrolled) closes the worker; it is back after the wait. + s = setup + s.channel.queue.extend([b'{}'] * 500) + s.receiver.poll() + assert s.channel.closed and s.receiver.channel is None and s.receiver.failed + created = [] + s.receiver.channel_factory = lambda: created.append(Channel()) or created[-1] + s.clock[0] += 1.9 s.sm.refresh(s.clock[0]) s.receiver.poll() - assert len(created) == 1 - for _ in range(3): - s.receiver.close() - s.clock[0] += 3 - s.sm.refresh(s.clock[0]) - s.receiver.poll() - assert len(created) == 3 and s.receiver.channel is None - s.clock[0] += 10 + assert not created + s.clock[0] += .2 + s.sm.refresh(s.clock[0]) s.receiver.poll() - assert len(created) == 3 + assert s.receiver.channel is created[0] + + +def test_a_first_start_that_fails_is_not_retried_every_frame(tmp_path): + clock, attempts = [1.], [] + + def factory(): + attempts.append(clock[0]) + raise OSError('no process') + receiver = tesla_receiver.TeslaReceiver(Saved(tmp_path), dict, tesla, clock=lambda: clock[0], channel_factory=factory) + for _ in range(100): + receiver.poll() + assert attempts == [1.] and receiver.failed and receiver.channel is None + clock[0] += 2. + receiver.poll() + assert attempts == [1., 3.] def test_a_worker_that_cannot_start_is_retried_after_a_pause_not_every_frame(setup): diff --git a/openpilot/starpilot/controllers/tests/test_tesla_controls_v7.py b/openpilot/starpilot/controllers/tests/test_tesla_controls_v7.py index 06397c5a64..8a79ab9910 100644 --- a/openpilot/starpilot/controllers/tests/test_tesla_controls_v7.py +++ b/openpilot/starpilot/controllers/tests/test_tesla_controls_v7.py @@ -249,19 +249,35 @@ def test_a_speed_cannot_be_set_on_a_control_that_is_not_on_set_speed_to(rig): @pytest.mark.parametrize('raw', [b'not json', b'[]', json.dumps({'version': 2, 'vehicle': 'TESLA_MODEL_3', 'bindings': {}}).encode(), - json.dumps({'version': 1, 'vehicle': 'TESLA_MODEL_Y', 'bindings': {}}).encode(), + json.dumps({'version': 1, 'vehicle': 'TESLA_MODEL_S', 'bindings': {}}).encode(), json.dumps({'version': 1, 'vehicle': 'TESLA_MODEL_3', 'bindings': {'unknown_control': {}}}).encode()]) -def test_invalid_or_other_vehicle_assignments_are_shown_and_never_overwritten(rig, raw): +def test_invalid_assignments_are_shown_and_never_overwritten(rig, raw): rig.params.put(PARAM, raw, block=True) rows = rig.feature.rows() assert [row.label for row in rows] == ROW_LABELS for row in rows: if row.key: - assert row.value == 'Invalid or other-vehicle assignments' and not row.available + assert row.value == 'Invalid saved assignments' and not row.available assert not rig.choose(LEFT, 'Bookmark') assert rig.saved(PARAM) == raw +@pytest.mark.parametrize('here,there', [('TESLA_MODEL_3', 'TESLA_MODEL_Y'), ('TESLA_MODEL_Y', 'TESLA_MODEL_3')]) +def test_assignments_saved_on_the_other_model_are_used_and_kept(tmp_path, here, there): + # A Model 3 and a Model Y have the same controls: a comma moved between them keeps its assignments, and the next + # change saves them under the car it is in. + rig = Rig(tmp_path, tesla(here)) + saved = {'version': 1, 'vehicle': there, 'bindings': {'right_wheel_left': {'key': BOOKMARK, 'value': None, 'label': 'Bookmark'}}} + rig.params.put(PARAM, json.dumps(saved).encode(), block=True) + row = rig.row(LEFT) + assert row.value == 'Bookmark' and row.available + assert rig.choose(PREFIX + 'right_wheel_right', 'Experimental Mode') + document = rig.document() + assert document['vehicle'] == here + assert document['bindings']['right_wheel_left'] == saved['bindings']['right_wheel_left'] + assert document['bindings']['right_wheel_right']['label'] == 'Experimental Mode' + + def test_three_finger_tap_can_be_always_on_lateral_on_off(rig): row = rig.row(SCREEN) assert row.choices[-1] == AOL_ACTION and row.choices[:-1] == tuple(OPTIONS) diff --git a/openpilot/starpilot/controllers/tests/test_tesla_worker.py b/openpilot/starpilot/controllers/tests/test_tesla_worker.py index 1390f0abf2..9b2d9432c9 100644 --- a/openpilot/starpilot/controllers/tests/test_tesla_worker.py +++ b/openpilot/starpilot/controllers/tests/test_tesla_worker.py @@ -184,10 +184,19 @@ def test_engaging_press_runs_no_action_while_engaged(setup): assert s.calls == ['resume'] -def test_hold_and_half_press_work_with_nothing_saved(setup): +def nothing_saved(s, saved): + """An empty saved document, or (None) an install where the Wheel Controls were never saved: no file at all.""" + if saved is None: + os.remove(s.params.get_param_path(PARAM)) + else: + s.params.put(PARAM, saved, block=True) + + +@pytest.mark.parametrize('saved', [b'{}', None]) +def test_hold_and_half_press_work_with_nothing_saved(setup, saved): # The right stalk hold is fixed and the half press while engaged starts on Resume Speed Limit + Offset. s = setup - s.params.put(PARAM, b'{}', block=True) # nothing assigned + nothing_saved(s, saved) s.actions[SPEED_RESUME] = NS(available=True, invoke=lambda: s.calls.append('resume'), invoke_value=None) s.sm.engaged = True for _ in range(6): @@ -200,6 +209,44 @@ def test_hold_and_half_press_work_with_nothing_saved(setup): assert s.calls == ['resume', 'resume'] +@pytest.mark.parametrize('saved', [b'{}', None]) +def test_the_scroll_sets_the_comma_speed_with_nothing_saved(setup, saved): + s = setup + nothing_saved(s, saved) + s.feed(wheel()) + s.feed(wheel(right_scroll=1)) + s.feed(wheel()) + assert s.calls == [0] + + +def test_the_file_removed_mid_drive_leaves_the_defaults(setup): + s = setup + s.feed(wheel()) + s.feed(wheel(right_wheel_left=2)) + s.feed(wheel()) + assert s.calls == [CUSTOM], 'the saved nudge left' + os.remove(s.params.get_param_path(PARAM)) + for scroll in (0, 1, 0): + s.feed(wheel(right_scroll=scroll)) + s.feed(wheel(right_wheel_left=2)) + s.feed(wheel()) + assert s.calls == [CUSTOM, 0], 'the scroll still acts; the nudge left has no default' + + +def test_assignments_saved_on_the_other_model_are_used(setup): + # A Model 3 and a Model Y have the same controls, so a comma moved from one to the other keeps its assignments. + s = setup + assert s.cp.carFingerprint == 'TESLA_MODEL_3' + s.doc['vehicle'] = 'TESLA_MODEL_Y' + save(s) + s.feed(wheel()) + s.feed(wheel(right_wheel_left=2)) + s.feed(wheel()) + s.feed(wheel(right_scroll=1)) + s.feed(wheel()) + assert s.calls == [CUSTOM, 0] + + @pytest.mark.parametrize('fault', ['safe', 'config', 'invalid', 'wrong_bus', 'offroad', 'vehicle', 'stale']) def test_held_gesture_cannot_cross_context(setup, fault): s = setup diff --git a/openpilot/starpilot/ui/tesla_controls_feature.py b/openpilot/starpilot/ui/tesla_controls_feature.py index d4863ff1a6..90f37a3c8d 100644 --- a/openpilot/starpilot/ui/tesla_controls_feature.py +++ b/openpilot/starpilot/ui/tesla_controls_feature.py @@ -48,7 +48,9 @@ class TeslaControlsFeature: cp = self.owner.vehicle_params() raw, readable = read_saved(self.owner.params, PARAM, MAX_ASSIGNMENT_BYTES) doc = parse_assignments(raw) if readable else None - valid = bool(doc is not None and (not doc['vehicle'] or cp is not None and doc['vehicle'] == cp.carFingerprint)) + # A saved document is a Model 3's or a Model Y's. The two have the same controls, so either car uses it, and the + # next change saves it under this car. + valid = doc is not None return cp, raw, doc, valid def allowed(self): @@ -90,7 +92,7 @@ class TeslaControlsFeature: notes = [*missing, *([SET_SPEED_NEEDS] if key == SPEED_SET and not owned else []), *([AOL_PENDING] if reserved and not aol_on else [AOL_NOTE] if aol else [])] help_text = '.\n'.join(notes) - rows.append(FeatureRow(PREFIX + name, group + ' / ' + label, choice if valid else 'Invalid or other-vehicle assignments', raw, + rows.append(FeatureRow(PREFIX + name, group + ' / ' + label, choice if valid else 'Invalid saved assignments', raw, tuple(OPTIONS) + ((AOL_ACTION,) if aol else ()), available=self.allowed() and valid and not fixed, reason=help_text, vehicle_fingerprint=self.owner.vehicle_fingerprint())) if key == SPEED_SET: