From 7dbbb43c3bce1c6366d05e0e755ea3551c38c390 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 10:27:31 +0000 Subject: [PATCH] Add Tesla Model 3/Y wheel controls and comma-set dashboard speed Everything here is limited to Tesla Model 3 and Model Y; other cars are unchanged. Most of it needs the Tesla CAN add-on cable (Vehicle CAN). Wheel Controls - Right scroll wheel nudge left / right and holding either, right stalk half and full press while engaged, and a three-finger tap on the Tesla screen as assignable actions. Scroll up / down and stalk Down / Up are shown grayed, the scroll rows with their step (1, or to the next 5 for a fast scroll). Nudge right starts on Cycle Driving Personality. - The three-finger tap's Always On Lateral on/off is chosen on its own row here: the Three-Finger AOL Tap row leaves Vehicle Settings, and TeslaAOLScreenTap is saved on by default. - The Short press and Hold step rows are left out on a Model 3/Y, where StarPilot never steps the set speed from cruise buttons. - A receive-only worker reads the wheel, stalk and screen frames. It only runs on a Model 3/Y with the cable. Vehicle Settings - Tesla CAN add-on cable row: detected or not, with buy and install links. - Comma can set speed on Tesla dashboard (TeslaSpeedSync): off by default, experimental, needs the cable and Alpha Longitudinal, not offered on release builds. Takes effect within a second, without a restart. With the switch on - StarPilot keeps its own set speed; the right scroll wheel changes it by 1, or to the next multiple of 5. - The Tesla's set speed is scrolled to match with right-scroll-wheel frames on Vehicle CAN, and scrolled back if the Tesla changes it. - Speed Limit Controller writes the limit plus offset into the set speed instead of capping beneath it. Adopt limits early writes it early, and back again if the Maps preview is withdrawn. After an accelerator override: with Hold the speed you reached, lifting off above the limit makes the speed reached the set speed until the limit changes. With the switch off, Speed Limit Controller and the set speed behave as before. Also adds the Tesla dashboard speed limit (DAS_fusedSpeedLimit) as a Speed Limit Controller Dashboard source. Panda: adds opendbc/safety/modes/tesla_speed_sync.h and safety-param bit 4096 (debug builds only), with tests. The bit is set at startup on every eligible Model 3/Y so the switch works without a restart, so the images need rebuilding. Always On Lateral's two exact-word checks accept the new bit. test_screen_recovery_callers.py and test_tesla_screen_integration.py expect the bit on a car with the cable and StarPilot longitudinal. Schema: SlcAction.ControllerCruiseAction gains stepUnits @13 and sourceTeslaGesture @14 (new TeslaGesture struct), SlcAction.Kind gains cruiseStep @13. Settings keys: TeslaSpeedSync, CarControlAssignments. Co-Authored-By: Claude Fable 5.2 --- .../opendbc/car/tesla/carcontroller.py | 7 + opendbc_repo/opendbc/car/tesla/carstate.py | 6 + opendbc_repo/opendbc/car/tesla/interface.py | 5 + .../opendbc/car/tesla/screen_button.py | 26 +- opendbc_repo/opendbc/car/tesla/speed_limit.py | 22 + opendbc_repo/opendbc/car/tesla/speed_sync.py | 728 +++++++++ .../car/tesla/tests/test_coop_speed_sync.py | 210 +++ .../tests/test_pedal_and_dashboard_v7.py | 138 ++ .../tesla/tests/test_speed_sync_handover.py | 311 ++++ .../car/tesla/tests/test_speed_sync_manual.py | 341 +++++ .../tesla/tests/test_speed_sync_selection.py | 161 ++ opendbc_repo/opendbc/car/tesla/values.py | 1 + opendbc_repo/opendbc/safety/modes/tesla.h | 18 +- .../opendbc/safety/modes/tesla_speed_sync.h | 215 +++ opendbc_repo/opendbc/safety/safety.h | 2 +- .../opendbc/safety/tests/libsafety/safety.c | 9 + .../tests/test_tesla_encoding_namespace.py | 23 + .../opendbc/safety/tests/test_tesla_hw1.py | 5 +- .../safety/tests/test_tesla_speed_sync.py | 974 ++++++++++++ openpilot/cereal/custom.capnp | 16 + openpilot/common/params_keys.h | 4 +- openpilot/selfdrive/car/card.py | 20 +- openpilot/selfdrive/car/cruise.py | 17 +- .../pandad/tests/test_aol_protocol.cc | 50 +- openpilot/selfdrive/ui/ui.py | 5 +- openpilot/starpilot/car/tesla/aol.py | 6 +- openpilot/starpilot/car/tesla/aol_policy.h | 5 + .../starpilot/car/tesla/coop_preferences.py | 6 + openpilot/starpilot/car/tesla/set_speed.py | 48 + .../custom_reviewed_schema_additions.json | 76 + .../tesla/tests/test_aol_speed_sync_words.py | 119 ++ .../car/tesla/tests/test_ordinary_aol.py | 5 +- .../tests/test_screen_recovery_callers.py | 3 +- .../tesla/tests/test_screen_tap_default.py | 56 + .../car/tesla/tests/test_set_speed_switch.py | 126 ++ .../tesla/tests/test_speed_sync_context.py | 410 +++++ .../tesla/tests/test_speed_sync_other_cars.py | 337 +++++ .../tesla/tests/test_speed_sync_startup.py | 179 +++ .../starpilot/car/tesla_speed_sync_context.py | 67 + .../starpilot/common/car_control_config.py | 113 ++ .../starpilot/controllers/cruise_action.py | 90 +- openpilot/starpilot/controllers/runtime.py | 13 +- .../starpilot/controllers/tesla_controls.py | 301 ++++ .../controllers/tesla_gesture_context.py | 79 + .../controllers/tesla_input_protocol.py | 69 + .../controllers/tesla_input_worker.py | 190 +++ .../starpilot/controllers/tesla_receiver.py | 271 ++++ .../controllers/tests/tesla_worker_fixture.py | 89 ++ .../controllers/tests/test_cruise_action.py | 46 + .../tests/test_slc_input_recovery.py | 185 +++ .../tests/test_tesla_controls_v7.py | 305 ++++ .../controllers/tests/test_tesla_decoder.py | 295 ++++ .../tests/test_tesla_keyed_lookup.py | 120 ++ .../tests/test_tesla_screen_gesture.py | 66 + .../tests/test_tesla_scroll_receipts.py | 553 +++++++ .../tests/test_tesla_scroll_speed.py | 520 +++++++ .../tests/test_tesla_wheel_hold.py | 259 ++++ .../controllers/tests/test_tesla_worker.py | 711 +++++++++ .../starpilot/galaxy/setting_descriptions.py | 2 - openpilot/starpilot/galaxy/settings.py | 2 + .../tests/description-key-inventory.json | 1 - .../tests/test_tesla_screen_settings.py | 37 +- .../starpilot/galaxy/web/css/settings.css | 1 + .../galaxy/web/js/galaxy-setting-row.js | 4 +- .../starpilot/speed_limits/COMPOSITION.md | 4 + openpilot/starpilot/speed_limits/README.md | 40 +- .../starpilot/speed_limits/acceptance.py | 33 +- .../starpilot/speed_limits/composition.py | 59 +- openpilot/starpilot/speed_limits/overrides.py | 273 ++++ .../speed_limits/physical_actions.py | 50 +- .../starpilot/speed_limits/planner_host.py | 18 +- openpilot/starpilot/speed_limits/runtime.py | 179 ++- .../speed_limits/runtime_settings.py | 3 + .../starpilot/speed_limits/speed_domain.py | 11 + .../speed_limits/tesla_set_speed_card.py | 138 ++ .../speed_limits/tests/test_overrides.py | 395 +++++ .../tests/test_tesla_pedal_hold.py | 217 +++ .../tests/test_tesla_set_speed.py | 1315 +++++++++++++++++ .../starpilot/tests/port_settings_fixture.py | 18 + .../tests/tesla_set_speed_fixture.py | 35 + .../tests/test_tesla_screen_integration.py | 3 +- .../starpilot/ui/feature_settings_owner.py | 10 +- .../starpilot/ui/feature_settings_state.py | 2 + openpilot/starpilot/ui/runtime_app.py | 27 +- openpilot/starpilot/ui/runtime_snapshot.py | 13 + openpilot/starpilot/ui/slc_resume_action.py | 37 + .../starpilot/ui/tesla_controls_feature.py | 161 ++ openpilot/starpilot/ui/tesla_rows.py | 50 + .../starpilot/ui/tesla_screen_feature.py | 12 +- .../starpilot/ui/tesla_set_speed_feature.py | 100 ++ openpilot/starpilot/ui/tesla_speed_actions.py | 53 + .../ui/tests/test_slc_resume_action.py | 244 +++ .../ui/tests/test_tesla_set_speed.py | 386 +++++ .../ui/tests/test_tesla_settings_wiring.py | 301 ++++ .../ui/tests/test_tesla_speed_actions.py | 202 +++ openpilot/starpilot/ui/vehicle_bool.py | 7 +- openpilot/starpilot/vehicle_preferences.py | 11 +- 97 files changed, 13371 insertions(+), 115 deletions(-) create mode 100644 opendbc_repo/opendbc/car/tesla/speed_limit.py create mode 100644 opendbc_repo/opendbc/car/tesla/speed_sync.py create mode 100644 opendbc_repo/opendbc/car/tesla/tests/test_coop_speed_sync.py create mode 100644 opendbc_repo/opendbc/car/tesla/tests/test_pedal_and_dashboard_v7.py create mode 100644 opendbc_repo/opendbc/car/tesla/tests/test_speed_sync_handover.py create mode 100644 opendbc_repo/opendbc/car/tesla/tests/test_speed_sync_manual.py create mode 100644 opendbc_repo/opendbc/car/tesla/tests/test_speed_sync_selection.py create mode 100644 opendbc_repo/opendbc/safety/modes/tesla_speed_sync.h create mode 100644 opendbc_repo/opendbc/safety/tests/test_tesla_speed_sync.py create mode 100644 openpilot/starpilot/car/tesla/set_speed.py create mode 100644 openpilot/starpilot/car/tesla/tests/test_aol_speed_sync_words.py create mode 100644 openpilot/starpilot/car/tesla/tests/test_screen_tap_default.py create mode 100644 openpilot/starpilot/car/tesla/tests/test_set_speed_switch.py create mode 100644 openpilot/starpilot/car/tesla/tests/test_speed_sync_context.py create mode 100644 openpilot/starpilot/car/tesla/tests/test_speed_sync_other_cars.py create mode 100644 openpilot/starpilot/car/tesla/tests/test_speed_sync_startup.py create mode 100644 openpilot/starpilot/car/tesla_speed_sync_context.py create mode 100644 openpilot/starpilot/common/car_control_config.py create mode 100644 openpilot/starpilot/controllers/tesla_controls.py create mode 100644 openpilot/starpilot/controllers/tesla_gesture_context.py create mode 100644 openpilot/starpilot/controllers/tesla_input_protocol.py create mode 100644 openpilot/starpilot/controllers/tesla_input_worker.py create mode 100644 openpilot/starpilot/controllers/tesla_receiver.py create mode 100644 openpilot/starpilot/controllers/tests/tesla_worker_fixture.py create mode 100644 openpilot/starpilot/controllers/tests/test_slc_input_recovery.py create mode 100644 openpilot/starpilot/controllers/tests/test_tesla_controls_v7.py create mode 100644 openpilot/starpilot/controllers/tests/test_tesla_decoder.py create mode 100644 openpilot/starpilot/controllers/tests/test_tesla_keyed_lookup.py create mode 100644 openpilot/starpilot/controllers/tests/test_tesla_screen_gesture.py create mode 100644 openpilot/starpilot/controllers/tests/test_tesla_scroll_receipts.py create mode 100644 openpilot/starpilot/controllers/tests/test_tesla_scroll_speed.py create mode 100644 openpilot/starpilot/controllers/tests/test_tesla_wheel_hold.py create mode 100644 openpilot/starpilot/controllers/tests/test_tesla_worker.py create mode 100644 openpilot/starpilot/speed_limits/overrides.py create mode 100644 openpilot/starpilot/speed_limits/tesla_set_speed_card.py create mode 100644 openpilot/starpilot/speed_limits/tests/test_overrides.py create mode 100644 openpilot/starpilot/speed_limits/tests/test_tesla_pedal_hold.py create mode 100644 openpilot/starpilot/speed_limits/tests/test_tesla_set_speed.py create mode 100644 openpilot/starpilot/tests/port_settings_fixture.py create mode 100644 openpilot/starpilot/tests/tesla_set_speed_fixture.py create mode 100644 openpilot/starpilot/ui/slc_resume_action.py create mode 100644 openpilot/starpilot/ui/tesla_controls_feature.py create mode 100644 openpilot/starpilot/ui/tesla_rows.py create mode 100644 openpilot/starpilot/ui/tesla_set_speed_feature.py create mode 100644 openpilot/starpilot/ui/tesla_speed_actions.py create mode 100644 openpilot/starpilot/ui/tests/test_slc_resume_action.py create mode 100644 openpilot/starpilot/ui/tests/test_tesla_set_speed.py create mode 100644 openpilot/starpilot/ui/tests/test_tesla_settings_wiring.py create mode 100644 openpilot/starpilot/ui/tests/test_tesla_speed_actions.py diff --git a/opendbc_repo/opendbc/car/tesla/carcontroller.py b/opendbc_repo/opendbc/car/tesla/carcontroller.py index 3fd7b826e8..ae61a1da73 100644 --- a/opendbc_repo/opendbc/car/tesla/carcontroller.py +++ b/opendbc_repo/opendbc/car/tesla/carcontroller.py @@ -1,3 +1,4 @@ +import time import numpy as np from opendbc.car import ACCEL_MAX_TAKEOFF from opendbc.can import CANPacker @@ -10,6 +11,7 @@ from opendbc.car.tesla.hw1 import HW1CarController from opendbc.car.tesla.values import CAR, CarControllerParams, TeslaSafetyFlags from opendbc.car.tesla.coop_steering import CooperativeSteeringController from opendbc.car.vehicle_model import VehicleModel +from opendbc.car.tesla.speed_sync import SpeedSynchronizer, selected as speed_sync_selected, sync_controller def get_safety_CP(): @@ -22,6 +24,7 @@ def get_safety_CP(): class CarController(CarControllerBase): def __init__(self, dbc_names, CP): super().__init__(dbc_names, CP) + self.speed_sync = SpeedSynchronizer() if speed_sync_selected(CP) else None if CP.carFingerprint == CAR.TESLA_MODEL_S_PREAP: self.preap = PreAPStockCarController(dbc_names, CP) return @@ -91,6 +94,10 @@ class CarController(CarControllerBase): cntr = (CS.das_control["DAS_controlCounter"] + 1) % 8 can_sends.append(self.tesla_can.create_longitudinal_command(13, 0, cntr, CS.out.vEgo, False)) + # Speed sync: append-only mirror; never changes the selected target or actuators. + if self.speed_sync is not None: + can_sends.extend(sync_controller(self, CC, CS, time.clock_gettime_ns(time.CLOCK_BOOTTIME))) + # TODO: HUD control new_actuators = actuators.as_builder() new_actuators.steeringAngleDeg = getattr(self, "command_angle", self.apply_angle_last) diff --git a/opendbc_repo/opendbc/car/tesla/carstate.py b/opendbc_repo/opendbc/car/tesla/carstate.py index 86a02132e2..fcd2abbbfb 100644 --- a/opendbc_repo/opendbc/car/tesla/carstate.py +++ b/opendbc_repo/opendbc/car/tesla/carstate.py @@ -1,4 +1,6 @@ import copy +from opendbc.car.dashboard_speed_limit import Tracker as LimitTracker +from opendbc.car.tesla.speed_limit import update_dashboard_limit from opendbc.can import CANDefine, CANParser from opendbc.car import Bus, create_button_events, structs from opendbc.car.common.conversions import Conversions as CV @@ -32,6 +34,7 @@ class CarState(CarStateBase): self.hands_on_level = 0 self.das_control = {} return + self.dashboard_limit = LimitTracker() self.cooperative_steering = (CP.carFingerprint in (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y) and bool(CP.safetyConfigs[0].safetyParam & TeslaSafetyFlags.COOP_STEERING)) self.can_define = CANDefine(DBC[CP.carFingerprint][Bus.party]) @@ -160,6 +163,9 @@ class CarState(CarStateBase): # Buttons # ToDo: add Gap adjust button + if self.CP.carFingerprint in (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y): + update_dashboard_limit(self.dashboard_limit, cp_party, cp_ap_party, speed_units) + # Messages needed by carcontroller self.das_control = copy.copy(cp_ap_party.vl["DAS_control"]) diff --git a/opendbc_repo/opendbc/car/tesla/interface.py b/opendbc_repo/opendbc/car/tesla/interface.py index 06e95852f8..2a6f116afd 100644 --- a/opendbc_repo/opendbc/car/tesla/interface.py +++ b/opendbc_repo/opendbc/car/tesla/interface.py @@ -13,6 +13,11 @@ class CarInterface(CarInterfaceBase): CarController = CarController RadarInterface = RadarInterface + def update(self, can_packets): + if self.CC is not None and self.CC.speed_sync is not None: + self.CC.speed_sync.observe(can_packets) + return super().update(can_packets) + @staticmethod def _get_params(ret: structs.CarParams, candidate, fingerprint, car_fw, alpha_long, is_release, docs) -> structs.CarParams: ret.brand = "tesla" diff --git a/opendbc_repo/opendbc/car/tesla/screen_button.py b/opendbc_repo/opendbc/car/tesla/screen_button.py index 10c6968d81..41d2fcd178 100644 --- a/opendbc_repo/opendbc/car/tesla/screen_button.py +++ b/opendbc_repo/opendbc/car/tesla/screen_button.py @@ -1,10 +1,20 @@ """Exact modern Tesla screen harness capability and frozen safety selection.""" -from opendbc.car.tesla.values import CAR, TeslaFlags +from opendbc.car.tesla.values import CAR, TeslaFlags, TeslaSafetyFlags SCREEN_WORDS = frozenset((512, 513, 1536, 1537, 768, 769, 1792, 1793)) BASE_WORDS = frozenset((0, 1, 256, 257)) ORDINARY_WORDS = frozenset((2048, 2049, 2304, 2305, 3072, 3073, 3328, 3329)) AOL_WORDS = SCREEN_WORDS | ORDINARY_WORDS +SPEED_SYNC = int(TeslaSafetyFlags.SCROLL_SPEED_SYNC) +# Exact native tesla_sync_param_valid words: scroll speed sync (4096) on a word that carries LONG_CONTROL. +SYNC_WORDS = frozenset(SPEED_SYNC | word for word in (1, 257, 513, 769, 1537, 1793, 2049, 2305, 3073, 3329)) +KNOWN_FLAGS = int(TeslaFlags.MISSING_DAS_SETTINGS | TeslaFlags.HAS_VEHICLE_BUS | TeslaFlags.AOL_SCREEN_BUTTON) + + +def speed_sync_allowed(cp, word): + return bool(word in SYNC_WORDS and cp.carFingerprint in (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y) and cp.openpilotLongitudinalControl and + cp.flags & TeslaFlags.HAS_VEHICLE_BUS and not cp.flags & ~KNOWN_FLAGS and + bool(word & 512) == bool(cp.flags & TeslaFlags.AOL_SCREEN_BUTTON)) def modern_aol_supported(cp): @@ -12,9 +22,13 @@ def modern_aol_supported(cp): if (cp.brand != 'tesla' or cp.carFingerprint not in (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y) or cp.passive or cp.dashcamOnly or cp.notCar or cp.alternativeExperience not in (0, 32) or len(cp.safetyConfigs) != 1 or int(cp.safetyConfigs[0].safetyModel.raw) != 10 or - cp.flags & ~int(TeslaFlags.MISSING_DAS_SETTINGS | TeslaFlags.HAS_VEHICLE_BUS | TeslaFlags.AOL_SCREEN_BUTTON)): + cp.flags & ~KNOWN_FLAGS): return False word = int(cp.safetyConfigs[0].safetyParam) + if word & SPEED_SYNC: + if not speed_sync_allowed(cp, word): + return False + word &= ~SPEED_SYNC return (word in BASE_WORDS | AOL_WORDS and bool(word & 1) == bool(cp.openpilotLongitudinalControl) and bool(word & 512) == bool(cp.flags & TeslaFlags.AOL_SCREEN_BUTTON) and @@ -31,12 +45,12 @@ modern_screen_supported = screen_tap_supported def screen_qualified(cp, *, marked_only=False): - return bool(screen_tap_supported(cp) and int(cp.safetyConfigs[0].safetyParam) in SCREEN_WORDS and + return bool(screen_tap_supported(cp) and (int(cp.safetyConfigs[0].safetyParam) & ~SPEED_SYNC) in SCREEN_WORDS and cp.alternativeExperience in ((32,) if marked_only else (0, 32))) def modern_aol_qualified(cp, *, marked_only=False): - return bool(modern_aol_supported(cp) and int(cp.safetyConfigs[0].safetyParam) in AOL_WORDS and + return bool(modern_aol_supported(cp) and (int(cp.safetyConfigs[0].safetyParam) & ~SPEED_SYNC) in AOL_WORDS and cp.alternativeExperience in ((32,) if marked_only else (0, 32))) @@ -44,7 +58,7 @@ def apply_modern_aol(cp, requested, screen, brake_disengage): if not modern_aol_supported(cp): return use_screen = requested and screen and screen_tap_supported(cp) - base = int(cp.safetyConfigs[0].safetyParam) & 257 + base = int(cp.safetyConfigs[0].safetyParam) & (257 | SPEED_SYNC) # scroll speed sync rides on top of any AOL word cp.flags &= ~int(TeslaFlags.AOL_SCREEN_BUTTON) cp.safetyConfigs[0].safetyParam = base if requested: @@ -56,7 +70,7 @@ def apply_modern_aol(cp, requested, screen, brake_disengage): def apply_screen_button(cp, requested, brake_disengage): if not screen_tap_supported(cp): return - base = int(cp.safetyConfigs[0].safetyParam) & 257 + base = int(cp.safetyConfigs[0].safetyParam) & (257 | SPEED_SYNC) cp.flags &= ~int(TeslaFlags.AOL_SCREEN_BUTTON) cp.safetyConfigs[0].safetyParam = base if requested: diff --git a/opendbc_repo/opendbc/car/tesla/speed_limit.py b/opendbc_repo/opendbc/car/tesla/speed_limit.py new file mode 100644 index 0000000000..2b428b98a3 --- /dev/null +++ b/opendbc_repo/opendbc/car/tesla/speed_limit.py @@ -0,0 +1,22 @@ +"""Tesla fused road-limit evidence for the 7.0 Dashboard producer.""" +import math +from opendbc.car.dashboard_speed_limit import Status, parser_expiry + + +def update_dashboard_limit(tracker, party, autopilot, speed_units): + limit_ns, limit_expiry = parser_expiry(autopilot, 'DAS_status', 'DAS_fusedSpeedLimit') + units_ns, units_expiry = parser_expiry(party, 'DI_state', 'DI_speedUnits') + stamp = max(limit_ns, units_ns) + if stamp <= tracker.observation.observed_ns: + return + status, speed = Status.UNKNOWN, 0.0 + expiry = min(limit_expiry, units_expiry) + if (limit_ns > 0 and units_ns > 0 and expiry > stamp and party.can_valid and autopilot.can_valid + and speed_units in ('MPH', 'KPH')): + value = float(autopilot.vl['DAS_status']['DAS_fusedSpeedLimit']) + # The DBC scales raw31/NONE to155; raw0 is UNKNOWN, never zero mph. + if math.isfinite(value) and 0 < value <= 150: + status, speed = Status.VALID, value * (0.44704 if speed_units == 'MPH' else 1 / 3.6) + elif value == 155: + status = Status.ABSENT + tracker.update(stamp, status, speed, valid_until_ns=expiry) diff --git a/opendbc_repo/opendbc/car/tesla/speed_sync.py b/opendbc_repo/opendbc/car/tesla/speed_sync.py new file mode 100644 index 0000000000..3a694043d2 --- /dev/null +++ b/opendbc_repo/opendbc/car/tesla/speed_sync.py @@ -0,0 +1,728 @@ +"""Speed sync: one-way native selected-speed mirror for the Tesla Model 3/Y. Experimental. + +No speed-control state is written here. Normal control packets are owned by the +existing controller. Only a bounded relative wheel request can be returned. + +Each request is one right-wheel frame: a single click (+-1 mph), or a fast flick +(+-5 clicks) that moves the Tesla to the next multiple of 5. The Tesla only treats +a flick as fast when it starts a new gesture: a scroll soon after the previous one +moves the speed by 1. So fast steps are spaced, and the spacing +is learned. The panda decides what may be sent. A request the panda does not transmit (no bus-129 return, or a +bus-193 rejection) never reached the car, so it is cleared and retried later. +""" +from dataclasses import dataclass +from collections import deque +import math + +from opendbc.car.tesla.values import TeslaFlags, TeslaSafetyFlags + +SYNC_FLAG = int(TeslaSafetyFlags.SCROLL_SPEED_SYNC) +MODELS = ("TESLA_MODEL_3", "TESLA_MODEL_Y") + + +def eligible(cp): + """A Model 3/Y with StarPilot longitudinal control, its own cruise and the CAN add-on cable (Vehicle CAN).""" + try: + return bool(cp.brand == "tesla" and cp.carFingerprint in MODELS and cp.openpilotLongitudinalControl and cp.pcmCruise and + not cp.passive and not cp.dashcamOnly and not cp.notCar and cp.flags & TeslaFlags.HAS_VEHICLE_BUS and + len(cp.safetyConfigs) == 1 and cp.safetyConfigs[0].safetyParam & TeslaSafetyFlags.LONG_CONTROL) + except (AttributeError, TypeError, ValueError, IndexError): + return False + + +def selected(cp): + """The car started with the scroll frame admitted, so the comma may own the set speed and scroll the Tesla's to match. + Whether it does follows the saved switch (openpilot/starpilot/car/tesla/set_speed.py).""" + try: + return bool(eligible(cp) and cp.safetyConfigs[0].safetyParam & SYNC_FLAG) + except (AttributeError, TypeError, ValueError, IndexError): + return False + + +def prepare(cp, requested): + """Admit the scroll frame in the car's parameters at startup (the panda sends it only with this bit).""" + if eligible(cp): + cp.safetyConfigs[0].safetyParam &= ~SYNC_FLAG + if requested: + cp.safetyConfigs[0].safetyParam |= SYNC_FLAG + return cp + + +NS = 1_000_000_000 +FRESH_NS = 250_000_000 +# No Tesla change by SETTLE_NS: the request went unanswered (the updated panda frees its own request after 0.8 s). +SETTLE_NS = 1_000_000_000 +TOKENS_MAX = 30 # panda rate limit: burst of 30 requests... +TOKEN_REFILL_NS = 1_050_000_000 # ...then one per second (a little slower here so the panda never refuses) +FAST_PAUSE_NS = 2 * NS # after a refused fast step, single clicks for this long +MANUAL_COMPLETION_NS = 2 * NS +HANDOVER_NS = 100_000_000 +TEMPLATE_SEND_NS = 100_000_000 # one wheel-frame period (panda allows 250 ms) +RETURN_NS = 100_000_000 # panda echoes a transmitted frame on bus 129 within ~5 ms +BACKOFF_NS = 300_000_000 # wait after a request the panda refused, +BACKOFF_MAX_NS = 2 * NS # doubling on each refusal in a row +MANUAL_SETTLE_NS = 600_000_000 # let the Tesla apply the driver's own scroll first +FAST_TICKS = 5 +# Fast-step spacing. Measured: a flick 0.1-0.24 s after the previous scroll moved +# the Tesla by 1; the driver's own flicks 0.4 s apart all jumped 5. Start short and +# lengthen on each fast step that lands as a single click; shorten again after a +# run of good ones. Nothing here ever stops the sync. +FAST_GAP_NS = 280_000_000 +FAST_GAP_STEP_NS = 100_000_000 +FAST_GAP_MAX_NS = 800_000_000 +FAST_GAP_RELAX = 30 # good fast steps in a row before trying a shorter gap +FAST_RESPONSE_NS = 250_000_000 # Tesla applies a new gesture after ~0.23 s +STREAM_STEP_NS = 100_000_000 # a click inside a gesture shows up at the next DI frame +ENGAGE_DELAY_NS = 150_000_000 # pandad tells the panda about engagement at 10 Hz +MAX_RETRIES = 3 # unanswered clicks retried at one speed before waiting + + +def neutral_wheel(data): + if len(data) != 8 or data[0] & 3 != 1: + return False + bits = int.from_bytes(data, "little") + return (all((bits >> shift) & 3 == 1 for shift in (3, 5, 8, 10, 12, 14)) and + data[2] & 63 == 0 and data[3] & 63 == 0 and data[4] & 15 == 0) + + +def scroll_request(template, ticks): + """Copy a physical neutral frame and set only the right-wheel scroll count.""" + if not neutral_wheel(template) or ticks not in (-FAST_TICKS, -1, 1, FAST_TICKS): + return None + data = bytearray(template) + data[3] = (data[3] & 0xC0) | (ticks & 0x3F) + return (0x3C2, bytes(data), 1) + + +def plan_step(native, target, allow_fast): + """Return (ticks, expected native) for the next step from native toward target. + + A fast flick lands on the next multiple of 5 in that direction (measured: nearly + every flick of 3+ clicks did this in one change). Use it only + when that multiple does not pass the target and saves at least one click. + """ + sign = 1 if target > native else -1 + if allow_fast: + nxt = (native // 5 + 1) * 5 if sign > 0 else ((native - 1) // 5) * 5 + if abs(nxt - native) >= 2 and (target - nxt) * sign >= 0: + return sign * FAST_TICKS, nxt + return sign, native + sign + + +@dataclass(frozen=True) +class SyncAuthority: + observed_boot_ns: int + target_kph: float + is_metric: bool + configuration_id: str + software_owned: bool + document_hash: str = "" + vehicle_hash: str = "" + drive_start_ns: int = 0 + manual_receipts: tuple = () + + +@dataclass(frozen=True) +class ManualReceipt: + boot_ns: int + frame_index: int + name: str + fast: bool + worker_session: str + sequence: int + document_hash: str + vehicle_hash: str + drive_start_ns: int + processed_boot_ns: int + target_kph: float + + +@dataclass +class Pending: + before: float + direction: int + units: int + sent_ns: int + data: bytes + ticks: int = 0 + retry: bool = False + returned: bool = False + expected: int = 0 + gap_ns: int = 0 # time since the previous scroll when sent + + +class SpeedSynchronizer: + def __init__(self): + self.template = None + self.template_ns = 0 + self.driver_ns = 0 + self.native_ns = 0 + self.native = None + self.units = None + self.cruise_state = None + self.autopark = None + self.counter = None + self.di_valid = False + self.di_key = (0, -1) + self.wheel_stamp = 0 + self.pending = None + self.unanswered = None + self.unanswered_count = 0 + self.last_sent = 0 + self.last_template_sent = 0 + self.last_update = 0 + self.backoff_until = 0 + self.target = None + self.steps = 0 + self.blocked = None + self.status = "idle" + self.active = False + self.authority_id = None + self.manual_armed = False + self.manual_active = None + self.manual_queue = [] + self.manual_receipts = {} + self.manual_receipt_acks = [] + self.manual_ack_key = (0, -1) + self.wheel_key = (0, -1) + self.wheel_held = False # the last wheel frame was a tilt or press without a scroll + self.gas_was_pressed = False + self.handover_until = 0 + self.response_ns = 0 + self.history = deque(maxlen=32) + self.failure_logged = False + # Nothing is switched off for good: a refusal only pauses that feature. + self.fast_paused_until = 0 + self.retry_refused = False + self.tokens = TOKENS_MAX + self.refill_ns = 0 + self.last_scroll_ns = 0 # last scroll the Tesla saw: our sent request or the driver's + self.fast_gap_ns = FAST_GAP_NS + self.fast_streak = 0 + self.engaged_ns = 0 + self.refusals = 0 + self.notices = [] + self.noticed = set() + + def observe(self, packets): + """Use original arrival timestamps; cached values never refresh freshness.""" + for stamp, frames in packets: + if type(stamp) is not int or stamp <= 0: + continue + for frame_index, (address, data, bus) in enumerate(frames): + if address == 0x3C2 and bus in (129, 193): + # Panda echo of a frame we asked it to send: 129 = transmitted, + # 193 = refused by safety. Exact bytes and clock must match. + p = self.pending + if p is not None and not p.returned and stamp >= p.sent_ns and bytes(data) == p.data: + if bus == 129: + p.returned = True + self.last_scroll_ns = max(self.last_scroll_ns, p.sent_ns) + self.refusals = 0 + self.steps += 1 + self.tokens = max(self.tokens - 1, 0) + else: + self._not_transmitted(p, "panda_rejected") + continue + if address == 0x3C2 and bus == 1: + key = (stamp, frame_index) + if key == self.wheel_key: + continue + if key < self.wheel_key: + self.template = None + self.blocked = "wheel_clock_reversal" + continue + self.wheel_key = key + self.wheel_stamp = stamp + if len(data) != 8: + self.template = None + if self.manual_active: + self._pause_manual("ambiguous_manual_input") + self.manual_armed = False + continue + mux = data[0] & 3 + if mux == 0: + continue + if mux != 1: + self.template = None + if self.manual_active: + self._pause_manual("ambiguous_manual_input") + self.manual_armed = False + continue + self._observe_manual(data, stamp, frame_index) + if neutral_wheel(data): + self.template, self.template_ns = bytes(data), stamp + else: + self.template = None + self.driver_ns = stamp + self.last_scroll_ns = max(self.last_scroll_ns, stamp) + # Genuine controls take priority. The request stays outstanding + # until the Tesla's speed changes; direction is then recomputed + # from reality, so nothing is repeated blindly. + if self.pending is not None: + self._record("input_during_request", stamp) + elif address == 0x286 and bus == 0: + # Several DI frames can share one receive batch (same stamp), so + # order by (stamp, index) like the wheel frames above. + key = (stamp, frame_index) + if key <= self.di_key: + if key < self.di_key: + self.blocked = "feedback_clock_reversal" + self.native_ns = 0 + continue + self.di_key = key + if len(data) != 8 or data[0] != ((0x86 + 2 + sum(data[1:])) & 0xFF): + self.di_valid = False + continue + counter = data[1] & 15 + advancing = self.counter is None or (counter - self.counter) % 16 == 1 + self.counter = counter + # Same rule as the panda: a frame after a counter gap is not used, + # and nothing may be sent until the next in-sequence frame. + self.di_valid = advancing + if not advancing: + continue + bits = int.from_bytes(data, "little") + self.native = ((bits >> 15) & 511) * .5 + self.units = (bits >> 24) & 1 # 0 mph, 1 km/h + self.cruise_state = (bits >> 12) & 7 + self.autopark = (bits >> 25) & 15 + self.native_ns = stamp + + def _observe_manual(self, data, stamp, frame_index): + right = data[3] & 63 + right = right - 64 if right >= 32 else right + if right: + released = bytearray(data) + released[3] &= 0xC0 + name = "right_wheel_up" if right > 0 else "right_wheel_down" + if self.manual_active is None and self.wheel_held and abs(right) == 1 and neutral_wheel(released): + # A wheel tilted or pressed often clicks once as it springs back. That click ends the nudge and is not a + # scroll: the comma does not act on it, so nothing waits for it, and the Tesla's change is corrected below. + self._record("nudge_release_click", stamp) + self.wheel_held = False + self.manual_armed = False + return + if (not neutral_wheel(released) or + self.manual_active is None and not (self.manual_armed and self.template is not None and + 0 < self.template_ns <= stamp <= self.template_ns + FRESH_NS) or + self.manual_active is not None and self.manual_active[0] != name): + self._pause_manual("ambiguous_manual_input") + return + peak = max(abs(right), self.manual_active[1] if self.manual_active else 0) + self.manual_active = (name, peak) + self.manual_armed = False + self.wheel_held = False + elif neutral_wheel(data): + if self.manual_active: + if len(self.manual_queue) >= 16: + self._fail("manual_input_overflow") + else: + name, peak = self.manual_active + self.manual_queue.append((stamp, frame_index, name, peak >= 2)) + self.manual_active = None + self.manual_armed = True + self.wheel_held = False + else: + if self.manual_active: + self._pause_manual("ambiguous_manual_input") + self.manual_active = None + self.manual_armed = False + self.wheel_held = True + + def _pause_manual(self, reason): + """Wheel input that cannot be read as one clean scroll. The comma's own input reader ignores the same gesture, so + nothing waits for it: sync carries on and, after the driver's settle time, puts the Tesla back on the comma's speed. + Logged once per engagement.""" + self._notice(reason) + self._record(reason, self.last_update) + self.manual_active = None + self.manual_armed = False + + def accept_manual_receipts(self, authority, now_ns): + # Metadata may arrive before Card sees the corresponding CAN batch. Cache + # only bounded, validated receipts; never infer a gesture from the receipt. + if type(authority.manual_receipts) is not tuple or len(authority.manual_receipts) > 16: + self._fail("invalid_manual_receipts") + return + for receipt in authority.manual_receipts: + if not isinstance(receipt, ManualReceipt): + continue + try: + good = ( + type(receipt.boot_ns) is int and type(receipt.processed_boot_ns) is int and + 0 < receipt.boot_ns <= receipt.processed_boot_ns <= now_ns and + type(receipt.frame_index) is int and 0 <= receipt.frame_index < 4096 and + receipt.name in ("right_wheel_up", "right_wheel_down") and type(receipt.fast) is bool and + type(receipt.worker_session) is str and len(receipt.worker_session) == 32 and + all(c in "0123456789abcdef" for c in receipt.worker_session) and + type(receipt.sequence) is int and receipt.sequence > 0 and + receipt.document_hash == authority.document_hash and len(authority.document_hash) == 64 and + receipt.vehicle_hash == authority.vehicle_hash and len(authority.vehicle_hash) == 64 and + type(receipt.drive_start_ns) is int and receipt.drive_start_ns == authority.drive_start_ns > 0 and + type(receipt.target_kph) in (int, float) and math.isfinite(receipt.target_kph) and + 0 < receipt.target_kph < 255) + except (AttributeError, TypeError, ValueError): + good = False + if not good: + continue + if now_ns > receipt.boot_ns + MANUAL_COMPLETION_NS: + # Validated but expired metadata cannot complete a gesture. Dispose of + # it explicitly so it cannot occupy the producer queue indefinitely; + # update() independently faults any unconfirmed observed gesture. + self._ack_manual_receipt(receipt) + continue + key = (receipt.boot_ns, receipt.frame_index) + if key <= self.manual_ack_key: + self._ack_manual_receipt(receipt) + continue + if key not in self.manual_receipts and len(self.manual_receipts) >= 16: + self._fail("manual_receipt_overflow") + return + if key in self.manual_receipts and self.manual_receipts[key] != receipt: + self._fail("conflicting_manual_receipt") + return + self.manual_receipts[key] = receipt + self._ack_manual_receipt(receipt) + self.manual_receipts = {key: r for key, r in self.manual_receipts.items() if now_ns <= r.boot_ns + MANUAL_COMPLETION_NS} + while self.manual_queue: + stamp, index, name, fast = self.manual_queue[0] + receipt = self.manual_receipts.get((stamp, index)) + if receipt is None: + break + if (receipt.name, receipt.fast) != (name, fast): + self._fail("manual_receipt_mismatch") + return + self.manual_queue.pop(0) + self.manual_receipts.pop((stamp, index)) + self.manual_ack_key = (stamp, index) + self.target = None # Re-read the processed target; never write its owner. + + def _ack_manual_receipt(self, receipt): + # Acknowledge metadata custody only; this never acknowledges or repeats a + # speed action. Card removes exactly these immutable receipts next frame. + if receipt not in self.manual_receipt_acks: + if len(self.manual_receipt_acks) >= 16: + self._fail("manual_receipt_ack_overflow") + else: + self.manual_receipt_acks.append(receipt) + + def take_manual_receipt_acks(self): + result = tuple(self.manual_receipt_acks) + self.manual_receipt_acks.clear() + return result + + def _fail(self, reason): + if not self.blocked: + self._record("fault", self.last_update, reason=reason) + self.blocked = reason + self.pending = None + self.unanswered = None + self._reset_handover() + self.status = reason + return None + + def _notice(self, kind, **extra): + # One log line per kind per engagement; these are recoverable pauses. + if kind not in self.noticed: + self.noticed.add(kind) + self.notices.append(dict(kind=kind, native=self.native, target=self.target, **extra)) + + def _not_transmitted(self, p, reason): + """The panda never put this frame on the bus, so the car never saw it.""" + self.pending = None + if abs(p.ticks) > 1: + # Use single clicks for a while, then try fast steps again. + self.fast_paused_until = self.last_update + FAST_PAUSE_NS + self._notice("fast_step_refused", reason=reason) + elif p.retry: + # Wait for the Tesla's speed to change for this request only. + self.retry_refused = True + self._notice("retry_refused", reason=reason) + else: + self._notice("request_not_transmitted", reason=reason) + self.backoff_until = self.last_update + min(BACKOFF_NS << min(self.refusals, 3), BACKOFF_MAX_NS) + self.refusals += 1 + self._record("not_transmitted", self.last_update, reason=reason, ticks=p.ticks) + + def _learn_fast_gap(self, p): + landed = math.floor(self.native + .5) + before = math.floor(p.before + .5) + if landed == p.expected: + self.fast_streak += 1 + if self.fast_streak >= FAST_GAP_RELAX and self.fast_gap_ns > FAST_GAP_NS: + self.fast_gap_ns = max(self.fast_gap_ns - FAST_GAP_STEP_NS, FAST_GAP_NS) + self.fast_streak = 0 + elif abs(landed - before) == 1 and abs(p.expected - before) >= 2: + # The Tesla took it as part of the previous gesture: space them further. + self.fast_streak = 0 + if p.gap_ns < FAST_GAP_MAX_NS: + self.fast_gap_ns = min(max(self.fast_gap_ns, p.gap_ns) + FAST_GAP_STEP_NS, FAST_GAP_MAX_NS) + self._notice("fast_step_landed_single", gap_ns=p.gap_ns, fast_gap_ns=self.fast_gap_ns) + self._record("fast_landed_single", self.last_update, gap_ns=p.gap_ns, fast_gap_ns=self.fast_gap_ns) + + def _reset_handover(self): + self.gas_was_pressed = False + self.handover_until = 0 + + def _record(self, event, now_ns, **extra): + self.history.append(dict(event=event, boot_ns=now_ns, native=self.native, + target=self.target, native_ns=self.native_ns, + template_ns=self.template_ns, last_sent=self.last_sent, + units=self.units, cruise_state=self.cruise_state, **extra)) + + def _resolve_pending(self, now_ns): + """Advance the outstanding request. Returns True while it still blocks sending.""" + p = self.pending + if p is None: + return False + if self.units is not None and self.units != p.units: + self._fail("units_changed_during_request") + return True + if not p.returned and now_ns - p.sent_ns >= RETURN_NS: + self._not_transmitted(p, "no_bus_return") + return True + if self.native_ns > p.sent_ns and self.native != p.before: + # Fresh selected-speed feedback releases one outstanding request. + # This is not an acknowledgement of command delivery or input origin: + # Tesla may change its selection independently. Recompute from reality. + self.pending = None + self.unanswered = None + self.unanswered_count = 0 + self.retry_refused = False + self.response_ns = self.native_ns + if abs(p.ticks) == FAST_TICKS: + self._learn_fast_gap(p) + self._record("native_response", now_ns, before=p.before, sent_ns=p.sent_ns, ticks=p.ticks) + self.status = "native_speed_changed" + return False + if now_ns - p.sent_ns >= SETTLE_NS: + # Unanswered. The panda keeps its own request open until the speed + # changes (or, with the updated firmware, until its 1 s timeout). + self.pending = None + self.unanswered = p + self.unanswered_count += 1 + self._notice("no_native_response", before=p.before, ticks=p.ticks) + self._record("unanswered", now_ns, before=p.before, ticks=p.ticks) + return True + self.status = "waiting_for_response" + return True + + def update(self, now_ns, *, target_kph, enabled, safe, longitudinal_active=True, gas_pressed=False): + if not enabled: + self.pending = None + self.unanswered = None + self.unanswered_count = 0 + self.retry_refused = False + self.target = None + self.steps = 0 + self.blocked = None + self.active = False + self.authority_id = None + self._reset_handover() + self.response_ns = 0 + self.backoff_until = 0 + self.engaged_ns = 0 + self.failure_logged = False + self.noticed.clear() + self.history.clear() + self.manual_armed = bool(self.template is not None and + 0 < self.template_ns <= now_ns <= self.template_ns + FRESH_NS) + self.manual_active = None + self.manual_queue.clear() + self.manual_receipts.clear() + self.manual_receipt_acks.clear() + self.manual_ack_key = self.wheel_key + self.status = "inactive" + self.last_update = now_ns + return None + if type(now_ns) is not int or now_ns <= 0 or (self.last_update and now_ns <= self.last_update): + return self._fail("controller_clock_reversal") + gap = bool(self.last_update and now_ns - self.last_update > FRESH_NS) + self.last_update = now_ns + self.active = True + if not self.engaged_ns: + self.engaged_ns = now_ns + if self.blocked: + self.status = self.blocked + return None + if self._resolve_pending(now_ns) and self.pending is not None: + return None + if self.blocked: + return None + if gap: + # A late controller frame only pauses this frame; a request is never + # sent on timing that has not been observed continuously. + self._reset_handover() + self.status = "controller_clock_gap" + return None + # Past this bound no matching receipt can pass accept_manual_receipts: the comma did not act on that scroll + # (it refused it, or never saw it). Drop it and carry on; the Tesla's change is then corrected like any other + # change of its own. Never infer completion or repeat the input. + if self.manual_queue and now_ns > self.manual_queue[0][0] + MANUAL_COMPLETION_NS: + dropped = [entry for entry in self.manual_queue if now_ns > entry[0] + MANUAL_COMPLETION_NS] + self.manual_queue = [entry for entry in self.manual_queue if entry not in dropped] + self.manual_ack_key = max(self.manual_ack_key, (dropped[-1][0], dropped[-1][1])) + self._notice("manual_action_unconfirmed", dropped=len(dropped)) + self._record("manual_action_unconfirmed", now_ns, dropped=len(dropped)) + self.target = None + if not safe: + self._reset_handover() + self.target = None + self.status = "inhibited" + return None + if not (0 < self.native_ns <= now_ns <= self.native_ns + FRESH_NS and self.di_valid and + self.native is not None and self.native > 0 and + self.cruise_state in (2, 4) and self.autopark not in (3, 4, 9)): + self._reset_handover() + self.status = "waiting_for_native_speed" + return None + if not math.isfinite(target_kph) or not 0 < target_kph < 255: + self._reset_handover() + self.status = "invalid_target" + return None + # Match the displayed selected speed in Tesla's units, not actual vehicle + # speed or a transient model/curve/lead slowdown. + target = math.floor((target_kph if self.units else target_kph / 1.609344) + .5) + if target <= 0: + self.status = "invalid_target" + return None + target_key = (target, self.units) + if self.target != target_key: + self.target = target_key + # Card and controls publish independently. A genuine pedal release may + # precede longActive by a frame; never transmit while neither current + # authority is present. + if self.gas_was_pressed and not gas_pressed: + self.handover_until = now_ns + HANDOVER_NS + self.gas_was_pressed = bool(gas_pressed) + authorized = bool(longitudinal_active or gas_pressed) + if authorized: + self.handover_until = 0 + elif not (self.handover_until and now_ns < self.handover_until): + self._reset_handover() + self.status = "inhibited" + return None + if self.manual_active is not None or self.manual_queue: + self.status = "waiting_for_manual_processing" + return None + if not authorized: + if self.status != "waiting_for_handover": + self._record("handover_wait", now_ns, until_ns=self.handover_until) + self.status = "waiting_for_handover" + return None + native = math.floor(self.native + .5) + if native == target: + self.unanswered = None + self.unanswered_count = 0 + self.status = "matched" + return None + # The driver's own scroll takes 0.18-0.4 s to reach the Tesla's selected + # speed (measured). A request in that window can cancel a fast flick, so + # let the Tesla act on it first. + if self.driver_ns and now_ns < self.driver_ns + MANUAL_SETTLE_NS: + self.status = "waiting_for_driver_scroll" + return None + retry = False + if self.unanswered is not None: + u = self.unanswered + if self.native_ns > u.sent_ns and self.native != u.before: + self.unanswered = None + self.unanswered_count = 0 + self.retry_refused = False + elif self.retry_refused or self.unanswered_count > MAX_RETRIES: + # e.g. the Tesla is at its own speed limit; don't keep scrolling. + self.status = "waiting_for_native_change" + return None + else: + retry = True + if now_ns < self.backoff_until: + self.status = "backoff" + return None + # The panda only learns that comma engaged from pandad's next heartbeat. + if now_ns < self.engaged_ns + ENGAGE_DELAY_NS: + self.status = "waiting_for_panda_engage" + return None + # Mirror the panda's rate limit so it never has to refuse a request. + if self.refill_ns == 0: + self.refill_ns = now_ns + while self.tokens < TOKENS_MAX and now_ns - self.refill_ns >= TOKEN_REFILL_NS: + self.tokens += 1 + self.refill_ns += TOKEN_REFILL_NS + if self.tokens >= TOKENS_MAX: + self.refill_ns = now_ns + if self.tokens <= 0: + self.status = "rate_limited" + return None + # Any physical neutral frame newer than the last one used, still current. + if not (self.template is not None and 0 < self.template_ns <= now_ns <= self.template_ns + TEMPLATE_SEND_NS and + self.template_ns > self.last_template_sent): + self.status = "waiting_for_neutral_wheel" + return None + ticks, expected = plan_step(native, target, allow_fast=now_ns >= self.fast_paused_until and self.units == 0) + gap_ns = now_ns - self.last_scroll_ns if self.last_scroll_ns else 10 * NS + if abs(ticks) == FAST_TICKS and gap_ns < self.fast_gap_ns: + # Too soon for the Tesla to start a new gesture. Clicks give 1 mph per + # 0.1 s and each one restarts the gap, so while fast steps are quicker + # overall (gap under 0.5 s) wait for them on any change of 5 or more. + # For a short change, wait only if that beats clicking there. + wait_ns = self.fast_gap_ns - gap_ns + if ((self.fast_gap_ns < FAST_TICKS * STREAM_STEP_NS and abs(target - native) >= FAST_TICKS) or + wait_ns + FAST_RESPONSE_NS <= abs(expected - native) * STREAM_STEP_NS): + self.status = "waiting_for_fast_gap" + return None + ticks, expected = plan_step(native, target, allow_fast=False) + message = scroll_request(self.template, ticks) + if message is None: + return self._fail("invalid_template") + direction = 1 if ticks > 0 else -1 + self.pending = Pending(self.native, direction, self.units, now_ns, message[1], ticks=ticks, retry=retry, + expected=expected, gap_ns=gap_ns) + # A retry keeps the unanswered request on record until the speed changes, + # so a refused retry falls back to waiting rather than retrying forever. + self.last_sent = now_ns + self.last_template_sent = self.template_ns + self.status = "request_pending" + self._record("request", now_ns, direction=direction, ticks=ticks, retry=retry, gap_ns=gap_ns) + return message + + +def sync_controller(controller, CC, CS, now_ns): + """Read-only mirror. now_ns is BOOTTIME, matching the CAN producer clock.""" + from opendbc.car.structs import CarState + synchronizer = controller.speed_sync + out = CS.out + authority = getattr(controller, "speed_sync_authority", None) + authority_valid = bool( + isinstance(authority, SyncAuthority) and authority.software_owned is True and + type(authority.observed_boot_ns) is int and + 0 < authority.observed_boot_ns <= now_ns <= authority.observed_boot_ns + 100_000_000 and + type(authority.is_metric) is bool and synchronizer.units == int(authority.is_metric) and + type(authority.target_kph) in (int, float) and math.isfinite(authority.target_kph) and authority.target_kph == float(out.vCruise) and + type(authority.configuration_id) is str and len(authority.configuration_id) == 64 and all(c in "0123456789abcdef" for c in authority.configuration_id)) + if authority_valid and CC.enabled: + if synchronizer.authority_id not in (None, authority.configuration_id): + synchronizer._fail("configuration_changed") + synchronizer.authority_id = authority.configuration_id + synchronizer.accept_manual_receipts(authority, now_ns) + safe = (authority_valid and out.canValid and not out.canTimeout and out.cruiseState.enabled and + out.gearShifter == CarState.GearShifter.drive and + not (out.standstill or out.brakePressed or out.accFaulted or out.stockAeb or out.stockFcw or + out.espDisabled or out.espActive or out.vehicleSensorsInvalid or out.carNotReady or out.doorOpen or out.seatbeltUnlatched or + out.steerFaultPermanent or out.steerFaultTemporary or out.stockLkas or + out.invalidLkasSetting or CS.autopark)) + message = synchronizer.update(now_ns, target_kph=float(out.vCruise), + enabled=bool(CC.enabled and not CC.cruiseControl.cancel), safe=bool(safe), + longitudinal_active=bool(CC.longActive), gas_pressed=bool(out.gasPressed)) + if not authority_valid and CC.enabled and not synchronizer.blocked: + synchronizer.status = "owner_or_config_ineligible" + if synchronizer.notices or (synchronizer.blocked and not synchronizer.failure_logged): + from opendbc.car.carlog import carlog + for notice in synchronizer.notices: + carlog.warning("speed sync paused: %s", dict(notice, boot_ns=now_ns, history=list(synchronizer.history)[-8:])) + synchronizer.notices.clear() + if synchronizer.blocked and not synchronizer.failure_logged: + synchronizer.failure_logged = True + carlog.warning("speed sync stopped: %s", {"reason": synchronizer.blocked, "boot_ns": now_ns, + "native": synchronizer.native, "target": synchronizer.target, "history": list(synchronizer.history)}) + return [] if message is None else [message] diff --git a/opendbc_repo/opendbc/car/tesla/tests/test_coop_speed_sync.py b/opendbc_repo/opendbc/car/tesla/tests/test_coop_speed_sync.py new file mode 100644 index 0000000000..236d73446c --- /dev/null +++ b/opendbc_repo/opendbc/car/tesla/tests/test_coop_speed_sync.py @@ -0,0 +1,210 @@ +"""Startup preferences keep the exact speed-sync safety words: co-op steering and Always On Lateral compose with it.""" +from pathlib import Path +import re + +import pytest +from opendbc.car import gen_empty_fingerprint +from opendbc.car.structs import car +from opendbc.car.tesla.interface import CarInterface +from opendbc.car.tesla.carcontroller import CarController +from opendbc.car.tesla.carstate import CarState +from opendbc.car.tesla.screen_button import (SYNC_WORDS, apply_modern_aol, apply_screen_button, modern_aol_qualified, modern_aol_supported, + screen_qualified, screen_tap_supported, speed_sync_allowed) +from opendbc.car.tesla.speed_sync import SYNC_FLAG, prepare as apply_speed_sync, selected +from opendbc.car.tesla.values import CAR, CANBUS, DBC, TeslaFlags +from openpilot.starpilot.car.tesla.coop_preferences import prepare as apply_cooperative, supported + +MODERN = (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y) +# The words tesla_sync_param_valid accepts (safety/modes/tesla_speed_sync.h): 4096 on a word that carries LONG_CONTROL. +NATIVE_SYNC_WORDS = frozenset(4096 | word for word in (1, 257, 513, 769, 1537, 1793, 2049, 2305, 3073, 3329)) + + +def sync_params(candidate=CAR.TESLA_MODEL_3, long=True): + """A Model 3/Y with the add-on cable, as it leaves startup with Comma can set speed on Tesla dashboard requested.""" + fingerprint = gen_empty_fingerprint() + fingerprint[CANBUS.vehicle][0x3DF] = 8 + fingerprint[CANBUS.autopilot_party][0x489] = 8 + return apply_speed_sync(CarInterface.get_params(candidate, fingerprint, [], long, False, False), True) + + +def raw(cp): + return cp.as_reader().as_builder().to_bytes() + + +def startup(cp, coop, screen=False, brake=False): + apply_screen_button(cp, screen, brake) + apply_cooperative(cp, coop) + return cp + + +def expected_word(coop, screen, brake): + return 4097 | (256 if coop else 0) | ((512 | (1024 if brake else 0)) if screen else 0) + + +def assert_rejected(cp): + before = raw(cp) + assert not supported(cp) + assert not screen_tap_supported(cp) + assert not screen_qualified(cp) + assert not modern_aol_supported(cp) + apply_cooperative(cp, True) + apply_screen_button(cp, True, True) + apply_modern_aol(cp, True, True, True) + assert raw(cp) == before + + +def test_python_words_mirror_the_native_list(): + assert SYNC_WORDS == NATIVE_SYNC_WORDS + header = (Path(__file__).parents[3] / 'safety/modes/tesla_speed_sync.h').read_text() + body = header[header.index('static bool tesla_sync_param_valid'):] + assert frozenset(4096 | int(word) for word in re.findall(r'base == (\d+)U', body)) == SYNC_WORDS + assert 'GET_FLAG(param, 4096U)' in body + + +@pytest.mark.parametrize('candidate', MODERN) +def test_selected_word_precondition(candidate): + cp = sync_params(candidate) + assert cp.safetyConfigs[0].safetyParam == 4097 and selected(cp) + assert cp.openpilotLongitudinalControl + assert cp.flags & TeslaFlags.HAS_VEHICLE_BUS + assert speed_sync_allowed(cp, 4097) + assert supported(cp) and screen_tap_supported(cp) and modern_aol_supported(cp) and not screen_qualified(cp) + assert CarController(DBC[cp.carFingerprint], cp).speed_sync is not None + + +@pytest.mark.parametrize('candidate', MODERN) +@pytest.mark.parametrize('coop', (False, True)) +def test_cooperative_on_off_keeps_sync(candidate, coop): + cp = startup(sync_params(candidate), coop) + assert cp.safetyConfigs[0].safetyParam == (4353 if coop else 4097) + apply_cooperative(cp, not coop) + assert cp.safetyConfigs[0].safetyParam == (4097 if coop else 4353) + assert selected(cp) + + +@pytest.mark.parametrize('candidate', MODERN) +@pytest.mark.parametrize('coop', (False, True)) +@pytest.mark.parametrize('screen', (False, True)) +@pytest.mark.parametrize('brake', (False, True)) +def test_screen_brake_matrix_composes_native_words(candidate, coop, screen, brake): + cp = startup(sync_params(candidate), coop, screen, brake) + expected = expected_word(coop, screen, brake) + assert expected in NATIVE_SYNC_WORDS + assert cp.safetyConfigs[0].safetyParam == expected + assert supported(cp) and screen_tap_supported(cp) and selected(cp) + assert screen_qualified(cp) == screen + assert bool(cp.flags & TeslaFlags.AOL_SCREEN_BUTTON) == screen + apply_screen_button(cp, not screen, brake) + assert cp.safetyConfigs[0].safetyParam == expected_word(coop, not screen, brake) + assert screen_qualified(cp) == (not screen) + + +@pytest.mark.parametrize('candidate', MODERN) +@pytest.mark.parametrize('coop', (False, True)) +@pytest.mark.parametrize('screen', (False, True)) +@pytest.mark.parametrize('brake', (False, True)) +def test_always_on_lateral_composes_native_words(candidate, coop, screen, brake): + # Ordinary Always On Lateral is 2048 and the screen tap 512; either one keeps speed sync on top. + cp = sync_params(candidate) + apply_modern_aol(cp, True, screen, brake) + apply_cooperative(cp, coop) + expected = 4097 | (512 if screen else 2048) | (1024 if brake else 0) | (256 if coop else 0) + assert cp.safetyConfigs[0].safetyParam == expected and expected in NATIVE_SYNC_WORDS + assert selected(cp) and supported(cp) and modern_aol_supported(cp) and modern_aol_qualified(cp) + apply_modern_aol(cp, False, screen, brake) + assert cp.safetyConfigs[0].safetyParam == 4097 | (256 if coop else 0) + assert selected(cp) and not modern_aol_qualified(cp) + + +@pytest.mark.parametrize('candidate', MODERN) +@pytest.mark.parametrize('order', ('sync last', 'sync first', 'sync between')) +@pytest.mark.parametrize('aol', (None, 'ordinary', 'screen')) +def test_any_startup_order_gives_the_same_word(candidate, order, aol): + cp = sync_params(candidate) + apply_speed_sync(cp, False) + steps = [lambda: apply_modern_aol(cp, aol is not None, aol == 'screen', True), lambda: apply_cooperative(cp, True)] + steps.insert({'sync first': 0, 'sync between': 1, 'sync last': 2}[order], lambda: apply_speed_sync(cp, True)) + for _ in range(2): # prepare, then finalize on the same parameters + for step in steps: + step() + expected = 4097 | 256 | {None: 0, 'ordinary': 2048 | 1024, 'screen': 512 | 1024}[aol] + assert cp.safetyConfigs[0].safetyParam == expected and expected in NATIVE_SYNC_WORDS + + +@pytest.mark.parametrize('coop_first', (False, True)) +@pytest.mark.parametrize('brake', (False, True)) +def test_repeated_startup_ordering_preserves_sync(coop_first, brake): + cp = sync_params() + expected = expected_word(True, True, brake) + for _ in range(3): + if coop_first: + apply_cooperative(cp, True) + apply_screen_button(cp, True, brake) + else: + apply_screen_button(cp, True, brake) + apply_cooperative(cp, True) + assert cp.safetyConfigs[0].safetyParam == expected + assert screen_qualified(cp) + apply_cooperative(cp, False) + assert cp.safetyConfigs[0].safetyParam == expected & ~256 + apply_screen_button(cp, False, brake) + assert cp.safetyConfigs[0].safetyParam == 4097 + apply_cooperative(cp, True) + assert cp.safetyConfigs[0].safetyParam == 4353 + + +def test_sync_longitudinal_off_rejected(): + for word in (4096, 4097, 4352): + cp = sync_params(long=False) + assert not cp.safetyConfigs[0].safetyParam & SYNC_FLAG, 'never requested without longitudinal control' + cp.safetyConfigs[0].safetyParam = word + assert_rejected(cp) + cp = sync_params() + cp.openpilotLongitudinalControl = False + assert_rejected(cp) + + +def test_sync_without_vehicle_bus_or_with_unknown_flag_rejected(): + cp = sync_params() + cp.flags &= ~int(TeslaFlags.HAS_VEHICLE_BUS) + assert_rejected(cp) + cp = sync_params() + cp.flags |= 64 + assert_rejected(cp) + + +@pytest.mark.parametrize('word', (4097 | 2, 4097 | 4, 4097 | 16, 4097 | 8192, 4097 | 1024, 4353 | 8192, 4097 | 512 | 2048)) +def test_sync_with_unknown_safety_bit_rejected(word): + cp = sync_params() + cp.safetyConfigs[0].safetyParam = word + assert_rejected(cp) + + +def test_screen_word_must_match_the_screen_flag(): + cp = sync_params() + cp.safetyConfigs[0].safetyParam = 4097 | 512 # the screen word without the screen flag in CarParams + assert_rejected(cp) + + +@pytest.mark.parametrize('candidate', MODERN) +def test_real_controller_and_carstate_cooperate_after_sync_startup(candidate): + cp = startup(sync_params(candidate), True) + assert cp.safetyConfigs[0].safetyParam == 4353 + cs = CarState(cp) + cs.hands_on_level = 0 + cs.das_control = {'DAS_controlCounter': 0} + cs.out.vEgo = cs.out.vEgoRaw = 20. + cs.out.steeringAngleDeg = 0. + cs.out.gasPressed = False + controller = CarController(DBC[candidate], cp) + assert controller.coop_enabled and controller.speed_sync is not None + cc = car.CarControl.new_message(latActive=True) + for tick in range(10): + cs.out.steeringTorque, cs.out.steeringDisengage = 1., False + _, sends = controller.update(cc.as_reader(), cs, 1_000_000_000 + tick * 10_000_000) + assert not [message for message in sends if message[0] == 0x3C2], 'no scroll request without the comma set speed context' + assert controller.steering_limit_info.get('valid', False) + cs.out.steeringTorque, cs.out.steeringDisengage = 5.1, True + controller.update(cc.as_reader(), cs, 1_100_000_000) + assert not controller.steering_limit_info.get('valid', False) + assert cp.safetyConfigs[0].safetyParam == 4353 diff --git a/opendbc_repo/opendbc/car/tesla/tests/test_pedal_and_dashboard_v7.py b/opendbc_repo/opendbc/car/tesla/tests/test_pedal_and_dashboard_v7.py new file mode 100644 index 0000000000..be5c903e63 --- /dev/null +++ b/opendbc_repo/opendbc/car/tesla/tests/test_pedal_and_dashboard_v7.py @@ -0,0 +1,138 @@ +"""The Tesla longitudinal command and the dashboard speed limit: the real formatter, CAN parser and car state; no +vehicle output. The command is the stock one for every Tesla, pedal or not: nothing in it follows the set-speed work.""" +import inspect +from types import SimpleNamespace + +import pytest +from opendbc.can import CANPacker +from opendbc.car import gen_empty_fingerprint +from opendbc.car.structs import car +from opendbc.car.tesla.interface import CarInterface +from opendbc.car.tesla.carcontroller import CarController +from opendbc.car.tesla.carstate import CarState +from opendbc.car.tesla.speed_sync import prepare +from opendbc.car.tesla.teslacan import TeslaCAN +from opendbc.car.tesla.values import CAR, CANBUS, DBC, CarControllerParams +from opendbc.car.dashboard_speed_limit import Status +from openpilot.starpilot.speed_limits.runtime import dashboard_observation +from openpilot.starpilot.speed_limits.acceptance import ObservationKind + +MODERN = (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y) + + +class Capture: + """Stands in for the CAN packer: returns the values the formatter chose.""" + def make_can_msg(self, name, bus, values): + return name, bus, dict(values) + + +def stock_command(acc_state, accel, counter, v_ego): + """The longitudinal command as the stock formatter builds it.""" + return {'DAS_setSpeed': min(max(v_ego + accel, 0) * 3.6, 400), 'DAS_accState': acc_state, 'DAS_aebEvent': 0, + 'DAS_jerkMin': -4.9, 'DAS_jerkMax': 4.9, 'DAS_accelMin': accel, 'DAS_accelMax': max(accel, 0), + 'DAS_controlCounter': counter} + + +def test_the_formatter_takes_the_stock_arguments_and_keeps_no_state(): + parameters = list(inspect.signature(TeslaCAN.create_longitudinal_command).parameters.values()) + assert [(p.name, p.kind, p.default) for p in parameters] == [ + (name, inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.empty) + for name in ('self', 'acc_state', 'accel', 'counter', 'v_ego', 'active')] + assert sorted(vars(TeslaCAN(None, Capture()))) == ['CP', 'packer'] + assert (CarControllerParams.JERK_LIMIT_MIN, CarControllerParams.JERK_LIMIT_MAX) == (-4.9, 4.9) + + +@pytest.mark.parametrize('acc_state', [4, 13]) +@pytest.mark.parametrize('accel', [-3.48, -.1, 0., .8, 2.]) +@pytest.mark.parametrize('v_ego', [0., 1.5, 20., 45., 120.]) +@pytest.mark.parametrize('active', [False, True]) +def test_the_command_is_the_stock_one(acc_state, accel, v_ego, active): + codec = TeslaCAN(None, Capture()) + for counter in range(16): + name, bus, values = codec.create_longitudinal_command(acc_state, accel, counter % 8, v_ego, active) + assert (name, bus) == ('DAS_control', CANBUS.party) + assert values == pytest.approx(stock_command(acc_state, accel, counter % 8, v_ego)), 'the same on every call' + assert set(values) == set(stock_command(acc_state, accel, 0, v_ego)) + + +def controller(candidate, *, selected, long=True): + fingerprint = gen_empty_fingerprint() + fingerprint[CANBUS.autopilot_party][0x489] = 8 + fingerprint[CANBUS.vehicle][0x3DF] = 8 + cp = prepare(CarInterface.get_params(candidate, fingerprint, [], long, False, False), selected) + cs = CarState(cp) + cs.hands_on_level = 0 + cs.das_control = {'DAS_controlCounter': 3} + cs.out = car.CarState.new_message(vEgo=20., vEgoRaw=20., canValid=True) + unit = CarController(DBC[candidate], cp) + unit.tesla_can = TeslaCAN(cp, Capture()) + return unit, cs + + +def commands(sends): + return [message[2] for message in sends if message[0] == 'DAS_control'] + + +@pytest.mark.parametrize('candidate', MODERN) +@pytest.mark.parametrize('selected', [False, True]) +def test_the_real_controller_sends_the_stock_command_through_a_pedal_press_and_release(candidate, selected): + unit, cs = controller(candidate, selected=selected) + seen = [] + for frame in range(400): + cs.out.gasPressed = 100 <= frame < 180 + cc = car.CarControl.new_message(enabled=True, longActive=not cs.out.gasPressed, actuators={'accel': .8}) + _, sends = unit.update(cc.as_reader(), cs, 1_000_000_000 + frame * 10_000_000) + for values in commands(sends): + assert values == pytest.approx(stock_command(4, .8, (frame // 4) % 8, 20.)), frame + seen.append(frame) + assert seen == list(range(0, 400, 4)), 'every fourth frame, pedal or not' + + +@pytest.mark.parametrize('candidate', MODERN) +def test_the_real_controller_cancels_with_the_stock_command_without_longitudinal_control(candidate): + unit, cs = controller(candidate, selected=False, long=False) + cc = car.CarControl.new_message(enabled=False, cruiseControl={'cancel': True}) + _, sends = unit.update(cc.as_reader(), cs, 1_000_000_000) + assert commands(sends) == [pytest.approx(stock_command(13, 0, 4, 20.))], 'from the first frame, with the full jerk limits' + _, sends = unit.update(car.CarControl.new_message().as_reader(), cs, 1_010_000_000) + assert commands(sends) == [] + + +@pytest.mark.parametrize('candidate', MODERN) +def test_the_car_state_and_controller_carry_nothing_for_a_pedal_hand_over(candidate): + unit, cs = controller(candidate, selected=True) + for holder in (unit, cs, unit.tesla_can): + assert not [name for name in vars(holder) if 'handover' in name or 'gas_release' in name] + with pytest.raises(ImportError): + __import__('opendbc.car.tesla.pedal_handover') + + +@pytest.mark.parametrize('candidate', [CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y]) +@pytest.mark.parametrize('units,limit,expected', [(0, 30, 13.4112), (1, 50, 50 / 3.6), (0, 155, 0), (0, 0, 0)]) +def test_actual_carstate_publishes_fused_limit(candidate, units, limit, expected): + cp = CarInterface.get_non_essential_params(candidate) + state = CarState(cp) + parsers = state.get_can_parsers(cp) + state.update(parsers) # Register the production parser subscriptions. + packers = {bus: CANPacker(parser.dbc.name) for bus, parser in parsers.items()} + stamp = 0 + for i in range(30): + stamp = 1_000_000_000 + i * 100_000_000 + for bus, parser in parsers.items(): + messages = [] + for address in sorted(parser.addresses): + msg = parser.dbc.addr_to_msg[address].name + values = {'DI_speedUnits': units} if msg == 'DI_state' else {'DAS_fusedSpeedLimit': limit} if msg == 'DAS_status' else {} + messages.append(packers[bus].make_can_msg(msg, parser.bus, values)) + parser.update([stamp, messages]) + state.update(parsers) + obs = state.dashboard_limit.observation + assert obs.status == (Status.VALID if expected else Status.ABSENT if limit == 155 else Status.UNKNOWN) + assert obs.speed_mps == pytest.approx(expected) + evidence = SimpleNamespace(status=obs.status.value, speedMps=obs.speed_mps, observedMonoTime=obs.observed_ns, + validUntilMonoTime=obs.valid_until_ns, episode=obs.episode, producerSessionId='real-parser') + result = dashboard_observation(evidence, car_fingerprint=str(candidate), session_id='drive', now_ns=stamp) + assert result.kind == (ObservationKind.VALID if expected else ObservationKind.ABSENT if limit == 155 else ObservationKind.UNKNOWN) + if expected: + stale = dashboard_observation(evidence, car_fingerprint=str(candidate), session_id='drive', now_ns=obs.valid_until_ns + 1) + assert stale.kind is ObservationKind.STALE 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 new file mode 100644 index 0000000000..8c8873a9e6 --- /dev/null +++ b/opendbc_repo/opendbc/car/tesla/tests/test_speed_sync_handover.py @@ -0,0 +1,311 @@ +"""Speed sync requests around the accelerator pedal, lost feedback and unanswered requests. Pure protocol: no device.""" +import pytest +from opendbc.car.tesla.speed_sync import (ENGAGE_DELAY_NS, FAST_TICKS, FRESH_NS, HANDOVER_NS, MANUAL_COMPLETION_NS, MAX_RETRIES, + TEMPLATE_SEND_NS, SpeedSynchronizer, neutral_wheel, plan_step, scroll_request) + +NEUTRAL = bytes.fromhex('2955000000000040') + + +def clicks(msg): + """The signed scroll count of a request.""" + ticks = msg[1][3] & 63 + return ticks - 64 if ticks >= 32 else ticks + + +class Rig: + def __init__(self, *, engaged=True): + self.sync = SpeedSynchronizer() + self.now = 1_000_000_000 + self.counter = 0 + self.speed, self.target, self.units = 45, 50, 1 + self.sent = [] + self.echo = True # the panda transmits each request and echoes it on bus 129 + self._echo = None + if engaged: + # Engaged without longitudinal authority for longer than the panda needs to hear about engagement. + for _ in range(ENGAGE_DELAY_NS // 10_000_000 + 1): + assert self.tick(long=False) is None + + def tick(self, dt=10_000_000, *, long=True, gas=False, safe=True, enabled=True, + feedback=True, wheel=NEUTRAL, wheel_bus=1): + self.now += dt + frames = [] + if self._echo is not None: + frames.append((0x3c2, self._echo, 129)) + self._echo = None + if feedback: + self.counter = (self.counter + 1) % 16 + bits = (self.counter << 8) | (2 << 12) | (round(self.speed * 2) << 15) | (self.units << 24) + di = bytearray(bits.to_bytes(8, 'little')) + di[0] = (0x88 + sum(di[1:])) & 255 + frames.append((0x286, bytes(di), 0)) + if wheel is not None: + frames.append((0x3c2, wheel, wheel_bus)) + self.sync.observe([(self.now, frames)]) + msg = self.sync.update(self.now, target_kph=self.target, enabled=enabled, + safe=safe, longitudinal_active=long, gas_pressed=gas) + if msg: + self.sent.append((self.now, msg)) + if self.echo: + self._echo = msg[1] + return msg + + +@pytest.mark.parametrize('before', [False, True]) +def test_pending_response_on_either_side_of_release(before): + # A request sent under the pedal is answered before or after the release; nothing new is sent in the hand-over + # window, and requests carry on once longitudinal control is back. + r = Rig() + assert r.tick(long=False, gas=True) + if before: + r.speed += 1 + assert r.tick(long=False) is None + assert r.sync.blocked is None + r.speed = 46 + for _ in range(15): + msg = r.tick() + if msg: + break + assert r.sync.blocked is None + assert msg is not None and len(r.sent) == 2 + + +def test_no_initial_authority_and_held_pedal_engage(): + r = Rig() + for _ in range(20): + assert r.tick(long=False) is None + assert not r.sent and r.sync.handover_until == 0 + assert r.tick(long=False, gas=True) is not None + + +def test_no_new_command_during_handover_even_after_response(): + r = Rig() + assert r.tick(long=False, gas=True) + r.speed += 1 + for _ in range(8): + assert r.tick(long=False) is None + assert r.sync.pending is None and len(r.sent) == 1 + assert r.sync.status == 'waiting_for_handover' + + +def test_grace_expires_once_not_renewed_by_false_samples(): + r = Rig() + r.target = r.speed + r.tick(long=False, gas=True) + r.target = 50 + r.tick(long=False) + deadline = r.sync.handover_until + assert deadline == r.now + HANDOVER_NS + for _ in range(9): + assert r.tick(long=False) is None + assert r.sync.handover_until == deadline and r.sync.status == 'waiting_for_handover' + assert r.tick(long=False) is None + assert r.now == deadline and r.sync.handover_until == 0 and r.sync.status == 'inhibited' + for _ in range(20): + assert r.tick(long=False) is None, 'no authority, no request' + assert r.sync.blocked is None and not r.sent + + +def test_release_with_a_request_open_sends_nothing_until_authority_returns(): + r = Rig() + assert r.tick(long=False, gas=True) + for _ in range(20): + assert r.tick(long=False) is None + r.speed += 1 # the Tesla answers after the release + for _ in range(20): + assert r.tick(long=False) is None + assert r.sync.status == 'inhibited' and len(r.sent) == 1 + assert any(r.tick() for _ in range(5)), 'carries on with longitudinal control' + + +def test_hard_failure_and_disengagement_clear_edge_history(): + r = Rig() + r.target = r.speed + r.tick(gas=True) + r.tick(safe=False) + r.target = 50 + assert r.tick(long=False) is None and r.sync.handover_until == 0 + r.tick(gas=True, enabled=False) + assert r.tick(long=False) is None and r.sync.handover_until == 0 + + +def test_feedback_loss_pauses_until_fresh_feedback(): + r = Rig() + r.target = r.speed + for _ in range(30): + assert r.tick(feedback=False) is None + r.target = 50 + assert r.tick(feedback=False) is None + assert r.sync.status == 'waiting_for_native_speed' and r.sync.blocked is None + assert r.tick() is not None, 'carries on once the Tesla speed is fresh again' + + +def test_units_change_inflight_is_not_handover(): + r = Rig() + r.tick(gas=True) + r.units = 0 + assert r.tick(long=False) is None + assert r.sync.blocked == 'units_changed_during_request' + + +def test_manual_input_during_a_request_wins(): + # The driver's own scroll is recorded and given time to land; the open request is not repeated. + r = Rig() + assert r.tick(gas=True) + assert r.tick(long=False, wheel=scroll_request(NEUTRAL, -1)[1]) is None + assert r.sync.blocked is None + assert any(h['event'] == 'input_during_request' for h in r.sync.history) + r.speed -= 1 + for _ in range(10): + assert r.tick() is None + assert r.sync.status == 'waiting_for_manual_processing', "waits for the comma to act on the driver's scroll" + assert len(r.sent) == 1 + for _ in range(MANUAL_COMPLETION_NS // 10_000_000): + r.tick() + assert 'manual_action_unconfirmed' in r.sync.noticed and r.sync.blocked is None + assert len(r.sent) > 1, "after the wait the Tesla is scrolled back to the comma's speed" + + +def test_no_response_is_retried_a_few_times_then_waits_for_the_tesla(): + r = Rig() + r.tick() + for _ in range(100): + r.tick(dt=100_000_000) + assert r.sync.blocked is None and 'no_native_response' in r.sync.noticed + assert r.sync.status == 'waiting_for_native_change' + sent = len(r.sent) + assert sent == MAX_RETRIES + 1, 'the first request and its retries' + for _ in range(20): + assert r.tick() is None + r.speed += 1 # the Tesla moves: requests carry on + assert any(r.tick() for _ in range(20)) + + +def test_request_needs_a_new_physical_neutral_frame(): + r = Rig() + r.tick() + r.speed += 1 + assert r.tick(wheel=None) is None, 'no neutral frame newer than the one the last request copied' + assert r.tick(wheel=NEUTRAL, wheel_bus=129) is None, "a bus-129 echo is not the driver's wheel" + assert r.sync.status == 'waiting_for_neutral_wheel' + assert r.tick() is not None + + +def test_request_not_echoed_by_the_panda_is_not_transmitted(): + r = Rig() + r.echo = False + assert r.tick() + for _ in range(9): + assert r.tick() is None + r.tick() + assert any(h['event'] == 'not_transmitted' and h['reason'] == 'no_bus_return' for h in r.sync.history) + assert r.sync.pending is None and r.sync.blocked is None + + +def test_template_age_is_tighter_than_receive_freshness(): + r = Rig() + r.target = r.speed + r.tick() + r.target = 50 + assert r.tick(dt=TEMPLATE_SEND_NS + 1, wheel=None) is None + assert r.sync.status == 'waiting_for_neutral_wheel' + assert r.tick() is not None + + +@pytest.mark.parametrize('direction', [-1, 1]) +def test_convergence_one_request_per_tesla_change(direction): + r = Rig() + r.target = r.speed + 10 * direction + waiting = None + for _ in range(400): + msg = r.tick() + if msg: + assert waiting is None, 'never two requests open at once' + waiting = r.speed + elif waiting is not None and r.sync.pending is not None and r.now - r.sync.pending.sent_ns >= 30_000_000: + r.speed += direction # the Tesla answers about 30 ms later + waiting = None + if r.sync.status == 'matched': + break + assert r.speed == r.target and len(r.sent) == 10 + assert len(r.sync.history) <= 32 + + +def test_same_rounded_target_never_sends(): + r = Rig() + r.speed = 45.5 + r.target = 46 + for _ in range(10): + assert r.tick() is None + assert r.sync.status == 'matched' + + +def test_controller_clock_gap_pauses_one_frame(): + r = Rig() + r.tick(gas=True) + r.speed += 1 + assert r.tick(dt=FRESH_NS + 1, long=False) is None + assert r.sync.status == 'controller_clock_gap' and r.sync.blocked is None and r.sync.handover_until == 0 + + +def test_disengaging_clears_the_engagement(): + r = Rig() + assert r.tick() + assert r.tick(enabled=False) is None + assert r.sync.status == 'inactive' and r.sync.pending is None and r.sync.target is None and not r.sync.active + assert not r.sync.history and not r.sync.noticed + + +@pytest.mark.parametrize('native,target,fast,expected', [ + (50, 51, True, (1, 51)), (50, 49, True, (-1, 49)), + (50, 55, True, (FAST_TICKS, 55)), (50, 45, True, (-FAST_TICKS, 45)), + (52, 60, True, (FAST_TICKS, 55)), (52, 44, True, (-FAST_TICKS, 50)), + (52, 54, True, (1, 53)), (53, 51, True, (-1, 52)), # the next multiple of five would pass the target + (54, 60, True, (1, 55)), (56, 50, True, (-1, 55)), # one away from the multiple: a click is as quick + (50, 60, False, (1, 51)), (50, 40, False, (-1, 49)), # fast steps paused, or km/h +]) +def test_next_step_toward_the_target(native, target, fast, expected): + assert plan_step(native, target, fast) == expected + + +@pytest.mark.parametrize('ticks', [-FAST_TICKS, -1, 1, FAST_TICKS]) +def test_a_request_is_the_neutral_frame_with_only_the_scroll_count_set(ticks): + address, data, bus = scroll_request(NEUTRAL, ticks) + assert (address, bus) == (0x3C2, 1) and len(data) == 8 + assert data[3] == (NEUTRAL[3] & 0xC0) | (ticks & 0x3F) + assert data[:3] == NEUTRAL[:3] and data[4:] == NEUTRAL[4:] + assert not neutral_wheel(data), 'a scroll is not a template for the next request' + + +@pytest.mark.parametrize('ticks', [0, 2, 3, 4, 6, -2, -6, 31, -32]) +def test_only_one_click_or_one_fast_flick_is_ever_requested(ticks): + assert scroll_request(NEUTRAL, ticks) is None + + +def test_no_request_is_built_from_a_frame_that_is_not_neutral(): + assert neutral_wheel(NEUTRAL) + pressed = bytearray(NEUTRAL) + pressed[1] = (pressed[1] & ~0x03) | 0x02 # right wheel tilted left + for frame in (bytes(pressed), scroll_request(NEUTRAL, 1)[1], NEUTRAL[:7], bytes(8)): + assert not neutral_wheel(frame) + assert scroll_request(frame, 1) is None + + +@pytest.mark.parametrize('direction', [-1, 1]) +def test_mph_convergence_uses_fast_steps_and_lands_on_the_target(direction): + r = Rig(engaged=False) + r.units, r.speed = 0, 52 + r.target = (52 + 14 * direction) * 1.609344 + for _ in range(ENGAGE_DELAY_NS // 10_000_000 + 1): + assert r.tick(long=False) is None + for _ in range(2000): + r.tick() + p = r.sync.pending + if p is not None and p.returned and r.now - p.sent_ns >= 30_000_000: + r.speed = p.expected # the Tesla answers about 30 ms later + if r.sync.status == 'matched': + break + assert r.speed == 52 + 14 * direction and r.sync.blocked is None + sizes = [abs(clicks(msg)) for _, msg in r.sent] + assert FAST_TICKS in sizes and 1 in sizes + assert len(r.sent) <= 5, 'far fewer requests than fourteen single clicks' diff --git a/opendbc_repo/opendbc/car/tesla/tests/test_speed_sync_manual.py b/opendbc_repo/opendbc/car/tesla/tests/test_speed_sync_manual.py new file mode 100644 index 0000000000..7235edc594 --- /dev/null +++ b/opendbc_repo/opendbc/car/tesla/tests/test_speed_sync_manual.py @@ -0,0 +1,341 @@ +"""The driver's own scroll and speed sync. Wheel input that cannot be read as one clean scroll pauses sync; it never +stops it until disengaging. + +A right-wheel nudge that springs back with one scroll click is taken by the Tesla and not by the comma, so sync +scrolls the Tesla back. A clean scroll waits for the comma: card's receipt for the step it applied releases it at +once, and without one it is dropped after its window and corrected the same way. +""" +from dataclasses import replace + +import pytest + +from opendbc.car.tesla.speed_sync import MANUAL_COMPLETION_NS, MANUAL_SETTLE_NS, ManualReceipt, SpeedSynchronizer, SyncAuthority + +MPH = 1.609344 +DOCUMENT, VEHICLE, SESSION, DRIVE = 'd' * 64, 'e' * 64, '0123456789abcdef' * 2, 100_000_000 + +NEUTRAL = bytes.fromhex('2955000000000040') +TICK = 50_000_000 + + +def wheel(right_left=1, right_scroll=0): + bits = int.from_bytes(NEUTRAL, 'little') + bits = (bits & ~(3 << 8)) | (right_left << 8) + bits = (bits & ~(63 << 24)) | ((right_scroll & 63) << 24) + return bits.to_bytes(8, 'little') + + +class Rig: + """The Tesla in mph at 77, the comma's set speed 77; nothing answers requests unless a test moves `speed`.""" + def __init__(self): + self.sync = SpeedSynchronizer() + self.now = 1_000_000_000 + self.counter = 0 + self.speed = self.target = 77 + self.sent = [] + + def tick(self, data=NEUTRAL): + self.now += TICK + self.counter = (self.counter + 1) % 16 + bits = (self.counter << 8) | (2 << 12) | (round(self.speed * 2) << 15) + di = bytearray(bits.to_bytes(8, 'little')) + di[0] = (0x88 + sum(di[1:])) & 255 + self.sync.observe([(self.now, [(0x286, bytes(di), 0), (0x3c2, data, 1)])]) + msg = self.sync.update(self.now, target_kph=self.target * 1.609344, enabled=True, safe=True, longitudinal_active=True) + if msg: + self.sent.append((self.now, msg)) + return msg + + def settle(self, seconds): + return [m for m in (self.tick() for _ in range(round(seconds * 1e9 / TICK))) if m] + + +def clicks(msg): + ticks = msg[1][3] & 63 + return ticks - 64 if ticks >= 32 else ticks + + +def test_nudge_release_click_is_corrected_not_a_stop(): + r = Rig() + assert not r.settle(1) + r.tick(wheel(right_left=2)) + r.tick(wheel(right_left=2)) + r.tick(wheel(right_scroll=1)) # springs back with one click + r.speed = 78 # the Tesla took it; the comma stays at 77 + sent = r.settle(1.5) + assert r.sync.blocked is None + assert 'ambiguous_manual_input' not in r.sync.noticed + assert sent and clicks(sent[0]) == -1, 'sync puts the Tesla back on the comma speed' + assert any(h['event'] == 'nudge_release_click' for h in r.sync.history) + + +def test_unclear_scroll_pauses_and_sync_carries_on(): + r = Rig() + r.settle(1) + r.tick(wheel(right_left=2)) + r.tick(wheel(right_left=2, right_scroll=1)) # a scroll while the wheel is still tilted + assert r.sync.blocked is None and 'ambiguous_manual_input' in r.sync.noticed + r.tick() + r.speed = 78 + sent = r.settle(1.5) + assert r.sync.blocked is None and sent and clicks(sent[0]) == -1 + + +def test_a_driver_scroll_waits_its_window_and_is_then_dropped_with_a_notice(): + r = Rig() + r.settle(1) + r.tick(wheel(right_scroll=1)) # a clean scroll; the comma's own speed does not follow it here + r.tick() + r.speed = 78 + assert not r.settle(MANUAL_COMPLETION_NS / 1e9 - 0.2), "nothing is sent while the comma may still act on the driver's scroll" + assert r.sync.status == 'waiting_for_manual_processing' + sent = r.settle(1) + assert r.sync.blocked is None and 'manual_action_unconfirmed' in r.sync.noticed + assert any(h['event'] == 'manual_action_unconfirmed' and h['dropped'] == 1 for h in r.sync.history) + assert not r.sync.manual_queue + assert sent and clicks(sent[0]) == -1, "then the Tesla is put back on the comma's speed" + + +def test_a_driver_scroll_the_comma_followed_needs_no_correction(): + r = Rig() + r.settle(1) + r.tick(wheel(right_scroll=1)) + r.tick() + r.speed = r.target = 78 # the Tesla and the comma both took the scroll + assert not r.settle(MANUAL_COMPLETION_NS / 1e9 + 1) + assert r.sync.status == 'matched' and r.sync.blocked is None + assert 'manual_action_unconfirmed' in r.sync.noticed, 'the wait always ends with the same notice' + + +def test_a_fast_driver_scroll_is_one_gesture_and_one_notice_per_engagement(): + r = Rig() + r.settle(1) + for _ in range(2): + r.tick(wheel(right_scroll=3)) + r.tick(wheel(right_scroll=2)) # the same flick, still turning + r.tick() + assert len(r.sync.manual_queue) == 1 and r.sync.manual_queue[0][2:] == ('right_wheel_up', True) + r.settle(MANUAL_COMPLETION_NS / 1e9 + 0.2) + assert not r.sync.manual_queue + assert len([h for h in r.sync.history if h['event'] == 'manual_action_unconfirmed']) == 2 + assert [n['kind'] for n in r.sync.notices].count('manual_action_unconfirmed') == 1 + + +def test_nothing_is_sent_right_after_a_driver_scroll_that_was_never_queued(): + r = Rig() + r.settle(1) + r.tick(wheel(right_left=2, right_scroll=1)) # unclear input: paused, not queued + r.tick() + r.speed = 78 + assert not r.settle(MANUAL_SETTLE_NS / 1e9 - 0.15), "the Tesla gets time to apply the driver's own scroll first" + assert r.sync.status == 'waiting_for_driver_scroll' + assert r.settle(0.5) + + +def test_clock_faults_still_stop(): + r = Rig() + r.settle(0.5) + r.sync.observe([(r.now - TICK, [(0x3c2, NEUTRAL, 1)])]) + assert r.sync.blocked == 'wheel_clock_reversal' + + +# Card's receipts for the driver's own scrolls. + +def scrolled(r, ticks=1): + """The driver scrolls once; returns the engine's record of it: (stamp, frame index, name, fast).""" + r.settle(1) + r.tick(wheel(right_scroll=ticks)) + r.tick() + entry, = r.sync.manual_queue + return entry + + +def receipt_for(entry, **changes): + """What card records when it applies the comma step for that scroll, in the frame the scroll was seen.""" + stamp, index, name, fast = entry + values = dict(boot_ns=stamp, frame_index=index, name=name, fast=fast, worker_session=SESSION, sequence=1, + document_hash=DOCUMENT, vehicle_hash=VEHICLE, drive_start_ns=DRIVE, processed_boot_ns=stamp, + target_kph=78 * MPH) + values.update(changes) + return ManualReceipt(**values) + + +def authority(r, *receipts, **changes): + values = dict(observed_boot_ns=r.now, target_kph=r.target * MPH, is_metric=False, configuration_id='a' * 64, software_owned=True, + document_hash=DOCUMENT, vehicle_hash=VEHICLE, drive_start_ns=DRIVE, manual_receipts=tuple(receipts)) + values.update(changes) + return SyncAuthority(**values) + + +def test_a_receipt_releases_the_drivers_scroll_at_once(): + r = Rig() + entry = scrolled(r) + assert entry[1:] == (1, 'right_wheel_up', False) and r.sync.status == 'waiting_for_manual_processing' + receipt = receipt_for(entry) + r.speed = r.target = 78 # the Tesla and the comma both took it + r.sync.target = ('stale',) + r.sync.accept_manual_receipts(authority(r, receipt), r.now) + assert not r.sync.manual_queue and r.sync.target is None, 'the comma target is read again' + assert r.sync.take_manual_receipt_acks() == (receipt,) and r.sync.take_manual_receipt_acks() == () + r.tick() + assert r.sync.status == 'matched' and r.sync.blocked is None + assert not r.settle(MANUAL_COMPLETION_NS / 1e9 + .5) + assert 'manual_action_unconfirmed' not in r.sync.noticed + + +def test_with_a_receipt_a_difference_is_corrected_without_waiting_out_the_window(): + r = Rig() + receipt = receipt_for(scrolled(r)) + r.speed, r.target = 79, 78 # the Tesla moved further than the comma did + r.sync.accept_manual_receipts(authority(r, receipt), r.now) + sent = r.settle(MANUAL_SETTLE_NS / 1e9 + .2) + assert sent and clicks(sent[0]) == -1, "corrected as soon as the Tesla has applied the driver's own scroll" + assert r.sent[0][0] - receipt.boot_ns < MANUAL_COMPLETION_NS // 2 + waiting = Rig() + scrolled(waiting) + waiting.speed, waiting.target = 79, 78 + assert not waiting.settle(MANUAL_SETTLE_NS / 1e9 + .2), 'without a receipt the scroll still waits' + + +def test_a_receipt_may_arrive_before_the_scroll_is_seen_on_the_bus(): + r = Rig() + r.settle(1) + r.tick(wheel(right_scroll=3)) + early = receipt_for((r.now + TICK, 1, 'right_wheel_up', True), processed_boot_ns=r.now + TICK) + r.now += TICK # card applied the step in the frame the release arrives in; speed sync sees that frame next + r.sync.accept_manual_receipts(authority(r, early), r.now) + assert r.sync.manual_receipts == {(early.boot_ns, 1): early} and r.sync.take_manual_receipt_acks() == (early,) + r.now -= TICK + r.tick() + assert r.sync.manual_queue == [(early.boot_ns, 1, 'right_wheel_up', True)] + r.sync.accept_manual_receipts(authority(r), r.now) + assert not r.sync.manual_queue and not r.sync.manual_receipts and r.sync.blocked is None + + +@pytest.mark.parametrize('changes', [dict(name='right_wheel_down'), dict(fast=True)]) +def test_a_receipt_for_a_different_scroll_at_the_same_frame_stops_sync(changes): + r = Rig() + receipt = receipt_for(scrolled(r), **changes) + r.sync.accept_manual_receipts(authority(r, receipt), r.now) + assert r.sync.blocked == 'manual_receipt_mismatch' + assert not r.settle(3), 'stopped until disengaging' + + +@pytest.mark.parametrize('changes', [ + dict(document_hash='f' * 64), dict(vehicle_hash='f' * 64), dict(drive_start_ns=DRIVE + 1), dict(drive_start_ns=0), + dict(worker_session='x' * 32), dict(worker_session='0' * 31), dict(sequence=0), dict(sequence=1.0), + dict(name='right_wheel_left'), dict(name='left_wheel_up'), dict(fast=1), + dict(frame_index=-1), dict(frame_index=4096), dict(frame_index=1.0), + dict(target_kph=0), dict(target_kph=255), dict(target_kph=float('nan')), dict(target_kph='125'), + dict(processed_boot_ns=0), dict(boot_ns=0), dict(boot_ns=1.5), +]) +def test_a_receipt_that_fails_any_check_is_ignored_and_the_scroll_waits_out_its_window(changes): + r = Rig() + entry = scrolled(r) + receipt = receipt_for(entry, **changes) + r.sync.accept_manual_receipts(authority(r, receipt), r.now) + assert r.sync.manual_queue == [entry] and r.sync.blocked is None + assert r.sync.take_manual_receipt_acks() == (), 'never taken into custody' + r.settle(MANUAL_COMPLETION_NS / 1e9 + .2) + assert 'manual_action_unconfirmed' in r.sync.noticed and not r.sync.manual_queue + + +def test_a_receipt_processed_in_the_future_or_before_its_scroll_is_ignored(): + r = Rig() + entry = scrolled(r) + for changes in (dict(processed_boot_ns=r.now + 1), dict(processed_boot_ns=entry[0] - 1)): + r.sync.accept_manual_receipts(authority(r, receipt_for(entry, **changes)), r.now) + assert r.sync.manual_queue == [entry] and r.sync.take_manual_receipt_acks() == () + + +@pytest.mark.parametrize('changes', [dict(document_hash=''), dict(vehicle_hash=''), dict(document_hash='d' * 63)]) +def test_receipts_need_an_admission_that_names_the_assignments_and_the_car(changes): + r = Rig() + entry = scrolled(r) + receipt = receipt_for(entry, **changes) + r.sync.accept_manual_receipts(authority(r, receipt, **changes), r.now) + assert r.sync.manual_queue == [entry] and r.sync.take_manual_receipt_acks() == () + + +def test_an_expired_receipt_is_disposed_of_and_completes_nothing(): + r = Rig() + entry = scrolled(r) + receipt = receipt_for(entry) + r.now = entry[0] + MANUAL_COMPLETION_NS + 1 + r.sync.accept_manual_receipts(authority(r, receipt), r.now) + assert r.sync.manual_queue == [entry] and not r.sync.manual_receipts + assert r.sync.take_manual_receipt_acks() == (receipt,), 'handed back so card drops it' + r.now = entry[0] + MANUAL_COMPLETION_NS + r.sync.accept_manual_receipts(authority(r, receipt), r.now) + assert not r.sync.manual_queue, 'exactly at the end of the window still counts' + + +def test_a_receipt_for_a_scroll_already_dealt_with_is_handed_back(): + r = Rig() + entry = scrolled(r) + receipt = receipt_for(entry) + r.sync.accept_manual_receipts(authority(r, receipt), r.now) + r.sync.take_manual_receipt_acks() + r.sync.accept_manual_receipts(authority(r, receipt), r.now) # card had not yet seen the acknowledgment + assert r.sync.take_manual_receipt_acks() == (receipt,) and not r.sync.manual_receipts and r.sync.blocked is None + + +def test_a_cached_receipt_expires_with_its_window(): + r = Rig() + r.settle(1) + early = receipt_for((r.now, 1, 'right_wheel_up', False), processed_boot_ns=r.now) + r.sync.accept_manual_receipts(authority(r, early), r.now) + assert r.sync.manual_receipts + r.settle(MANUAL_COMPLETION_NS / 1e9 + .1) + r.sync.accept_manual_receipts(authority(r), r.now) + assert not r.sync.manual_receipts and r.sync.blocked is None + + +def test_more_receipts_than_card_ever_holds_stop_sync(): + r = Rig() + entry = scrolled(r) + many = tuple(receipt_for(entry, sequence=index + 1) for index in range(17)) + r.sync.accept_manual_receipts(authority(r, *many), r.now) + assert r.sync.blocked == 'invalid_manual_receipts' + r = Rig() + scrolled(r) + r.sync.accept_manual_receipts(replace(authority(r), manual_receipts=[]), r.now) + assert r.sync.blocked == 'invalid_manual_receipts', 'only a tuple, as card builds it' + + +def test_sixteen_receipts_are_accepted(): + r = Rig() + r.settle(1) + receipts = tuple(receipt_for((r.now - index, index, 'right_wheel_up', False), processed_boot_ns=r.now, sequence=index + 1) + for index in range(16)) + r.sync.accept_manual_receipts(authority(r, *receipts), r.now) + assert r.sync.blocked is None and len(r.sync.manual_receipts) == 16 + assert r.sync.take_manual_receipt_acks() == receipts + + +def test_two_different_receipts_for_one_scroll_stop_sync(): + r = Rig() + r.settle(1) + first = receipt_for((r.now, 1, 'right_wheel_up', False), processed_boot_ns=r.now) + r.sync.accept_manual_receipts(authority(r, first), r.now) + r.sync.accept_manual_receipts(authority(r, replace(first, sequence=2)), r.now) + assert r.sync.blocked == 'conflicting_manual_receipt' + + +def test_anything_that_is_not_a_receipt_is_skipped(): + r = Rig() + entry = scrolled(r) + receipt = receipt_for(entry) + r.sync.accept_manual_receipts(authority(r, None, 'receipt', (1, 2), receipt), r.now) + assert not r.sync.manual_queue and r.sync.take_manual_receipt_acks() == (receipt,) + + +def test_disengaging_forgets_receipts_and_acknowledgments(): + r = Rig() + r.settle(1) + early = receipt_for((r.now, 1, 'right_wheel_up', False), processed_boot_ns=r.now) + r.sync.accept_manual_receipts(authority(r, early), r.now) + assert r.sync.manual_receipts and r.sync.manual_receipt_acks + r.now += TICK + r.sync.update(r.now, target_kph=77 * MPH, enabled=False, safe=True) + assert not r.sync.manual_receipts and not r.sync.manual_receipt_acks and r.sync.take_manual_receipt_acks() == () diff --git a/opendbc_repo/opendbc/car/tesla/tests/test_speed_sync_selection.py b/opendbc_repo/opendbc/car/tesla/tests/test_speed_sync_selection.py new file mode 100644 index 0000000000..a36a97db93 --- /dev/null +++ b/opendbc_repo/opendbc/car/tesla/tests/test_speed_sync_selection.py @@ -0,0 +1,161 @@ +"""Comma can set speed on Tesla dashboard: which cars can have it, and how the startup choice lands in CarParams.""" +from types import SimpleNamespace + +import pytest + +from opendbc.car import gen_empty_fingerprint, get_safety_config, structs +from opendbc.car.tesla.carcontroller import CarController +from opendbc.car.tesla.interface import CarInterface +from opendbc.car.tesla.speed_sync import MODELS, SYNC_FLAG, SpeedSynchronizer, eligible, prepare, selected +from opendbc.car.tesla.values import CAR, CANBUS, DBC, TeslaFlags, TeslaSafetyFlags + +MODERN = (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y) + + +def tesla(candidate=CAR.TESLA_MODEL_3, *, cable=True, long=True): + fingerprint = gen_empty_fingerprint() + fingerprint[CANBUS.autopilot_party][0x489] = 8 + if cable: + fingerprint[CANBUS.vehicle][0x3DF] = 8 + return CarInterface.get_params(candidate, fingerprint, [], long, False, False) + + +def word(cp): + return int(cp.safetyConfigs[0].safetyParam) + + +def raw(cp): + """The whole CarParams as bytes, from a copy so the builder can be written again.""" + return cp.as_reader().as_builder().to_bytes() + + +def two_configs(cp): + cp.safetyConfigs = [get_safety_config(structs.CarParams.SafetyModel.tesla, 1 | SYNC_FLAG), + get_safety_config(structs.CarParams.SafetyModel.tesla, 1 | SYNC_FLAG)] + + +def no_configs(cp): + cp.safetyConfigs = [] + + +# Each one alone takes the feature away from an otherwise eligible Model 3. +MISSING = { + 'other brand': lambda cp: setattr(cp, 'brand', 'hyundai'), + 'model x': lambda cp: setattr(cp, 'carFingerprint', str(CAR.TESLA_MODEL_X)), + 'model s hw1': lambda cp: setattr(cp, 'carFingerprint', str(CAR.TESLA_MODEL_S_HW1)), + 'model s pre-ap': lambda cp: setattr(cp, 'carFingerprint', str(CAR.TESLA_MODEL_S_PREAP)), + 'unknown fingerprint': lambda cp: setattr(cp, 'carFingerprint', 'MOCK'), + 'stock longitudinal': lambda cp: setattr(cp, 'openpilotLongitudinalControl', False), + 'no car cruise': lambda cp: setattr(cp, 'pcmCruise', False), + 'passive': lambda cp: setattr(cp, 'passive', True), + 'dashcam': lambda cp: setattr(cp, 'dashcamOnly', True), + 'not a car': lambda cp: setattr(cp, 'notCar', True), + 'no cable': lambda cp: setattr(cp, 'flags', int(cp.flags) & ~int(TeslaFlags.HAS_VEHICLE_BUS)), + 'no safety config': no_configs, + 'two safety configs': two_configs, + 'safety word without longitudinal': lambda cp: setattr(cp.safetyConfigs[0], 'safetyParam', word(cp) & ~1), +} + + +def test_the_flag_is_its_own_bit(): + assert SYNC_FLAG == 4096 == int(TeslaSafetyFlags.SCROLL_SPEED_SYNC) + others = [flag for flag in TeslaSafetyFlags if flag is not TeslaSafetyFlags.SCROLL_SPEED_SYNC] + assert not any(SYNC_FLAG & int(flag) for flag in others) + assert not SYNC_FLAG & 2048, 'ordinary Always On Lateral keeps 2048' + assert MODELS == tuple(str(model) for model in MODERN) + + +@pytest.mark.parametrize('candidate', MODERN) +def test_model_3_and_y_with_cable_and_longitudinal_are_eligible_and_start_unselected(candidate): + cp = tesla(candidate) + assert eligible(cp) + assert word(cp) == 1 and not selected(cp), 'the car interface never selects it; startup preferences do' + + +@pytest.mark.parametrize('candidate', MODERN) +@pytest.mark.parametrize('cable,long', [(False, True), (True, False), (False, False)]) +def test_cable_and_longitudinal_are_both_needed(candidate, cable, long): + cp = tesla(candidate, cable=cable, long=long) + before = raw(cp) + assert not eligible(cp) and not selected(cp) + assert prepare(cp, True) is cp and raw(cp) == before + + +@pytest.mark.parametrize('reason', MISSING) +def test_every_condition_is_required(reason): + cp = tesla() + prepare(cp, True) + assert selected(cp) + MISSING[reason](cp) + assert not eligible(cp), reason + assert not selected(cp), 'a set bit alone selects nothing' + + +@pytest.mark.parametrize('reason', MISSING) +@pytest.mark.parametrize('requested', (False, True)) +def test_prepare_never_touches_a_car_that_is_not_eligible(reason, requested): + cp = tesla() + if reason not in ('no safety config', 'two safety configs'): + cp.safetyConfigs[0].safetyParam = word(cp) | SYNC_FLAG # even a stale bit is left for the car's own code + MISSING[reason](cp) + before = raw(cp) + assert prepare(cp, requested) is cp + assert raw(cp) == before + + +@pytest.mark.parametrize('candidate', MODERN) +@pytest.mark.parametrize('base', (1, 257, 513, 769, 1537, 1793, 2049, 2305, 3073, 3329)) +def test_prepare_sets_and_clears_only_its_own_bit(candidate, base): + cp = tesla(candidate) + cp.safetyConfigs[0].safetyParam = base + rest = raw(cp) + for _ in range(2): + assert prepare(cp, True) is cp + assert word(cp) == base | SYNC_FLAG and selected(cp) + for _ in range(2): + assert prepare(cp, False) is cp + assert word(cp) == base and not selected(cp) and eligible(cp) + assert raw(cp) == rest, 'nothing else in CarParams moved' + + +def test_prepare_clears_a_stale_selection(): + cp = tesla() + cp.safetyConfigs[0].safetyParam = 4097 + prepare(cp, False) + assert word(cp) == 1 and not selected(cp) + + +@pytest.mark.parametrize('cp', [None, object(), SimpleNamespace(), SimpleNamespace(brand='tesla'), + SimpleNamespace(brand='tesla', carFingerprint='TESLA_MODEL_3', openpilotLongitudinalControl=True, + pcmCruise=True, passive=False, dashcamOnly=False, notCar=False, flags=None, + safetyConfigs=[])]) +def test_missing_or_malformed_car_parameters_are_not_eligible(cp): + assert eligible(cp) is False and selected(cp) is False + assert prepare(cp, True) is cp + + +def test_a_reader_is_judged_like_its_builder(): + cp = tesla() + assert eligible(cp.as_reader()) and not selected(cp.as_reader()) + prepare(cp, True) + assert selected(cp.as_reader()) + + +@pytest.mark.parametrize('candidate', MODERN) +def test_the_controller_builds_a_synchronizer_only_when_selected(candidate): + cp = tesla(candidate) + assert CarController(DBC[candidate], cp).speed_sync is None + prepare(cp, True) + assert isinstance(CarController(DBC[candidate], cp).speed_sync, SpeedSynchronizer) + prepare(cp, False) + assert CarController(DBC[candidate], cp).speed_sync is None + + +@pytest.mark.parametrize('candidate', (CAR.TESLA_MODEL_X, CAR.TESLA_MODEL_S_HW1, CAR.TESLA_MODEL_S_PREAP)) +def test_other_teslas_never_get_a_synchronizer(candidate): + cp = tesla(candidate) + before = raw(cp) + assert not eligible(cp) and not selected(cp) + prepare(cp, True) + assert raw(cp) == before + assert CarController(DBC[candidate], cp).speed_sync is None diff --git a/opendbc_repo/opendbc/car/tesla/values.py b/opendbc_repo/opendbc/car/tesla/values.py index 17872ee0c4..cf22c91d27 100644 --- a/opendbc_repo/opendbc/car/tesla/values.py +++ b/opendbc_repo/opendbc/car/tesla/values.py @@ -132,6 +132,7 @@ class CarControllerParams: class TeslaSafetyFlags(IntFlag): LONG_CONTROL = 1 HW1 = 16 + SCROLL_SPEED_SYNC = 4096 # 2048 is the ordinary AOL word COOP_STEERING = 256 AOL_SCREEN_BUTTON = 512 AOL_SCREEN_DISENGAGE_ON_BRAKE = 1024 diff --git a/opendbc_repo/opendbc/safety/modes/tesla.h b/opendbc_repo/opendbc/safety/modes/tesla.h index fb1bc3884d..1e5519f941 100644 --- a/opendbc_repo/opendbc/safety/modes/tesla.h +++ b/opendbc_repo/opendbc/safety/modes/tesla.h @@ -2,6 +2,7 @@ #include "opendbc/safety/declarations.h" #include "opendbc/safety/modes/tesla_screen_aol.h" +#include "opendbc/safety/modes/tesla_speed_sync.h" static bool tesla_longitudinal = false; static bool tesla_coop_steering = false; @@ -167,6 +168,7 @@ static void tesla_rx_hook(const CANPacket_t *msg) { } tesla_screen_rx(msg, tesla_autopark); + tesla_sync_rx(msg); if (msg_matches(msg, 0x155U, 0U)) { vehicle_moving = !GET_BIT(msg, 41U); // ESP_vehicleStandstillSts @@ -195,6 +197,11 @@ static void tesla_rx_hook(const CANPacket_t *msg) { } } +static void tesla_optional_rx(const CANPacket_t *msg) { + tesla_screen_optional_rx(msg); + tesla_sync_optional_rx(msg); +} + static bool tesla_tx_hook(const CANPacket_t *msg) { const AngleSteeringLimits TESLA_STEERING_LIMITS = { .max_angle = 3600, // 360 deg, EPAS faults above this @@ -290,6 +297,11 @@ static bool tesla_tx_hook(const CANPacket_t *msg) { tx = false; } + // Speed sync: the wheel frame is decided by its own gate alone (Autopark included); nothing above has a side effect for it + if (msg->addr == 0x3C2U) { + tx = tesla_sync_tx(msg, tesla_stock_aeb, tesla_autopark, tesla_stock_lkas); + } + return tx; } @@ -326,6 +338,7 @@ static safety_config tesla_init(uint16_t param) { }; static const CanMsg TESLA_M3_Y_LONG_TX_MSGS[] = { + {0x3C2, 1, 8, .check_relay = false}, // speed sync: gated single-wheel-step capability {0x488, 0, 4, .check_relay = true, .disable_static_blocking = true}, // DAS_steeringControl {0x2b9, 0, 8, .check_relay = true, .disable_static_blocking = true}, // DAS_control {0x27D, 0, 3, .check_relay = true, .disable_static_blocking = true}, // APS_eacMonitor @@ -336,7 +349,8 @@ static safety_config tesla_init(uint16_t param) { #ifdef ALLOW_DEBUG tesla_longitudinal = GET_FLAG(param, 1U); #endif - tesla_screen_configure(param); + tesla_screen_configure(tesla_sync_base_param(param)); + tesla_sync_configure(param, tesla_longitudinal); tesla_stock_aeb = false; tesla_stock_lkas = false; tesla_stock_lkas_prev = false; @@ -369,7 +383,7 @@ static safety_config tesla_init(uint16_t param) { const safety_hooks tesla_hooks = { .init = tesla_init, .rx = tesla_rx_hook, - .optional_rx = tesla_screen_optional_rx, + .optional_rx = tesla_optional_rx, .tx = tesla_tx_hook, .fwd = tesla_fwd_hook, .get_counter = tesla_get_counter, diff --git a/opendbc_repo/opendbc/safety/modes/tesla_speed_sync.h b/opendbc_repo/opendbc/safety/modes/tesla_speed_sync.h new file mode 100644 index 0000000000..15267e400c --- /dev/null +++ b/opendbc_repo/opendbc/safety/modes/tesla_speed_sync.h @@ -0,0 +1,215 @@ +#pragma once +// Speed sync: experimental wheel-only capability. No press/tilt/stalk authority. +// Disabled unless the separate debug-only flag AND longitudinal mode are set. +static bool tesla_sync_enabled = false; +static bool tesla_sync_seen = false; +static bool tesla_sync_di_seen = false; +static bool tesla_sync_di_valid = false; +static bool tesla_sync_neutral = false; +static bool tesla_sync_blocked = false; +static bool tesla_sync_pending = false; +static bool tesla_sync_drive = false; +static bool tesla_sync_occupant = false; +static bool tesla_sync_native_active = false; +static uint8_t tesla_sync_template[8]; +static uint32_t tesla_sync_wheel_ts = 0U; +static uint32_t tesla_sync_di_ts = 0U; +static uint32_t tesla_sync_last_template = 0U; +// A request the Tesla never answered is released after this long, so the host +// can try again instead of waiting for the driver to change the speed. +#define TESLA_SYNC_PENDING_TIMEOUT_US 800000U +static unsigned int tesla_sync_steps = 0U; +// Rate limit instead of a per-session cap: a burst of up to 30 requests, then +// one more every second. Normal syncing never runs out; a runaway host is held to +// one request per second instead of being stopped for the rest of the drive. +#define TESLA_SYNC_TOKENS_MAX 30U +#define TESLA_SYNC_TOKEN_REFILL_US 1000000U +static unsigned int tesla_sync_tokens = TESLA_SYNC_TOKENS_MAX; +static uint32_t tesla_sync_refill_ts = 0U; +static int tesla_sync_speed = 0; +static unsigned int tesla_sync_units = 0U; +static unsigned int tesla_sync_sent_units = 0U; + +static bool tesla_sync_wheel_neutral(const uint8_t *d) { + return ((d[0] & 3U) == 1U) && + (((d[0] >> 3U) & 3U) == 1U) && (((d[0] >> 5U) & 3U) == 1U) && + ((d[1] & 3U) == 1U) && (((d[1] >> 2U) & 3U) == 1U) && + (((d[1] >> 4U) & 3U) == 1U) && (((d[1] >> 6U) & 3U) == 1U) && + ((d[2] & 63U) == 0U) && ((d[3] & 63U) == 0U) && ((d[4] & 15U) == 0U); +} + +static void tesla_sync_configure(uint16_t param, bool longitudinal) { + tesla_sync_enabled = false; +#ifdef ALLOW_DEBUG + tesla_sync_enabled = longitudinal && GET_FLAG(param, 4096U); +#else + (void)param; + (void)longitudinal; +#endif + tesla_sync_seen = false; + tesla_sync_di_seen = false; + tesla_sync_di_valid = false; + tesla_sync_neutral = false; + tesla_sync_blocked = false; + tesla_sync_pending = false; + tesla_sync_drive = false; + tesla_sync_occupant = false; + tesla_sync_native_active = false; + tesla_sync_wheel_ts = 0U; + tesla_sync_di_ts = 0U; + tesla_sync_last_template = 0U; + tesla_sync_steps = 0U; + tesla_sync_tokens = TESLA_SYNC_TOKENS_MAX; + tesla_sync_refill_ts = microsecond_timer_get(); +} + +static void tesla_sync_refill(uint32_t now) { + uint32_t elapsed = safety_get_ts_elapsed(now, tesla_sync_refill_ts); + while ((tesla_sync_tokens < TESLA_SYNC_TOKENS_MAX) && (elapsed >= TESLA_SYNC_TOKEN_REFILL_US)) { + tesla_sync_tokens++; + elapsed -= TESLA_SYNC_TOKEN_REFILL_US; + tesla_sync_refill_ts += TESLA_SYNC_TOKEN_REFILL_US; + } + if (tesla_sync_tokens >= TESLA_SYNC_TOKENS_MAX) { + tesla_sync_refill_ts = now; + } +} + +static void tesla_sync_optional_rx(const CANPacket_t *msg) { + if (tesla_sync_enabled && msg_matches(msg, 0x3C2U, 1U)) { + if (GET_LEN(msg) != 8U) { + tesla_sync_seen = false; + } else { + unsigned int mux = msg->data[0] & 3U; + if ((mux == 2U) || (mux == 3U)) { + tesla_sync_seen = false; + tesla_sync_neutral = false; + } else if (mux == 1U) { + tesla_sync_seen = true; + tesla_sync_wheel_ts = microsecond_timer_get(); + tesla_sync_neutral = tesla_sync_wheel_neutral(msg->data); + if (tesla_sync_neutral) { + for (unsigned int i = 0U; i < 8U; i++) { + tesla_sync_template[i] = msg->data[i]; + } + } + // Driver input during a request no longer latches the sync off. The + // request stays open until the speed changes or it times out, and the + // host recomputes from the observed speed. + } else { + // Index 0 carries no wheel input. + } + } + } +} + +static void tesla_sync_rx(const CANPacket_t *msg) { + if (tesla_sync_enabled) { + if (msg_matches(msg, 0x118U, 0U, 8U)) { + tesla_sync_drive = ((msg->data[2] >> 5U) & 7U) == 4U; + } + if (msg_matches(msg, 0x311U, 0U, 7U)) { + // Occupant status is already part of the validated required RX set. + // Exact bit positions are shared with tesla_screen_rx. + tesla_sync_occupant = GET_BIT(msg, 13U) && !GET_BIT(msg, 28U); + } + if (msg_matches(msg, 0x286U, 0U, 8U)) { + static unsigned int tesla_sync_counter = 0U; + unsigned int counter = msg->data[1] & 15U; + bool advancing = !tesla_sync_di_seen || (((counter - tesla_sync_counter) & 15U) == 1U); + tesla_sync_counter = counter; + tesla_sync_di_seen = true; + tesla_sync_di_valid = advancing; + if (advancing) { + unsigned int state = (msg->data[1] >> 4U) & 7U; + int speed = ((msg->data[2] << 1U) | (msg->data[1] >> 7U)); // half display units + unsigned int units = msg->data[3] & 1U; + tesla_sync_di_ts = microsecond_timer_get(); + tesla_sync_native_active = (state == 2U) || (state == 4U); + if ((state == 0U) || (state == 1U)) { + tesla_sync_pending = false; + tesla_sync_blocked = false; + tesla_sync_steps = 0U; + } + if (tesla_sync_pending && (units != tesla_sync_sent_units)) { + tesla_sync_blocked = true; + } + if (tesla_sync_pending && (speed != tesla_sync_speed)) { + // Feedback releases one request; it does not establish its origin. + // The host must recompute direction from this newly observed speed. + tesla_sync_pending = false; + } + tesla_sync_speed = speed; + tesla_sync_units = units; + } + } + } +} + +static bool tesla_sync_tx(const CANPacket_t *msg, bool stock_aeb, bool autopark, bool stock_lkas) { + static uint32_t tesla_sync_sent_ts = 0U; + uint32_t now = microsecond_timer_get(); + if (tesla_sync_pending && (safety_get_ts_elapsed(now, tesla_sync_sent_ts) > TESLA_SYNC_PENDING_TIMEOUT_US)) { + tesla_sync_pending = false; + } + tesla_sync_refill(now); + bool valid = tesla_sync_enabled && msg_matches(msg, 0x3C2U, 1U, 8U) && + controls_allowed && heartbeat_engaged && aol_rx_healthy() && !relay_malfunction && + vehicle_moving && !brake_pressed && !stock_aeb && !autopark && !stock_lkas && + tesla_sync_drive && tesla_sync_occupant && tesla_sync_native_active && tesla_sync_di_valid && + tesla_sync_seen && tesla_sync_neutral && !tesla_sync_blocked && !tesla_sync_pending && + (tesla_sync_tokens > 0U) && (tesla_sync_speed > 2) && (tesla_sync_speed < 508) && + (safety_get_ts_elapsed(now, tesla_sync_wheel_ts) <= 250000U) && + (safety_get_ts_elapsed(now, tesla_sync_di_ts) <= 250000U) && + ((tesla_sync_steps == 0U) || (tesla_sync_wheel_ts != tesla_sync_last_template)); + unsigned int ticks = msg->data[3] & 63U; + // One click (+-1), or one fast flick (+-5) that moves the Tesla to the next + // multiple of 5. Both are a single frame, as the driver's own wheel sends. + valid = valid && ((ticks == 1U) || (ticks == 63U) || (ticks == 5U) || (ticks == 59U)); + for (unsigned int i = 0U; i < 8U; i++) { + uint8_t mask = (i == 3U) ? 0xC0U : 0xFFU; + valid = valid && ((msg->data[i] & mask) == (tesla_sync_template[i] & mask)); + } + if (valid) { + tesla_sync_pending = true; + tesla_sync_sent_units = tesla_sync_units; + tesla_sync_last_template = tesla_sync_wheel_ts; + tesla_sync_sent_ts = now; + tesla_sync_tokens--; + if (tesla_sync_steps < 0xFFFFU) { + tesla_sync_steps++; // only marks that a request was sent this session + } + } + return valid; +} + +#ifdef ALLOW_DEBUG +static bool tesla_sync_param_valid(uint16_t param) { + // Scroll speed sync is 4096 on a word with LONG_CONTROL: base 1/257, screen AOL 513/769/1537/1793 and ordinary AOL 2049/2305/3073/3329. + const uint16_t base = (uint16_t)(param & ~4096U); + return GET_FLAG(param, 4096U) && + ((base == 1U) || (base == 257U) || (base == 513U) || (base == 769U) || (base == 1537U) || (base == 1793U) || + (base == 2049U) || (base == 2305U) || (base == 3073U) || (base == 3329U)); +} +#endif + +// A word outside the base Tesla namespace: screen or ordinary AOL, or one of the scroll speed sync words. +// RELEASE has no speed sync word. +static bool tesla_extended_param_valid(uint16_t param) { + bool valid = tesla_screen_param_valid(param); +#ifdef ALLOW_DEBUG + valid = valid || tesla_sync_param_valid(param); +#endif + return valid; +} + +// Speed sync rides on top of a base, screen AOL or ordinary AOL word: that word configures everything else. +static uint16_t tesla_sync_base_param(uint16_t param) { + uint16_t base = param; +#ifdef ALLOW_DEBUG + if (tesla_sync_param_valid(param)) { + base = (uint16_t)(param & ~4096U); + } +#endif + return base; +} diff --git a/opendbc_repo/opendbc/safety/safety.h b/opendbc_repo/opendbc/safety/safety.h index 1b7fa364f1..e27882816c 100644 --- a/opendbc_repo/opendbc/safety/safety.h +++ b/opendbc_repo/opendbc/safety/safety.h @@ -549,7 +549,7 @@ int set_safety_hooks(uint16_t mode, uint16_t param) { current_safety_param = 0; continue; } - if ((mode == SAFETY_TESLA) && (((param & ~(TESLA_HW1_FLAG | 257U)) != 0U) || ((param & TESLA_HW1_FLAG) && (param & 256U))) && !tesla_screen_param_valid(param)) { + if ((mode == SAFETY_TESLA) && (((param & ~(TESLA_HW1_FLAG | 257U)) != 0U) || ((param & TESLA_HW1_FLAG) && (param & 256U))) && !tesla_extended_param_valid(param)) { current_hooks = &nooutput_hooks; current_safety_mode = SAFETY_NOOUTPUT; current_safety_param = 0; diff --git a/opendbc_repo/opendbc/safety/tests/libsafety/safety.c b/opendbc_repo/opendbc/safety/tests/libsafety/safety.c index 371325da71..7d9f940991 100644 --- a/opendbc_repo/opendbc/safety/tests/libsafety/safety.c +++ b/opendbc_repo/opendbc/safety/tests/libsafety/safety.c @@ -443,6 +443,15 @@ unsigned int tesla_preap_test_config_read(uint8_t *out) { return tesla_preap_pedal_config_read(out); } +// Tesla scroll speed sync state for native tests: one bit per flag in declaration +// order, whether a request was sent this session, and the request tokens in bits 16-23. +unsigned int safety_test_tesla_sync_state(void) { + return (tesla_sync_enabled ? 1U : 0U) | (tesla_sync_seen ? 2U : 0U) | (tesla_sync_di_seen ? 4U : 0U) | + (tesla_sync_di_valid ? 8U : 0U) | (tesla_sync_neutral ? 16U : 0U) | (tesla_sync_blocked ? 32U : 0U) | + (tesla_sync_pending ? 64U : 0U) | (tesla_sync_drive ? 128U : 0U) | (tesla_sync_occupant ? 256U : 0U) | + (tesla_sync_native_active ? 512U : 0U) | ((tesla_sync_steps != 0U) ? 1024U : 0U) | (tesla_sync_tokens << 16U); +} + // A real foreign catalog must fail closed instead of acquiring the GV60 heartbeat. bool safety_test_hyundai_gv60_catalog_rejection(bool alternate) { bool rejected = false; diff --git a/opendbc_repo/opendbc/safety/tests/test_tesla_encoding_namespace.py b/opendbc_repo/opendbc/safety/tests/test_tesla_encoding_namespace.py index cca1a2efe7..f8567a6e38 100644 --- a/opendbc_repo/opendbc/safety/tests/test_tesla_encoding_namespace.py +++ b/opendbc_repo/opendbc/safety/tests/test_tesla_encoding_namespace.py @@ -36,6 +36,26 @@ def check_exact_current_and_hw1_profiles_keep_distinct_steering_encoding(): assert lib.safety_tx_hook(packet(message)) +def check_speed_sync_bit_extends_only_modern_long_control_words(): + modern = TeslaCAN(None, CANPacker(DBC[CAR.TESLA_MODEL_3][Bus.party])) + hw1 = ModelSHW1CAN(CANPacker(DBC[CAR.TESLA_MODEL_S_HW1][Bus.party])) + debug = lib.set_safety_hooks(structs.CarParams.SafetyModel.allOutput, 0) == 0 + # Alone, on a stock or HW1 word, or beside an unknown flag, the bit selects nothing. + for word in (4096, 4096 | 256, 4096 | 512, 4096 | 2048, 4096 | 16, 4096 | 17, 4096 | 3, 4096 | 1 | 0x8000, 8192 | 1): + assert lib.set_safety_hooks(10, word) == -1 + assert not lib.get_controls_allowed() + lib.set_controls_allowed(True) + assert not lib.safety_tx_hook(packet(modern.create_steering_control(0., False))) + assert not lib.safety_tx_hook(packet(hw1.create_steering_control(0., 0, False))) + # The ten exact words keep the modern profile; RELEASE firmware has no such word. + for base in (1, 257, 513, 769, 1537, 1793, 2049, 2305, 3073, 3329): + assert lib.set_safety_hooks(10, 4096 | base) == (0 if debug else -1) + lib.init_tests() # Clear the separate startup Autopark assumption for this encoding test. + lib.set_controls_allowed(False) + assert lib.safety_tx_hook(packet(modern.create_steering_control(0., False))) == debug + assert lib.get_current_safety_param() == (4096 | base if debug else 0) + + class TestTeslaEncodingNamespace(unittest.TestCase): def tearDown(self): lib.init_tests() @@ -47,3 +67,6 @@ class TestTeslaEncodingNamespace(unittest.TestCase): def test_exact_current_and_hw1_profiles_keep_distinct_steering_encoding(self): check_exact_current_and_hw1_profiles_keep_distinct_steering_encoding() + + def test_speed_sync_bit_extends_only_modern_long_control_words(self): + check_speed_sync_bit_extends_only_modern_long_control_words() diff --git a/opendbc_repo/opendbc/safety/tests/test_tesla_hw1.py b/opendbc_repo/opendbc/safety/tests/test_tesla_hw1.py index 89c615c5b1..9b60c6de41 100644 --- a/opendbc_repo/opendbc/safety/tests/test_tesla_hw1.py +++ b/opendbc_repo/opendbc/safety/tests/test_tesla_hw1.py @@ -38,7 +38,10 @@ class TestModelSHW1Safety(unittest.TestCase): def test_all_16bit_profile_words_are_isolated(self): debug = lib.set_safety_hooks(CarParams.SafetyModel.allOutput, 0) == 0 - supported = {0, 1, 16, 17, 256, 257, 512, 768, 1536, 1792, 2048, 2304, 3072, 3328} | ({513, 769, 1537, 1793, 2049, 2305, 3073, 3329} if debug else set()) + long_aol = {513, 769, 1537, 1793, 2049, 2305, 3073, 3329} + # Scroll speed sync (4096) rides only on the ten modern LONG_CONTROL words, never on an HW1 or stock word. + speed_sync = {4096 | word for word in {1, 257} | long_aol} + supported = {0, 1, 16, 17, 256, 257, 512, 768, 1536, 1792, 2048, 2304, 3072, 3328} | (long_aol | speed_sync if debug else set()) for param in range(65536): result = lib.set_safety_hooks(10, param) expected = 0 if param in supported else -1 diff --git a/opendbc_repo/opendbc/safety/tests/test_tesla_speed_sync.py b/opendbc_repo/opendbc/safety/tests/test_tesla_speed_sync.py new file mode 100644 index 0000000000..373a08ef2d --- /dev/null +++ b/opendbc_repo/opendbc/safety/tests/test_tesla_speed_sync.py @@ -0,0 +1,974 @@ +"""Tesla scroll speed sync: one gated right-wheel scroll frame (0x3C2 on bus 1) for the Model 3/Y.""" +import random +import re +import unittest +from functools import cache +from pathlib import Path + +from opendbc.car.structs import CarParams +from opendbc.car.tesla.screen_button import SYNC_WORDS +from opendbc.car.tesla.speed_sync import neutral_wheel, scroll_request +from opendbc.car.tesla.values import TeslaSafetyFlags +from opendbc.safety.tests import test_tesla +from opendbc.safety.tests import test_tesla_ordinary_aol as ordinary +from opendbc.safety.tests import test_tesla_screen_button as screen +from opendbc.safety.tests.common import CANPackerSafety, make_msg +from opendbc.safety.tests.libsafety import libsafety_py + +TESLA = CarParams.SafetyModel.tesla +NO_OUTPUT = CarParams.SafetyModel.noOutput +SYNC = int(TeslaSafetyFlags.SCROLL_SPEED_SYNC) +WHEEL = 0x3C2 + +# The bit rides only on a word with LONG_CONTROL: base, screen AOL and ordinary AOL, +# each with and without cooperative steering. +BASES = (1, 257, 513, 769, 1537, 1793, 2049, 2305, 3073, 3329) +WORDS = tuple(SYNC | base for base in BASES) +STOCK_WORDS = (0, 256, 512, 768, 1536, 1792, 2048, 2304, 3072, 3328) + +# VCLEFT_switchStatus, index 1: every tilt and press neutral, no scroll on either wheel. +NEUTRAL = bytes.fromhex('2955000000000000') +# The same neutral frame with every bit the panda does not interpret set. +NEUTRAL_BUSY = bytes.fromhex('AD55C0C0F0FFFFFF') +STEPS = (1, -1, 5, -5) +TICKS = tuple(ticks & 0x3F for ticks in STEPS) + +# safety_test_tesla_sync_state() +ENABLED, SEEN, DI_SEEN, DI_VALID, NEUTRAL_SEEN, BLOCKED, PENDING, DRIVE, OCCUPANT, ACTIVE, SENT = (1 << bit for bit in range(11)) +READY = ENABLED | SEEN | DI_SEEN | DI_VALID | NEUTRAL_SEEN | DRIVE | OCCUPANT | ACTIVE +TOKENS = 30 + +CAR = {'state': 2, 'speed': 120, 'units': 0, 'autopark': 0, 'gear': 4, 'door': False, 'belt': True, 'brake': False, + 'standstill': False, 'aeb': 0, 'stock_type': 0, 'kph': 80., 'esp_delta': 0., 'speed_valid': 1, 'angle': 0., 'hands': 0, + 'eps': 1, 'eps_error': 0, 'torque': 0., 'pedal': 0.} +# What a drive can do to each of them: the driver, the stock systems and the car's own faults. +EVENTS = {'state': (0, 1, 1, 3, 4, 4, 5, 6, 7), 'speed': (0, 2, 3, 121, 300, 507, 508), 'units': (1,), 'autopark': (1, 3, 4, 9), + 'gear': (0, 1, 2, 3, 7), 'door': (True,), 'belt': (False,), 'brake': (True,), 'standstill': (True,), 'aeb': (1, 2, 3), + 'stock_type': (1, 2, 3), 'kph': (0., 5., 120.), 'esp_delta': (12.,), 'speed_valid': (0,), 'angle': (5., -10., 30.), + 'hands': (1, 2, 3), 'eps': (0, 2, 3, 5), 'eps_error': (9,), 'torque': (1., -3., 5.5, -6.), 'pedal': (20.,)} + + +def is_debug(lib): + debug = lib.set_safety_hooks(CarParams.SafetyModel.allOutput, 0) == 0 + lib.set_safety_hooks(NO_OUTPUT, 0) + return debug + + +@cache +def release_safety(): + default = libsafety_py.libsafety + library = libsafety_py.ffi.dlopen(libsafety_py._build_libsafety(release=True)) + assert libsafety_py.libsafety is default + return library + + +class SyncFixture: + WORD = SYNC | 1 + EXPERIENCE = 0 + + def setUp(self): + self.lib = libsafety_py.libsafety + self.packer = CANPackerSafety('tesla_model3_party') + self.start(self.WORD) + + def tearDown(self): + self.lib.set_aol_test_heartbeat(False) + self.lib.init_tests() + self.lib.set_alternative_experience(0) + self.lib.set_safety_hooks(NO_OUTPUT, 0) + + def start(self, word, experience=None, ready=True, now=5_000_000): + self.lib.init_tests() + self.lib.set_alternative_experience(self.EXPERIENCE if experience is None else experience) + self.now = now + self.lib.set_timer(self.now & 0xFFFFFFFF) + self.assertEqual(self.lib.set_safety_hooks(TESLA, word), 0, word) + self.lib.set_aol_test_heartbeat(True) + self.car = dict(CAR) + self.packer.counters.clear() + self.counter = 0 + self.template = NEUTRAL + if ready: + self.ready() + + def ready(self): + """Engaged on the Tesla's own cruise with a current neutral wheel frame: a request must be admitted from here.""" + for _ in range(3): + self.step(us=0) + + def advance(self, us): + self.now += us + self.lib.set_timer(self.now & 0xFFFFFFFF) + + def rx(self, name, bus, values): + return bool(self.lib.safety_rx_hook(self.packer.make_can_msg_safety(name, bus, values))) + + def di(self, counter=None, **changes): + """DI_state with its counter under test control. The selected speed is in half display units, as the panda keeps it.""" + self.car.update(changes) + self.counter = (self.counter + 1) % 16 if counter is None else counter + car = self.car + return self.rx('DI_state', 0, {'DI_cruiseState': car['state'], 'DI_autoparkState': car['autopark'], + 'DI_digitalSpeed': car['speed'] * .5, 'DI_speedUnits': car['units'], + 'DI_locStatusCounter': self.counter}) + + def feed(self, skip=(), check=True, **changes): + """Every required message once, as the car sends them. Returns what the panda made of each.""" + self.car.update(changes) + car = self.car + frames = ( + ('DAS_control', 2, {'DAS_aebEvent': car['aeb']}), + ('DAS_steeringControl', 2, {'DAS_steeringControlType': car['stock_type']}), + ('DI_speed', 0, {'DI_vehicleSpeed': car['kph']}), + ('ESP_B', 0, {'ESP_vehicleSpeed': car['kph'] + car['esp_delta'], 'ESP_wheelSpeedsQF': car['speed_valid'], + 'ESP_vehicleStandstillSts': int(car['standstill'])}), + ('EPAS3S_sysStatus', 0, {'EPAS3S_internalSAS': car['angle'], 'EPAS3S_eacStatus': car['eps'], 'EPAS3S_eacErrorCode': car['eps_error'], + 'EPAS3S_handsOnLevel': car['hands'], 'EPAS3S_torsionBarTorque': car['torque']}), + ('DI_systemStatus', 0, {'DI_gear': car['gear'], 'DI_accelPedalPos': car['pedal']}), + ('ESP_status', 0, {'ESP_driverBrakeApply': 2 if car['brake'] else 1}), + ('UI_warning', 0, {'anyDoorOpen': int(car['door']), 'buckleStatus': int(car['belt'])}), + ) + results = [self.rx(name, bus, values) for name, bus, values in frames if name not in skip] + if 'DI_state' not in skip: + results.append(self.di()) + if check: + self.assertTrue(all(results), results) + self.lib.safety_tick() + return results + + def wheel(self, data=None, bus=1, address=WHEEL): + """A wheel frame from the car on the vehicle bus. The panda copies a neutral one as its template.""" + self.lib.safety_rx_hook(make_msg(bus, address, dat=self.template if data is None else bytes(data))) + + def step(self, us=20_000, skip=(), wheel=True, **changes): + """One cycle of car traffic: the required messages, then a new neutral wheel frame.""" + self.advance(us) + self.feed(skip, **changes) + if wheel: + self.wheel() + + def answer(self, ticks=1, us=20_000): + """The Tesla moves its selected speed, which releases the outstanding request.""" + self.step(us=us, speed=self.car['speed'] + 2 * ticks) + + def frame(self, ticks=1, template=None): + data = bytearray(self.template if template is None else template) + data[3] = (data[3] & 0xC0) | (ticks & 0x3F) + return bytes(data) + + def tx(self, ticks=1, data=None, bus=1): + data = self.frame(ticks) if data is None else bytes(data) + return bool(self.lib.safety_tx_hook(make_msg(bus, WHEEL, dat=data))) + + def hook(self, ticks=1): + """The Tesla TX hook alone, without the shared relay and allow-list checks around it.""" + return bool(self.lib.safety_test_selected_tx(make_msg(1, WHEEL, dat=self.frame(ticks)))) + + def state(self, mask=0x7FF): + return self.lib.safety_test_tesla_sync_state() & mask + + def tokens(self): + return self.lib.safety_test_tesla_sync_state() >> 16 + + def force_controls(self): + self.lib.set_controls_allowed(True) + + +class TestTeslaSpeedSyncWords(unittest.TestCase): + def setUp(self): + self.lib = libsafety_py.libsafety + self.debug = is_debug(self.lib) + + def tearDown(self): + self.lib.set_safety_hooks(NO_OUTPUT, 0) + + def test_only_the_ten_exact_words_carry_the_bit(self): + self.assertEqual(frozenset(WORDS), SYNC_WORDS, 'the car port selects from the same ten words') + for word in range(0x10000): + if word & SYNC: + valid = self.debug and word in WORDS + self.assertEqual(self.lib.set_safety_hooks(TESLA, word), 0 if valid else -1, word) + self.assertEqual(self.lib.get_current_safety_mode(), TESLA if valid else NO_OUTPUT, word) + self.assertEqual(self.lib.get_current_safety_param(), word if valid else 0, word) + if valid: + self.assertEqual(self.lib.safety_test_tesla_sync_state(), ENABLED | (TOKENS << 16), word) + + def test_near_miss_words_select_no_output(self): + near = [SYNC, 2 * SYNC, SYNC | 16, SYNC | 17, SYNC | 273, SYNC | 1025, SYNC | 1281, SYNC | 2561, SYNC | 3585] + near += [SYNC | word for word in STOCK_WORDS] # no LONG_CONTROL + near += [word | extra for word in WORDS for extra in (2, 4, 8, 16, 32, 64, 128, 8192, 16384, 32768)] + near += [word ^ flag for word in WORDS for flag in (1, 512, 1024, 2048) if word ^ flag not in WORDS] + for word in near: + self.assertNotIn(word, WORDS) + self.assertEqual(self.lib.set_safety_hooks(TESLA, word), -1, word) + self.assertEqual(self.lib.get_current_safety_mode(), NO_OUTPUT, word) + self.lib.set_controls_allowed(True) + self.assertFalse(self.lib.safety_tx_hook(make_msg(1, WHEEL, dat=NEUTRAL[:3] + b'\x01' + NEUTRAL[4:])), word) + + def test_every_base_word_is_a_long_control_word_valid_on_its_own(self): + for base in BASES: + self.assertTrue(base & TeslaSafetyFlags.LONG_CONTROL) + self.assertEqual(self.lib.set_safety_hooks(TESLA, base), 0 if self.debug else (0 if base in (1, 257) else -1), base) + self.assertFalse(self.lib.safety_test_tesla_sync_state() & ENABLED, base) + + +class TestTeslaSpeedSyncDisabled(SyncFixture, unittest.TestCase): + WORD = 1 + + def setUp(self): + self.debug = is_debug(libsafety_py.libsafety) + super().setUp() + + def scroll_frames_refused(self): + self.force_controls() + for ticks in STEPS: + for bus in range(3): + self.assertFalse(self.tx(ticks, bus=bus)) + self.assertFalse(self.hook(ticks)) + + def test_without_the_bit_no_wheel_frame_is_admitted_or_tracked(self): + words = STOCK_WORDS + (BASES if self.debug else ()) + for word in words: + for experience in (0, 32): + with self.subTest(word=word, experience=experience): + self.start(word, experience) + for template in (NEUTRAL, NEUTRAL_BUSY): + self.template = template + self.step() + self.assertTrue(self.lib.get_controls_allowed()) + self.assertEqual(self.state(), 0) + self.assertEqual(self.tokens(), TOKENS) + self.scroll_frames_refused() + self.assertEqual(self.state(), 0) + self.assertEqual(self.tokens(), TOKENS) + + def test_release_firmware_refuses_the_bit_and_the_wheel_frame(self): + release = release_safety() + self.assertFalse(is_debug(release)) + for word in range(0x10000): + if word & SYNC: + self.assertEqual(release.set_safety_hooks(TESLA, word), -1, word) + self.assertEqual(release.get_current_safety_mode(), NO_OUTPUT, word) + native = TestTeslaSpeedSyncDisabled(methodName='test_without_the_bit_no_wheel_frame_is_admitted_or_tracked') + native.lib = release + native.packer = CANPackerSafety('tesla_model3_party') + native.debug = False + try: + native.test_without_the_bit_no_wheel_frame_is_admitted_or_tracked() + for word in BASES: + self.assertEqual(release.set_safety_hooks(TESLA, word), 0 if word in (1, 257) else -1, word) + release.set_controls_allowed(True) + self.assertFalse(release.safety_tx_hook(make_msg(1, WHEEL, dat=native.frame())), word) + finally: + native.tearDown() + self.assertIsNot(libsafety_py.libsafety, release) + + def test_other_modes_never_send_the_wheel_frame_after_a_sync_session(self): + if not self.debug: + self.skipTest('RELEASE firmware refuses the sync words') + for mode, word in ((TESLA, 1), (TESLA, 0), (TESLA, 17), (CarParams.SafetyModel.teslaPreap, 0), (NO_OUTPUT, 0), + (CarParams.SafetyModel.silent, 0), (CarParams.SafetyModel.hondaBosch, 0)): + with self.subTest(mode=mode, word=word): + self.start(SYNC | 1) + self.assertTrue(self.tx()) + self.answer() + self.assertEqual(self.lib.set_safety_hooks(mode, word), 0) + self.force_controls() + for ticks in STEPS: + for bus in range(3): + self.assertFalse(self.tx(ticks, bus=bus)) + + +class TestTeslaSpeedSyncChangesNothingElse(SyncFixture, unittest.TestCase): + """Every eligible Model 3/Y carries the bit, switch on or off: apart from the wheel frame, the panda must behave as without it.""" + WORD = 1 + REQUIRED = ('DAS_control', 'DAS_steeringControl', 'DI_speed', 'ESP_B', 'EPAS3S_sysStatus', 'DI_systemStatus', 'ESP_status', + 'UI_warning', 'DI_state') + FORWARDED = (0x488, 0x2b9, 0x27d, WHEEL, 0x3DF, 0x257) + + @classmethod + def setUpClass(cls): + if not is_debug(libsafety_py.libsafety): + raise unittest.SkipTest('RELEASE firmware refuses the sync words') + + def observe(self): + """Everything the panda decides or reports outside the speed sync state itself.""" + lib = self.lib + return (bool(lib.get_controls_allowed()), lib.aol_get_request_mask(), lib.aol_get_permission_mask(), bool(lib.get_relay_malfunction()), + bool(lib.get_gas_pressed_prev()), bool(lib.get_brake_pressed_prev()), bool(lib.get_regen_braking_prev()), + bool(lib.get_steering_disengage_prev()), bool(lib.get_cruise_engaged_prev()), bool(lib.get_vehicle_moving()), + lib.get_vehicle_speed_min(), lib.get_vehicle_speed_max(), lib.get_angle_meas_min(), lib.get_angle_meas_max(), + lib.get_desired_angle_last(), lib.get_heartbeat_engaged_mismatches(), bool(lib.safety_config_valid()), + lib.get_current_safety_mode(), lib.get_current_safety_param() & ~SYNC, + tuple(lib.safety_fwd_hook(bus, address) for bus in range(3) for address in self.FORWARDED)) + + def assert_same(self, rows, plain, context): + self.assertEqual(len(rows), len(plain), context) + for step, (row, expected) in enumerate(zip(rows, plain, strict=True)): + self.assertEqual(row, expected, (step, context)) + + def scripted_drive(self, word, experience): + commands = CANPackerSafety('tesla_model3_party') # its own counters: the car's frames keep theirs + script = ({'state': 0}, {'state': 1}, 'press', {'state': 2}, {'brake': True}, {'brake': False}, {'state': 0}, {'state': 1}, + {'state': 2}, 'press', {'door': True}, {'door': False}, {'state': 1}, {'state': 2}, {'gear': 1}, {'gear': 4}, + {'aeb': 1}, {'aeb': 0}, {'state': 1}, {'stock_type': 2}, {'state': 2}, {'stock_type': 0}, {'belt': False}, + {'belt': True}, {'state': 5}, {'state': 0}, {'state': 2}, {'torque': 5.5}, {'torque': 0.}, {'state': 1}, {'state': 2}, + {'hands': 3}, {'hands': 0}, {'state': 1}, {'state': 2}, {'standstill': True}, {'state': 4}) + self.start(word, experience, ready=False) + rows = [] + for item in script: + if item == 'press': + for count in (0, 3): + self.lib.safety_rx_hook(make_msg(1, 0x3DF, dat=bytes((0, 0, 0, count, 0, 0, 0, 0)))) + else: + self.step(**item) + self.lib.aol_set_host_request(3) + steering = commands.make_can_msg_safety('DAS_steeringControl', 0, {'DAS_steeringAngleRequest': 0, 'DAS_steeringControlType': 1}) + accel = commands.make_can_msg_safety('DAS_control', 0, {'DAS_accelMin': 1, 'DAS_accelMax': 1}) + rows.append((bool(self.lib.safety_tx_hook(steering)), bool(self.lib.safety_tx_hook(accel)), *self.observe())) + return rows + + def random_drive(self, word, experience, seed, scroll, steps=300): + """A seeded drive of faults, driver inputs and commands. With `scroll` the host also asks for wheel steps; without it + the owner's switch is off. Returns every answer and report except the answers to those wheel requests.""" + rng = random.Random(seed) + commands = CANPackerSafety('tesla_model3_party') + keys = sorted(EVENTS) + 4 * ['state'] + 2 * ['stock_type', 'units'] + # Mostly neutral wheel frames; also a scroll, a tilt, the other indexes, a short frame and a missing one. + wheels = 7 * (NEUTRAL,) + 2 * (NEUTRAL_BUSY,) + (NEUTRAL[:3] + b'\x02' + NEUTRAL[4:], b'\x31' + NEUTRAL[1:], b'\x2a' + NEUTRAL[1:], + bytes(8), NEUTRAL[:6], None) + self.start(word, experience, ready=False) + rows, admitted, engage = [], 0, False + for _ in range(steps): + roll = rng.random() + if engage: + self.car['state'], engage = 2, False + elif roll < .3: + key = rng.choice(keys) + self.car[key] = rng.choice(EVENTS[key]) + elif roll < .5: + self.car, engage = dict(CAR, state=1), True # everything normal again; the driver engages on the next cycle + self.advance(rng.choice((10_000, 20_000, 20_000, 20_000, 40_000, 120_000))) + if rng.random() < .03: + self.counter = (self.counter + 1) % 16 # a DI_state frame went missing + row = self.feed((rng.choice(self.REQUIRED),) if rng.random() < .03 else (), check=False) + if rng.random() < .3: + row.append(bool(self.lib.safety_rx_hook(make_msg(1, 0x3DF, dat=bytes((0, 0, 0, rng.choice((0, 3, 3, 1)), 0, 0, 0, 0)))))) + wheel = rng.choice(wheels) + if wheel is not None: + row.append(bool(self.lib.safety_rx_hook(make_msg(1, WHEEL, dat=wheel)))) + if neutral_wheel(wheel): + self.template = wheel + if rng.random() < .6: + self.lib.aol_set_host_request(rng.choice((0, 1, 2, 3, 3, 3, 7))) + heartbeat = rng.random() + if heartbeat < .03 or heartbeat > .7: + self.lib.set_aol_test_heartbeat(heartbeat > .7) + angle = self.car['angle'] + rng.choice((0., 0., .2, -.3, 2., -15.)) + low, high = rng.choice(((0., 0.), (1., 1.), (-1., 1.5), (-2., -1.), (0., 3.6), (-3.6, 0.), (-.5, 0.))) + for name, values in ( + ('DAS_steeringControl', {'DAS_steeringAngleRequest': angle, 'DAS_steeringControlType': rng.choice((1, 1, 1, 0, 2, 3))}), + ('DAS_control', {'DAS_setSpeed': 100, 'DAS_accState': rng.choice((4, 4, 13)), 'DAS_aebEvent': rng.choice((0, 0, 0, 0, 1)), + 'DAS_accelMin': low, 'DAS_accelMax': high}), + ('APS_eacMonitor', {}), + ): + row.append(bool(self.lib.safety_tx_hook(commands.make_can_msg_safety(name, 0, values)))) + ticks = rng.choice((1, 1, 1, -1, 5, -5, 0, 7)) + if rng.random() < .6 and scroll: + admitted += self.tx(ticks) + rows.append((*row, *self.observe())) + return rows, admitted + + def test_scripted_drive_is_identical_with_and_without_the_bit(self): + for base in BASES: + for experience in (0, 32): + with self.subTest(base=base, experience=experience): + plain = self.scripted_drive(base, experience) + self.assert_same(self.scripted_drive(SYNC | base, experience), plain, base) + # The script is a real drive: steering and acceleration are each allowed and refused in it, + # and a screen or ordinary AOL word with its saved opt-in grants its own permission. + for column in (0, 1): + self.assertEqual({row[column] for row in plain}, {False, True}) + self.assertEqual(any(row[4] for row in plain), experience == 32 and base > 257) + + def test_random_drives_are_identical_with_and_without_the_bit(self): + # From the end of a row: the three command answers, then observe(). + columns = {'steering': -23, 'acceleration': -22, 'eac monitor': -21, 'controls': -20, 'gas': -16, 'brake': -15, + 'steering disengage': -13, 'cruise': -12, 'moving': -11, 'receive health': -4} + reached = {name: set() for name in columns} + for index, base in enumerate(BASES): + for experience in (0, 32): + with self.subTest(base=base, experience=experience): + seed = 64 * index + experience + plain, admitted = self.random_drive(base, experience, seed, scroll=True) + self.assertEqual(admitted, 0, 'no wheel request without the bit') + for scroll in (True, False): + rows, admitted = self.random_drive(SYNC | base, experience, seed, scroll) + self.assert_same(rows, plain, (base, experience, scroll)) + self.assertEqual(admitted > 0, scroll, 'the wheel request is the only difference') + for name, column in columns.items(): + reached[name] |= {row[column] for row in plain} + self.assertEqual(any(row[-18] for row in plain), experience == 32 and base > 257, 'AOL permission') + self.assertEqual({row[-20] for row in plain}, {False, True}) + # Together the drives reach both answers of every command and report they compare. + self.assertEqual(reached, {name: {False, True} for name in columns}) + + def test_speed_sync_state_is_private_to_its_header(self): + """Outside its header the feature is five calls in tesla.h and one in safety.h; inside, it assigns only what it + declares and calls only helpers that change nothing. So no other Tesla decision can depend on the bit.""" + safety = Path(__file__).parents[1] + uses = {} + for path in sorted(safety.rglob('*.h')): + found = re.findall(r'\b(?:tesla_sync_\w+|tesla_extended_param_valid)\b', path.read_text()) + if found and path.name != 'tesla_speed_sync.h': + uses[path.relative_to(safety).as_posix()] = found + self.assertEqual(uses, {'modes/tesla.h': ['tesla_sync_rx', 'tesla_sync_optional_rx', 'tesla_sync_tx', 'tesla_sync_base_param', + 'tesla_sync_configure'], + 'safety.h': ['tesla_extended_param_valid']}) + # The request decision reaches only the wheel frame, and it is the hook's last word on it. + last_word = ' if (msg->addr == 0x3C2U) {\n tx = tesla_sync_tx(msg, tesla_stock_aeb, tesla_autopark, tesla_stock_lkas);\n }\n\n return tx;\n}\n' + self.assertIn(last_word, (safety / 'modes/tesla.h').read_text()) + code = re.sub(r'//[^\n]*', '', (safety / 'modes/tesla_speed_sync.h').read_text()) + declared = set(re.findall(r'\b(?:bool|int|uint8_t|uint16_t|uint32_t)\s+(\w+)(?:\[\w+\])?\s*[=;]', code)) + assigned = set(re.findall(r'\b([A-Za-z_]\w*)(?:\[\w+\])?\s*(?:(?:[-+*/%&|^]|<<|>>)?=(?!=)|\+\+|--)', code)) + self.assertTrue(assigned) + self.assertLessEqual(assigned, declared, 'the header assigns only what it declares') + lasting = set(re.findall(r'\bstatic\s+(?:const\s+)?(?:unsigned\s+)?\w+\s+(\w+)(?:\[\w+\])?\s*[=;]', code)) + self.assertTrue(lasting and all(name.startswith('tesla_sync_') for name in lasting), 'what outlives a call is its own') + called = set(re.findall(r'\b([A-Za-z_]\w*)\s*\(', code)) - {'if', 'else', 'while', 'for', 'return'} + self.assertEqual({name for name in called if not name.startswith('tesla_sync_') and name != 'tesla_extended_param_valid'}, + {'msg_matches', 'GET_LEN', 'GET_BIT', 'GET_FLAG', 'microsecond_timer_get', 'safety_get_ts_elapsed', + 'aol_rx_healthy', 'tesla_screen_param_valid'}) + + def test_upstream_aol_cases_hold_with_the_bit_on_every_long_word(self): + """Upstream's own screen and ordinary AOL cases, with the bit added to every LONG_CONTROL word they select.""" + selected = set() + for case_class in (screen.TestTeslaScreenButton, ordinary.TestTeslaOrdinaryAol): + for name in unittest.TestLoader().getTestCaseNames(case_class): + with self.subTest(case=case_class.__name__, test=name): + case = case_class(methodName=name) + + def start(word, case=case): + word |= SYNC if word & 1 else 0 + screen.TestTeslaScreenButton.start(case, word) + self.assertEqual(bool(case.lib.safety_test_tesla_sync_state() & ENABLED), bool(word & SYNC)) + selected.add(word) + case.start = start + case.setUp() + try: + getattr(case, name)() + finally: + case.tearDown() + self.assertLessEqual({SYNC | 513, SYNC | 1537, SYNC | 2049, SYNC | 3073}, selected) + + +class TestTeslaLongitudinalSpeedSyncSafety(test_tesla.TestTeslaLongitudinalSafety): + """Upstream's complete Tesla longitudinal suite with the bit set and no wheel request made: nothing in it may differ.""" + SAFETY_PARAM = TeslaSafetyFlags.LONG_CONTROL | TeslaSafetyFlags.SCROLL_SPEED_SYNC + + @classmethod + def setUpClass(cls): + super().setUpClass() + if not is_debug(libsafety_py.libsafety): + raise unittest.SkipTest('RELEASE firmware refuses the sync words') + + def setUp(self): + super().setUp() + self.assertTrue(self.safety.safety_test_tesla_sync_state() & ENABLED) + + +class TestTeslaSpeedSync(SyncFixture, unittest.TestCase): + @classmethod + def setUpClass(cls): + if not is_debug(libsafety_py.libsafety): + raise unittest.SkipTest('RELEASE firmware refuses the sync words') + + def blocked_until(self, fault, clear): + """One fault refuses the request and spends nothing; clearing it admits the same request.""" + self.start(self.WORD) + self.step() + fault() + self.assertFalse(self.tx()) + self.assertFalse(self.hook()) + self.assertFalse(self.state(PENDING | SENT)) + self.assertEqual(self.tokens(), TOKENS) + clear() + self.assertTrue(self.tx()) + + # ***** admitted requests ***** + + def test_ready_state_admits_one_request_and_records_it(self): + self.assertEqual(self.state(), READY) + self.assertEqual(self.tokens(), TOKENS) + self.assertTrue(self.tx()) + self.assertEqual(self.state(), READY | PENDING | SENT) + self.assertEqual(self.tokens(), TOKENS - 1) + + def test_every_word_admits_the_four_steps_the_sender_builds(self): + for word in WORDS: + for experience in (0, 32): + for template in (NEUTRAL, NEUTRAL_BUSY): + with self.subTest(word=word, experience=experience, template=template.hex()): + self.start(word, experience) + self.template = template + for ticks in STEPS: + self.step() + address, data, bus = scroll_request(template, ticks) + self.assertEqual((address, bus, data), (WHEEL, 1, self.frame(ticks))) + self.assertTrue(self.lib.safety_tx_hook(make_msg(bus, address, dat=data))) + self.answer(ticks) + self.assertEqual(self.tokens(), TOKENS - len(STEPS)) + + def test_override_state_and_both_units_are_admitted(self): + for changes in ({'state': 4}, {'units': 1}, {'state': 4, 'units': 1}): + with self.subTest(changes=changes): + self.start(self.WORD) + self.step(**changes) + self.assertEqual(self.state(), READY) + self.assertTrue(self.tx()) + + def test_first_request_is_admitted_with_a_template_stamped_zero(self): + self.start(self.WORD, now=0) + self.assertEqual(self.state(), READY) + self.assertTrue(self.tx()) + self.step(us=0, speed=self.car['speed'] + 2) + self.assertFalse(self.state(PENDING)) + self.assertFalse(self.tx(), 'the same wheel frame cannot carry a second request') + + # ***** frame shape ***** + + def test_frame_must_copy_the_template_with_one_legal_scroll_count(self): + for template in (NEUTRAL, NEUTRAL_BUSY): + with self.subTest(template=template.hex()): + self.start(self.WORD) + self.template = template + for ticks in range(64): + self.step(us=5_000) + self.assertEqual(self.tx(ticks), ticks in TICKS, ticks) + if ticks in TICKS: + self.answer(us=5_000) + self.assertEqual(self.tokens(), TOKENS - len(TICKS)) + self.step() + for bit in range(64): + if bit not in range(24, 30): + data = bytearray(self.frame()) + data[bit // 8] ^= 1 << (bit % 8) + self.assertFalse(self.tx(data=data), bit) + for bus in (0, 2, 3): + self.assertFalse(self.tx(bus=bus), bus) + for length in range(8): + self.assertFalse(self.tx(data=self.frame()[:length]), length) + self.assertFalse(self.tx(data=self.frame() + bytes(4))) + self.assertFalse(self.tx(data=self.template), 'a neutral frame is not a request') + self.assertEqual(self.tokens(), TOKENS - len(TICKS)) + self.assertFalse(self.state(PENDING)) + self.assertTrue(self.tx()) + + def test_frame_built_from_an_older_template_is_refused(self): + self.template = NEUTRAL_BUSY + self.step() + self.assertFalse(self.tx(data=self.frame(template=NEUTRAL))) + self.assertTrue(self.tx()) + + # ***** engagement and vehicle state ***** + + def test_engagement_gates(self): + gates = { + 'controls': (lambda: self.lib.set_controls_allowed(False), self.force_controls), + 'heartbeat': (lambda: self.lib.set_aol_test_heartbeat(False), lambda: self.lib.set_aol_test_heartbeat(True)), + 'relay': (lambda: self.lib.set_relay_malfunction(True), lambda: self.lib.set_relay_malfunction(False)), + 'standstill': (lambda: self.step(standstill=True), lambda: self.step(standstill=False)), + 'stock AEB': (lambda: self.step(aeb=1), lambda: self.step(aeb=0)), + 'door': (lambda: self.step(door=True), lambda: self.step(door=False)), + 'belt': (lambda: self.step(belt=False), lambda: self.step(belt=True)), + } + for gear in (0, 1, 2, 3, 5, 6, 7): + gates[f'gear {gear}'] = (lambda gear=gear: self.step(gear=gear), lambda: self.step(gear=4)) + for name, (fault, clear) in gates.items(): + with self.subTest(gate=name): + self.blocked_until(fault, clear) + self.assertTrue(self.lib.get_controls_allowed()) + + def test_brake_blocks_even_with_controls_forced(self): + def brake(): + self.step(brake=True) + self.assertFalse(self.lib.get_controls_allowed()) + self.force_controls() + + def release(): + self.step(brake=False) + self.force_controls() + self.blocked_until(brake, release) + + def test_required_message_health_is_part_of_every_request(self): + def stale(): + # EPAS3S_sysStatus is a 100 Hz source: older than 100 ms is unhealthy long before it is lagging. + self.step(us=60_000, skip=('EPAS3S_sysStatus',)) + self.step(us=40_001, skip=('EPAS3S_sysStatus',)) + self.assertTrue(self.lib.get_controls_allowed()) + self.blocked_until(stale, self.step) + + def test_stock_lkas_blocks_while_engaged(self): + def stock_lkas(): + self.step(state=1) + self.step(stock_type=2) # rising edge while not engaged latches stock LKAS + self.step(state=2) + self.assertTrue(self.lib.get_controls_allowed()) + self.blocked_until(stock_lkas, lambda: self.step(stock_type=0)) + + def test_autopark_blocks_even_with_controls_forced(self): + def autopark(): + self.step(state=1) + self.step(autopark=3) + self.step(state=2) + self.assertFalse(self.lib.get_controls_allowed()) + self.assertTrue(self.state(ACTIVE)) + self.force_controls() + self.blocked_until(autopark, lambda: self.step(autopark=0)) + + def test_only_enabled_and_override_cruise_states_are_active(self): + for state in (0, 1, 3, 5, 6, 7): + with self.subTest(state=state): + def inactive(state=state): + self.step(state=state) + self.assertFalse(self.state(ACTIVE)) + self.force_controls() + self.blocked_until(inactive, lambda: self.step(state=2)) + + def test_selected_speed_bounds(self): + for refused, admitted in ((2, 3), (508, 507), (0, 4), (511, 506)): + with self.subTest(refused=refused, admitted=admitted): + self.blocked_until(lambda refused=refused: self.step(speed=refused), lambda admitted=admitted: self.step(speed=admitted)) + + # ***** DI_state tracking ***** + + def test_counter_gap_withholds_the_frame_and_the_request(self): + for gap in (0, 2, 15): + with self.subTest(gap=gap): + def skipped(gap=gap): + self.advance(20_000) + self.assertTrue(self.di(counter=(self.counter + gap) % 16, speed=2, state=1, units=1)) + self.assertEqual(self.state(), READY & ~DI_VALID, 'a frame out of sequence updates nothing but the counter') + self.force_controls() # the shared cruise check has no such counter rule + self.blocked_until(skipped, lambda: self.step(speed=120, state=2, units=0)) + self.assertEqual(self.state(), READY | PENDING | SENT) + + def test_out_of_sequence_frame_cannot_release_or_block_a_request(self): + self.assertTrue(self.tx()) + self.advance(20_000) + self.assertTrue(self.di(counter=(self.counter + 5) % 16, speed=130, units=1)) + self.assertEqual(self.state(), (READY & ~DI_VALID) | PENDING | SENT) + self.assertTrue(self.di(speed=120, units=0)) + self.assertEqual(self.state(), READY | PENDING | SENT) + + def test_first_frame_of_a_session_is_taken_whatever_its_counter(self): + self.step() + self.assertEqual(self.counter, 4) + self.assertEqual(self.lib.set_safety_hooks(TESLA, self.WORD), 0) + self.lib.set_aol_test_heartbeat(True) + self.assertEqual(self.state(), ENABLED) + self.advance(20_000) + self.feed(skip=('DI_state',)) + self.assertTrue(self.di(counter=9)) + self.lib.safety_tick() + self.wheel() + self.assertEqual(self.state(), READY) + self.assertTrue(self.tx()) + + def test_gear_and_occupant_tracking(self): + for gear in range(8): + self.step(gear=gear) + self.assertEqual(bool(self.state(DRIVE)), gear == 4, gear) + for door in (False, True): + for belt in (False, True): + self.step(door=door, belt=belt) + self.assertEqual(bool(self.state(OCCUPANT)), belt and not door, (door, belt)) + for state in range(8): + self.step(state=state) + self.assertEqual(bool(self.state(ACTIVE)), state in (2, 4), state) + + # ***** wheel frame tracking ***** + + def test_wheel_frame_is_needed_before_any_request(self): + self.start(self.WORD, ready=False) + for _ in range(3): + self.step(wheel=False) + self.assertEqual(self.state(), READY & ~(SEEN | NEUTRAL_SEEN)) + self.assertFalse(self.tx()) + for bus in (0, 2): + self.wheel(bus=bus) + for address in (0x3C1, 0x3C3, 0x3DF): + self.wheel(address=address) + self.assertEqual(self.state(), READY & ~(SEEN | NEUTRAL_SEEN)) + self.assertFalse(self.tx()) + self.wheel() + self.assertEqual(self.state(), READY) + self.assertTrue(self.tx()) + + def test_malformed_and_other_index_wheel_frames(self): + for length in (*range(8), 12, 16): + with self.subTest(length=length): + self.blocked_until(lambda length=length: self.wheel(data=(NEUTRAL + bytes(8))[:length]), self.wheel) + for index in (2, 3): + with self.subTest(index=index): + def other(index=index): + self.wheel(data=bytes((NEUTRAL[0] & 0xFC | index,)) + NEUTRAL[1:]) + self.assertEqual(self.state(), READY & ~(SEEN | NEUTRAL_SEEN)) + self.blocked_until(other, self.wheel) + + def test_index_zero_frame_is_ignored(self): + self.wheel(data=bytes(8)) + self.wheel(data=bytes((0xFC,)) + bytes(7 * (0xFF,))) + self.assertEqual(self.state(), READY) + self.assertTrue(self.tx()) + # It is not a wheel frame: it neither refreshes the template nor counts as a newer one. + self.advance(20_000) + self.feed(speed=self.car['speed'] + 2) + self.wheel(data=bytes(8)) + self.assertFalse(self.state(PENDING)) + self.assertFalse(self.tx()) + self.wheel() + self.assertTrue(self.tx()) + + def test_any_driver_input_on_the_wheel_refuses_until_neutral_again(self): + checked = (*range(3, 7), *range(8, 22), *range(24, 30), *range(32, 36)) + for bit in range(2, 64): + with self.subTest(bit=bit): + self.start(self.WORD) + self.step() + data = bytearray(NEUTRAL) + data[bit // 8] ^= 1 << (bit % 8) + self.wheel(data=data) + self.assertEqual(bool(self.state(NEUTRAL_SEEN)), bit not in checked) + self.assertTrue(self.state(SEEN)) + if bit in checked: + self.assertFalse(self.tx()) + self.assertFalse(self.tx(data=self.frame(template=data))) + self.wheel() + self.assertTrue(self.tx()) + else: + self.assertFalse(self.tx(), 'the newest neutral frame is the template') + self.assertTrue(self.tx(data=self.frame(template=data))) + + def test_neutral_matches_the_sender_for_every_two_bit_deviation(self): + for first in range(2, 64): + for second in range(first, 64): + data = bytearray(NEUTRAL) + data[first // 8] ^= 1 << (first % 8) + if second != first: + data[second // 8] ^= 1 << (second % 8) + self.wheel(data=data) + self.assertEqual(bool(self.state(NEUTRAL_SEEN)), neutral_wheel(bytes(data)), data.hex()) + self.assertEqual(scroll_request(bytes(data), 1) is not None, neutral_wheel(bytes(data))) + + # ***** freshness ***** + + def test_wheel_frame_is_current_for_250ms(self): + for age, admitted in ((250_000, True), (250_001, False)): + with self.subTest(age=age): + self.start(self.WORD) + self.step() + self.step(us=200_000, wheel=False) + self.advance(age - 200_000) + self.assertEqual(self.tx(), admitted) + if not admitted: + self.assertEqual(self.state(), READY) + self.wheel() + self.assertTrue(self.tx()) + + def test_selected_speed_is_current_for_250ms(self): + for age, admitted in ((250_000, True), (250_001, False)): + with self.subTest(age=age): + self.start(self.WORD) + self.step() + self.step(us=200_000, skip=('DI_state',)) + self.advance(age - 200_000) + self.assertEqual(self.tx(), admitted) + if not admitted: + self.assertEqual(self.state(), READY) + self.assertTrue(self.di()) + self.assertTrue(self.tx()) + + # ***** one request at a time ***** + + def test_request_stays_open_until_the_selected_speed_moves(self): + self.assertTrue(self.tx()) + for _ in range(5): + self.step() + self.assertTrue(self.state(PENDING)) + self.assertFalse(self.tx()) + self.assertEqual(self.tokens(), TOKENS - 1) + self.answer(-1) + self.assertFalse(self.state(PENDING)) + self.assertTrue(self.tx()) + self.assertEqual(self.tokens(), TOKENS - 2) + + def test_unanswered_request_is_released_after_800ms(self): + self.assertTrue(self.tx()) + for _ in range(8): + self.step(us=100_000) + self.assertFalse(self.tx(), 'still open at exactly 800 ms') + self.assertTrue(self.state(PENDING)) + self.advance(1) + self.assertTrue(self.tx()) + self.assertEqual(self.tokens(), TOKENS - 2) + + def test_each_request_needs_a_newer_wheel_frame(self): + self.assertTrue(self.tx()) + self.advance(20_000) + self.feed(speed=self.car['speed'] + 2) + self.assertEqual(self.state(), READY | SENT) + self.assertFalse(self.tx()) + self.advance(1) + self.wheel() + self.assertTrue(self.tx()) + + def test_cruise_off_or_standby_closes_the_request(self): + for state in (0, 1): + with self.subTest(state=state): + self.start(self.WORD) + self.assertTrue(self.tx()) + self.step(state=state) + self.assertEqual(self.state(), READY & ~ACTIVE) + self.step(state=2) + self.assertTrue(self.tx()) + + def test_units_change_during_a_request_blocks_until_cruise_is_off(self): + for release in (0, 1): + for moved in (0, 2): + with self.subTest(release=release, moved=moved): + self.start(self.WORD) + self.assertTrue(self.tx()) + self.step(units=1, speed=self.car['speed'] + moved) + self.assertEqual(self.state(), READY | BLOCKED | SENT | (0 if moved else PENDING)) + self.answer() + for state in (2, 3, 4, 6, 7, 5): + self.step(state=state) + self.assertTrue(self.state(BLOCKED), state) + self.step(state=2) + self.force_controls() + self.assertFalse(self.tx()) + self.assertEqual(self.tokens(), TOKENS - 1) + self.step(state=release) + self.assertFalse(self.state(BLOCKED | PENDING | SENT)) + self.step(state=2) + self.assertTrue(self.tx()) + + def test_units_change_with_no_request_open_does_not_block(self): + self.assertTrue(self.tx()) + self.answer() + self.step(units=1) + self.assertEqual(self.state(), READY | SENT) + self.assertTrue(self.tx()) + self.step(units=1, speed=self.car['speed'] + 2) + self.assertEqual(self.state(), READY | SENT) + + # ***** rate limit ***** + + def burst(self, count): + for sent in range(count): + self.assertTrue(self.tx(), sent) + self.answer(1 if sent % 2 else -1, us=5_000) + + def test_thirty_requests_then_one_per_second(self): + self.step(us=10_000_000) # an idle start earns nothing above the full bucket + start = self.now + self.burst(TOKENS) + self.assertEqual(self.tokens(), 0) + self.assertFalse(self.tx()) + for second in (1, 2, 3): + self.step(us=start + second * 1_000_000 - 1 - self.now, speed=self.car['speed'] + 2) + self.assertFalse(self.tx(), 'one microsecond early') + self.assertEqual(self.tokens(), 0) + self.advance(1) + self.assertTrue(self.tx()) + self.assertEqual(self.tokens(), 0) + # Five idle seconds earn five requests, not a new burst. + self.step(us=start + 8_000_000 - self.now, speed=self.car['speed'] + 2) + self.burst(5) + self.assertFalse(self.tx()) + self.assertEqual(self.tokens(), 0) + # However long the pause, the bucket never holds more than thirty. + self.step(us=600_000_000) + self.burst(TOKENS) + self.assertFalse(self.tx()) + self.assertEqual(self.tokens(), 0) + + def test_refused_attempts_do_not_earn_or_spend_tokens(self): + self.burst(3) + spent = self.now + for _ in range(40): + self.step(us=20_000) + self.assertFalse(self.tx(0)) + self.assertFalse(self.tx(bus=0)) + self.assertLess(self.now - spent, 1_000_000) + self.assertEqual(self.tokens(), TOKENS - 3) + self.assertFalse(self.state(PENDING)) + + def test_timer_wraparound_keeps_every_window(self): + self.start(self.WORD, now=(1 << 32) - 300_000) + self.assertTrue(self.tx()) + for _ in range(8): + self.step(us=100_000) + self.assertGreater(self.now, 1 << 32) + self.assertFalse(self.tx()) + self.advance(1) + self.assertTrue(self.tx()) + self.answer() + self.step(us=200_000, wheel=False) + self.advance(50_001) + self.assertFalse(self.tx()) + self.wheel() + self.assertTrue(self.tx()) + self.assertEqual(self.tokens(), TOKENS - 2, 'three sent, one earned back a second after the first') + + # ***** resets ***** + + def test_reselecting_the_mode_starts_cold(self): + self.assertTrue(self.tx()) + self.step(units=1) + self.assertEqual(self.state(), READY | PENDING | BLOCKED | SENT) + self.assertEqual(self.tokens(), TOKENS - 1) + used = self.frame() + for word in (self.WORD, SYNC | 3329, 1, self.WORD): + with self.subTest(word=word): + self.assertEqual(self.lib.set_safety_hooks(TESLA, word), 0) + self.assertEqual(self.state(), ENABLED if word & SYNC else 0) + self.assertEqual(self.tokens(), TOKENS) + self.lib.set_aol_test_heartbeat(True) + self.force_controls() + self.assertFalse(self.tx(data=used), 'nothing from the last session may be sent') + self.assertFalse(self.hook()) + # A new session needs its own traffic: the required messages, then a wheel frame. + self.advance(20_000) + self.feed(units=0) + self.assertEqual(self.state(), READY & ~(SEEN | NEUTRAL_SEEN)) + self.assertFalse(self.tx(data=used)) + self.wheel() + self.assertTrue(self.tx()) + self.assertEqual(self.tokens(), TOKENS - 1) + + def test_wheel_frame_is_never_forwarded_or_a_relay_fault(self): + self.lib.init_tests() # counts the mode as settled, so relay checks are live + self.lib.set_timer(self.now & 0xFFFFFFFF) + for _ in range(5): + self.step() + self.assertTrue(self.tx()) + self.assertFalse(self.lib.get_relay_malfunction()) + self.assertEqual([self.lib.safety_fwd_hook(bus, WHEEL) for bus in range(3)], [2, -1, 0]) + + +class TestTeslaSpeedSyncScreenAol(TestTeslaSpeedSync): + """The same request rules on a screen AOL word with its opt-in saved, as most cars in the field will run.""" + WORD = SYNC | 1793 + EXPERIENCE = 32 + + +class TestTeslaSpeedSyncOrdinaryAol(TestTeslaSpeedSync): + """The same request rules on an ordinary AOL word with its opt-in saved.""" + WORD = SYNC | 3329 + EXPERIENCE = 32 + + +if __name__ == "__main__": + unittest.main() diff --git a/openpilot/cereal/custom.capnp b/openpilot/cereal/custom.capnp index fce25ca2c8..30e5b62ee6 100644 --- a/openpilot/cereal/custom.capnp +++ b/openpilot/cereal/custom.capnp @@ -480,6 +480,21 @@ struct SlcAction @0x9ccdc8676701b412 { sourceCarStateMonoTime @10 :UInt64; carParamsFingerprint @11 :Text; targetSpeedMps @12 :Float32; + stepUnits @13 :Int8; # Tesla scroll: +-1 display unit, or +-5 to the next multiple of five + sourceTeslaGesture @14 :TeslaGesture; # optional Tesla wheel-gesture provenance; never an action + } + + struct TeslaGesture { + version @0 :UInt16; + workerSession @1 :Text; + sequence @2 :UInt64; + sourceCanBootTime @3 :UInt64; + sourceCanFrameIndex @4 :UInt16; + name @5 :Text; + fast @6 :Bool; + assignmentsHash @7 :Text; + vehicleHash @8 :Text; + driveStartMonoTime @9 :UInt64; } struct ConditionalManualAction { @@ -512,6 +527,7 @@ struct SlcAction @0x9ccdc8676701b412 { forceCoastToggle @10; pulseGlideToggle @11; disengageRequest @12; + cruiseStep @13; } } diff --git a/openpilot/common/params_keys.h b/openpilot/common/params_keys.h index d1d4fd3f34..e75a2cc2b3 100644 --- a/openpilot/common/params_keys.h +++ b/openpilot/common/params_keys.h @@ -85,8 +85,10 @@ inline static std::unordered_map keys = { {"UsageStatsState", {PERSISTENT | DONT_LOG, JSON}}, {"UsageStatsStatus", {CLEAR_ON_MANAGER_START | DONT_LOG, JSON}}, {"TeslaCoopSteering", {PERSISTENT, BOOL, "0"}}, - {"TeslaAOLScreenTap", {PERSISTENT, BOOL, "0"}}, + {"TeslaAOLScreenTap", {PERSISTENT, BOOL, "1"}}, {"TeslaAOLDisengageOnBrake", {PERSISTENT, BOOL, "0"}}, + {"TeslaSpeedSync", {PERSISTENT, BOOL, "0"}}, + {"CarControlAssignments", {PERSISTENT | DONT_LOG, JSON}}, {"ForceStopDistanceOffset", {PERSISTENT, INT, "0"}}, {"LeadApproachBuffer", {PERSISTENT, BOOL, "0"}}, {"FasterLeadTakeoff", {PERSISTENT, BOOL, "0"}}, diff --git a/openpilot/selfdrive/car/card.py b/openpilot/selfdrive/car/card.py index 6e4df80686..6531740324 100644 --- a/openpilot/selfdrive/car/card.py +++ b/openpilot/selfdrive/car/card.py @@ -34,7 +34,7 @@ from opendbc.car.hyundai.values import CAR as HYUNDAI_CAR from opendbc.car.interfaces import CarInterfaceBase, RadarInterfaceBase from openpilot.selfdrive.pandad import can_capnp_to_list, can_list_to_can_capnp from openpilot.selfdrive.car.cruise import LOW_SPEED_CRUISE_ON_SET, SlcWheelContext, VCruiseHelper, slc_target_kph -from openpilot.starpilot.speed_limits import physical_actions as slc_physical +from openpilot.starpilot.speed_limits import physical_actions as slc_physical, tesla_set_speed_card from openpilot.starpilot.aol.intent import AolProcessFaultContext, independent_axis_requested, read_settings from openpilot.starpilot.aol.transport_pause import TransportPauseFeedback, cp_identity from opendbc.car.honda.stock_aol import qualified as qualified_honda_stock_aol, native_observation as honda_native_observation @@ -453,6 +453,7 @@ class Car: self.controller_cruise_consumer = CruiseActionConsumer() self.controller_cruise_sock = messaging.sub_sock('slcAction', conflate=False) if cruise_action_eligible(self.CP) else None self.v_cruise_helper = VCruiseHelper(self.CP) + self.slc_set_speed = tesla_set_speed_card.attach(self) self.v_cruise_helper.intervals = read_cruise_intervals(self.params, self.CP) self.experimental_mode = self.params.get_bool("ExperimentalMode") @@ -592,7 +593,8 @@ class Car: break self.controller_cruise_consumer.apply(request, self.CP, CS, self.sm, self.v_cruise_helper, now_ns=now_ns, is_metric=self.is_metric, - enabled=bool(host_control_enabled and can_rcv_valid and not self.params.get_bool("SafeMode"))) + enabled=bool((host_control_enabled or cruise_helper.tesla_set_speed and host_enabled) and + can_rcv_valid and not self.params.get_bool("SafeMode"))) if self.slc_replay: self.apply_slc_adopt(now_ns, host_control_enabled=host_control_enabled, after_ns=floor_ns) consumed = self.v_cruise_helper.slc_consumed_button @@ -809,6 +811,7 @@ class Car: slc_replay=self.slc_replay, host_long_active=host_long_active, observed_ns=now_ns) if curve_receipt is not None: self.slc_receipts.append(curve_receipt) + tesla_set_speed_card.apply_commands(self, CS, observation, now_ns, long_active=slc_long_active, after_ns=floor_ns) blocked_keys = set() if self.manual_receipt is not None: blocked_keys.add(key_for(self.manual_receipt[0])) @@ -851,8 +854,9 @@ class Car: if self.sm['carControl'].enabled and not self.CC_prev.enabled: target, initial = None, None now_ns = int(self.can_log_mono_time) if REPLAY and hasattr(self, 'can_log_mono_time') else time.monotonic_ns() - if (getattr(self, 'slc_match_on_engage', False) and getattr(self, 'slc_control_enabled', False) and - not self.CP.pcmCruise and self.CP.openpilotLongitudinalControl and + rule = tesla_set_speed_card.rule(self) + if ((rule or getattr(self, 'slc_match_on_engage', False) and not self.CP.pcmCruise) and + getattr(self, 'slc_control_enabled', False) and self.CP.openpilotLongitudinalControl and CS.canValid and not CS.canTimeout and CS.cruiseState.available and self.sm.valid['carControl'] and self.sm.alive['carControl'] and 0 < int(self.sm.logMonoTime['carControl']) <= now_ns and @@ -866,7 +870,7 @@ class Car: evidence = getattr(self.CI.CS, 'dashboard_limit', None) target, initial = slc_physical.engagement_target( self.sm, evidence.observation if evidence is not None else None, self.slc_producer_session, - now_ns, after_ns=getattr(self, 'slc_source_floor_ns', 0)) + now_ns, after_ns=getattr(self, 'slc_source_floor_ns', 0), current_only=rule) adopted = self.v_cruise_helper.initialize_v_cruise( self.CS_prev, self.experimental_mode, resume=self.vehicle_startup.consume_cruise_resume(), initial_speed=self.initial_cruise_speed, slc_target_mps=target, is_metric=self.is_metric) @@ -1235,6 +1239,8 @@ class Car: record.decisionId = int(detail.decisionId) record.presentationId = int(detail.presentationId) record.button = 'decel' + else: + tesla_set_speed_card.write_receipt(record, kind, detail) self.pm.send('slcCruiseEvent', event) if getattr(self, 'conditional_replay', False) and self.manual_receipt is not None: @@ -1891,6 +1897,9 @@ class Car: self.can_log_mono_time if REPLAY else time.clock_gettime_ns(time.CLOCK_BOOTTIME) if self.volt_startup_keepalive() or monitored_steering else int(time.monotonic() * 1e9)) + if getattr(self.CI.CC, "speed_sync", None) is not None: + from openpilot.starpilot.car.tesla_speed_sync_context import publish_context + publish_context(self, CS) learning_snapshot = None try: from openpilot.starpilot.flm.evidence_hooks import begin_applied_frame, applied_snapshot @@ -1989,6 +1998,7 @@ class Car: if getattr(self, 'slc_transport_available', False): self.slc_match_on_engage = self.read_slc_match_on_engage() self.v_cruise_helper.intervals = read_cruise_intervals(self.params, self.CP) + tesla_set_speed_card.refresh(self) for name in ('bluepilot_inputs', 'hands_free_cluster_input'): source = getattr(self.CI.CC, name, None) if source is not None: diff --git a/openpilot/selfdrive/car/cruise.py b/openpilot/selfdrive/car/cruise.py index e026d8a1ad..902dcd0a5b 100644 --- a/openpilot/selfdrive/car/cruise.py +++ b/openpilot/selfdrive/car/cruise.py @@ -63,6 +63,11 @@ class VCruiseHelper: self.CP = CP from opendbc.car.hyundai.software_cruise import selected as hyundai_software_selected self.hyundai_software_cruise = hyundai_software_selected(CP) + # Tesla Model 3/Y with Comma can set speed on Tesla dashboard on: the comma owns SET and the car's is scrolled to + # match. Card keeps this current from the saved switch (speed_limits/tesla_set_speed_card.py). + self.tesla_set_speed = False + self.tesla_pedal_hold = False # After an accelerator override: Hold the speed you reached, applied by card there + self.slc_pcm = False # live Speed Limit Controller writes SET on that Tesla self.intervals = CruiseIntervals() self.low_speed_on_set = False self.v_cruise_kph = V_CRUISE_UNSET @@ -88,8 +93,9 @@ class VCruiseHelper: def update_v_cruise(self, CS, enabled, is_metric, slc_pending: SlcPendingConfirmation | None = None, *, slc_enabled: bool = False, wheel_context: SlcWheelContext | None = None): from opendbc.car.subaru.software_cruise import selected as subaru_software_selected - stock_software = subaru_software_selected(self.CP) or self.hyundai_software_cruise + stock_software = subaru_software_selected(self.CP) or self.hyundai_software_cruise or self.tesla_set_speed software_cruise = not self.CP.pcmCruise or stock_software + self.slc_pcm = bool(slc_enabled and self.tesla_set_speed) self.slc_cruise_change = None self.slc_consumed_button = None self.slc_released_suppressed = False @@ -242,7 +248,7 @@ class VCruiseHelper: def adjust_v_cruise(self, button_type, CS, is_metric: bool, *, long_press: bool = False) -> bool: """Apply the normal software cruise step without synthesizing button events.""" from opendbc.car.subaru.software_cruise import selected as subaru_software_selected - stock_software = subaru_software_selected(self.CP) or self.hyundai_software_cruise + stock_software = subaru_software_selected(self.CP) or self.hyundai_software_cruise or self.tesla_set_speed if ((self.CP.pcmCruise and not stock_software) or button_type not in (ButtonType.accelCruise, ButtonType.decelCruise) or not 0 < self.v_cruise_kph < V_CRUISE_UNSET or (button_type == ButtonType.accelCruise and CS.cruiseState.standstill)): @@ -298,8 +304,9 @@ class VCruiseHelper: if (not self.CP.openpilotLongitudinalControl or slc_target_mps is None or type(slc_target_mps) not in (int, float) or not math.isfinite(slc_target_mps) or not V_CRUISE_MIN / 3.6 - 1e-5 <= slc_target_mps <= V_CRUISE_MAX / 3.6 + 1e-5): slc_target_mps = None - # Native cruise owns PCM SET, including when SLC supplies a planner cap. - if self.CP.pcmCruise: + # Native cruise owns PCM SET, including when SLC supplies a planner cap. On a Tesla where SLC writes SET (slc_pcm), + # engaging starts SET at the current limit. + if self.CP.pcmCruise and (not self.slc_pcm or slc_target_mps is None): return False # A car-owned acknowledgment can outlive the physical button event. if resume is None: @@ -307,7 +314,7 @@ class VCruiseHelper: resume = (0 < self.pending_resume_ns and 0 <= age <= 500_000_000) or any( b.type in (ButtonType.accelCruise, ButtonType.resumeCruise) for b in CS.buttonEvents) self.pending_resume_ns = 0 - if resume and self.v_cruise_initialized: + if resume and self.v_cruise_initialized and not (self.slc_pcm and slc_target_mps is not None): self.v_cruise_kph = self.v_cruise_kph_last self.v_cruise_cluster_kph = self.v_cruise_kph return False diff --git a/openpilot/selfdrive/pandad/tests/test_aol_protocol.cc b/openpilot/selfdrive/pandad/tests/test_aol_protocol.cc index b75f7c24de..13ec154f25 100644 --- a/openpilot/selfdrive/pandad/tests/test_aol_protocol.cc +++ b/openpilot/selfdrive/pandad/tests/test_aol_protocol.cc @@ -263,30 +263,46 @@ int main() { } constexpr uint16_t tesla_screen_words[] = {512U, 513U, 768U, 769U, 1536U, 1537U, 1792U, 1793U, 2048U, 2049U, 2304U, 2305U, 3072U, 3073U, 3328U, 3329U}; + // Scroll speed sync (4096) rides on any of those words that carries longitudinal control (bit 1), and on no other. + constexpr uint16_t tesla_speed_sync = 4096U; + unsigned tesla_capable_words = 0U; for (uint32_t word = 0U; word <= 65535U; ++word) { bool expected = false; - for (const auto exact : tesla_screen_words) expected |= word == exact; + for (const auto exact : tesla_screen_words) { + expected |= word == exact; + expected |= ((exact & 1U) != 0U) && (word == (exact | tesla_speed_sync)); + } + assert(tesla_screen_aol_param(static_cast(word)) == expected); auto tesla = status(); tesla.safety_mode = 10U; tesla.safety_param = static_cast(word); assert(aol_capable(tesla, 10U, VEHICLE_REGISTRY) == expected); + tesla_capable_words += expected ? 1U : 0U; } - for (const auto word : tesla_screen_words) { - AolAxisNegotiator negotiator(VEHICLE_REGISTRY); - FakeTransport transport; - auto tesla = status(); - tesla.safety_mode = 10U; - tesla.safety_param = word; - queue(transport, tesla, tesla); - auto neutral = run(negotiator, transport, axis("tesla-screen", false, false), NOW, 10U); - assert(neutral.plan.capable && neutral.plan.request_mask == 0U && neutral.outcome.compatible); - auto active = tesla; - active.request_mask = 1U; - active.permission_mask = 1U; - queue(transport, tesla, active); - auto engaged = run(negotiator, transport, axis("tesla-screen", true, false), NOW, 10U); - assert(engaged.plan.request_mask == 1U && engaged.outcome.compatible); - assert(engaged.outcome.status && engaged.outcome.status->safety_param == word && engaged.outcome.status->permission_mask == 1U); + assert(tesla_capable_words == 24U); + for (const uint16_t rejected : {uint16_t{4096U}, uint16_t{4097U}, uint16_t{4353U}, uint16_t{4608U}, uint16_t{6144U}, uint16_t{8192U | 513U}}) { + assert(!tesla_screen_aol_param(rejected)); + } + for (const auto screen_word : tesla_screen_words) { + for (const bool speed_sync : {false, true}) { + if (speed_sync && (screen_word & 1U) == 0U) continue; + const uint16_t word = speed_sync ? static_cast(screen_word | tesla_speed_sync) : screen_word; + AolAxisNegotiator negotiator(VEHICLE_REGISTRY); + FakeTransport transport; + auto tesla = status(); + tesla.safety_mode = 10U; + tesla.safety_param = word; + queue(transport, tesla, tesla); + auto neutral = run(negotiator, transport, axis("tesla-screen", false, false), NOW, 10U); + assert(neutral.plan.capable && neutral.plan.request_mask == 0U && neutral.outcome.compatible); + auto active = tesla; + active.request_mask = 1U; + active.permission_mask = 1U; + queue(transport, tesla, active); + auto engaged = run(negotiator, transport, axis("tesla-screen", true, false), NOW, 10U); + assert(engaged.plan.request_mask == 1U && engaged.outcome.compatible); + assert(engaged.outcome.status && engaged.outcome.status->safety_param == word && engaged.outcome.status->permission_mask == 1U); + } } AolAxisNegotiator ford_pause(VEHICLE_REGISTRY); FakeTransport ford_transport; diff --git a/openpilot/selfdrive/ui/ui.py b/openpilot/selfdrive/ui/ui.py index 2fe9c2ac73..f9f9819ac2 100755 --- a/openpilot/selfdrive/ui/ui.py +++ b/openpilot/selfdrive/ui/ui.py @@ -72,7 +72,10 @@ def main(): borrowed_messages=True, evidence_wait_ms=0) controllers = None if ui_state.replay_clock is not None else ControllerRuntime(ui_state.params, actions=layout.star._favorite_actions, favorites=layout.star.favorites_owner.snapshot, - invoke_favorite=layout.star.favorites_owner.invoke, authority=controller_authority, input_capture=game_input) + invoke_favorite=layout.star.favorites_owner.invoke, authority=controller_authority, input_capture=game_input, + vehicle=lambda: ui_state.CP, messages=lambda: ui_state.sm, + speed_actions=getattr(layout.star, '_comma_speed_actions', None), + keyed_actions=getattr(layout.star, '_favorite_render_actions', None)) preview = None if ui_state.replay_clock is not None else LayoutPreviewRuntime(ui_state.params, (Profile.LARGE if BIG_UI else Profile.COMPACT).value, offroad_hint=ui_state.is_offroad, authority=preview_authority) else: diff --git a/openpilot/starpilot/car/tesla/aol.py b/openpilot/starpilot/car/tesla/aol.py index 798472f6d1..dc8b32a3bd 100644 --- a/openpilot/starpilot/car/tesla/aol.py +++ b/openpilot/starpilot/car/tesla/aol.py @@ -2,7 +2,7 @@ from opendbc.car import structs from opendbc.car.tesla.preap.aol import qualified, temporary_restriction as preap_temporary_restriction from openpilot.starpilot.aol.policy import AolVehiclePolicy from openpilot.starpilot.car.tesla.stock_intent import TeslaPreapCardIntent -from opendbc.car.tesla.screen_button import modern_aol_supported, modern_aol_qualified, AOL_WORDS +from opendbc.car.tesla.screen_button import modern_aol_supported, modern_aol_qualified, AOL_WORDS, SPEED_SYNC, SYNC_WORDS from openpilot.starpilot.car.tesla.screen_intent import TeslaScreenCardIntent @@ -25,7 +25,9 @@ def policy_for(cp): def native_profile_supported(model, param): - return (model == 39 and param in (0, 1, 2, 3, 6, 7)) or (model == 10 and param in AOL_WORDS) + # Scroll speed sync rides on top of an Always On Lateral word; the panda reports the whole word. + screen = param & ~SPEED_SYNC if param in SYNC_WORDS else param + return (model == 39 and param in (0, 1, 2, 3, 6, 7)) or (model == 10 and screen in AOL_WORDS) def native_accepts_cp(cp, model, param): diff --git a/openpilot/starpilot/car/tesla/aol_policy.h b/openpilot/starpilot/car/tesla/aol_policy.h index 15abe25de8..cda49c57cb 100644 --- a/openpilot/starpilot/car/tesla/aol_policy.h +++ b/openpilot/starpilot/car/tesla/aol_policy.h @@ -10,6 +10,11 @@ inline constexpr AolSafetyProfile TESLA_PREAP_AOL_PROFILE{39U, tesla_preap_aol_p inline bool tesla_screen_aol_param(uint16_t param) { param &= ~256U; + // Scroll speed sync (4096) rides on a word with longitudinal control; Always On Lateral sees the word without it, + // as the panda's own screen policy does. + if (((param & 4096U) != 0U) && ((param & 1U) != 0U)) { + param &= ~4096U; + } return param == 512U || param == 513U || param == 1536U || param == 1537U || param == 2048U || param == 2049U || param == 3072U || param == 3073U; } diff --git a/openpilot/starpilot/car/tesla/coop_preferences.py b/openpilot/starpilot/car/tesla/coop_preferences.py index b9f2c025bb..da92456e94 100644 --- a/openpilot/starpilot/car/tesla/coop_preferences.py +++ b/openpilot/starpilot/car/tesla/coop_preferences.py @@ -1,4 +1,5 @@ """Frozen Model 3/Y cooperative steering selection.""" +from opendbc.car.tesla.screen_button import SPEED_SYNC, speed_sync_allowed from opendbc.car.tesla.values import CAR, TeslaSafetyFlags, TeslaFlags @@ -9,6 +10,11 @@ def supported(cp): cp.flags & ~int(TeslaFlags.MISSING_DAS_SETTINGS | TeslaFlags.HAS_VEHICLE_BUS | TeslaFlags.AOL_SCREEN_BUTTON)): return False word = int(cp.safetyConfigs[0].safetyParam) + # Scroll speed sync rides on top of the cooperative word (e.g. 4353 = 4096 | 256 | 1); it is stripped before the check. + if word & SPEED_SYNC: + if not speed_sync_allowed(cp, word): + return False + word &= ~SPEED_SYNC return (word in (0, 1, 256, 257, 512, 513, 768, 769, 1536, 1537, 1792, 1793, 2048, 2049, 2304, 2305, 3072, 3073, 3328, 3329) and bool(word & 1) == bool(cp.openpilotLongitudinalControl)) except (AttributeError, TypeError, ValueError, IndexError): diff --git a/openpilot/starpilot/car/tesla/set_speed.py b/openpilot/starpilot/car/tesla/set_speed.py new file mode 100644 index 0000000000..82dafb69fd --- /dev/null +++ b/openpilot/starpilot/car/tesla/set_speed.py @@ -0,0 +1,48 @@ +"""Comma can set speed on Tesla dashboard: the saved switch, followed while the car is on. + +The car's parameters only say whether the panda admits the scroll frame (opendbc.car.tesla.speed_sync.selected, fixed +when the car starts). Whether the comma owns the set speed follows the saved switch: card, the planner's Speed Limit +Controller and the screen each read it here about once a second, so a change takes effect without a restart. For up to +a second the processes can differ. If card follows first, the limit still caps the comma's set speed. If the planner +follows first, the limit neither caps nor is written until card follows, so the car holds the Tesla's own set speed +for that moment. The switch can only be changed while parked, so neither happens while driving unless Safe Mode is +toggled. +""" +import time + +from opendbc.car.tesla.speed_sync import selected +from openpilot.starpilot.saved_source import read_saved + +PARAM = 'TeslaSpeedSync' + + +def requested(params) -> bool: + """The switch is saved on, and Safe Mode is off.""" + return bool(read_saved(params, PARAM, 8) == (b'1', True) and + read_saved(params, 'SafeMode', 8) in ((None, True), (b'0', True))) + + +def active(params, cp) -> bool: + """The comma owns the set speed on this car now: a Tesla Model 3/Y that started with the scroll frame admitted, with + the switch on. False for every other car without reading anything.""" + try: + return bool(selected(cp) and requested(params)) + except (AttributeError, TypeError, ValueError, OSError): + return False + + +class Polled: + """active(), read from storage at most once a second: for loops that ask many times a second.""" + + def __init__(self, params, clock=time.monotonic): + self.params, self.clock = params, clock + self.read_at = None + self.value = False + + def __call__(self, cp) -> bool: + if not selected(cp): + return False + now = self.clock() + if self.read_at is None or not 0 <= now - self.read_at < 1.: + self.read_at, self.value = now, requested(self.params) + return self.value diff --git a/openpilot/starpilot/car/tesla/tests/fixtures/custom_reviewed_schema_additions.json b/openpilot/starpilot/car/tesla/tests/fixtures/custom_reviewed_schema_additions.json index 285b013596..cb14a2d7cb 100644 --- a/openpilot/starpilot/car/tesla/tests/fixtures/custom_reviewed_schema_additions.json +++ b/openpilot/starpilot/car/tesla/tests/fixtures/custom_reviewed_schema_additions.json @@ -1096,6 +1096,82 @@ } } ] + }, + "0xb539e7c0aa8c1e69": { + "kind": "struct", + "before_name": "SlcAction.ControllerCruiseAction", + "after_name": "SlcAction.ControllerCruiseAction", + "old_field_count": 13, + "old_storage": { + "dataWordCount": 7, + "pointerCount": 4, + "preferredListEncoding": "inlineComposite", + "isGroup": false, + "discriminantCount": 0, + "discriminantOffset": 0 + }, + "new_storage": { + "dataWordCount": 7, + "pointerCount": 5, + "preferredListEncoding": "inlineComposite", + "isGroup": false, + "discriminantCount": 0, + "discriminantOffset": 0 + }, + "added_fields": [ + { + "slot": { + "offset": 3, + "type": { + "int8": null + }, + "defaultValue": { + "int8": 0 + }, + "hadExplicitDefault": false + }, + "name": "stepUnits", + "codeOrder": 13, + "discriminantValue": 65535, + "ordinal": { + "explicit": 13 + } + }, + { + "slot": { + "offset": 4, + "type": { + "struct": { + "typeId": 18362708538740964012 + } + }, + "defaultValue": { + "schemaValueHex": "00000000040000000000000002000100100000000000000000000000000000000000000000000000" + }, + "hadExplicitDefault": false + }, + "name": "sourceTeslaGesture", + "codeOrder": 14, + "discriminantValue": 65535, + "ordinal": { + "explicit": 14 + } + } + ] + }, + "0xb8cbd9e666181b95": { + "kind": "enum", + "before_name": "SlcAction.Kind", + "after_name": "SlcAction.Kind", + "old_field_count": 13, + "old_storage": {}, + "new_storage": {}, + "added_enumerants": [ + { + "name": "cruiseStep", + "codeOrder": 13 + } + ] } }, "published_addition_commits": { diff --git a/openpilot/starpilot/car/tesla/tests/test_aol_speed_sync_words.py b/openpilot/starpilot/car/tesla/tests/test_aol_speed_sync_words.py new file mode 100644 index 0000000000..2856473732 --- /dev/null +++ b/openpilot/starpilot/car/tesla/tests/test_aol_speed_sync_words.py @@ -0,0 +1,119 @@ +"""Always On Lateral on a Tesla Model 3/Y that started with the scroll frame admitted: the panda reports the whole +safety word, speed-sync bit included, and Always On Lateral must accept it exactly where it accepted the word without.""" +from pathlib import Path +import re + +import pytest +from opendbc.car.tesla.screen_button import (AOL_WORDS, ORDINARY_WORDS, SCREEN_WORDS, SPEED_SYNC, SYNC_WORDS, apply_modern_aol, + modern_aol_qualified, modern_aol_supported) +from opendbc.car.tesla.speed_sync import prepare as admit_scroll_frame, selected +from openpilot.starpilot.aol import vehicle +from openpilot.starpilot.car.tesla import aol +from openpilot.starpilot.car.tesla.coop_preferences import prepare as apply_cooperative +from openpilot.starpilot.tests.tesla_set_speed_fixture import tesla + +TESLA, PREAP = 10, 39 +# Every Always On Lateral word: the screen tap (512) or ordinary (2048), with brake disengage (1024), co-op steering +# (256) and longitudinal control (1) or not. +EVERY_AOL_WORD = sorted(AOL_WORDS) +WITH_SPEED_SYNC = sorted(SPEED_SYNC | word for word in AOL_WORDS if word & 1) +HEADER = Path(__file__).resolve().parents[1] / 'aol_policy.h' + + +def test_the_word_lists_are_the_sixteen_always_on_lateral_words(): + assert SPEED_SYNC == 4096 and len(EVERY_AOL_WORD) == 16 and len(WITH_SPEED_SYNC) == 8 + assert AOL_WORDS == SCREEN_WORDS | ORDINARY_WORDS + assert set(WITH_SPEED_SYNC) == SYNC_WORDS - {4097, 4353}, 'every speed-sync word but the two without Always On Lateral' + + +@pytest.mark.parametrize('word', EVERY_AOL_WORD) +def test_every_always_on_lateral_word_is_accepted_with_and_without_the_speed_sync_bit(word): + assert aol.native_profile_supported(TESLA, word) and vehicle.native_profile_supported(TESLA, word) + with_sync = word | SPEED_SYNC + assert aol.native_profile_supported(TESLA, with_sync) is bool(word & 1), 'the bit needs longitudinal control' + assert vehicle.native_profile_supported(TESLA, with_sync) is bool(word & 1) + assert not aol.native_profile_supported(PREAP, with_sync) + + +def test_no_other_word_is_accepted(): + accepted = {word for word in range(65536) if aol.native_profile_supported(TESLA, word)} + assert accepted == set(EVERY_AOL_WORD) | set(WITH_SPEED_SYNC) + assert {word for word in range(65536) if aol.native_profile_supported(PREAP, word)} == {0, 1, 2, 3, 6, 7} + + +@pytest.mark.parametrize('word', [4096, 4097, 4353, 4096 | 256, 4096 | 512, 4096 | 768, 4096 | 1536, 4096 | 2048, 4096 | 2304, + 4096 | 3072, 4096 | 513 | 2048, 4096 | 513 | 2, 8192 | 513, 4096 | 8192 | 513]) +def test_the_bit_on_a_word_without_always_on_lateral_or_without_longitudinal_control_is_rejected(word): + assert not aol.native_profile_supported(TESLA, word) + assert not vehicle.native_profile_supported(TESLA, word) + + +def header_accepts(word): + """tesla_screen_aol_param in the pandad header, read from its text: co-op steering is ignored, the speed-sync bit is + dropped from a word with longitudinal control, and what is left must be one of the listed words.""" + text = HEADER.read_text() + body = text[text.index('inline bool tesla_screen_aol_param'):text.index('TESLA_SCREEN_AOL_PROFILE')] + assert 'param &= ~256U;' in body + assert re.search(r'if \(\(\(param & 4096U\) != 0U\) && \(\(param & 1U\) != 0U\)\) \{\s*param &= ~4096U;\s*\}', body) + listed = {int(value) for value in re.findall(r'param == (\d+)U', body)} + word &= ~256 + if word & 4096 and word & 1: + word &= ~4096 + return word in listed + + +def test_the_pandad_header_accepts_exactly_the_same_words(): + assert {word for word in range(65536) if header_accepts(word)} == set(EVERY_AOL_WORD) | set(WITH_SPEED_SYNC) + + +def model_3(*, screen, brake=False, coop=True): + """A Model 3 as startup leaves it with Always On Lateral on: the scroll frame admitted, marked for the panda.""" + cp = tesla(selected=True) + apply_modern_aol(cp, True, screen, brake) + apply_cooperative(cp, coop) + admit_scroll_frame(cp, True) + cp.alternativeExperience = 32 + return cp + + +@pytest.mark.parametrize('screen,word', [(False, 4096 | 2305), (True, 4096 | 769)]) +def test_a_model_3_with_the_speed_sync_bit_is_matched_to_the_word_the_panda_reports(screen, word): + cp = model_3(screen=screen) + assert int(cp.safetyConfigs[0].safetyParam) == word and selected(cp) + assert modern_aol_supported(cp) and modern_aol_qualified(cp, marked_only=True) + assert aol.native_accepts_cp(cp, TESLA, word) + assert vehicle.native_matches_cp(cp, TESLA, word) + policy = aol.policy_for(cp) + assert policy.intent_supported and policy.runtime_supported and policy.alternative_experience_addition == 32 + for other in (word & ~SPEED_SYNC, word & ~256, word ^ 1024, word | 2, 4097): + assert not aol.native_accepts_cp(cp, TESLA, other), other + assert not vehicle.native_matches_cp(cp, TESLA, other), other + assert not aol.native_accepts_cp(cp, PREAP, word) and not vehicle.native_matches_cp(cp, PREAP, word) + + +@pytest.mark.parametrize('screen', [False, True]) +@pytest.mark.parametrize('brake', [False, True]) +@pytest.mark.parametrize('coop', [False, True]) +@pytest.mark.parametrize('model', ['TESLA_MODEL_3', 'TESLA_MODEL_Y']) +def test_every_startup_combination_with_the_bit_is_matched(model, screen, brake, coop): + cp = tesla(model, selected=True) + apply_modern_aol(cp, True, screen, brake) + apply_cooperative(cp, coop) + cp.alternativeExperience = 32 + word = int(cp.safetyConfigs[0].safetyParam) + assert word & SPEED_SYNC and word in WITH_SPEED_SYNC + assert aol.native_accepts_cp(cp, TESLA, word) and vehicle.native_matches_cp(cp, TESLA, word) + without = tesla(model) + apply_modern_aol(without, True, screen, brake) + apply_cooperative(without, coop) + without.alternativeExperience = 32 + assert int(without.safetyConfigs[0].safetyParam) == word & ~SPEED_SYNC + assert aol.native_accepts_cp(without, TESLA, word & ~SPEED_SYNC), 'as before, without the bit' + assert not aol.native_accepts_cp(without, TESLA, word), "never a word the car's parameters do not carry" + + +def test_without_always_on_lateral_the_bit_alone_is_not_an_always_on_lateral_profile(): + cp = tesla(selected=True) + apply_cooperative(cp, True) + assert int(cp.safetyConfigs[0].safetyParam) == 4353 + assert not aol.native_accepts_cp(cp, TESLA, 4353) and not vehicle.native_matches_cp(cp, TESLA, 4353) diff --git a/openpilot/starpilot/car/tesla/tests/test_ordinary_aol.py b/openpilot/starpilot/car/tesla/tests/test_ordinary_aol.py index 19939a759a..f5cc286671 100644 --- a/openpilot/starpilot/car/tesla/tests/test_ordinary_aol.py +++ b/openpilot/starpilot/car/tesla/tests/test_ordinary_aol.py @@ -92,8 +92,9 @@ def test_actual_ui_master_and_brake_toggle_with_either_harness(tmp_path, harness gateway = SettingsGateway(params, owner, clock=lambda: 100.0) page = gateway.page('vehicle', 'session', b'generation') labels = {row['label'] for row in page['rows']} - assert 'Disengage AOL on Brake' in labels - assert ('Three-Finger AOL Tap' in labels) is harness + assert 'Disengage AOL on Brake' in labels and 'Three-Finger AOL Tap' not in labels + tap = next(row for row in gateway.page('wheel', 'session', b'generation')['rows'] if row['label'] == 'Tesla screen / Three-finger tap') + assert ('Always On Lateral on/off' in tap['choices']) is harness, 'the tap is chosen in Wheel Controls, and needs the harness' aol = gateway.page('aol', 'session', b'generation') assert next(row for row in aol['rows'] if row['label'] == 'Enable Always On Lateral')['available'] index = next(i for i, row in enumerate(page['rows']) if row['label'] == 'Disengage AOL on Brake') diff --git a/openpilot/starpilot/car/tesla/tests/test_screen_recovery_callers.py b/openpilot/starpilot/car/tesla/tests/test_screen_recovery_callers.py index 6a023175ac..b7a55452d1 100644 --- a/openpilot/starpilot/car/tesla/tests/test_screen_recovery_callers.py +++ b/openpilot/starpilot/car/tesla/tests/test_screen_recovery_callers.py @@ -143,7 +143,8 @@ class Exercise(unittest.TestCase): else: selected = start_card(screen_params(platform, marker, longitudinal=longitudinal, release=release)) cp, ci = selected.CP, selected.CI - self.assertEqual(cp.safetyConfigs[0].safetyParam, (1536 if brake_option else 512) + int(cp.openpilotLongitudinalControl)) + # Startup also admits the scroll speed sync frame (4096) on a car with the cable and StarPilot longitudinal. + self.assertEqual(cp.safetyConfigs[0].safetyParam, (1536 if brake_option else 512) + (4097 if cp.openpilotLongitudinalControl else 0)) self.assertEqual(cp.alternativeExperience, 32) self.assertEqual(cp.openpilotLongitudinalControl, longitudinal and not release) self.assertTrue(cp.pcmCruise) diff --git a/openpilot/starpilot/car/tesla/tests/test_screen_tap_default.py b/openpilot/starpilot/car/tesla/tests/test_screen_tap_default.py new file mode 100644 index 0000000000..e8deb7e21e --- /dev/null +++ b/openpilot/starpilot/car/tesla/tests/test_screen_tap_default.py @@ -0,0 +1,56 @@ +"""The three-finger tap starts on Always On Lateral on/off: its saved switch (TeslaAOLScreenTap) is on by default, and it +only does anything on a Model 3/Y with the CAN add-on cable and Always On Lateral turned on.""" +import pytest +from opendbc.car.tesla.screen_button import ORDINARY_WORDS, SCREEN_WORDS +from opendbc.car.tesla.values import CAR, TeslaFlags +from openpilot.common.params import Params +from openpilot.starpilot.common.car_control_config import screen_reserved +from openpilot.starpilot.tests.tesla_set_speed_fixture import save, tesla +from openpilot.starpilot.vehicle_preferences import VehicleStartupPreferences + +KEY = 'TeslaAOLScreenTap' +MODERN = (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y) + + +def started(tmp_path, cp, *, tap, aol=True): + """The car parameters after startup read the saved settings. tap: 'default' saves the registry default, as the manager + does for a setting never saved; True/False a saved choice; None leaves it unsaved.""" + params = Params(str(tmp_path)) + params.put_bool('AlwaysOnLateral', aol, block=True) + if tap == 'default': + params.put(KEY, params.get_default_value(KEY), block=True) + else: + save(params, KEY, tap) + snapshot = VehicleStartupPreferences.read(params, enabled=True) + snapshot.prepare(cp) + snapshot.finalize(cp) + return int(cp.safetyConfigs[0].safetyParam) & ~4096, cp + + +def test_the_saved_default_is_on(): + assert Params().get_default_value(KEY) is True + + +@pytest.mark.parametrize('candidate', MODERN) +def test_with_the_cable_the_default_puts_always_on_lateral_on_the_tap(tmp_path, candidate): + word, cp = started(tmp_path, tesla(candidate), tap='default') + assert word in SCREEN_WORDS and cp.flags & TeslaFlags.AOL_SCREEN_BUTTON and screen_reserved(cp) + + +@pytest.mark.parametrize('candidate', MODERN) +def test_without_the_cable_the_default_changes_nothing(tmp_path, candidate): + word, cp = started(tmp_path, tesla(candidate, cable=False), tap='default') + assert word in ORDINARY_WORDS and not cp.flags & TeslaFlags.AOL_SCREEN_BUTTON and not screen_reserved(cp) + (tmp_path / 'off').mkdir() + assert started(tmp_path / 'off', tesla(candidate, cable=False), tap=False)[0] == word + + +@pytest.mark.parametrize('tap', [False, None]) +def test_a_tap_saved_off_or_never_saved_stays_off(tmp_path, tap): + word, cp = started(tmp_path, tesla(), tap=tap) + assert word in ORDINARY_WORDS and not screen_reserved(cp) + + +def test_it_needs_always_on_lateral_turned_on(tmp_path): + word, cp = started(tmp_path, tesla(), tap='default', aol=False) + assert word not in SCREEN_WORDS | ORDINARY_WORDS and not screen_reserved(cp) diff --git a/openpilot/starpilot/car/tesla/tests/test_set_speed_switch.py b/openpilot/starpilot/car/tesla/tests/test_set_speed_switch.py new file mode 100644 index 0000000000..829158cb40 --- /dev/null +++ b/openpilot/starpilot/car/tesla/tests/test_set_speed_switch.py @@ -0,0 +1,126 @@ +"""Comma can set speed on Tesla dashboard, the saved switch: followed while the car is on, read at most once a second +by the loops that ask often, and never read for a car that cannot own its set speed.""" +import pytest +from opendbc.car.structs import car +from openpilot.common.params import Params +from openpilot.starpilot.car.tesla import set_speed +from openpilot.starpilot.common.car_control_config import comma_speed +from openpilot.starpilot.tests.tesla_set_speed_fixture import save, switch, tesla + +OTHER_CARS = { + 'no car': lambda: None, + 'tesla started without the scroll frame': tesla, + 'model y started without the scroll frame': lambda: tesla('TESLA_MODEL_Y'), + 'tesla without the cable': lambda: tesla(cable=False, selected=True), + 'tesla without longitudinal control': lambda: tesla(long=False, selected=True), + 'model s': lambda: tesla('TESLA_MODEL_S_HW1', selected=True), + 'model x': lambda: tesla('TESLA_MODEL_X', selected=True), + 'hyundai': lambda: car.CarParams.new_message(brand='hyundai', carFingerprint='HYUNDAI_IONIQ_5', pcmCruise=True, + openpilotLongitudinalControl=True, flags=8), + 'not car parameters': object, +} + + +class Reads: + """Saved settings that count how often each one is opened.""" + def __init__(self, path): + self.params = Params(str(path)) + self.opened = [] + + def get_param_path(self, key=''): + self.opened.append(key) + return self.params.get_param_path(key) + + +def test_the_switch_is_one_saved_setting(): + assert set_speed.PARAM == 'TeslaSpeedSync' + + +@pytest.mark.parametrize('saved,safe,expected', [ + (True, None, True), (True, False, True), + (None, None, False), (False, None, False), # never chosen, or off + (True, True, False), # Safe Mode + (b'2', None, False), (b'', None, False), (b'1' * 9, None, False), (b'true', None, False), + (True, b'maybe', False), # Safe Mode unreadable: treated as on +]) +def test_requested_is_the_switch_on_and_safe_mode_off(tmp_path, saved, safe, expected): + params = Params(str(tmp_path)) + save(params, 'TeslaSpeedSync', saved) + save(params, 'SafeMode', safe) + assert set_speed.requested(params) is expected + for model in ('TESLA_MODEL_3', 'TESLA_MODEL_Y'): + assert set_speed.active(params, tesla(model, selected=True)) is expected + assert comma_speed(params, tesla(model, selected=True)) is expected + + +def test_active_follows_the_switch_at_once_in_both_directions(tmp_path): + params = Params(str(tmp_path)) + cp = tesla(selected=True) + assert not set_speed.active(params, cp) + switch(params, True) + assert set_speed.active(params, cp) + save(params, 'SafeMode', True) + assert not set_speed.active(params, cp) + save(params, 'SafeMode', False) + assert set_speed.active(params, cp) + switch(params, False) + assert not set_speed.active(params, cp) + + +@pytest.mark.parametrize('case', OTHER_CARS) +def test_no_other_car_is_active_and_nothing_is_read_for_it(tmp_path, case): + reads = Reads(tmp_path) + switch(reads.params, True) + cp = OTHER_CARS[case]() + assert set_speed.active(reads, cp) is False and comma_speed(reads, cp) is False + polled = set_speed.Polled(reads, clock=lambda: 10.) + assert polled(cp) is False and polled.read_at is None + assert reads.opened == [] + + +def test_unreadable_storage_is_off(): + class Broken: + def get_param_path(self, key=''): + raise OSError('storage gone') + assert set_speed.active(Broken(), tesla(selected=True)) is False + + +def test_polled_reads_storage_at_most_once_a_second(tmp_path): + reads = Reads(tmp_path) + now = [100.] + polled = set_speed.Polled(reads, clock=lambda: now[0]) + cp = tesla(selected=True) + assert polled(cp) is False and reads.opened == ['TeslaSpeedSync'], 'off: Safe Mode is not even looked at' + switch(reads.params, True) + for _ in range(100): + now[0] += .0099 + assert polled(cp) is False, 'still the value read under a second ago' + assert reads.opened == ['TeslaSpeedSync'] + now[0] = 101. + assert polled(cp) is True and reads.opened == ['TeslaSpeedSync', 'TeslaSpeedSync', 'SafeMode'] + switch(reads.params, False) + now[0] = 101.999 + assert polled(cp) is True + now[0] = 102. + assert polled(cp) is False + + +def test_polled_reads_again_when_the_clock_steps_back(tmp_path): + reads = Reads(tmp_path) + now = [100.] + polled = set_speed.Polled(reads, clock=lambda: now[0]) + cp = tesla(selected=True) + assert polled(cp) is False + switch(reads.params, True) + now[0] = 50. + assert polled(cp) is True + + +def test_polled_answers_per_car_from_one_read(tmp_path): + reads = Reads(tmp_path) + switch(reads.params, True) + polled = set_speed.Polled(reads, clock=lambda: 5.) + assert polled(tesla(selected=True)) is True + count = len(reads.opened) + assert polled(tesla()) is False and polled(None) is False and polled(tesla('TESLA_MODEL_Y', selected=True)) is True + assert len(reads.opened) == count diff --git a/openpilot/starpilot/car/tesla/tests/test_speed_sync_context.py b/openpilot/starpilot/car/tesla/tests/test_speed_sync_context.py new file mode 100644 index 0000000000..10f77dfd3c --- /dev/null +++ b/openpilot/starpilot/car/tesla/tests/test_speed_sync_context.py @@ -0,0 +1,410 @@ +"""The comma's set speed as the Tesla's scroll target: card admits it each frame, and the car controller only scrolls +with a fresh admission that matches the set speed it is given, on a car that is safely engaged.""" +import time +from pathlib import Path +from types import SimpleNamespace as NS +from typing import Any + +import pytest +from opendbc.car.structs import car +from opendbc.car.tesla.carcontroller import CarController +from opendbc.car.tesla.carstate import CarState +from opendbc.car.tesla.speed_sync import ENGAGE_DELAY_NS, ManualReceipt, SpeedSynchronizer, SyncAuthority, sync_controller +from opendbc.car.tesla.values import DBC +from openpilot.common.params import Params +from openpilot.starpilot.car.tesla_speed_sync_context import SETTINGS_PERIOD_NS, publish_context +from openpilot.starpilot.common.car_control_config import PARAM +from openpilot.starpilot.controllers.cruise_action import TESLA_RECEIPT_NS, CruiseActionConsumer +from openpilot.starpilot.controllers.tesla_input_protocol import document_hash +from openpilot.starpilot.controllers.wheel_actions import cp_fingerprint +from openpilot.starpilot.tests.tesla_set_speed_fixture import tesla + +NEUTRAL = bytes.fromhex('2955000000000040') +MPH = 1.609344 +START = 1_000_000_000 +TICK = 10_000_000 +IDENTITY = 'a' * 64 + + +def di_frame(counter, speed, units): + bits = (counter << 8) | (2 << 12) | (round(speed * 2) << 15) | (units << 24) + data = bytearray(bits.to_bytes(8, 'little')) + data[0] = (0x88 + sum(data[1:])) & 255 + return bytes(data) + + +class Rig: + """A synchronizer watching a Tesla at 50 mph while the comma's set speed is 52 mph; ticks are 10 ms.""" + def __init__(self, *, units=0): + self.controller = NS(speed_sync=SpeedSynchronizer(), speed_sync_authority=None) + self.now, self.counter, self.units = START, 0, units + self.native = 50 + self.out = car.CarState.new_message(canValid=True, gearShifter='drive', cruiseState={'enabled': True, 'available': True}) + self.out.vCruise = 52 * MPH if units == 0 else 52. + self.cs = NS(out=self.out, autopark=False) + self.cc = car.CarControl.new_message(enabled=True, longActive=True) + self.sent = [] + + def authority(self, **changes): + values: dict[str, Any] = {'observed_boot_ns': self.now, 'target_kph': float(self.out.vCruise), 'is_metric': bool(self.units), + 'configuration_id': IDENTITY, 'software_owned': True} + values.update(changes) + return SyncAuthority(**values) + + def tick(self, admit=True, **changes): + self.now += TICK + self.counter = (self.counter + 1) % 16 + self.controller.speed_sync.observe([(self.now, [(0x286, di_frame(self.counter, self.native, self.units), 0), (0x3C2, NEUTRAL, 1)])]) + self.controller.speed_sync_authority = self.authority(**changes) if admit else None + messages = sync_controller(self.controller, self.cc.as_reader(), self.cs, self.now) + self.sent += messages + return messages + + def run(self, ticks=40, **kwargs): + for _ in range(ticks): + self.tick(**kwargs) + return self.sent + + @property + def status(self): + return self.controller.speed_sync.status + + +def test_a_fresh_matching_admission_lets_the_tesla_be_scrolled_to_the_comma_speed(): + r = Rig() + for _ in range(ENGAGE_DELAY_NS // TICK): + assert r.tick() == [] + sent = r.run(5) + assert len(sent) == 1 + address, data, bus = sent[0] + assert (address, bus, data[3] & 63) == (0x3C2, 1, 1), 'one click up, on the Vehicle CAN' + assert r.status == 'waiting_for_response' and r.controller.speed_sync.blocked is None + + +def test_matched_speeds_send_nothing(): + r = Rig() + r.native = 52 + assert r.run() == [] and r.status == 'matched' + + +@pytest.mark.parametrize('changes', [ + {'software_owned': False}, {'software_owned': 1}, + {'observed_boot_ns': 0}, {'observed_boot_ns': None}, {'observed_boot_ns': 1.5e9}, + {'target_kph': float('nan')}, {'target_kph': None}, {'target_kph': '84'}, + {'is_metric': True}, {'is_metric': 0}, {'is_metric': None}, + {'configuration_id': 'a' * 63}, {'configuration_id': 'A' * 64}, {'configuration_id': 'g' * 64}, {'configuration_id': None}, +]) +def test_a_malformed_or_foreign_admission_sends_nothing(changes): + r = Rig() + assert r.run(**changes) == [] + assert r.status == 'owner_or_config_ineligible' + + +def test_no_admission_sends_nothing(): + r = Rig() + assert r.run(admit=False) == [] and r.status == 'owner_or_config_ineligible' + r.controller.speed_sync_authority = object() + assert sync_controller(r.controller, r.cc.as_reader(), r.cs, r.now + TICK) == [] + del r.controller.speed_sync_authority + assert sync_controller(r.controller, r.cc.as_reader(), r.cs, r.now + 2 * TICK) == [] + + +def test_an_admission_for_another_set_speed_sends_nothing(): + r = Rig() + assert r.run(target_kph=float(r.out.vCruise) + .1) == [] + assert r.run(target_kph=51 * MPH) == [] and r.status == 'owner_or_config_ineligible' + + +def test_an_old_or_future_admission_sends_nothing(): + r = Rig() + for _ in range(40): + r.tick(observed_boot_ns=r.now + TICK - 100_000_001) + assert r.sent == [] + for _ in range(40): + r.tick(observed_boot_ns=r.now + TICK + 1) + assert r.sent == [] + for _ in range(40): + r.tick(observed_boot_ns=r.now + TICK - 100_000_000) + assert len(r.sent) >= 1, 'exactly at the age limit still counts' + + +def test_tesla_units_must_match_the_comma_units(): + r = Rig(units=1) + assert r.run(is_metric=False) == [] + r = Rig(units=1) + sent = r.run() + assert len(sent) == 1 and sent[0][1][3] & 63 == 1, 'km/h: 50 to 52 starts with one click' + + +UNSAFE = { + 'can invalid': lambda r: setattr(r.out, 'canValid', False), + 'can timeout': lambda r: setattr(r.out, 'canTimeout', True), + 'tesla cruise off': lambda r: setattr(r.out.cruiseState, 'enabled', False), + 'not in drive': lambda r: setattr(r.out, 'gearShifter', 'reverse'), + 'standstill': lambda r: setattr(r.out, 'standstill', True), + 'brake': lambda r: setattr(r.out, 'brakePressed', True), + 'cruise fault': lambda r: setattr(r.out, 'accFaulted', True), + 'emergency braking': lambda r: setattr(r.out, 'stockAeb', True), + 'collision warning': lambda r: setattr(r.out, 'stockFcw', True), + 'stability control off': lambda r: setattr(r.out, 'espDisabled', True), + 'stability control active': lambda r: setattr(r.out, 'espActive', True), + 'sensors invalid': lambda r: setattr(r.out, 'vehicleSensorsInvalid', True), + 'car not ready': lambda r: setattr(r.out, 'carNotReady', True), + 'door open': lambda r: setattr(r.out, 'doorOpen', True), + 'seatbelt': lambda r: setattr(r.out, 'seatbeltUnlatched', True), + 'steering fault': lambda r: setattr(r.out, 'steerFaultPermanent', True), + 'steering fault for now': lambda r: setattr(r.out, 'steerFaultTemporary', True), + 'tesla lane keeping': lambda r: setattr(r.out, 'stockLkas', True), + 'lane keeping setting': lambda r: setattr(r.out, 'invalidLkasSetting', True), + 'autopark': lambda r: setattr(r.cs, 'autopark', True), +} + + +@pytest.mark.parametrize('reason', UNSAFE) +def test_nothing_is_sent_while_the_car_is_not_safely_engaged(reason): + r = Rig() + UNSAFE[reason](r) + assert r.run() == [] + assert r.status == 'inhibited' and r.controller.speed_sync.blocked is None + + +def test_not_engaged_or_canceling_is_inactive(): + r = Rig() + r.cc.enabled = False + assert r.run() == [] and r.status == 'inactive' + r = Rig() + r.cc.cruiseControl.cancel = True + assert r.run() == [] and r.status == 'inactive' + + +def test_without_longitudinal_control_or_the_pedal_nothing_is_sent(): + r = Rig() + r.cc.longActive = False + assert r.run() == [] and r.status == 'inhibited' + r.out.gasPressed = True + assert len(r.run()) == 1, 'the driver on the pedal is still the comma driving' + + +def test_a_changed_configuration_stops_sync_until_disengaged(): + r = Rig() + assert len(r.run()) == 1 + r.native = 51 + r.tick(configuration_id='b' * 64) + assert r.controller.speed_sync.blocked == 'configuration_changed' + sent = len(r.sent) + r.run() + assert len(r.sent) == sent + r.cc.enabled = False + r.tick() + r.cc.enabled = True + assert r.controller.speed_sync.blocked is None + r.run(configuration_id='b' * 64) + assert len(r.sent) == sent + 1 + + +# card's side: openpilot/starpilot/car/tesla_speed_sync_context.py + +class Card: + def __init__(self, tmp_path, cp=None, *, metric=False, v_cruise=52 * MPH): + self.CP = tesla(selected=True) if cp is None else cp + self.params = Params(str(tmp_path)) + self.is_metric = metric + self.v_cruise_helper = NS(tesla_set_speed=True, v_cruise_kph=v_cruise) + self.CI = NS(CC=NS(speed_sync=SpeedSynchronizer())) + self.state = car.CarState.new_message(vCruise=v_cruise) + + def publish(self, now=START): + publish_context(self, self.state, now_boot_ns=now) + return self.CI.CC.speed_sync_authority + + +def test_card_admits_its_own_set_speed(tmp_path): + card = Card(tmp_path) + authority = card.publish() + assert isinstance(authority, SyncAuthority) + assert authority.observed_boot_ns == START and authority.software_owned is True and authority.is_metric is False + assert authority.target_kph == float(card.state.vCruise) and authority.target_kph == pytest.approx(52 * MPH, abs=1e-4) + assert len(authority.configuration_id) == 64 and set(authority.configuration_id) <= set('0123456789abcdef') + + +def test_the_configuration_is_the_car_and_its_units(tmp_path): + ids = set() + for index, (model, metric) in enumerate([('TESLA_MODEL_3', False), ('TESLA_MODEL_3', True), ('TESLA_MODEL_Y', False)]): + path = tmp_path / str(index) + path.mkdir() + card = Card(path, tesla(model, selected=True), metric=metric) + if metric: + card.params.put_bool('IsMetric', True, block=True) + ids.add(card.publish().configuration_id) + assert card.publish(START + TICK).configuration_id in ids, 'the same every frame' + assert len(ids) == 3 + + +def test_card_stamps_with_the_boot_clock_by_default(tmp_path): + card = Card(tmp_path) + before = time.clock_gettime_ns(time.CLOCK_BOOTTIME) + publish_context(card, card.state) + after = time.clock_gettime_ns(time.CLOCK_BOOTTIME) + assert before <= card.CI.CC.speed_sync_authority.observed_boot_ns <= after + + +@pytest.mark.parametrize('reason', ['helper does not own it', 'unset speed', 'published speed differs', 'safe mode', 'units differ', + 'units unreadable', 'bad clock']) +def test_card_admits_nothing_when_it_does_not_own_a_valid_set_speed(tmp_path, reason): + card = Card(tmp_path) + now = START + if reason == 'helper does not own it': + card.v_cruise_helper.tesla_set_speed = False + if reason == 'unset speed': + card.v_cruise_helper.v_cruise_kph = card.state.vCruise = 255 + if reason == 'published speed differs': + card.state.vCruise = 51 * MPH + if reason == 'safe mode': + card.params.put_bool('SafeMode', True, block=True) + if reason == 'units differ': + card.params.put_bool('IsMetric', True, block=True) + if reason == 'units unreadable': + Path(card.params.get_param_path('IsMetric')).write_bytes(b'maybe') + if reason == 'bad clock': + now = 0 + assert card.publish(now) is None + + +def test_a_refusal_withdraws_the_previous_admission_at_once(tmp_path): + card = Card(tmp_path) + assert card.publish() is not None + card.state.vCruise = 60 * MPH + assert card.publish(START + TICK) is None + card.v_cruise_helper.v_cruise_kph = 60 * MPH + assert card.publish(START + 2 * TICK).target_kph == pytest.approx(60 * MPH, abs=1e-4) + del card.v_cruise_helper + assert card.publish(START + 3 * TICK) is None, 'an error while reading is a refusal too' + + +def test_saved_settings_are_read_once_a_second_not_every_frame(tmp_path): + card = Card(tmp_path) + assert card.publish(START) is not None + card.params.put_bool('SafeMode', True, block=True) + assert card.publish(START + SETTINGS_PERIOD_NS - 1) is not None, 'within the second: the earlier read' + assert card.publish(START + SETTINGS_PERIOD_NS) is None + card.params.put_bool('SafeMode', False, block=True) + assert card.publish(START + 2 * SETTINGS_PERIOD_NS) is not None + + +# Card hands speed sync the receipts for the driver's own scrolls, with what they must match. + +DRIVE = 100_000_000 + + +def receipt(card, now, index=0): + return ManualReceipt(boot_ns=now, frame_index=index, name='right_wheel_up', fast=False, worker_session='0123456789abcdef' * 2, + sequence=index + 1, document_hash=document_hash(b''), vehicle_hash=cp_fingerprint(card.CP), + drive_start_ns=DRIVE, processed_boot_ns=now, target_kph=float(card.state.vCruise)) + + +def driving(tmp_path): + card = Card(tmp_path) + card.sm = {'deviceState': NS(startedMonoTime=DRIVE)} + card.controller_cruise_consumer = CruiseActionConsumer() + return card + + +def test_card_names_the_assignments_the_car_and_the_drive(tmp_path): + card = driving(tmp_path) + authority = card.publish() + assert authority.document_hash == document_hash(b''), 'nothing saved: the hash the input worker stamps for that' + assert authority.vehicle_hash == cp_fingerprint(card.CP) and authority.drive_start_ns == DRIVE + assert authority.manual_receipts == () + saved = b'{"version":1,"vehicle":"TESLA_MODEL_3","bindings":{}}' + Path(card.params.get_param_path(PARAM)).write_bytes(saved) + assert card.publish(START + SETTINGS_PERIOD_NS - 1).document_hash == document_hash(b''), 'read with the settings, once a second' + assert card.publish(START + SETTINGS_PERIOD_NS).document_hash == document_hash(saved) + card.CP = tesla('TESLA_MODEL_Y', selected=True) + assert card.publish(START + 2 * SETTINGS_PERIOD_NS).vehicle_hash == authority.vehicle_hash, "the car's identity is worked out once" + + +def test_card_offers_its_receipts_and_drops_the_ones_speed_sync_took(tmp_path): + card = driving(tmp_path) + first, second = receipt(card, START), receipt(card, START, 1) + card.controller_cruise_consumer.tesla_receipts += [first, second] + assert card.publish(START).manual_receipts == (first, second) + card.CI.CC.speed_sync.manual_receipt_acks.append(first) # speed sync took custody of the first + assert card.publish(START + TICK).manual_receipts == (second,) + assert card.controller_cruise_consumer.tesla_receipts == [second] and card.CI.CC.speed_sync.manual_receipt_acks == [] + assert card.publish(START + TESLA_RECEIPT_NS).manual_receipts == (second,) + assert card.publish(START + TESLA_RECEIPT_NS + 1).manual_receipts == (), 'not offered past its two seconds' + assert card.controller_cruise_consumer.tesla_receipts == [] + + +def test_the_engine_takes_cards_receipt_through_the_admission(tmp_path): + card = driving(tmp_path) + card.CI.CC.speed_sync_authority = None + item = receipt(card, START) + card.controller_cruise_consumer.tesla_receipts.append(item) + card.CI.CC.speed_sync.observe([(START, [(0x286, di_frame(1, 50, 0), 0)])]) # the Tesla shows mph, as card does + card.publish(START) + cc = car.CarControl.new_message(enabled=True, longActive=True).as_reader() + out = car.CarState.new_message(canValid=True, gearShifter='drive', cruiseState={'enabled': True, 'available': True}, + vCruise=float(card.state.vCruise)) + sync_controller(card.CI.CC, cc, NS(out=out, autopark=False), START) + assert card.CI.CC.speed_sync.manual_receipts == {(START, 0): item}, 'cached until its scroll is seen on the bus' + card.publish(START + TICK) + assert card.controller_cruise_consumer.tesla_receipts == [], 'and handed back to card the next frame' + + +def test_receipts_wait_with_card_while_it_admits_nothing(tmp_path): + card = driving(tmp_path) + item = receipt(card, START) + card.controller_cruise_consumer.tesla_receipts.append(item) + card.v_cruise_helper.tesla_set_speed = False + assert card.publish(START) is None and card.controller_cruise_consumer.tesla_receipts == [item] + card.v_cruise_helper.tesla_set_speed = True + assert card.publish(START + TICK).manual_receipts == (item,) + + +def test_card_without_a_step_consumer_or_drive_offers_no_receipts(tmp_path): + card = Card(tmp_path) + authority = card.publish() + assert authority.manual_receipts == () and authority.drive_start_ns == 0 and len(authority.document_hash) == 64 + + +@pytest.mark.parametrize('controller', [None, NS(), NS(speed_sync=None)]) +def test_card_does_nothing_for_a_controller_without_a_synchronizer(tmp_path, controller): + card = Card(tmp_path) + card.CI.CC = controller + publish_context(card, card.state, now_boot_ns=START) + assert not hasattr(controller, 'speed_sync_authority') + + +@pytest.mark.parametrize('model', ['TESLA_MODEL_3', 'TESLA_MODEL_Y']) +def test_the_real_controller_scrolls_only_with_cards_admission(tmp_path, model): + cp = tesla(model, selected=True) + controller = CarController(DBC[model], cp) + cs = CarState(cp) + cs.hands_on_level = 0 + cs.das_control = {'DAS_controlCounter': 0} + cs.out = car.CarState.new_message(canValid=True, gearShifter='drive', vEgo=22., vEgoRaw=22., vCruise=52 * MPH, + cruiseState={'enabled': True, 'available': True, 'speed': 50 * .44704}) + card = Card(tmp_path, cp) + card.CI.CC = controller + card.state = cs.out + cc = car.CarControl.new_message(enabled=True, longActive=True).as_reader() + + def drive(frames, admit): + scrolls, counter = [], 0 + for _ in range(frames): + now = time.clock_gettime_ns(time.CLOCK_BOOTTIME) + counter = (counter + 1) % 16 + controller.speed_sync.observe([(now, [(0x286, di_frame(counter, 50, 0), 0), (0x3C2, NEUTRAL, 1)])]) + if admit: + publish_context(card, cs.out) + else: + controller.speed_sync_authority = None + _, sends = controller.update(cc, cs, now) + scrolls += [message for message in sends if message[0] == 0x3C2] + time.sleep(.01) + return scrolls + + assert drive(25, admit=False) == [], 'the controller alone never scrolls' + scrolls = drive(40, admit=True) + assert len(scrolls) >= 1 and all(bus == 1 and data[3] & 63 == 1 for _, data, bus in scrolls) 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 new file mode 100644 index 0000000000..eaff0b7778 --- /dev/null +++ b/openpilot/starpilot/car/tesla/tests/test_speed_sync_other_cars.py @@ -0,0 +1,337 @@ +"""Nothing the Tesla set-speed and car-control work added acts for another car: every new behavior sits behind a gate +that is false for other fingerprints, for a Tesla without the cable, and for a Tesla whose switch is off.""" +from pathlib import Path +import re +from types import SimpleNamespace +from unittest.mock import patch + +import pytest +from opendbc.car.car_helpers import interfaces +from opendbc.car.structs import car +from opendbc.car.tesla import speed_sync +from opendbc.car.tesla.carcontroller import CarController +from opendbc.car.tesla.values import DBC +from opendbc.car.values import PLATFORMS +from openpilot.common.params import Params +from openpilot.selfdrive.car.cruise import VCruiseHelper +from openpilot.starpilot.car.tesla import set_speed +from openpilot.starpilot.common import car_control_config +from openpilot.starpilot.controllers import cruise_action +from openpilot.starpilot.speed_limits import planner_host, tesla_set_speed_card +from openpilot.starpilot.tests.tesla_set_speed_fixture import switch, tesla +from openpilot.starpilot.ui.feature_settings_state import FeatureSettingsRequest +from openpilot.starpilot.ui.tesla_controls_feature import TeslaControlsFeature +from openpilot.starpilot.ui.tesla_rows import TeslaVehicleRows, TeslaWheelRows +from openpilot.starpilot.ui.tesla_set_speed_feature import TeslaSetSpeedFeature, addon_cable + +ROOT = Path(__file__).resolve().parents[5] +MODELS = ('TESLA_MODEL_3', 'TESLA_MODEL_Y') +OTHER_PLATFORMS = sorted(name for name in PLATFORMS if name not in MODELS) +OTHER_TESLAS = ('TESLA_MODEL_X', 'TESLA_MODEL_S_HW1', 'TESLA_MODEL_S_PREAP') +EXAMPLES = ('HYUNDAI_IONIQ_5', 'TOYOTA_RAV4_TSS2', 'HONDA_CIVIC_BOSCH', 'CHEVROLET_BOLT_EUV', 'FORD_MAVERICK_MK1', + 'SUBARU_OUTBACK', 'VOLKSWAGEN_GOLF_MK7') + OTHER_TESLAS + + +class SwitchOn: + """Saved settings with Comma can set speed on Tesla dashboard on, noting every setting that is opened.""" + def __init__(self, path): + self.params = switch(Params(str(path)), True) + self.opened = [] + + def get_param_path(self, key=''): + self.opened.append(key) + return self.params.get_param_path(key) + + +def source(path): + return (ROOT / path).read_text() + + +def squeezed(text): + return re.sub(r'\s+', ' ', text) + + +def other(platform): + return interfaces[platform].get_non_essential_params(platform) + + +def test_the_examples_are_real_platforms(): + assert set(EXAMPLES) <= set(PLATFORMS) and set(MODELS) <= set(PLATFORMS) + assert speed_sync.MODELS == car_control_config.MODELS == MODELS + + +@pytest.mark.parametrize('platform', OTHER_PLATFORMS) +def test_no_other_platform_passes_any_gate_and_the_switch_is_never_read_for_it(tmp_path, platform): + saved = SwitchOn(tmp_path) + cp = other(platform) + for longitudinal in (bool(cp.openpilotLongitudinalControl), True): + cp.openpilotLongitudinalControl = longitudinal + assert not speed_sync.eligible(cp) and not speed_sync.selected(cp) + assert not cruise_action.tesla_set_speed(cp) + assert not set_speed.active(saved, cp) and not car_control_config.comma_speed(saved, cp) + assert not set_speed.Polled(saved)(cp) + assert not car_control_config.vehicle_supported(cp) + assert addon_cable(cp) is None + assert cruise_action.eligible(cp) is bool(not cp.pcmCruise and longitudinal and not cp.passive and not cp.dashcamOnly and + not cp.notCar), 'the software cruise rule other cars had' + helper = VCruiseHelper(cp) + card = SimpleNamespace(CP=cp, params=saved, v_cruise_helper=helper, slc_transport_available=True) + with patch.object(tesla_set_speed_card.messaging, 'sub_sock', side_effect=AssertionError('no receiver for another car')), \ + patch.object(tesla_set_speed_card.messaging, 'recv_one_or_none', side_effect=AssertionError('nothing to read')): + tesla_set_speed_card.refresh(card) + card.slc_set_speed = tesla_set_speed_card.attach(card) + tesla_set_speed_card.apply_commands(card, car.CarState.new_message(), None, 1, long_active=True) + assert card.slc_set_speed is None and not tesla_set_speed_card.rule(card) + assert helper.tesla_set_speed is False and helper.slc_pcm is False + with patch.object(planner_host.messaging, 'pub_sock', side_effect=AssertionError('no command publisher for another car')): + assert planner_host.SavedSlcLifecycle(saved.params, cp, {}).command_sock is None + assert saved.opened == [], 'the switch is not read for a car that cannot own its set speed' + + +@pytest.mark.parametrize('platform', EXAMPLES) +def test_another_car_with_every_tesla_looking_field_set_still_passes_no_gate(tmp_path, platform): + # The cable flag (8) and the scroll-frame bit (4096) are other brands' own flags; neither makes a car a Tesla Model 3/Y. + saved = SwitchOn(tmp_path) + cp = other(platform) + cp.openpilotLongitudinalControl = True + cp.pcmCruise = True + cp.dashcamOnly = False + cp.flags = int(cp.flags) | 8 + for config in cp.safetyConfigs: + config.safetyParam = int(config.safetyParam) | 4096 | 1 + before = cp.as_reader().as_builder().to_bytes() + assert not speed_sync.eligible(cp) and not speed_sync.selected(cp) + assert not cruise_action.tesla_set_speed(cp) and not cruise_action.eligible(cp) + assert not car_control_config.comma_speed(saved, cp) and not car_control_config.vehicle_supported(cp) + assert not VCruiseHelper(cp).tesla_set_speed and saved.opened == [] + speed_sync.prepare(cp, True) + speed_sync.prepare(cp, False) + assert cp.as_reader().as_builder().to_bytes() == before + + +@pytest.mark.parametrize('make,on', [(lambda: tesla(selected=True), False), (lambda: tesla('TESLA_MODEL_Y', selected=True), False), + (tesla, True), (lambda: tesla(cable=False, selected=True), True), + (lambda: tesla(long=False, selected=True), True)]) +def test_a_tesla_with_the_switch_off_or_without_the_frame_the_cable_or_longitudinal_control_owns_no_set_speed(tmp_path, make, on): + params = switch(Params(str(tmp_path)), on) + cp = make() + assert not set_speed.active(params, cp) and not car_control_config.comma_speed(params, cp) + helper = VCruiseHelper(cp) + tesla_set_speed_card.refresh(SimpleNamespace(CP=cp, params=params, v_cruise_helper=helper)) + assert helper.tesla_set_speed is False + bindings = car_control_config.effective_bindings(None, comma_speed=car_control_config.comma_speed(params, cp)) + assert 'right_wheel_up' not in bindings and 'right_wheel_down' not in bindings + + +@pytest.mark.parametrize('platform', EXAMPLES) +def test_other_cars_get_no_settings_rows_and_no_saved_changes(tmp_path, platform): + cp = other(platform) + params = Params(str(tmp_path)) + owner = SimpleNamespace(params=params, authority=lambda group: True, vehicle_params=lambda: cp, + vehicle_fingerprint=lambda: cp.carFingerprint) + assert TeslaSetSpeedFeature(owner).rows(True) == () and TeslaSetSpeedFeature(owner).capability() is None + assert TeslaControlsFeature(owner).rows() == [] + assert not TeslaVehicleRows(owner).set_speed.active() + for key, value in (('TeslaSpeedSync', 'On'), ('tesla_input:right_wheel_left', 'Bookmark')): + request = FeatureSettingsRequest(key, None, value, confirmation=True, vehicle_fingerprint=cp.carFingerprint, + capability=(str(cp.carFingerprint), str(cp.brand), int(cp.flags), True, True, ())) + assert not TeslaVehicleRows(owner).apply(request) + assert not params.get_bool('TeslaSpeedSync') and params.get('CarControlAssignments') is None + assert isinstance(TeslaWheelRows(owner).tesla.rows(), list) and not TeslaWheelRows(owner).tesla.rows() + + +@pytest.mark.parametrize('platform', OTHER_TESLAS) +def test_other_teslas_get_no_synchronizer(platform): + cp = other(platform) + assert CarController(DBC[platform], cp).speed_sync is None + cp = tesla(platform, selected=True) + assert CarController(DBC[platform], cp).speed_sync is None + + +def test_a_car_that_is_not_a_tesla_by_brand_is_not_one_by_name(): + cp = car.CarParams.new_message(brand='mock', carFingerprint='TESLA_MODEL_3', flags=8, pcmCruise=True, openpilotLongitudinalControl=True) + cp.safetyConfigs = [car.CarParams.SafetyConfig.new_message(safetyParam=4097)] + assert not speed_sync.eligible(cp) and not speed_sync.selected(cp) and not car_control_config.vehicle_supported(cp) + assert addon_cable(cp) is None + + +# The gates themselves, as written in the code every car runs. A new use of the feature in these files must sit +# behind one of them; add it here once it has been checked. +GATES = { + 'openpilot/selfdrive/car/cruise.py': [ + 'self.tesla_set_speed = False', + 'stock_software = subaru_software_selected(self.CP) or self.hyundai_software_cruise or self.tesla_set_speed', + 'self.slc_pcm = bool(slc_enabled and self.tesla_set_speed)', + 'if self.CP.pcmCruise and (not self.slc_pcm or slc_target_mps is None):', + 'if resume and self.v_cruise_initialized and not (self.slc_pcm and slc_target_mps is not None):', + ], + 'openpilot/selfdrive/car/card.py': [ + 'enabled=bool((host_control_enabled or cruise_helper.tesla_set_speed and host_enabled) and', + 'if getattr(self.CI.CC, "speed_sync", None) is not None:', + 'rule = tesla_set_speed_card.rule(self)', + ], + 'openpilot/starpilot/speed_limits/tesla_set_speed_card.py': [ + 'if selected(card.CP): card.v_cruise_helper.tesla_set_speed = set_speed.active(card.params, card.CP)', + 'if not (card.slc_transport_available and selected(card.CP)): return None', + "receiver = getattr(card, 'slc_set_speed', None) if receiver is None: return", + 'if not helper.tesla_set_speed: receiver.commands.clear()', + "return bool(getattr(card, 'slc_set_speed', None) is not None and card.v_cruise_helper.tesla_set_speed)", + "if kind in ('commandApplied', 'commandRejected'):", + ], + 'openpilot/starpilot/car/tesla/set_speed.py': [ + 'return bool(selected(cp) and requested(params))', + 'if not selected(cp): return False', + ], + 'openpilot/starpilot/speed_limits/planner_host.py': [ + "self.command_sock = messaging.pub_sock('slcCruiseCommand') if tesla_set_speed_selected(cp) else None", + 'if self.command_sock is not None and tesla_set_speed.active(self.params, self.cp):', + 'if output.command is not None and self.command_sock is not None:', + ], + 'openpilot/starpilot/speed_limits/runtime.py': [ + 'self.set_speed_rule = bool(self.settings.set_speed_rule and tesla_set_speed_selected(CP))', + 'command = self._command(result, frame, sm, now_ns, old_pending, action, adopt) if self.set_speed_rule else None', + ], + 'openpilot/starpilot/controllers/cruise_action.py': [ + 'return bool(cp is not None and (not cp.pcmCruise or tesla_set_speed(cp)) and cp.openpilotLongitudinalControl and', + 'not tesla_set_speed(cp)):', + "if kind == \"cruiseStep\" and not getattr(helper, 'tesla_set_speed', False):", + "if not (eligible(cp) and (not cp.pcmCruise or getattr(helper, 'tesla_set_speed', False)) and", + ], + 'openpilot/starpilot/controllers/tesla_receiver.py': [ + 'if not vehicle_supported(self.vehicle()):', + 'binding = effective_bindings(doc, comma_speed=comma_speed(self.params, cp)).get(name)', + ], + '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))', + ], + 'openpilot/starpilot/car/tesla_speed_sync_context.py': [ + 'if controller is None or getattr(controller, "speed_sync", None) is None: return', + 'if type(stamp) is not int or stamp <= 0 or not helper.tesla_set_speed: return', + ], + 'openpilot/starpilot/ui/runtime_app.py': [ + 'if ui_state.CP is not None and (not ui_state.CP.pcmCruise or self._tesla_set_speed(ui_state.CP)):', + ], + 'openpilot/starpilot/ui/tesla_speed_actions.py': [ + 'if vehicle_supported(ui_state.CP):', + ], + 'openpilot/starpilot/ui/tesla_controls_feature.py': [ + 'if cp is None or cp.carFingerprint not in MODELS:', + ], + 'openpilot/starpilot/ui/tesla_set_speed_feature.py': [ + "if cp is None or cp.brand != 'tesla' or cp.carFingerprint not in MODELS:", + 'if addon_cable(cp) is None:', + ], + 'openpilot/starpilot/vehicle_preferences.py': [ + 'prepare_speed_sync(cp, self.tesla_speed_sync)', + ], + 'opendbc_repo/opendbc/car/tesla/speed_sync.py': [ + 'return bool(cp.brand == "tesla" and cp.carFingerprint in MODELS and cp.openpilotLongitudinalControl and cp.pcmCruise and', + 'return bool(eligible(cp) and cp.safetyConfigs[0].safetyParam & SYNC_FLAG)', + 'if eligible(cp):', + ], + 'opendbc_repo/opendbc/car/tesla/carcontroller.py': [ + 'self.speed_sync = SpeedSynchronizer() if speed_sync_selected(CP) else None', + 'if self.speed_sync is not None:', + ], + 'opendbc_repo/opendbc/car/tesla/interface.py': [ + 'if self.CC is not None and self.CC.speed_sync is not None:', + ], + 'opendbc_repo/opendbc/car/tesla/carstate.py': [ + 'if self.CP.carFingerprint in (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y): update_dashboard_limit(', + ], +} +# Every line of the files all cars share that uses the selection or the switch, apart from imports, definitions and +# comments. +SOFTWARE = 'stock_software = subaru_software_selected(self.CP) or self.hyundai_software_cruise or self.tesla_set_speed' +SHARED = { + 'openpilot/selfdrive/car/cruise.py': (r'tesla_set_speed|speed_sync', [ + 'self.tesla_set_speed = False', SOFTWARE, 'self.slc_pcm = bool(slc_enabled and self.tesla_set_speed)', SOFTWARE]), + 'openpilot/selfdrive/car/card.py': (r'tesla_set_speed|speed_sync', [ + 'self.slc_set_speed = tesla_set_speed_card.attach(self)', + 'enabled=bool((host_control_enabled or cruise_helper.tesla_set_speed and host_enabled) and', + 'tesla_set_speed_card.apply_commands(self, CS, observation, now_ns, long_active=slc_long_active, after_ns=floor_ns)', + 'rule = tesla_set_speed_card.rule(self)', + 'tesla_set_speed_card.write_receipt(record, kind, detail)', + 'if getattr(self.CI.CC, "speed_sync", None) is not None:', + 'tesla_set_speed_card.refresh(self)']), + 'openpilot/starpilot/controllers/cruise_action.py': (r'tesla_set_speed', [ + 'Card applies a request only while the switch is on (helper.tesla_set_speed)."""', + 'return bool(cp is not None and (not cp.pcmCruise or tesla_set_speed(cp)) and cp.openpilotLongitudinalControl and', + 'not tesla_set_speed(cp)):', + "if kind == \"cruiseStep\" and not getattr(helper, 'tesla_set_speed', False):", + "if not (eligible(cp) and (not cp.pcmCruise or getattr(helper, 'tesla_set_speed', False)) and"]), + 'openpilot/starpilot/ui/runtime_app.py': (r'tesla_set_speed\(', [ + 'if ui_state.CP is not None and (not ui_state.CP.pcmCruise or self._tesla_set_speed(ui_state.CP)):']), + 'openpilot/starpilot/vehicle_preferences.py': (r'prepare_speed_sync\(|tesla_speed_sync=speed_sync', [ + 'tesla_screen_brake=screen_brake, tesla_cooperative=cooperative, tesla_speed_sync=speed_sync, toyota_auto_hold=toyota,', + 'prepare_speed_sync(cp, self.tesla_speed_sync)', 'prepare_speed_sync(cp, self.tesla_speed_sync)']), + 'openpilot/starpilot/speed_limits/planner_host.py': (r'tesla_set_speed', [ + "self.command_sock = messaging.pub_sock('slcCruiseCommand') if tesla_set_speed_selected(cp) else None", + 'if self.command_sock is not None and tesla_set_speed.active(self.params, self.cp):']), + 'openpilot/starpilot/speed_limits/runtime.py': (r'tesla_set_speed', [ + 'self.set_speed_rule = bool(self.settings.set_speed_rule and tesla_set_speed_selected(CP))']), +} + + +@pytest.mark.parametrize('path', GATES) +def test_each_gate_is_still_in_place(path): + text = squeezed(source(path)) + for gate in GATES[path]: + assert squeezed(gate) in text, f'{path}: gate not found: {gate}' + + +@pytest.mark.parametrize('path', SHARED) +def test_shared_code_uses_the_selection_only_at_its_reviewed_gates(path): + pattern, expected = SHARED[path] + lines = [squeezed(line.split(' #')[0]).strip() for line in source(path).splitlines() + if re.search(pattern, line) and not line.lstrip().startswith(('#', 'from ', 'import ', 'def '))] + assert lines == expected, f'{path}: a use of the selection changed; check it is gated, then update this list' + + +def test_startup_is_the_only_place_that_writes_the_selection(): + writers = [] + for path in list((ROOT / 'openpilot').rglob('*.py')) + list((ROOT / 'opendbc_repo/opendbc').rglob('*.py')): + if '/tests/' in path.as_posix() or path.name.startswith('test_'): + continue + text = path.read_text(errors='ignore') + if re.search(r'\|=\s*(SYNC_FLAG|.*SCROLL_SPEED_SYNC)|prepare_speed_sync\(|speed_sync import .*\bprepare\b', text): + writers.append(path.relative_to(ROOT).as_posix()) + assert sorted(writers) == ['opendbc_repo/opendbc/car/tesla/speed_sync.py', 'openpilot/starpilot/vehicle_preferences.py'] + + +def test_only_cards_settings_thread_turns_ownership_on(): + writers = [] + for path in (ROOT / 'openpilot').rglob('*.py'): + if '/tests/' in path.as_posix() or path.name.startswith('test_'): + continue + if re.search(r'\.tesla_set_speed\s*=[^=]', path.read_text(errors='ignore')): + writers.append(path.relative_to(ROOT).as_posix()) + assert sorted(writers) == ['openpilot/selfdrive/car/cruise.py', 'openpilot/starpilot/speed_limits/tesla_set_speed_card.py'] + + +def test_the_car_interface_does_not_select_it(): + text = source('opendbc_repo/opendbc/car/tesla/interface.py') + assert 'SCROLL_SPEED_SYNC' not in text and 'EXPERIMENTAL_TEST_BUILD' not in text and 'PROTOCOL_QUALIFIED' not in text + engine = source('opendbc_repo/opendbc/car/tesla/speed_sync.py') + assert 'EXPERIMENTAL_TEST_BUILD' not in engine and 'PROTOCOL_QUALIFIED' not in engine + + +@pytest.mark.parametrize('name', ['match_speed_owner', 'software_cruise_requested', 'tesla_controls_requested', 'tesla_controls_active', + 'slc_sets_set_speed', 'TeslaIndependentSetSpeed', 'TeslaOverrideSetSpeed', 'TeslaGentleSlowing', + 'WHEEL_GESTURES', 'WheelPress', '_wheel_deferred', 'dash_speed', 'tesla_speed_sync_warning', + 'pedal_handover', 'PedalHandover', 'HandoverSample', 'gas_release_frame', 'tesla_vehicle_feature', + 'indicator_left_half', 'beam_pull', 'wiper_half']) +def test_removed_parts_are_gone_from_the_code(name): + found = [] + roots = [ROOT / 'openpilot/starpilot', ROOT / 'openpilot/selfdrive', ROOT / 'openpilot/common', ROOT / 'openpilot/cereal', + ROOT / 'opendbc_repo/opendbc/car/tesla', ROOT / 'opendbc_repo/opendbc/safety/modes'] + for root in roots: + for path in root.rglob('*'): + if (path.suffix not in ('.py', '.capnp', '.h', '.js') or '/tests/' in path.as_posix() or path.name.startswith('test_') or + '/gen/' in path.as_posix()): + continue + if re.search(r'\b' + re.escape(name) + r'\b', path.read_text(errors='ignore')): + found.append(path.relative_to(ROOT).as_posix()) + assert not found, f'{name} is still named in {found}' diff --git a/openpilot/starpilot/car/tesla/tests/test_speed_sync_startup.py b/openpilot/starpilot/car/tesla/tests/test_speed_sync_startup.py new file mode 100644 index 0000000000..40050ec933 --- /dev/null +++ b/openpilot/starpilot/car/tesla/tests/test_speed_sync_startup.py @@ -0,0 +1,179 @@ +"""Startup admits the scroll frame of Comma can set speed on Tesla dashboard: one safety-word bit in the car parameters +of every eligible Tesla Model 3/Y, whatever the switch says, so the switch itself works without a restart.""" +from dataclasses import replace +from pathlib import Path + +import pytest +from opendbc.car.car_helpers import interfaces +from opendbc.car.tesla.screen_button import SYNC_WORDS +from opendbc.car.tesla.speed_sync import SYNC_FLAG, eligible, prepare, selected +from opendbc.car.tesla.values import CAR +from opendbc.car.values import PLATFORMS +from openpilot.common.params import Params +from openpilot.starpilot.car.tesla import set_speed +from openpilot.starpilot.tests.tesla_set_speed_fixture import tesla +from openpilot.starpilot.vehicle_preferences import VehicleStartupPreferences + +MODERN = (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y) +OFF, ON = VehicleStartupPreferences(), VehicleStartupPreferences(tesla_speed_sync=True) +OTHER_PLATFORMS = sorted(name for name in PLATFORMS if name not in ('TESLA_MODEL_3', 'TESLA_MODEL_Y')) + + +def raw(cp): + return cp.as_reader().as_builder().to_bytes() + + +def word(cp): + return int(cp.safetyConfigs[0].safetyParam) + + +def saved(tmp_path, **values): + """Saved settings: True/False through the settings store, bytes written as they are, None left unset.""" + params = Params(str(tmp_path)) + for key, value in values.items(): + if isinstance(value, bytes): + Path(params.get_param_path(key)).write_bytes(value) + elif value is not None: + params.put_bool(key, value, block=True) + return params + + +def test_it_is_off_unless_read_on(): + assert OFF.tesla_speed_sync is False and ON.tesla_speed_sync is True + + +@pytest.mark.parametrize('enabled,safe,release,expected', [ + (True, None, None, True), + (True, False, False, True), + (False, None, None, False), # StarPilot not enabled + (True, True, None, False), # Safe Mode + (True, None, True, False), # a release branch + (True, True, True, False), + (True, b'invalid', None, False), # Safe Mode unreadable: treated as on + (True, None, b'invalid', False), # release marker unreadable: treated as a release +]) +@pytest.mark.parametrize('switch', [None, False, True, b'2']) +def test_startup_admits_the_scroll_frame_whatever_the_switch_says(tmp_path, enabled, safe, release, expected, switch): + params = saved(tmp_path, TeslaSpeedSync=switch, SafeMode=safe, IsReleaseBranch=release) + snapshot = VehicleStartupPreferences.read(params, enabled=enabled) + assert snapshot.tesla_speed_sync is expected + for candidate in MODERN: + cp = tesla(candidate) + snapshot.prepare(cp) + assert selected(cp) is expected and word(cp) == (4097 if expected else 1) + snapshot.finalize(cp) + assert selected(cp) is expected and word(cp) == (4097 if expected else 1) + assert set_speed.active(params, cp) is bool(expected and switch is True), 'owning the set speed still needs the switch' + + +def test_startup_does_not_read_the_switch(tmp_path): + params = saved(tmp_path, TeslaSpeedSync=True) + reads = [] + + class Spy: + """The saved settings, noting which files are opened.""" + def __getattr__(self, name): + return getattr(params, name) + + def get_param_path(self, key=''): + reads.append(key) + return params.get_param_path(key) + assert VehicleStartupPreferences.read(Spy(), enabled=True).tesla_speed_sync + assert reads and 'TeslaSpeedSync' not in reads and 'IsReleaseBranch' in reads and 'SafeMode' in reads + + +def test_the_admission_does_not_depend_on_the_other_tesla_switches(tmp_path): + snapshot = VehicleStartupPreferences.read(saved(tmp_path), enabled=True) + assert snapshot.tesla_speed_sync and not snapshot.tesla_cooperative and not snapshot.tesla_aol and not snapshot.tesla_screen + params = saved(tmp_path, TeslaCoopSteering=True, AlwaysOnLateral=True, TeslaAOLScreenTap=True) + snapshot = VehicleStartupPreferences.read(params, enabled=True) + assert snapshot.tesla_speed_sync and snapshot.tesla_cooperative and snapshot.tesla_aol and snapshot.tesla_screen + + +@pytest.mark.parametrize('candidate', MODERN) +@pytest.mark.parametrize('step', ['prepare', 'finalize']) +def test_prepare_and_finalize_each_set_and_clear_the_bit(candidate, step): + cp = tesla(candidate) + before = raw(cp) + getattr(ON, step)(cp) + assert word(cp) == 4097 and selected(cp) + getattr(ON, step)(cp) + assert word(cp) == 4097, 'the same again' + getattr(OFF, step)(cp) + assert word(cp) == 1 and not selected(cp) + assert raw(cp) == before, 'only that bit ever moved' + + +@pytest.mark.parametrize('candidate', MODERN) +def test_a_stale_bit_is_cleared_when_the_switch_is_off(candidate): + cp = tesla(candidate, selected=True) + OFF.finalize(cp) + assert word(cp) == 1 + cp = tesla(candidate, selected=True) + OFF.prepare(cp) + assert word(cp) == 1 + + +@pytest.mark.parametrize('candidate', MODERN) +@pytest.mark.parametrize('cable,long', [(False, True), (True, False), (False, False)]) +def test_a_tesla_without_the_cable_or_longitudinal_control_is_never_selected(candidate, cable, long): + cp = tesla(candidate, cable=cable, long=long) + before = raw(cp) + ON.prepare(cp) + ON.finalize(cp) + assert not selected(cp) and not word(cp) & SYNC_FLAG + off = tesla(candidate, cable=cable, long=long) + OFF.prepare(off) + OFF.finalize(off) + assert raw(cp) == raw(off) == before + + +@pytest.mark.parametrize('candidate', MODERN) +@pytest.mark.parametrize('coop', (False, True)) +@pytest.mark.parametrize('aol,screen', [(False, False), (True, False), (True, True)]) +@pytest.mark.parametrize('brake', (False, True)) +def test_with_the_other_tesla_switches_the_word_is_one_the_panda_accepts(candidate, coop, aol, screen, brake): + snapshot = replace(ON, tesla_cooperative=coop, tesla_aol=aol, tesla_screen=screen, tesla_screen_brake=brake) + cp = tesla(candidate) + for _ in range(2): + snapshot.prepare(cp) + assert word(cp) in SYNC_WORDS and selected(cp) + snapshot.finalize(cp) + assert word(cp) in SYNC_WORDS and selected(cp) + expected = 4097 | (256 if coop else 0) | ((512 if screen else 2048) | (1024 if brake else 0) if aol else 0) + assert word(cp) == expected + without = tesla(candidate) + replace(snapshot, tesla_speed_sync=False).prepare(without) + replace(snapshot, tesla_speed_sync=False).finalize(without) + assert word(without) == expected & ~SYNC_FLAG, 'the switch adds its bit and changes nothing else' + cp.safetyConfigs[0].safetyParam = word(without) + assert raw(cp) == raw(without) + + +def test_every_other_platform_exists_for_the_check_below(): + assert len(OTHER_PLATFORMS) > 100 and {'TESLA_MODEL_X', 'TESLA_MODEL_S_HW1', 'TESLA_MODEL_S_PREAP'} <= set(OTHER_PLATFORMS) + + +@pytest.mark.parametrize('platform', OTHER_PLATFORMS) +def test_every_other_car_is_left_exactly_as_without_the_switch(platform): + results = [] + for snapshot in (OFF, ON): + cp = interfaces[platform].get_non_essential_params(platform) + assert not eligible(cp) + prepared = snapshot.prepare(cp) + snapshot.finalize(prepared) + assert not selected(prepared) + results.append(raw(prepared)) + assert results[0] == results[1] + + +@pytest.mark.parametrize('platform', ['HYUNDAI_IONIQ_5', 'TOYOTA_RAV4_TSS2', 'HONDA_CIVIC_BOSCH', 'TESLA_MODEL_X', 'TESLA_MODEL_S_HW1']) +def test_another_car_whose_safety_word_already_uses_the_same_bit_keeps_it(platform): + # 4096 means something else to other brands' safety code: startup must neither clear nor read it. + for snapshot in (OFF, ON): + cp = interfaces[platform].get_non_essential_params(platform) + cp.openpilotLongitudinalControl = True + cp.safetyConfigs[0].safetyParam = int(cp.safetyConfigs[0].safetyParam) | SYNC_FLAG + before = raw(cp) + prepare(cp, snapshot.tesla_speed_sync) + assert raw(cp) == before and not selected(cp) and not eligible(cp) diff --git a/openpilot/starpilot/car/tesla_speed_sync_context.py b/openpilot/starpilot/car/tesla_speed_sync_context.py new file mode 100644 index 0000000000..d3eae6037a --- /dev/null +++ b/openpilot/starpilot/car/tesla_speed_sync_context.py @@ -0,0 +1,67 @@ +"""Speed sync: read-only admission of the comma's set speed as the Tesla's target; no action dispatch.""" +import hashlib +import math +import time + +from opendbc.car.tesla.speed_sync import SyncAuthority +from openpilot.starpilot.common.car_control_config import MAX_ASSIGNMENT_BYTES, PARAM +from openpilot.starpilot.saved_source import read_saved + +SETTINGS_PERIOD_NS = 1_000_000_000 + + +def _settings(card, now_ns): + """(Safe Mode off and the saved units matching card's, the saved assignments' hash), read once a second: this runs in + card's 100 Hz loop. The hash is the one the input worker stamps on each scroll it reports.""" + cached = getattr(card, "_tesla_sync_settings", None) + if cached is not None and 0 <= now_ns - cached[0] < SETTINGS_PERIOD_NS: + return cached[1], cached[2] + metric, metric_readable = read_saved(card.params, "IsMetric", 8) + good = bool(read_saved(card.params, "SafeMode", 8) in ((None, True), (b"0", True)) and + metric_readable and metric in (None, b"0", b"1") and + type(card.is_metric) is bool and card.is_metric == (metric == b"1")) + raw, readable = read_saved(card.params, PARAM, MAX_ASSIGNMENT_BYTES) + document = hashlib.sha256(raw or b"").hexdigest() if readable else "" + card._tesla_sync_settings = (now_ns, good, document) + return good, document + + +def _vehicle(card): + """This car's identity as the input worker reports it; the car's parameters never change while card runs.""" + vehicle = getattr(card, "_tesla_sync_vehicle", None) + if vehicle is None: + from openpilot.starpilot.controllers.wheel_actions import cp_fingerprint + vehicle = card._tesla_sync_vehicle = cp_fingerprint(card.CP) + return vehicle + + +def publish_context(card, state, *, now_boot_ns=None): + controller = card.CI.CC + if controller is None or getattr(controller, "speed_sync", None) is None: + return + # A failed read invalidates the previous frame's admission immediately. + controller.speed_sync_authority = None + try: + cp, helper = card.CP, card.v_cruise_helper + stamp = time.clock_gettime_ns(time.CLOCK_BOOTTIME) if now_boot_ns is None else now_boot_ns + if type(stamp) is not int or stamp <= 0 or not helper.tesla_set_speed: + return + good, document = _settings(card, stamp) + if not good: + return + target = float(helper.v_cruise_kph) + if not math.isfinite(target) or not 0 < target < 255 or abs(target - float(state.vCruise)) > 1e-4: + return + identity = hashlib.sha256(repr((str(cp.carFingerprint), card.is_metric)).encode()).hexdigest() + # The driver's own scrolls that card has applied: speed sync matches each to the scroll it saw on the car's bus, + # and hands back the ones it has taken so they are dropped here. + consumer = getattr(card, "controller_cruise_consumer", None) + receipts = () + if consumer is not None: + consumer.acknowledge_tesla_receipts(controller.speed_sync.take_manual_receipt_acks()) + receipts = consumer.peek_tesla_receipts(stamp) + drive = int(card.sm["deviceState"].startedMonoTime) if getattr(card, "sm", None) is not None else 0 + controller.speed_sync_authority = SyncAuthority(stamp, float(state.vCruise), card.is_metric, identity, True, + document, _vehicle(card), drive, receipts) + except (AttributeError, KeyError, TypeError, ValueError, OverflowError, OSError, RuntimeError): + return diff --git a/openpilot/starpilot/common/car_control_config.py b/openpilot/starpilot/common/car_control_config.py new file mode 100644 index 0000000000..bd064d79b7 --- /dev/null +++ b/openpilot/starpilot/common/car_control_config.py @@ -0,0 +1,113 @@ +"""Pure car-control configuration shared by the input daemon and cruise owner.""" +import json +import math + +INPUTS = {} +for action, label in [('left','Nudge left'),('right','Nudge right'),('up','Scroll up'),('down','Scroll down')]: + INPUTS[f'right_wheel_{action}'] = ('Right scroll wheel', label) +for direction in ('up', 'down'): + for stage in ('half', 'full'): + INPUTS[f'right_stalk_{direction}_{stage}'] = ('Right stalk', f'{direction.title()} — {stage} press') +# A quick press down while cruise is already on; a press that engages cruise is not one. The half press keeps its +# original key (it was the only "tap while engaged" before the full press had its own). +STALK_TAP = 'right_stalk_down_tap_engaged' +INPUTS[STALK_TAP] = ('Right stalk', 'Down — half press while engaged') +STALK_TAP_FULL = 'right_stalk_down_full_engaged' +INPUTS[STALK_TAP_FULL] = ('Right stalk', 'Down — full press while engaged') +# Holding the stalk down also makes the Tesla set its own speed to the limit it detects (after about a second). +STALK_HOLD = 'right_stalk_down_hold' +INPUTS[STALK_HOLD] = ('Right stalk', 'Down — hold') +INPUTS['park_press'] = ('Right stalk', 'Park button') +# The right scroll wheel nudged left or right and held: each plain nudge -> its hold control. +WHEEL_HOLDS = {} +for _base, _label in (('right_wheel_left', 'Nudge left'), ('right_wheel_right', 'Nudge right')): + WHEEL_HOLDS[_base] = _base + '_hold' + INPUTS[_base + '_hold'] = ('Right scroll wheel', _label + ' — hold') +INPUTS['screen_three_finger_tap'] = ('Tesla screen', 'Three-finger tap') + + +PARAM = 'CarControlAssignments' +MAX_ASSIGNMENT_BYTES = 16384 # the Wheel Controls editor writes no more than this +MODELS = ('TESLA_MODEL_3', 'TESLA_MODEL_Y') + + +def parse_assignments(raw): + if raw in (None, '', b'') or raw == {}: + return {'version':1, 'vehicle':'', 'bindings':{}} + try: + data = json.loads(raw) if isinstance(raw, (str, bytes)) else raw + if data == {}: + return {'version':1, 'vehicle':'', 'bindings':{}} + if not isinstance(data, dict) or set(data) != {'version','vehicle','bindings'}: + return None + if type(data['version']) is not int or data['version'] != 1 or data['vehicle'] not in MODELS or not isinstance(data['bindings'], dict): + return None + for name, binding in data['bindings'].items(): + if name not in INPUTS or not isinstance(binding, dict) or set(binding) != {'key','value','label'}: + return None + if not isinstance(binding['key'], str) or not binding['key'] or not isinstance(binding['label'], str): + return None + value = binding['value'] + if value is not None and (type(value) not in (int,float) or not math.isfinite(value)): + return None + return data + except (ValueError, TypeError, UnicodeError): + return None + + +SPEED_UP = '__starpilot_controller_action__:comma_speed_up' +SPEED_DOWN = '__starpilot_controller_action__:comma_speed_down' +SPEED_SET = '__starpilot_controller_action__:set_speed' +SPEED_RESUME = '__starpilot_controller_action__:resume_speed_limit' +SPEED_ACTIONS = frozenset((SPEED_UP, SPEED_DOWN, SPEED_SET, SPEED_RESUME)) +# Why Resume is unavailable while SLC runs but has no live limit (the map source drops out for a second or two). +NO_LIMIT_REASON = 'No current speed limit' +# An explicit "Unassigned" saved over a default binding. +NO_ACTION = '__starpilot_controller_action__:none' +_RESUME = {'key': SPEED_RESUME, 'value': None, 'label': 'Resume Speed Limit + Offset'} +# Holding the right stalk down always sets the comma speed to its limit (the Tesla sets its own limit too). +FIXED_BINDINGS = {STALK_HOLD: _RESUME} +# The favorites catalog's Cycle Driving Personality (favorites/actions.py CYCLE_PERSONALITY; this module imports nothing). +CYCLE_PERSONALITY = '__starpilot_controller_action__:cycle_driving_personality' +# What a control starts on until it is changed: the half press while engaged on the hold's action, and the right scroll +# wheel's nudge right on Cycle Driving Personality. +DEFAULT_BINDINGS = {STALK_TAP: _RESUME, + 'right_wheel_right': {'key': CYCLE_PERSONALITY, 'value': None, 'label': 'Cycle Driving Personality'}} + + +# The right scroll wheel's scroll is never assignable. While the comma owns the set speed (Comma can set speed on Tesla +# dashboard is on) a scroll moves the comma's set speed, by 1 or to the next multiple of 5 for a fast scroll, as the Tesla's +# own cruise does; otherwise the scroll is left to the Tesla. +SCROLL_BINDINGS = {'right_wheel_up': {'key': SPEED_UP, 'value': None, 'label': 'Increase Comma Set Speed'}, + 'right_wheel_down': {'key': SPEED_DOWN, 'value': None, 'label': 'Decrease Comma Set Speed'}} +# The Tesla controls StarPilot uses: the right scroll wheel, the right stalk's presses while engaged and its hold, and the +# screen tap. The others steer, signal, light, wipe or shift the car. +ACTIVE_INPUTS = frozenset(('right_wheel_up', 'right_wheel_down', 'right_wheel_left', 'right_wheel_right', *WHEEL_HOLDS.values(), + STALK_TAP, STALK_TAP_FULL, STALK_HOLD, 'screen_three_finger_tap')) + + +def effective_bindings(document, *, comma_speed=False): + """The bindings that act: saved ones over the defaults, with the fixed ones always, explicit Unassigned removed, and only + on the controls StarPilot uses. comma_speed: the comma owns the set speed on this car, so the scroll sets it.""" + bindings = {**DEFAULT_BINDINGS, **(document['bindings'] if document else {}), **FIXED_BINDINGS} + bindings = {name: binding for name, binding in bindings.items() if name not in SCROLL_BINDINGS} + if comma_speed: + bindings.update(SCROLL_BINDINGS) + return {name: binding for name, binding in bindings.items() if binding['key'] != NO_ACTION and name in ACTIVE_INPUTS} + + +def comma_speed(params, cp): + """Comma can set speed on Tesla dashboard is on for this car: the comma owns the set speed.""" + from openpilot.starpilot.car.tesla.set_speed import active + return active(params, cp) + + +def vehicle_supported(cp): + from opendbc.car.tesla.values import TeslaFlags + return bool(cp is not None and cp.carFingerprint in MODELS and cp.brand=='tesla' and + cp.flags & TeslaFlags.HAS_VEHICLE_BUS and not cp.passive and not cp.notCar and not cp.dashcamOnly) + +def screen_reserved(cp): + from opendbc.car.tesla.values import TeslaFlags,TeslaSafetyFlags + return bool(cp.flags & TeslaFlags.AOL_SCREEN_BUTTON or + any(s.safetyParam & TeslaSafetyFlags.AOL_SCREEN_BUTTON for s in cp.safetyConfigs)) diff --git a/openpilot/starpilot/controllers/cruise_action.py b/openpilot/starpilot/controllers/cruise_action.py index 7d4d1da114..64f0fbde42 100644 --- a/openpilot/starpilot/controllers/cruise_action.py +++ b/openpilot/starpilot/controllers/cruise_action.py @@ -3,6 +3,7 @@ import math import re import secrets +import time from openpilot.cereal import messaging from opendbc.car.structs import car @@ -11,10 +12,21 @@ from openpilot.starpilot.conditional_mode.ui_action import fresh_service LIFETIME_NS = 250_000_000 SESSION = re.compile(r"[0-9a-f]{32}\Z") +# A Tesla scroll: one display unit, or to the next multiple of five for a fast scroll, as the Tesla's own cruise steps. +TESLA_STEPS = (-5, -1, 1, 5) +# How long speed sync can still match a receipt to its scroll (opendbc speed_sync MANUAL_COMPLETION_NS). +TESLA_RECEIPT_NS = 2_000_000_000 + + +def tesla_set_speed(cp) -> bool: + """A Tesla Model 3/Y where StarPilot may own SET beside the car's own cruise (Comma can set speed on Tesla dashboard). + Card applies a request only while the switch is on (helper.tesla_set_speed).""" + from opendbc.car.tesla.speed_sync import selected + return selected(cp) def eligible(cp) -> bool: - return bool(cp is not None and not cp.pcmCruise and cp.openpilotLongitudinalControl and + return bool(cp is not None and (not cp.pcmCruise or tesla_set_speed(cp)) and cp.openpilotLongitudinalControl and not cp.passive and not cp.dashcamOnly and not cp.notCar) @@ -35,22 +47,37 @@ class CruiseActionPublisher: self.session = secrets.token_hex(16) self.sequence = 0 - def dispatch(self, increase: bool, sm, cp, publisher, *, now_ns: int, target_mps: float | None = None) -> bool: + def dispatch(self, increase: bool, sm, cp, publisher, *, now_ns: int, target_mps: float | None = None, + step_units: int | None = None) -> bool: if (target_mps is not None and (type(target_mps) not in (int, float) or not math.isfinite(target_mps) or not V_CRUISE_MIN / 3.6 <= target_mps <= V_CRUISE_MAX / 3.6)) or not ui_authority(sm, cp, now_ns): return False + if step_units is not None and (type(step_units) is not int or step_units not in TESLA_STEPS or target_mps is not None or + not tesla_set_speed(cp)): + return False self.sequence += 1 msg = messaging.new_message("slcAction", valid=True) msg.logMonoTime = now_ns - msg.slcAction.kind = "cruiseSet" if target_mps is not None else "cruiseIncrease" if increase else "cruiseDecrease" + msg.slcAction.kind = ("cruiseStep" if step_units is not None else "cruiseSet" if target_mps is not None else + "cruiseIncrease" if increase else "cruiseDecrease") msg.slcAction.controllerCruise = { "version": 1, "sessionId": self.session, "sequence": self.sequence, "observedMonoTime": now_ns, "validUntilMonoTime": now_ns + LIFETIME_NS, "driveStartMonoTime": int(sm["deviceState"].startedMonoTime), "carFingerprint": cp.carFingerprint, "sourceCarControlMonoTime": int(sm.logMonoTime["carControl"]), } + if step_units is not None: + msg.slcAction.controllerCruise.stepUnits = step_units if target_mps is not None: msg.slcAction.controllerCruise.targetSpeedMps = float(target_mps) + if step_units is not None: + # Which physical scroll this step came from. Metadata accompanies the action; it never creates or alters one. + from openpilot.starpilot.controllers.tesla_gesture_context import current_source + source = current_source() + if source is not None and source.step == step_units and source.drive == int(sm["deviceState"].startedMonoTime): + now_boot = time.clock_gettime_ns(time.CLOCK_BOOTTIME) + if 0 < source.boot_ns <= now_boot <= source.boot_ns + 500_000_000: + msg.slcAction.controllerCruise.sourceTeslaGesture = source.to_wire() publisher.send("slcAction", msg) return True @@ -60,11 +87,48 @@ class CruiseActionConsumer: self.sequences = {} self.drive = 0 self.last_apply_ns = 0 + # Tesla scroll steps this consumer applied, for speed sync to match to the scrolls it saw on the car's bus. + self.tesla_receipts = [] + + def peek_tesla_receipts(self, now_boot_ns: int): + """The receipts still worth offering. One that speed sync has not taken within its own window never will be + (it did not see that scroll, or the receipt failed its checks), so it is dropped here.""" + self.tesla_receipts[:] = [item for item in self.tesla_receipts if 0 <= now_boot_ns - item.boot_ns <= TESLA_RECEIPT_NS] + return tuple(self.tesla_receipts) + + def acknowledge_tesla_receipts(self, receipts): + # Only discard the exact metadata that the synchronizer accepted. + if type(receipts) is not tuple or len(receipts) > 16: + return + self.tesla_receipts[:] = [item for item in self.tesla_receipts if item not in receipts] + + def _record_tesla_receipt(self, request, cp, helper): + # Never turn missing or bad optional metadata into a second action or a retry. + try: + from openpilot.starpilot.controllers.tesla_gesture_context import parse_source + from openpilot.starpilot.controllers.wheel_actions import cp_fingerprint + from opendbc.car.tesla.speed_sync import ManualReceipt + source = parse_source(request.sourceTeslaGesture.to_dict()) + now_boot = time.clock_gettime_ns(time.CLOCK_BOOTTIME) + target = float(helper.v_cruise_kph) + if (source is None or source.drive != self.drive or source.vehicle != cp_fingerprint(cp) or + source.step != int(request.stepUnits) or not math.isfinite(target) or not 0 < target < 255 or + not 0 < source.boot_ns <= now_boot <= source.boot_ns + TESLA_RECEIPT_NS): + return + if len(self.tesla_receipts) >= 16: + return # speed sync then treats this scroll like one the comma did not act on + self.tesla_receipts.append(ManualReceipt(source.boot_ns, source.frame_index, source.name, source.fast, + source.worker_session, source.sequence, source.document, + source.vehicle, source.drive, now_boot, target)) + except (AttributeError, KeyError, TypeError, ValueError, OverflowError): + return def apply(self, msg, cp, cs, sm, helper, *, now_ns: int, is_metric: bool, enabled: bool) -> bool: try: kind = str(msg.slcAction.kind) - if kind not in ("cruiseIncrease", "cruiseDecrease", "cruiseSet") or not msg.valid: + if kind not in ("cruiseIncrease", "cruiseDecrease", "cruiseSet", "cruiseStep") or not msg.valid: + return False + if kind == "cruiseStep" and not getattr(helper, 'tesla_set_speed', False): return False request = msg.slcAction.controllerCruise drive = int(sm["deviceState"].startedMonoTime) @@ -72,10 +136,12 @@ class CruiseActionConsumer: self.sequences.clear() self.drive = drive self.last_apply_ns = 0 + self.tesla_receipts.clear() session, sequence = str(request.sessionId), int(request.sequence) observed, expires = int(request.observedMonoTime), int(request.validUntilMonoTime) source = int(request.sourceCarControlMonoTime) - if not (eligible(cp) and enabled and not cs.buttonEvents and now_ns - self.last_apply_ns >= 100_000_000 and + if not (eligible(cp) and (not cp.pcmCruise or getattr(helper, 'tesla_set_speed', False)) and + enabled and not cs.buttonEvents and now_ns - self.last_apply_ns >= 100_000_000 and cs.canValid and not cs.canTimeout and cs.cruiseState.available and sm["deviceState"].started and fresh_service(sm, "deviceState", drive, now_ns, 1_000_000_000) and fresh_service(sm, "carControl", drive, now_ns) and sm["carControl"].enabled and @@ -89,14 +155,26 @@ class CruiseActionConsumer: return False self.sequences[session] = sequence self.last_apply_ns = now_ns - if kind == "cruiseSet": + if kind in ("cruiseSet", "cruiseStep"): target = float(request.targetSpeedMps) + if kind == "cruiseStep": + step = int(request.stepUnits) + if step not in TESLA_STEPS or not helper.v_cruise_initialized: + return False + unit = 1 / 3.6 if is_metric else .44704 + # Step from the displayed selection, avoiding rounded kph/mph boundary drift. + displayed = math.floor(helper.v_cruise_kph / 3.6 / unit + .5) + value = (displayed + step if abs(step) == 1 else + (displayed // 5 + 1) * 5 if step > 0 else ((displayed - 1) // 5) * 5) + target = value * unit if not math.isfinite(target) or not V_CRUISE_MIN / 3.6 - 1e-5 <= target <= V_CRUISE_MAX / 3.6 + 1e-5: return False previous = helper.v_cruise_kph helper.apply_slc_target(target, is_metric) if helper.v_cruise_kph != previous: helper.slc_cruise_change = (float(previous / 3.6), float(helper.v_cruise_kph / 3.6), 'accel' if helper.v_cruise_kph > previous else 'decel', False) + if kind == "cruiseStep": + self._record_tesla_receipt(request, cp, helper) return True button = car.CarState.ButtonEvent.Type.accelCruise if kind == "cruiseIncrease" else car.CarState.ButtonEvent.Type.decelCruise return helper.adjust_v_cruise(button, cs, is_metric) diff --git a/openpilot/starpilot/controllers/runtime.py b/openpilot/starpilot/controllers/runtime.py index 7969ad43c1..324b520597 100644 --- a/openpilot/starpilot/controllers/runtime.py +++ b/openpilot/starpilot/controllers/runtime.py @@ -10,11 +10,15 @@ LOGGER = logging.getLogger(__name__) class ControllerRuntime: - def __init__(self, params, *, actions, favorites, invoke_favorite, authority=None, reader=None, socket_path=None, input_capture=lambda: None): + def __init__(self, params, *, actions, favorites, invoke_favorite, authority=None, reader=None, socket_path=None, + vehicle=lambda: None, messages=lambda: None, input_capture=lambda: None, speed_actions=None, keyed_actions=None): self.authority = authority if authority is not None else LiveContextSource(params) self.reader = reader if reader is not None else InputReader() self.owner = ControllerOwner(params, parked=self.authority.parked, actions=actions, favorites=favorites, invoke_favorite=invoke_favorite) + from openpilot.starpilot.controllers.tesla_receiver import TeslaReceiver + self.tesla = TeslaReceiver(params, actions, vehicle, messages=messages, speed_actions=speed_actions, + keyed_actions=keyed_actions) self.service = ControllerService(self.owner, socket_path) self.input_capture = input_capture self._closed = False @@ -29,6 +33,12 @@ class ControllerRuntime: def poll(self): if self._closed: return + try: + self.tesla.poll() + except Exception: + LOGGER.exception('Tesla input stopped') + self.tesla.close() + self.tesla.next_start = time.monotonic() + 2. try: now = time.monotonic() if now >= self._next_warm: @@ -53,6 +63,7 @@ class ControllerRuntime: if self._closed: return self._closed = True + self.tesla.close() try: self.service.close() finally: diff --git a/openpilot/starpilot/controllers/tesla_controls.py b/openpilot/starpilot/controllers/tesla_controls.py new file mode 100644 index 0000000000..dfd10388f2 --- /dev/null +++ b/openpilot/starpilot/controllers/tesla_controls.py @@ -0,0 +1,301 @@ +"""Optional, receive-only Model 3/Y inputs. Never participates in CAN validity.""" +from dataclasses import dataclass +from typing import Any + +from openpilot.starpilot.common.car_control_config import STALK_HOLD, STALK_TAP, STALK_TAP_FULL, WHEEL_HOLDS + +# Raw scroll count in one ~100 ms packet; retain the peak until neutral. +FAST_SCROLL_TICKS = 2 +# Wheel tilts and presses, which can end with one stray scroll click as the wheel springs back. +NUDGES = frozenset(f'{side}_wheel_{action}' for side in ('left', 'right') for action in ('left', 'right', 'press')) +# Holding the right stalk down sets the Tesla's own set speed to its detected limit after about 1 s (measured 1.02 to +# 1.07 s into a hold); taps to engage last under 0.4 s. The hold fires earlier, so the comma's own change lands first +# and the Tesla's reply is not adopted as a driver change. A down press shorter than this, started once cruise had been +# on for ENGAGED_BEFORE_PRESS_SECONDS, is a tap while engaged. +HOLD_SECONDS = .6 +# A down press counts as "while engaged" only if cruise had already been on for this long, in frame time, when the press +# started. The car engages on the same press that engages cruise, so cruise is already on by that press's first frames. +ENGAGED_BEFORE_PRESS_SECONDS = .5 +# The right scroll wheel nudged left or right. Its status arrives every 0.1 s: a quick nudge reads as one or two frames, +# a 1.3 s hold as thirteen. A hold fires once while the wheel is still held, and its release then gives nothing. +WHEEL_HOLD_SECONDS = .6 +WHEEL_FRAME_GAP_SECONDS = .35 # three missed frames: start again +WHEEL_TIME_SLACK = .005 # frame times jitter by a few ms: six 0.1 s intervals count as 0.6 s + + +class WheelHold: + """Hold of one right scroll wheel nudge, from its 10 Hz pressed bit.""" + + def __init__(self): + self.clear() + + def clear(self): + self.armed = False # a released frame has been seen since the last clear + self.start = None # when the current nudge was first seen + self.fired = False # the current nudge already gave its hold + self.last = None + + def update(self, pressed, timestamp): + """True once, when the nudge has been held for WHEEL_HOLD_SECONDS.""" + if self.last is not None and not 0 < timestamp - self.last <= WHEEL_FRAME_GAP_SECONDS: + self.clear() + self.last = timestamp + if not pressed: + self.armed, self.start, self.fired = True, None, False + return False + if not self.armed: + return False + if self.start is None: + self.start = timestamp + return False + if not self.fired and timestamp - self.start >= WHEEL_HOLD_SECONDS - WHEEL_TIME_SLACK: + self.fired = True + return True + return False + + +@dataclass +class Gesture: + armed: bool = False + key: str | None = None + family: str | None = None + rank: int = 0 + + def clear(self): + self.armed, self.key, self.family, self.rank = False, None, None, 0 + + def update(self, values, details=False): + if values is None or len(values) > 1: + self.clear() + return [] + if not values: + result = [(self.key, self.rank) if details else self.key] if self.armed and self.key else [] + self.clear() + self.armed = True + return result + if not self.armed: + return [] + key, family, rank = values[0] + if self.family is not None and family != self.family: + if (self.key in NUDGES and family in (f"{self.key.split('_')[0]}_wheel_up", f"{self.key.split('_')[0]}_wheel_down") + and rank == 1): + # A wheel tilted or pressed often clicks once as it springs back: that click ends the nudge (or press) and is + # not a scroll. Emit the nudge; the next neutral frame arms the next gesture. + result = [(self.key, self.rank) if details else self.key] + self.clear() + return result + self.clear() + elif rank >= self.rank: + self.key, self.family, self.rank = key, family, rank + return [] + + +class ScreenGesture: + """Asynchronous count-only touch input; emit once on complete release.""" + MAX_DURATION = 1.2 + + def __init__(self): + self.clear() + + def clear(self): + self.armed = False + self.started = None + self.peak = 0 + self.last = None + + def feed(self, data, timestamp, details): + if len(data) != 8 or (self.last is not None and timestamp < self.last): + self.clear() + return [] + self.last = timestamp + count = data[3] + if count == 0: + emit = self.armed and self.peak == 3 and self.started is not None and 0 < timestamp - self.started <= self.MAX_DURATION + self.clear() + self.armed, self.last = True, timestamp + return [('screen_three_finger_tap', False) if details else 'screen_three_finger_tap'] if emit else [] + if not self.armed: + return [] + if self.started is None: + self.started = timestamp + self.peak = max(self.peak, count) + if self.peak > 3 or timestamp - self.started > self.MAX_DURATION: + self.armed = False + return [] + + +class TeslaInputDecoder: + # >3x measured maximum intervals: wheel (mux 1) .2031s, right stalk .2032s. + TIMEOUTS = {0x3c2: .75, 0x229: .75, 0x3df: None} + + def __init__(self, bus, *, stalk_hold=False, stalk_tap=False, stalk_tap_full=False, wheel_holds=()): + self.bus = bus + # Only the assigned ones: each right scroll wheel nudge's hold control. + self.wheel_holds = {base: name for base, name in WHEEL_HOLDS.items() if name in wheel_holds} + # Only when assigned: a hold, or a half / full press while engaged, then replaces the down press it would end as. + self.stalk_hold = stalk_hold + self.stalk_tap = stalk_tap + self.stalk_tap_full = stalk_tap_full + # The worker sets this from carState before feeding each batch of frames. + self.cruise_engaged = False + self.reset() + + def reset(self): + previous_screen = getattr(self, 'groups', {}).get(0x3df) + released = bool(previous_screen and previous_screen.armed and previous_screen.started is None) + # One Gesture per wheel or stalk message, and the ScreenGesture for the touch count. + self.groups: dict[int, Any] = {address: Gesture() for address in self.TIMEOUTS} + self.groups[0x3df] = ScreenGesture() + # Keep a positively observed released baseline, never an in-progress touch. + self.groups[0x3df].armed = released + self.last = {} + self.counters = {} + self.states = {} + self.lengths = {} + self.down_start = None + self.down_engaged = False + self.wheel_presses = {base: WheelHold() for base in WHEEL_HOLDS} + # Frame time of the first frame seen with cruise on; None while cruise is off. + self.engaged_since = None + + @staticmethod + def _wheel(bits): + values = [] + for name, shift in [('left_wheel_left',14),('left_wheel_right',3),('left_wheel_press',5), + ('right_wheel_left',8),('right_wheel_right',10),('right_wheel_press',12)]: + value = (bits >> shift) & 3 + if value not in (1, 2): + return None + if value == 2: + values.append((name, name, 1)) + for side, shift in [('left',16),('right',24)]: + value = (bits >> shift) & 63 + value = value - 64 if value >= 32 else value + if value: + key = f'{side}_wheel_{"up" if value > 0 else "down"}' + values.append((key, key, abs(value))) + return values + + @staticmethod + def _stalk(bits): + """The right stalk's position and its Park button.""" + values = [] + def add(value, mapping): + if value == 0: + return True + entry = mapping.get(value) + if entry is None: + return False + values.append(entry) + return True + good = add((bits >> 12) & 7, { + 1: ('right_stalk_up_half','right_stalk_up',1), 2: ('right_stalk_up_full','right_stalk_up',2), + 3: ('right_stalk_down_half','right_stalk_down',1), 4: ('right_stalk_down_full','right_stalk_down',2), + }) and add((bits >> 16) & 3, {1: ('park_press','park_press',1)}) + return values if good else None + + def _stalk_down(self, group, values, timestamp, released): + """The right stalk down from neutral: a hold (fires once while still held; the release then emits nothing) or a tap + while engaged (a release before HOLD_SECONDS of a press that started with cruise already on for + ENGAGED_BEFORE_PRESS_SECONDS). None keeps the plain press.""" + if group.armed and values and len(values) == 1 and values[0][1] == 'right_stalk_down': + if self.down_start is None: + self.down_start = timestamp + self.down_engaged = (self.engaged_since is not None and + timestamp - self.engaged_since >= ENGAGED_BEFORE_PRESS_SECONDS) + elif self.stalk_hold and timestamp - self.down_start >= HOLD_SECONDS: + group.clear() + self.down_start = None + return STALK_HOLD + return None + start, engaged = self.down_start, self.down_engaged + self.down_start, self.down_engaged = None, False + if (engaged and start is not None and len(released) == 1 and timestamp - start < HOLD_SECONDS and + released[0] in ('right_stalk_down_half', 'right_stalk_down_full')): + if released[0] == 'right_stalk_down_half' and self.stalk_tap: + return STALK_TAP + if released[0] == 'right_stalk_down_full' and self.stalk_tap_full: + return STALK_TAP_FULL + return None + + def _wheel_hold(self, values, timestamp): + """The assigned hold that this frame completes, or None. Each nudge counts on its own: tilting the other way, + pressing or scrolling the right wheel at the same time is not its hold (one stray scroll click as the wheel moves is + allowed), and the left wheel is its own business.""" + if values is None: + for press in self.wheel_presses.values(): + press.clear() + return None + right = [(key, rank) for key, _, rank in values if key.startswith('right_wheel_')] + fired = None + for base, press in self.wheel_presses.items(): + if any(key != base and not (key.endswith(('_up', '_down')) and rank == 1) for key, rank in right): + press.clear() + continue + if press.update(any(key == base for key, _ in right), timestamp) and fired is None: + fired = self.wheel_holds.get(base) + return fired + + def feed(self, address, data, bus, timestamp, *, details=False): + if bus != self.bus or address not in self.groups: + return [] + if not self.cruise_engaged: + self.engaged_since = None + elif self.engaged_since is None: + self.engaged_since = timestamp + group = self.groups[address] + if address == 0x3df: + return group.feed(data, timestamp, details) + if len(data) != (8 if address == 0x3c2 else 3): + group.clear() + return [] + bits = int.from_bytes(data, 'little') + if address == 0x3c2 and bits & 3 != 1: + if bits & 3 in (2,3): + group.clear() + return [] + previous = self.last.get(address) + if previous is not None and timestamp < previous: + group.clear() + return [] + if previous is None or timestamp - previous > self.TIMEOUTS[address]: + group.clear() + self.counters.pop(address, None) + self.last[address] = timestamp + if self.lengths.get(address, len(data)) != len(data): + group.clear() + self.counters.pop(address, None) + self.lengths[address] = len(data) + if address != 0x3c2: + counter = (bits >> 8) & 15 + previous_counter = self.counters.get(address) + previous_state = self.states.get(address) + self.states[address] = bits >> 12 + self.counters[address] = counter + if previous_counter is not None: + delta = (counter - previous_counter) % 16 + if delta == 0: + # Captured Park event followed by its periodic release reuses the + # counter. Permit that exact state-bit transition, never a stalk move. + park_only_change = address == 0x229 and previous_state is not None and (previous_state ^ (bits >> 12)) == 16 + if not park_only_change: + if previous_state != bits >> 12: + group.clear() + return [] + if delta not in (0, 1): + group.clear() + values = self._wheel(bits) if address == 0x3c2 else self._stalk(bits) + hold = self._wheel_hold(values, timestamp) if address == 0x3c2 and self.wheel_holds else None + if hold: + group.clear() # the release that follows is part of this hold + return [(hold, False)] if details else [hold] + result = group.update(values, details=details) + if address == 0x229 and (self.stalk_hold or self.stalk_tap or self.stalk_tap_full): + released = [item[0] if details else item for item in result] + special = self._stalk_down(group, values, timestamp, released) + if special: + return [(special, False)] if details else [special] + if details: + return [(key, address == 0x3c2 and key.endswith(('_wheel_up', '_wheel_down')) and rank >= FAST_SCROLL_TICKS) + for key, rank in result] + return result diff --git a/openpilot/starpilot/controllers/tesla_gesture_context.py b/openpilot/starpilot/controllers/tesla_gesture_context.py new file mode 100644 index 0000000000..30c9ae4c07 --- /dev/null +++ b/openpilot/starpilot/controllers/tesla_gesture_context.py @@ -0,0 +1,79 @@ +"""Speed sync: optional gesture identity. Carries context, never dispatches actions.""" +from contextlib import contextmanager +from contextvars import ContextVar +from dataclasses import dataclass +import re + +HEX32 = re.compile(r"[0-9a-f]{32}\Z") +HEX64 = re.compile(r"[0-9a-f]{64}\Z") +_FIELDS = {"version", "workerSession", "sequence", "sourceCanBootTime", "sourceCanFrameIndex", + "name", "fast", "assignmentsHash", "vehicleHash", "driveStartMonoTime"} +_current = ContextVar("tesla_gesture", default=None) + + +@dataclass(frozen=True) +class GestureSource: + worker_session: str + sequence: int + boot_ns: int + frame_index: int + name: str + fast: bool + document: str + vehicle: str + drive: int + + def to_wire(self): + return {"version": 1, "workerSession": self.worker_session, "sequence": self.sequence, + "sourceCanBootTime": self.boot_ns, "sourceCanFrameIndex": self.frame_index, + "name": self.name, "fast": self.fast, "assignmentsHash": self.document, + "vehicleHash": self.vehicle, "driveStartMonoTime": self.drive} + + @property + def step(self): + """The comma speed step this scroll produces: one unit, or five (to the next multiple of five) for a fast scroll.""" + return (1 if self.name == "right_wheel_up" else -1) * (5 if self.fast else 1) + + +def parse_source(value): + try: + if not isinstance(value, dict) or set(value) != _FIELDS: + return None + if (type(value["version"]) is not int or value["version"] != 1 or + any(type(value[k]) is not int or not 0 < value[k] < 2**64 + for k in ("sequence", "sourceCanBootTime", "driveStartMonoTime")) or + type(value["sourceCanFrameIndex"]) is not int or not 0 <= value["sourceCanFrameIndex"] < 4096 or + type(value["fast"]) is not bool or value["name"] not in ("right_wheel_up", "right_wheel_down") or + type(value["workerSession"]) is not str or not HEX32.fullmatch(value["workerSession"]) or + any(type(value[k]) is not str or not HEX64.fullmatch(value[k]) + for k in ("assignmentsHash", "vehicleHash"))): + return None + return GestureSource(value["workerSession"], value["sequence"], value["sourceCanBootTime"], + value["sourceCanFrameIndex"], value["name"], value["fast"], + value["assignmentsHash"], value["vehicleHash"], value["driveStartMonoTime"]) + except (KeyError, TypeError, ValueError): + return None + + +def source_from_event(event): + source = parse_source(event.get("provenance")) + if source is None: + return None + if (source.sequence != event["sequence"] or source.name != event["name"] or + source.fast != event["fast"] or source.document != event["document"] or + source.vehicle != event["vehicle"] or source.drive != event["drive"]): + return None + return source + + +@contextmanager +def source_scope(event): + token = _current.set(source_from_event(event)) + try: + yield + finally: + _current.reset(token) + + +def current_source(): + return _current.get() diff --git a/openpilot/starpilot/controllers/tesla_input_protocol.py b/openpilot/starpilot/controllers/tesla_input_protocol.py new file mode 100644 index 0000000000..e2f63be83e --- /dev/null +++ b/openpilot/starpilot/controllers/tesla_input_protocol.py @@ -0,0 +1,69 @@ +"""Tesla input worker: private receiver protocol; no authority is granted by the worker.""" +import hashlib +import json +import math + +from openpilot.starpilot.conditional_mode.ui_action import fresh_service + +MAX_PACKET = 2048 +MAX_EVENTS = 4 +MAX_AGE = .25 +# The worker's first message: it is up and reading CAN. +READY = b'TESLA_INPUT_READY' + + +def drive_id(sm, now): + try: + now_ns = int(now * 1e9) + drive = int(sm['deviceState'].startedMonoTime) + if (sm['deviceState'].started and 0 < drive < now_ns + and fresh_service(sm, 'deviceState', drive, now_ns, 1_000_000_000) + and fresh_service(sm, 'carState', drive, now_ns) + and sm['carState'].canValid and not sm['carState'].canTimeout): + return drive + except (AttributeError, KeyError, TypeError, ValueError, OverflowError): + pass + return None + + +def document_hash(raw): + return hashlib.sha256(raw).hexdigest() + + +def encode_event(sequence, name, fast, stamp, drive, document, vehicle, *, provenance=None): + value = {'version': 1, 'sequence': sequence, 'name': name, 'fast': bool(fast), + 'stamp': stamp, 'drive': drive, 'document': document, 'vehicle': vehicle} + if provenance is not None: + # Which physical scroll this was (speed sync matches it to the frame it saw on the car's bus). + from openpilot.starpilot.controllers.tesla_gesture_context import source_from_event + value.update(version=2, provenance=provenance) + if source_from_event(value) is None: + raise ValueError("Invalid Tesla gesture provenance") + return json.dumps(value, separators=(',', ':')).encode() + + +def decode_event(raw, now): + try: + if not raw or len(raw) > MAX_PACKET: + return None + value = json.loads(raw) + keys = {'version', 'sequence', 'name', 'fast', 'stamp', 'drive', 'document', 'vehicle'} + if isinstance(value, dict) and value.get('version') == 2: + keys.add('provenance') + if (not isinstance(value, dict) or set(value) != keys + or type(value['version']) is not int or value['version'] not in (1, 2) + or type(value['sequence']) is not int or value['sequence'] <= 0 + or type(value['name']) is not str or type(value['fast']) is not bool + or type(value['stamp']) not in (int, float) or not math.isfinite(value['stamp']) + or not 0 <= now - value['stamp'] <= MAX_AGE + or type(value['drive']) is not int or not 0 < value['drive'] < value['stamp'] * 1e9 + or any(type(value[k]) is not str or len(value[k]) != 64 + or any(c not in '0123456789abcdef' for c in value[k]) for k in ('document', 'vehicle'))): + return None + if value['version'] == 2: + from openpilot.starpilot.controllers.tesla_gesture_context import source_from_event + if source_from_event(value) is None: + return None + return value + except (ValueError, TypeError, UnicodeError, OverflowError): + return None diff --git a/openpilot/starpilot/controllers/tesla_input_worker.py b/openpilot/starpilot/controllers/tesla_input_worker.py new file mode 100644 index 0000000000..4f2b7bf35d --- /dev/null +++ b/openpilot/starpilot/controllers/tesla_input_worker.py @@ -0,0 +1,190 @@ +"""Tesla input worker. Receive-only CAN; never invokes vehicle/UI actions.""" +import os +import select +import secrets +import socket +import sys +import time + +def configure_worker(): + # A subprocess can inherit UI FIFO policy/affinity at startup. This is solely + # the new custom worker's policy, not a change to any stock process. + os.sched_setscheduler(0, os.SCHED_OTHER, os.sched_param(0)) + os.setpriority(os.PRIO_PROCESS, 0, 10) + os.sched_setaffinity(0, {0, 1, 2, 3}) + + +if __name__ == '__main__': + configure_worker() + +from openpilot.starpilot.common.car_control_config import (PARAM, MAX_ASSIGNMENT_BYTES, STALK_HOLD, STALK_TAP, STALK_TAP_FULL, + WHEEL_HOLDS, effective_bindings, parse_assignments, + vehicle_supported, screen_reserved) +from openpilot.starpilot.car.tesla.set_speed import Polled +from opendbc.car.tesla.speed_sync import selected as speed_sync_selected +from openpilot.starpilot.saved_source import read_saved +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 + + +class InputPump: + def __init__(self, params, send, *, socket_factory, receive, clock=time.monotonic, boot_clock_ns=None): + self.params, self.send, self.clock = params, send, clock + self.boot_clock_ns = boot_clock_ns or (lambda: time.clock_gettime_ns(time.CLOCK_BOOTTIME)) + self.worker_session = secrets.token_hex(16) + # Speed sync is admitted on this car: each scroll carries where it was seen on the bus. + self.sync_provenance = False + self.comma_speed = Polled(params, clock) + self.socket_factory, self.receive = socket_factory, receive + self.socket = None + self.decoder: TeslaInputDecoder | None = None + self.identity = None + self.sequence = 0 + self.raw = None + self.document = None + self.cp = None + self.cp_hash = None + + def reset(self): + self.socket = None + self.decoder = None + self.identity = None + + def set_vehicle(self, cp): + fingerprint = cp_fingerprint(cp) if vehicle_supported(cp) else None + provenance = bool(fingerprint) and speed_sync_selected(cp) + if fingerprint != self.cp_hash or provenance != self.sync_provenance: + self.reset() + self.cp = cp + self.sync_provenance = provenance + self.cp_hash = fingerprint + + def poll(self, sm): + cp = self.cp + now = self.clock() + drive = drive_id(sm, now) + if (not self.cp_hash or drive is None or + read_saved(self.params, 'SafeMode', 8) not in ((None, True), (b'0', True))): + self.reset() + return + raw, readable = read_saved(self.params, PARAM, MAX_ASSIGNMENT_BYTES) + if raw != self.raw: + 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 {}) + if not bindings: + self.reset() + return + identity = (raw, self.cp_hash, drive, 'right_wheel_up' in bindings) + if identity != self.identity: + self.reset() + self.identity = identity + from opendbc.car.tesla.values import CANBUS + self.decoder = TeslaInputDecoder(CANBUS.vehicle, stalk_hold=STALK_HOLD in bindings, + stalk_tap=STALK_TAP in bindings, stalk_tap_full=STALK_TAP_FULL in bindings, + wheel_holds=frozenset(name for name in WHEEL_HOLDS.values() if name in bindings)) + self.socket = self.socket_factory() + decoder = self.decoder + if decoder is None: + return + try: + decoder.cruise_engaged = bool(sm['carState'].cruiseState.enabled) + except (AttributeError, KeyError, TypeError): + decoder.cruise_engaged = False + count = 0 + # A fixed per-tick bound prevents an unending drain. If still overloaded on + # following ticks, original producer timestamps expire and reset the decoder. + for _ in range(256): + event = self.receive(self.socket) + if event is None: + break + # CAN is stamped on the boot clock. Keep that raw integer stamp for speed sync, and translate only the private + # freshness stamp to this process's monotonic clock: the two clocks are never compared directly. + source_boot_ns = int(event.logMonoTime) + before = self.clock() + boot = self.boot_clock_ns() + after = self.clock() + if not (0 <= after - before <= .005 and 0 < source_boot_ns <= boot and + boot - source_boot_ns <= int(MAX_AGE * 1e9)): + decoder.reset() + continue + stamp = after - (boot - source_boot_ns) / 1e9 + if not event.valid or not 0 <= self.clock() - stamp <= MAX_AGE: + decoder.reset() + continue + for frame_index, frame in enumerate(event.can): + # These checks precede payload conversion and decoder access. + if frame.src != decoder.bus or frame.address not in decoder.groups: + continue + for name, fast in decoder.feed(frame.address, bytes(frame.dat), frame.src, stamp, details=True): + if name == 'screen_three_finger_tap' and screen_reserved(cp): + continue + if name not in bindings or count >= 4: + continue + if (read_saved(self.params, PARAM, MAX_ASSIGNMENT_BYTES) != (raw, True) + or read_saved(self.params, 'SafeMode', 8) not in ((None, True), (b'0', True)) + or drive_id(sm, self.clock()) != drive or self.clock() - stamp > MAX_AGE): + self.reset() + return + self.sequence += 1 + provenance = None + if self.sync_provenance and name in ("right_wheel_up", "right_wheel_down"): + from openpilot.starpilot.controllers.tesla_gesture_context import GestureSource + provenance = GestureSource(self.worker_session, self.sequence, source_boot_ns, frame_index, + name, fast, document_hash(raw or b''), self.cp_hash, drive).to_wire() + packet = encode_event(self.sequence, name, fast, stamp, drive, document_hash(raw or b''), self.cp_hash, + provenance=provenance) + try: + self.send(packet) + except (BlockingIOError, OSError): + # No retry of an input action; fail the worker on a full/disconnected IPC channel. + self.reset() + raise + count += 1 + + +def main(fd, parent): + from openpilot.cereal import messaging + from openpilot.common.params import Params + + channel = socket.socket(fileno=fd) + channel.setblocking(False) + sm = messaging.SubMaster(['deviceState', 'carState', 'carParams']) + pump = InputPump(Params(), channel.send, + socket_factory=lambda: messaging.sub_sock('can'), + receive=lambda sock: messaging.recv_one_or_none(sock)) + channel.send(READY) + # Card publishes the car's parameters only every 50 s; a worker started mid-drive reads this drive's saved copy. + try: + saved = pump.params.get("CarParams") + if saved: + from opendbc.car.structs import car + pump.set_vehicle(messaging.log_from_bytes(saved, car.CarParams)) + except Exception: + pass + try: + while os.getppid() == parent: + # Closure is observed even when no gestures occur. No UI heartbeat writes. + if select.select([channel], [], [], 0)[0]: + break + sm.update(0) + if sm.updated['carParams']: + pump.set_vehicle(sm['carParams'].as_builder().as_reader()) + pump.poll(sm) + time.sleep(.01) + finally: + pump.reset() + channel.close() + + +if __name__ == '__main__': + from openpilot.common.swaglog import cloudlog + try: + main(int(sys.argv[1]), int(sys.argv[2])) + except Exception: + cloudlog.exception('Tesla input worker failed') + raise diff --git a/openpilot/starpilot/controllers/tesla_receiver.py b/openpilot/starpilot/controllers/tesla_receiver.py new file mode 100644 index 0000000000..254683350a --- /dev/null +++ b/openpilot/starpilot/controllers/tesla_receiver.py @@ -0,0 +1,271 @@ +"""Tesla input worker: bounded UI dispatch; raw CAN decoding lives in a separate process.""" +from openpilot.common.swaglog import cloudlog as LOGGER +import os +import socket +import subprocess +import sys +import time + +from openpilot.starpilot.common.car_control_config import ( + comma_speed, effective_bindings, NO_LIMIT_REASON, + PARAM, MAX_ASSIGNMENT_BYTES, parse_assignments, vehicle_supported, screen_reserved, SPEED_UP, SPEED_DOWN, SPEED_RESUME, +) +from openpilot.starpilot.saved_source import read_saved +from openpilot.starpilot.controllers.wheel_actions import cp_fingerprint +from openpilot.starpilot.controllers.tesla_input_protocol import ( + MAX_PACKET, MAX_EVENTS, READY, decode_event, document_hash, drive_id, +) + +# 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. + + +class WorkerChannel: + """An inherited private socketpair: no listening port, file socket or network.""" + def __init__(self): + self.ready = False + self.socket, child = socket.socketpair(socket.AF_UNIX, socket.SOCK_SEQPACKET) + self.socket.setblocking(False) + try: + self.process = subprocess.Popen( + [sys.executable, '-B', '-m', 'openpilot.starpilot.controllers.tesla_input_worker', + str(child.fileno()), str(os.getpid())], + pass_fds=(child.fileno(),), stdin=subprocess.DEVNULL, + # The ordinary process logger retains failures; never pipe unconsumed output. + close_fds=True, + ) + except BaseException: + self.socket.close() + raise + finally: + child.close() + + def receive(self): + if self.process.poll() is not None: + raise EOFError('Tesla input worker exited') + try: + value = self.socket.recv(MAX_PACKET + 1) + except BlockingIOError: + return None + if not value: + raise EOFError('Tesla input worker disconnected') + if value == READY: + self.ready = True + return None + return value + + def close(self): + self.socket.close() + if self.process.poll() is None: + self.process.terminate() + # close is shutdown/failure only, never normal frame work. + try: + self.process.wait(timeout=.1) + except subprocess.TimeoutExpired: + self.process.kill() + self.process.wait(timeout=.1) + + +class TeslaReceiver: + def __init__(self, params, actions, vehicle, *, clock=time.monotonic, + messages=lambda: None, channel_factory=WorkerChannel, speed_actions=None, keyed_actions=None): + self.params, self.actions, self.vehicle = params, actions, vehicle + self.speed_actions = speed_actions + # Looks up only the requested keys. The full catalog checks every settings + # 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._diagnostic_at = 0. + self.clock, self.messages, self.channel_factory = clock, messages, channel_factory + self.channel = None + self.sequence = 0 + self.next_start = 0. + self.failed = False + # (event, assignment document, deadline) of a Resume press waiting for the speed limit to come back. + self._waiting_resume = None + # A scroll step the UI refused to send (nothing was published), tried once more on the next poll. + self._retry_step = None + # The worker starts once a supported Tesla is known (poll); no other car ever runs it. + self._started = False + + def _start(self): + try: + self.channel = self.channel_factory() + self._started = True + 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. + + def close(self): + if self.channel is not None: + channel, self.channel = self.channel, None + channel.close() + + def drive(self): + return drive_id(self.messages(), self.clock()) + + def _offroad(self): + sm = self.messages() + now = self.clock() + if sm is None: + return False + try: + return bool(sm.seen['deviceState'] and sm.alive['deviceState'] and sm.valid['deviceState'] + and not sm['deviceState'].started + and 0 <= now - sm.logMonoTime['deviceState'] / 1e9 <= 1. + and 0 <= now - sm.recv_time['deviceState'] <= 1.) + except (AttributeError, KeyError, TypeError, ValueError): + return False + + def poll(self): + if not vehicle_supported(self.vehicle()): + # Not a Model 3/Y with the add-on cable: nothing to read, so no worker. + self.close() + return + if self.channel is None: + if not self._started: + self._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 + self._start() + return + try: + retry, self._retry_step = self._retry_step, None + if retry is not None: + self._dispatch(retry, retry=True) + packets = [] + for _ in range(MAX_EVENTS + 1): + raw = self.channel.receive() + if raw is None: + break + packets.append(raw) + if len(packets) > MAX_EVENTS: + # Never replay a backlog across frames. Discard and reset the worker. + raise RuntimeError('Tesla input event backlog') + for raw in packets: + 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. + + def _dispatch(self, raw, *, retry=False): + event = decode_event(raw, self.clock()) + if event is None or (event['sequence'] <= self.sequence and not retry): + self._diagnostic('invalid_expired_or_duplicate', event or {}) + return + self.sequence = max(self.sequence, event['sequence']) + cp = self.vehicle() + if not vehicle_supported(cp) or self.drive() != event['drive']: + self._diagnostic('vehicle_or_drive_unavailable', event) + return + if read_saved(self.params, 'SafeMode', 8) not in ((None, True), (b'0', True)): + return + current, readable = read_saved(self.params, PARAM, MAX_ASSIGNMENT_BYTES) + if not readable or document_hash(current or b'') != event['document']: + 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']: + self._diagnostic('assignment_vehicle_identity_mismatch', event) + return + name = event['name'] + if name == 'screen_three_finger_tap' and screen_reserved(cp): + return + binding = effective_bindings(doc, comma_speed=comma_speed(self.params, cp)).get(name) + if binding is None: + return + # The comma-speed actions (scroll steps and Resume Speed Limit + Offset) come from their own quick lookup, which + # reads the car's messages with a button's age limit; the favorites catalog is for everything else. + if binding['key'] in (SPEED_UP, SPEED_DOWN, SPEED_RESUME) and self.speed_actions is not None: + action = self.speed_actions().get(binding['key']) + elif self.keyed_actions is not None: + action = self.keyed_actions({binding['key']}).get(binding['key']) + else: + action = self.actions().get(binding['key']) + if action is None or not action.available: + if (binding['key'] == SPEED_RESUME and binding['value'] is None and self.speed_actions is not None and + getattr(action, 'reason', '') == NO_LIMIT_REASON): + # The limit drops out for a second or two at a time: wait for it rather than refuse the press. + self._waiting_resume = (event, current, self.clock() + RESUME_WAIT_SECONDS) + self._diagnostic('resume_waiting_for_limit', event) + return + self._diagnostic('action_unavailable', event, getattr(action, 'reason', 'not found')) + return + # Action discovery may perform work. Recheck exact context at dispatch. + if (decode_event(raw, self.clock()) is None or self.drive() != event['drive'] + or read_saved(self.params, PARAM, MAX_ASSIGNMENT_BYTES) != (current, True) + or read_saved(self.params, 'SafeMode', 8) not in ((None, True), (b'0', True)) + or not vehicle_supported(self.vehicle()) or cp_fingerprint(self.vehicle()) != event['vehicle']): + self._diagnostic('context_changed_or_expired', event) + return + value = binding['value'] + if binding['key'] in (SPEED_UP, SPEED_DOWN): + if value is None and action.invoke_value is not None: + from openpilot.starpilot.controllers.tesla_gesture_context import source_scope + with source_scope(event): + applied = action.invoke_value(1 if event['fast'] else 0) + if applied is False and not retry: + # Refused before anything was published (a live check failed this frame), so a retry cannot repeat the + # step. Once only, and only while the event is still fresh. + self._retry_step = raw + self._diagnostic('retry_next_frame', event) + else: + self._diagnostic('dispatched' if applied is not False else 'publisher_rejected', event) + elif value is None: + if action.invoke is not None: + if binding['key'] == SPEED_RESUME: + self._waiting_resume = None + applied = action.invoke() + if binding['key'] == SPEED_RESUME: + self._diagnostic('dispatched' if applied is not False else 'publisher_rejected', event) + elif action.invoke_value is not None: + action.invoke_value(value) + + def _retry_resume(self): + """Run a Resume press that arrived during a speed-limit dropout once the limit is back, at most once and only + within RESUME_WAIT_SECONDS of the press, in the same drive with the same assignments and vehicle.""" + if self._waiting_resume is None: + return + event, document, deadline = self._waiting_resume + if self.clock() > deadline: + self._waiting_resume = None + self._diagnostic('action_unavailable', event, NO_LIMIT_REASON) + return + cp = self.vehicle() + if (self.drive() != event['drive'] or read_saved(self.params, PARAM, MAX_ASSIGNMENT_BYTES) != (document, True) + or read_saved(self.params, 'SafeMode', 8) not in ((None, True), (b'0', True)) + or not vehicle_supported(cp) or cp_fingerprint(cp) != event['vehicle'] or self.speed_actions is None): + self._waiting_resume = None + self._diagnostic('context_changed_or_expired', event) + return + action = self.speed_actions().get(SPEED_RESUME) + if action is not None and not action.available and getattr(action, 'reason', '') == NO_LIMIT_REASON: + return + self._waiting_resume = None + if action is None or not action.available or action.invoke is None: + self._diagnostic('action_unavailable', event, getattr(action, 'reason', 'not found')) + return + applied = action.invoke() + self._diagnostic('dispatched' if applied is not False else 'publisher_rejected', event) + + def _diagnostic(self, reason, event, detail=''): + now = self.clock() + if now < self._diagnostic_at: + return + self._diagnostic_at = now + .1 + LOGGER.info({'event':'tesla_speed_input', 'reason':reason, 'input':event.get('name',''), 'detail':detail, + 'sequence':event.get('sequence',0), 'age_ms':round((now-event.get('stamp',now))*1000, 1)}) diff --git a/openpilot/starpilot/controllers/tests/tesla_worker_fixture.py b/openpilot/starpilot/controllers/tests/tesla_worker_fixture.py new file mode 100644 index 0000000000..2cb52e060a --- /dev/null +++ b/openpilot/starpilot/controllers/tests/tesla_worker_fixture.py @@ -0,0 +1,89 @@ +"""The Tesla input worker's pump and the UI's receiver joined by an in-memory channel, for the worker tests.""" +import collections +import json +from types import SimpleNamespace as NS + +from openpilot.cereal import messaging +from openpilot.starpilot.common.car_control_config import PARAM, SPEED_UP, comma_speed +from openpilot.starpilot.controllers.tesla_input_worker import InputPump +from openpilot.starpilot.controllers.tesla_receiver import TeslaReceiver +from openpilot.starpilot.tests.port_settings_fixture import Saved +from openpilot.starpilot.tests.tesla_set_speed_fixture import switch, tesla + +CUSTOM = 'custom' + + +class Messages(dict): + def refresh(self, now, *, started=True): + self['deviceState'] = NS(started=started, startedMonoTime=100_000_000) + self['carState'] = NS(canValid=True, canTimeout=False, cruiseState=NS(enabled=getattr(self, 'engaged', False))) + self.seen = self.alive = self.valid = dict.fromkeys(self, True) + self.logMonoTime = {k: int(now * 1e9) for k in self} + self.recv_time = dict.fromkeys(self, now) + + +class Channel: + def __init__(self): + self.queue = collections.deque() + self.closed = False + self.receives = 0 + + def receive(self): + self.receives += 1 + return self.queue.popleft() if self.queue else None + + def close(self): + self.closed = True + + +def stalk(value, counter): + return ((counter << 8) | (value << 12)).to_bytes(3, 'little') + + +def build(tmp_path, cp, *, comma=False): + """The worker's pump and the UI's receiver joined by an in-memory channel, for the car `cp`. comma: the saved switch + Comma can set speed on Tesla dashboard. One clock drives everything: CAN is stamped with it as the boot clock.""" + params = Saved(tmp_path) + switch(params, comma) + doc = {'version': 1, 'vehicle': 'TESLA_MODEL_3', 'bindings': { + 'right_wheel_left': {'key': CUSTOM, 'value': None, 'label': 'Custom'}}} + params.put(PARAM, json.dumps(doc).encode(), block=True) + clock = [1.] + sm = Messages() + sm.refresh(clock[0]) + calls = [] + channel = Channel() + frames = collections.deque() + actions = {SPEED_UP: NS(available=True, invoke_value=calls.append, invoke=None), + CUSTOM: NS(available=True, invoke=lambda: calls.append(CUSTOM), invoke_value=None)} + receiver = TeslaReceiver(params, lambda: actions, lambda: cp, clock=lambda: clock[0], + messages=lambda: sm, channel_factory=lambda: channel) + assert receiver.channel is None, 'nothing starts before a supported Tesla is known' + receiver.poll() + pump = InputPump(params, channel.queue.append, clock=lambda: clock[0], boot_clock_ns=lambda: round(clock[0] * 1e9), + socket_factory=object, receive=lambda _: frames.popleft() if frames else None) + pump.set_vehicle(cp) + + def feed(data, delta=.1, bus=1, valid=True, address=0x3c2, dispatch=True): + clock[0] += delta + sm.refresh(clock[0]) + ev = messaging.new_message('can', 1, valid=valid, logMonoTime=round(clock[0] * 1e9)) + ev.can[0] = {'address': address, 'dat': data, 'src': bus} + frames.append(ev) + pump.poll(sm) + if dispatch: + receiver.poll() + + return NS(params=params, cp=cp, doc=doc, clock=clock, sm=sm, calls=calls, + channel=channel, frames=frames, receiver=receiver, pump=pump, feed=feed, actions=actions) + + +def save(s): + s.params.put(PARAM, json.dumps(s.doc).encode(), block=True) + + +def selected_rig(tmp_path): + """A Model 3 with the cable and Comma can set speed on Tesla dashboard on: the scroll sets the comma speed.""" + s = build(tmp_path, tesla(selected=True), comma=True) + assert s.receiver.channel is s.channel and comma_speed(s.params, s.cp) + return s diff --git a/openpilot/starpilot/controllers/tests/test_cruise_action.py b/openpilot/starpilot/controllers/tests/test_cruise_action.py index f8b0b0af56..ead7b78aa3 100644 --- a/openpilot/starpilot/controllers/tests/test_cruise_action.py +++ b/openpilot/starpilot/controllers/tests/test_cruise_action.py @@ -1,5 +1,6 @@ from types import SimpleNamespace from pathlib import Path +from typing import Any import tempfile import unittest from unittest.mock import Mock, patch @@ -12,11 +13,15 @@ from opendbc.car.toyota import toyotacan from openpilot.selfdrive.car.cruise import VCruiseHelper, V_CRUISE_MAX, V_CRUISE_MIN from openpilot.starpilot.controllers.cruise_action import CruiseActionPublisher, CruiseActionConsumer from openpilot.starpilot.controllers.toyota_cruise import capability, ToyotaCruisePreference +from openpilot.starpilot.tests.tesla_set_speed_fixture import tesla from openpilot.starpilot.longitudinal.cruise_intervals import CruiseIntervals, read_cruise_intervals from openpilot.starpilot.ui.feature_settings_owner import FeatureSettingsOwner from openpilot.starpilot.ui.feature_settings_state import FeaturePage, FeatureSettingsRequest, row_change +OTHER_STEPS: tuple[Any, ...] = (0, 2, 10, -10, 1.0, True) # anything but one unit or one fast step + + class State(dict): def __init__(self, now): super().__init__(deviceState=SimpleNamespace(started=True, startedMonoTime=now-1_000_000_000), @@ -84,6 +89,47 @@ class TestControllerCruise(unittest.TestCase): self.sm['deviceState'].startedMonoTime+=1 self.assertFalse(self.apply(msg)) + def test_tesla_scroll_step_is_refused_for_every_car_that_is_not_a_selected_tesla(self): + for vehicle in (self.cp, cp(True), cp(True, 'tesla'), tesla(), tesla(cable=False, selected=True)): + for step in (-5, -1, 1, 5): + self.assertFalse(self.sender.dispatch(step > 0, self.sm, vehicle, self.publisher, now_ns=self.now, step_units=step)) + self.assertFalse(hasattr(self.publisher, 'message')) + forged = self.request().as_builder() + forged.slcAction.kind = 'cruiseStep' + forged.slcAction.controllerCruise.stepUnits = 5 + self.assertFalse(self.apply(forged.as_reader())) + self.assertEqual(self.helper.v_cruise_kph, 80) + self.assertFalse(self.helper.tesla_set_speed) + self.assertTrue(self.apply(self.request())) + self.assertEqual(self.helper.v_cruise_kph, 81) + self.assertEqual(self.consumer.tesla_receipts, [], 'other cars never leave a scroll receipt') + + def test_tesla_scroll_step_moves_one_unit_or_to_the_next_multiple_of_five_on_a_selected_tesla(self): + vehicle = tesla(selected=True) + for metric, start, step, expected in ((True, 83, 1, 84), (True, 83, -1, 82), (True, 83, 5, 85), (True, 83, -5, 80), + (False, 53, 1, 54), (False, 53, -1, 52), (False, 53, 5, 55), (False, 53, -5, 50), + (False, 55, 5, 60), (False, 55, -5, 50)): + with self.subTest(metric=metric, start=start, step=step): + self.now += 200_000_000 + self.sm = State(self.now) + unit = 1 if metric else 1.609344 + helper = VCruiseHelper(vehicle) + helper.v_cruise_kph = start * unit + self.assertTrue(self.sender.dispatch(step > 0, self.sm, vehicle, self.publisher, now_ns=self.now, step_units=step)) + self.assertEqual(self.publisher.message.slcAction.kind, 'cruiseStep') + self.assertFalse(self.consumer.apply(self.publisher.message, vehicle, self.cs, self.sm, helper, + now_ns=self.now, is_metric=metric, enabled=True), 'the switch is off') + self.assertEqual(helper.v_cruise_kph, start * unit) + helper.tesla_set_speed = True # card keeps this current from the saved switch + self.assertTrue(self.consumer.apply(self.publisher.message, vehicle, self.cs, self.sm, helper, + now_ns=self.now, is_metric=metric, enabled=True)) + self.assertEqual(round(helper.v_cruise_kph / unit), expected) + self.assertEqual(list(self.cs.buttonEvents), []) + assert helper.slc_cruise_change is not None + self.assertEqual(helper.slc_cruise_change[2], 'accel' if step > 0 else 'decel') + for bad in OTHER_STEPS: + self.assertFalse(self.sender.dispatch(True, self.sm, vehicle, self.publisher, now_ns=self.now, step_units=bad)) + def test_normal_steps_units_bounds_override_and_standstill(self): up,down=car.CarState.ButtonEvent.Type.accelCruise,car.CarState.ButtonEvent.Type.decelCruise self.helper.adjust_v_cruise(up,self.cs,False) diff --git a/openpilot/starpilot/controllers/tests/test_slc_input_recovery.py b/openpilot/starpilot/controllers/tests/test_slc_input_recovery.py new file mode 100644 index 0000000000..2bfca03bca --- /dev/null +++ b/openpilot/starpilot/controllers/tests/test_slc_input_recovery.py @@ -0,0 +1,185 @@ +"""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.""" +import json +from types import SimpleNamespace as NS +from unittest.mock import Mock, patch + +import pytest + +from openpilot.starpilot.common.car_control_config import MAX_ASSIGNMENT_BYTES, PARAM +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 + + +@pytest.fixture +def setup(tmp_path): + return selected_rig(tmp_path) + + +def bare_runtime(presses=(), capture=None): + r = ControllerRuntime.__new__(ControllerRuntime) + 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())) + return r + + +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() + r.service.poll.assert_called_once() + r.reader.close.assert_not_called() + + +def test_the_tesla_receiver_is_polled_first_and_whatever_the_gamepad_path_does(): + order = [] + r = bare_runtime() + r.tesla.poll.side_effect = lambda: order.append('tesla') + r.reader.poll = lambda _: order.append('gamepad') or [] + r.service.poll.side_effect = lambda: order.append('settings') + r.poll() + assert order == ['tesla', 'gamepad', 'settings'] + failing = bare_runtime() + failing.reader.poll = Mock(side_effect=OSError('gamepad unplugged')) + failing.poll() + failing.tesla.poll.assert_called_once() + assert failing._closed, 'the gamepad failure still stops the runtime, after the Tesla input was read' + + +def test_closing_the_runtime_closes_the_tesla_receiver_once(): + r = bare_runtime() + r.close() + r.close() + r.tesla.close.assert_called_once() + r.poll() + r.tesla.poll.assert_not_called() + + +def test_modal_capture_receives_each_button_once(): + capture = Mock() + press = object() + r = bare_runtime([press], capture) + r.poll() + r.owner.feed.assert_called_once_with(press, capture=capture) + + +def test_a_real_runtime_starts_no_worker_without_a_supported_tesla(): + spawned = [] + with patch('openpilot.starpilot.controllers.runtime.ControllerOwner', return_value=Mock()), \ + patch('openpilot.starpilot.controllers.runtime.ControllerService', return_value=Mock()), \ + patch.object(tesla_receiver.subprocess, 'Popen', side_effect=lambda *a, **kw: spawned.append(a)): + reader = Mock() + reader.poll.return_value = [] + reader.devices.return_value = [] + runtime = ControllerRuntime(None, actions=Mock(), favorites=Mock(), invoke_favorite=Mock(), authority=Mock(), reader=reader) + for _ in range(5): + runtime.poll() + runtime.close() + assert not spawned and runtime.tesla.channel is None and not runtime.tesla.failed + + +def test_identical_periodic_carparams_does_not_drop_held_scroll(setup): + s = setup + s.feed(wheel()) + s.feed(wheel(right_scroll=1)) + s.pump.set_vehicle(s.cp.as_reader()) + s.feed(wheel()) + assert s.calls == [0] + + +def test_changed_carparams_drop_a_held_scroll(setup): + s = setup + s.feed(wheel()) + s.feed(wheel(right_scroll=1)) + changed = s.cp.as_reader().as_builder() + changed.safetyConfigs[0].safetyParam = 1 # no longer selected + s.pump.set_vehicle(changed.as_reader()) + s.feed(wheel()) + assert s.calls == [] + + +def test_speed_input_does_not_build_unrelated_action_catalog(setup): + s = setup + s.receiver.speed_actions = lambda: s.actions + s.receiver.actions = Mock(side_effect=ValueError('expensive or failing UI page')) + s.feed(wheel()) + s.feed(wheel(right_scroll=1)) + s.feed(wheel()) + assert s.calls == [0] + s.receiver.actions.assert_not_called() + + +def test_worker_recovery_is_bounded_and_requires_fresh_drive(setup): + s = setup + created = [] + + def factory(): + created.append(Channel()) + return created[-1] + s.receiver.channel_factory = factory + s.receiver.close() + s.clock[0] += 3 + 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 + s.receiver.poll() + assert len(created) == 3 + + +def test_a_worker_that_cannot_start_is_retried_after_a_pause_not_every_frame(setup): + s = setup + attempts = [] + + def factory(): + attempts.append(s.clock[0]) + raise OSError('no process') + s.receiver.channel_factory = factory + s.receiver.close() + s.clock[0] += 3 + s.sm.refresh(s.clock[0]) + for _ in range(100): + s.receiver.poll() + assert len(attempts) == 1 and s.receiver.failed and s.receiver.channel is None + s.clock[0] += 2.1 + s.sm.refresh(s.clock[0]) + s.receiver.poll() + assert len(attempts) == 2 + + +def test_a_large_saved_document_is_read_alike_by_the_worker_and_the_receiver(setup): + s = setup + raw = (' ' * 16000 + json.dumps(s.doc)).encode() + assert 16000 < len(raw) < MAX_ASSIGNMENT_BYTES == 16384, 'the size the Wheel Controls editor may write' + s.params.put(PARAM, raw, block=True) + s.feed(wheel()) + s.feed(wheel(right_scroll=1)) + s.feed(wheel()) + assert s.calls == [0] + s.params.put(PARAM, (' ' * MAX_ASSIGNMENT_BYTES + json.dumps(s.doc)).encode(), block=True) + s.feed(wheel()) + s.feed(wheel(right_scroll=1)) + s.feed(wheel()) + assert s.calls == [0], 'too large to read: no input acts' + + +def test_recovered_worker_must_see_neutral_before_a_new_gesture(setup): + s = setup + s.feed(wheel(right_scroll=2)) + s.feed(wheel()) + assert not s.calls + s.feed(wheel(right_scroll=1)) + s.feed(wheel()) + assert s.calls == [0] diff --git a/openpilot/starpilot/controllers/tests/test_tesla_controls_v7.py b/openpilot/starpilot/controllers/tests/test_tesla_controls_v7.py new file mode 100644 index 0000000000..06397c5a64 --- /dev/null +++ b/openpilot/starpilot/controllers/tests/test_tesla_controls_v7.py @@ -0,0 +1,305 @@ +"""Tesla Model 3/Y controls in Wheel Controls: the scroll shown as fixed information, then the assignable nudges, their +holds, the right stalk and the three-finger tap, saved as one exact document for one vehicle.""" +from dataclasses import replace +import json +from types import SimpleNamespace as NS + +import pytest +from opendbc.car.structs import car +from opendbc.car.tesla.values import TeslaFlags +from openpilot.starpilot.common.car_control_config import (DEFAULT_BINDINGS, FIXED_BINDINGS, NO_ACTION, PARAM, SPEED_DOWN, SPEED_RESUME, SPEED_SET, + SPEED_UP, STALK_HOLD, STALK_TAP, STALK_TAP_FULL, effective_bindings, parse_assignments) +from openpilot.starpilot.favorites.actions import BOOKMARK, CYCLE_PERSONALITY +from openpilot.starpilot.tests.port_settings_fixture import Saved, request +from openpilot.starpilot.tests.tesla_set_speed_fixture import switch, tesla +from openpilot.starpilot.ui.tesla_controls_feature import (AOL_ACTION, AOL_KEY, AOL_NOTE, AOL_PENDING, KEYS, OPTIONS, PREFIX, + SET_SPEED_NEEDS, TESLA_INPUTS, TeslaControlsFeature) +from openpilot.starpilot.ui.tesla_set_speed_feature import CABLE_MISSING + +SCROLL_LABELS = ['Right scroll wheel / Scroll up', 'Right scroll wheel / Fast scroll up', + 'Right scroll wheel / Scroll down', 'Right scroll wheel / Fast scroll down'] +ROW_LABELS = SCROLL_LABELS + [ + 'Right scroll wheel / Nudge left', 'Right scroll wheel / Nudge left — hold', + 'Right scroll wheel / Nudge right', 'Right scroll wheel / Nudge right — hold', + 'Right stalk / Down', 'Right stalk / Up', + 'Right stalk / Down — half press while engaged', 'Right stalk / Down — full press while engaged', 'Right stalk / Down — hold', + 'Tesla screen / Three-finger tap'] +LEFT = PREFIX + 'right_wheel_left' +SCREEN = PREFIX + 'screen_three_finger_tap' + + +DEFAULT = object() + + +class Rig: + def __init__(self, tmp_path, cp=DEFAULT): + self.params = Saved(tmp_path) + self.cp = tesla() if cp is DEFAULT else cp + self.parked = True + owner = NS(params=self.params, vehicle_params=lambda: self.cp, authority=lambda _: self.parked, + vehicle_fingerprint=lambda: getattr(self.cp, 'carFingerprint', None)) + self.feature = TeslaControlsFeature(owner) + + def rows(self): + return {row.label: row for row in self.feature.rows()} + + def row(self, key): + return next(row for row in self.feature.rows() if row.key == key) + + def choose(self, key, value): + return self.feature.apply(request(self.row(key), value)) + + def document(self): + return json.loads((self.params.path / PARAM).read_bytes()) + + def saved(self, key): + path = self.params.path / key + return path.read_bytes() if path.exists() else None + + +@pytest.fixture +def rig(tmp_path): + return Rig(tmp_path) + + +def cabled_request(tmp_path, value='Bookmark'): + """The request a Model 3 with the cable would send for its nudge left.""" + path = tmp_path / 'cabled' + path.mkdir() + return request(Rig(path).row(LEFT), value) + + +def test_the_keys_are_every_control_and_its_speed(): + assert TESLA_INPUTS == ('right_wheel_left', 'right_wheel_left_hold', 'right_wheel_right', 'right_wheel_right_hold', + STALK_TAP, STALK_TAP_FULL, STALK_HOLD, 'screen_three_finger_tap') + assert KEYS == frozenset(PREFIX + name + suffix for name in TESLA_INPUTS for suffix in ('', ':speed')) + assert PREFIX == 'tesla_input:' + + +@pytest.mark.parametrize('model', ['TESLA_MODEL_3', 'TESLA_MODEL_Y']) +def test_rows_are_the_scroll_information_then_the_controls_in_order(tmp_path, model): + rig = Rig(tmp_path, tesla(model)) + rows = rig.feature.rows() + assert [row.label for row in rows] == ROW_LABELS + assert [row.key for row in rows] == [''] * 4 + [PREFIX + name for name in TESLA_INPUTS[:4]] + ['', ''] + \ + [PREFIX + name for name in TESLA_INPUTS[4:]] + assert [row.value for row in rows[:4]] == ['Increase set speed'] * 2 + ['Decrease set speed'] * 2 + assert not any(row.available or row.choices for row in rows[:4]), 'the scroll is never assignable' + down, up = rows[8], rows[9] + assert (down.value, down.available, up.value, up.available) == ('Engage StarPilot', False, 'Disengage StarPilot', False) + hold = rig.row(PREFIX + STALK_HOLD) + assert (hold.value, hold.available) == ('Resume Speed Limit + Offset', False) + half = rig.row(PREFIX + STALK_TAP) + assert (half.value, half.available) == ('Resume Speed Limit + Offset', True), 'starts on Resume Speed Limit + Offset' + right = rig.row(PREFIX + 'right_wheel_right') + assert (right.value, right.available) == ('Cycle Driving Personality', True), 'starts on Cycle Driving Personality' + for name in ('right_wheel_left', 'right_wheel_left_hold', 'right_wheel_right_hold', STALK_TAP_FULL, 'screen_three_finger_tap'): + row = rig.row(PREFIX + name) + assert (row.value, row.available, row.vehicle_fingerprint) == ('Unassigned', True, model) + # No description on any control: the title says what it is. Only the tap says when its choice takes effect. + steps = ['By 1 mph', 'To the next 5 mph', 'By 1 mph', 'To the next 5 mph'] + assert [row.reason for row in rows] == steps + [''] * (len(rows) - 5) + [AOL_NOTE], 'only how far each scroll moves it' + assert AOL_NOTE == 'Always On Lateral on/off applies after the next startup' + + +@pytest.mark.parametrize('selected,comma', [(True, True), (True, False), (False, True), (False, False)]) +def test_the_rows_are_the_same_whoever_owns_the_set_speed(tmp_path, selected, comma): + rig = Rig(tmp_path, tesla(selected=selected)) + switch(rig.params, comma) + assert [(row.value, row.reason) for row in rig.feature.rows()[:4]] == [ + ('Increase set speed', 'By 1 mph'), ('Increase set speed', 'To the next 5 mph'), + ('Decrease set speed', 'By 1 mph'), ('Decrease set speed', 'To the next 5 mph')] + rig.params.put('IsMetric', b'1', block=True) + assert [row.reason for row in rig.feature.rows()[:4]] == ['By 1 km/h', 'To the next 5 km/h'] * 2, 'in the units shown' + assert [row.label for row in rig.feature.rows()] == ROW_LABELS, 'the same rows either way' + + +def test_the_comma_set_speed_steps_are_not_choices(rig): + assert 'Increase Comma Set Speed' not in OPTIONS and 'Decrease Comma Set Speed' not in OPTIONS + assert SPEED_UP not in OPTIONS.values() and SPEED_DOWN not in OPTIONS.values() + assert OPTIONS['Unassigned'] == '' and OPTIONS['Set Speed To'] == SPEED_SET and OPTIONS['Resume Speed Limit + Offset'] == SPEED_RESUME + for row in rig.feature.rows(): + assert 'Increase Comma Set Speed' not in row.choices and 'Decrease Comma Set Speed' not in row.choices + for value in ('Increase Comma Set Speed', 'Decrease Comma Set Speed'): + assert not rig.choose(LEFT, value) + assert rig.saved(PARAM) is None + + +@pytest.mark.parametrize('saved', [SPEED_UP, SPEED_DOWN, BOOKMARK]) +def test_a_saved_scroll_binding_is_not_shown_does_not_act_and_cannot_be_edited(rig, saved): + document = {'version': 1, 'vehicle': 'TESLA_MODEL_3', 'bindings': { + 'right_wheel_up': {'key': saved, 'value': None, 'label': 'Saved by an older build'}}} + rig.params.put(PARAM, json.dumps(document).encode(), block=True) + assert [row.label for row in rig.feature.rows()] == ROW_LABELS + assert rig.feature.rows()[0].value == 'Increase set speed' + parsed = parse_assignments(rig.saved(PARAM)) + assert 'right_wheel_up' not in effective_bindings(parsed) and effective_bindings(parsed, comma_speed=True)['right_wheel_up']['key'] == SPEED_UP + stale = request(rig.row(LEFT), 'Bookmark') + assert not rig.feature.apply(replace(stale, key=PREFIX + 'right_wheel_up')) + assert rig.choose(LEFT, 'Bookmark') + assert rig.document()['bindings']['right_wheel_up'] == document['bindings']['right_wheel_up'], 'left as saved' + + +def test_shared_settings_exact_document_and_vehicle_guards(rig): + row = rig.row(LEFT) + assert rig.feature.apply(request(row, 'Bookmark')) + assert rig.document() == {'version': 1, 'vehicle': 'TESLA_MODEL_3', 'bindings': { + 'right_wheel_left': {'key': BOOKMARK, 'value': None, 'label': 'Bookmark'}}} + assert rig.row(LEFT).value == 'Bookmark' + assert not rig.feature.apply(request(row, 'Experimental Mode')), 'the row shown before the save is stale' + rig.cp.flags = int(rig.cp.flags) | int(TeslaFlags.AOL_SCREEN_BUTTON) + # Reserved for screen-tap AOL this drive, but still assignable: the choice applies after the next startup. + assert rig.row(SCREEN).available and rig.row(SCREEN).reason == AOL_PENDING + current = rig.row(LEFT) + rig.parked = False + assert not rig.row(LEFT).available + assert not rig.feature.apply(request(current, 'Experimental Mode')) + rig.parked = True + assert not rig.feature.apply(replace(request(current, 'Experimental Mode'), vehicle_fingerprint='TESLA_MODEL_Y')) + assert not rig.feature.apply(replace(request(current, 'Experimental Mode'), vehicle_fingerprint=None)) + assert rig.document()['bindings']['right_wheel_left']['key'] == BOOKMARK + assert rig.feature.apply(request(current, 'Experimental Mode')) + + +def test_unassigned_removes_a_binding_and_is_kept_over_a_default(rig): + assert rig.choose(LEFT, 'Bookmark') and rig.choose(LEFT, 'Unassigned') + assert rig.document()['bindings'] == {} + assert STALK_TAP in DEFAULT_BINDINGS + assert rig.choose(PREFIX + STALK_TAP, 'Unassigned') + assert rig.document()['bindings'] == {STALK_TAP: {'key': NO_ACTION, 'value': None, 'label': 'Unassigned'}} + assert rig.row(PREFIX + STALK_TAP).value == 'Unassigned' + assert STALK_TAP not in effective_bindings(parse_assignments(rig.saved(PARAM))) + assert rig.choose(PREFIX + STALK_TAP, 'Resume Speed Limit + Offset') + assert rig.row(PREFIX + STALK_TAP).value == 'Resume Speed Limit + Offset' + + +def test_nudge_right_starts_on_cycle_driving_personality_and_can_be_changed(rig): + right = PREFIX + 'right_wheel_right' + assert set(DEFAULT_BINDINGS) == {STALK_TAP, 'right_wheel_right'} + assert DEFAULT_BINDINGS['right_wheel_right'] == {'key': CYCLE_PERSONALITY, 'value': None, 'label': 'Cycle Driving Personality'} + assert effective_bindings(parse_assignments(None))['right_wheel_right']['key'] == CYCLE_PERSONALITY + assert rig.row(right).value == 'Cycle Driving Personality' + assert rig.choose(right, 'Bookmark') and rig.row(right).value == 'Bookmark' + assert effective_bindings(parse_assignments(rig.saved(PARAM)))['right_wheel_right']['key'] == BOOKMARK + assert rig.choose(right, 'Unassigned') and rig.row(right).value == 'Unassigned' + assert rig.document()['bindings']['right_wheel_right'] == {'key': NO_ACTION, 'value': None, 'label': 'Unassigned'} + assert 'right_wheel_right' not in effective_bindings(parse_assignments(rig.saved(PARAM))), 'Unassigned is kept over the default' + assert rig.choose(right, 'Cycle Driving Personality') and rig.row(right).value == 'Cycle Driving Personality' + + +def test_the_stalk_hold_is_fixed(rig): + assert STALK_HOLD in FIXED_BINDINGS + row = rig.row(PREFIX + STALK_HOLD) + for value in ('Bookmark', 'Unassigned'): + assert not rig.feature.apply(request(row, value)) + assert rig.saved(PARAM) is None + rig.params.put(PARAM, json.dumps({'version': 1, 'vehicle': 'TESLA_MODEL_3', 'bindings': { + STALK_HOLD: {'key': BOOKMARK, 'value': None, 'label': 'Bookmark'}}}).encode(), block=True) + assert rig.row(PREFIX + STALK_HOLD).value == 'Resume Speed Limit + Offset', 'whatever was saved for it' + + +@pytest.mark.parametrize('value', ['Not a choice', '', AOL_ACTION]) +def test_only_listed_choices_are_saved(rig, value): + assert not rig.choose(LEFT, value) + assert rig.saved(PARAM) is None + + +def test_set_speed_to_adds_its_speed_in_the_device_units(rig): + assert rig.choose(LEFT, 'Set Speed To') + assert rig.document()['bindings']['right_wheel_left'] == {'key': SPEED_SET, 'value': 30, 'label': 'Set Speed To'} + speed = rig.row(LEFT + ':speed') + assert (speed.value, speed.unit, speed.minimum, speed.maximum, speed.step) == ('30', 'mph', 5, 90, 1.) + assert speed.dependencies == (('IsMetric', None),) and speed.available + assert [row.label for row in rig.feature.rows()][4:6] == ['Right scroll wheel / Nudge left', 'Right scroll wheel / Nudge left: set speed'] + assert rig.choose(LEFT + ':speed', '65') + assert rig.document()['bindings']['right_wheel_left']['value'] == 65. + stale = rig.row(LEFT + ':speed') + for bad in ('4', '91', 'fast', 'nan'): + assert not rig.feature.apply(request(stale, bad)), bad + rig.params.put('IsMetric', b'1', block=True) + assert not rig.feature.apply(request(stale, '70')), 'the units changed under the row' + metric = rig.row(LEFT + ':speed') + assert (metric.unit, metric.minimum, metric.maximum) == ('km/h', 8, 145) + assert rig.feature.apply(request(metric, '110')) and rig.document()['bindings']['right_wheel_left']['value'] == 110. + + +@pytest.mark.parametrize('selected,comma', [(True, True), (True, False), (False, True)]) +def test_set_speed_to_says_when_it_needs_the_switch(tmp_path, selected, comma): + rig = Rig(tmp_path, tesla(selected=selected)) + switch(rig.params, comma) + assert rig.row(LEFT).reason == '' + assert rig.choose(LEFT, 'Set Speed To') + row = rig.row(LEFT) + assert row.value == 'Set Speed To' and row.available, 'it can be assigned either way' + if selected and comma: + assert row.reason == '' + else: + assert row.reason == SET_SPEED_NEEDS + assert SET_SPEED_NEEDS == 'Set Speed To needs Comma can set speed on Tesla dashboard turned on in Vehicle Settings' + assert rig.row(PREFIX + 'right_wheel_right').reason == '' + switch(rig.params, True) + assert (SET_SPEED_NEEDS in rig.row(LEFT).reason) is (not selected), 'the note follows the switch at once' + + +def test_a_speed_cannot_be_set_on_a_control_that_is_not_on_set_speed_to(rig): + assert rig.choose(LEFT, 'Set Speed To') + speed = request(rig.row(LEFT + ':speed'), '50') + assert not rig.feature.apply(replace(speed, key=PREFIX + 'right_wheel_right:speed')) + assert 'right_wheel_right' not in rig.document()['bindings'] + + +@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_3', 'bindings': {'unknown_control': {}}}).encode()]) +def test_invalid_or_other_vehicle_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 not rig.choose(LEFT, 'Bookmark') + assert rig.saved(PARAM) == raw + + +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) + assert AOL_ACTION not in rig.row(LEFT).choices, 'only on the tap' + assert rig.choose(SCREEN, 'Bookmark') and rig.saved(AOL_KEY) == b'0', 'on by default, so another choice saves it off' + assert rig.choose(SCREEN, AOL_ACTION) + assert rig.saved(AOL_KEY) == b'1' and 'screen_three_finger_tap' not in rig.document()['bindings'] + assert rig.row(SCREEN).value == AOL_ACTION + assert rig.choose(SCREEN, 'Bookmark') + assert rig.saved(AOL_KEY) == b'0' and rig.row(SCREEN).value == 'Bookmark' + assert rig.choose(SCREEN, AOL_ACTION) and rig.choose(SCREEN, 'Unassigned') + assert rig.saved(AOL_KEY) == b'0' and rig.row(SCREEN).value == 'Unassigned' + + +def test_the_tap_shows_its_saved_switch(rig): + rig.params.put(AOL_KEY, b'1', block=True) # as startup saves it by default, or as chosen here + assert rig.row(SCREEN).value == AOL_ACTION + rig.params.put(AOL_KEY, b'0', block=True) + assert rig.row(SCREEN).value == 'Unassigned' + + +def test_without_the_cable_every_row_says_so_and_nothing_can_be_assigned(tmp_path): + rig = Rig(tmp_path, tesla(cable=False)) + rows = rig.feature.rows() + assert [row.label for row in rows] == ROW_LABELS + assert all(row.reason.split('.\n')[0] == CABLE_MISSING and not row.available for row in rows) + assert [row.reason for row in rows[4:]] == [CABLE_MISSING] * (len(rows) - 4) + assert rows[0].reason == CABLE_MISSING + '.\nBy 1 mph' + assert CABLE_MISSING == 'Needs the Tesla CAN add-on cable' + assert not rig.feature.apply(cabled_request(tmp_path)) + assert rig.saved(PARAM) is None + + +@pytest.mark.parametrize('make', [lambda: None, lambda: tesla('TESLA_MODEL_X'), lambda: tesla('TESLA_MODEL_S_HW1'), + lambda: car.CarParams.new_message(brand='hyundai', carFingerprint='HYUNDAI_IONIQ_5', flags=8), + lambda: car.CarParams.new_message(brand='toyota', carFingerprint='TOYOTA_RAV4_TSS2', flags=8)]) +def test_other_cars_have_no_rows_and_nothing_is_saved_for_them(tmp_path, make): + rig = Rig(tmp_path, make()) + assert rig.feature.rows() == [] + assert not rig.feature.apply(cabled_request(tmp_path)) + assert rig.saved(PARAM) is None diff --git a/openpilot/starpilot/controllers/tests/test_tesla_decoder.py b/openpilot/starpilot/controllers/tests/test_tesla_decoder.py new file mode 100644 index 0000000000..7a5738fff5 --- /dev/null +++ b/openpilot/starpilot/controllers/tests/test_tesla_decoder.py @@ -0,0 +1,295 @@ +"""Tesla Model 3/Y wheel and stalk frames decoded into controls: one event per gesture, on release.""" +import unittest + +from openpilot.starpilot.common.car_control_config import INPUTS +from openpilot.starpilot.controllers.tesla_controls import TeslaInputDecoder + + +def wheel(**values): + bits = 1 + shifts = {'left_wheel_left': 14, 'left_wheel_right': 3, 'left_wheel_press': 5, + 'right_wheel_left': 8, 'right_wheel_right': 10, 'right_wheel_press': 12} + for name, shift in shifts.items(): + bits |= values.get(name, 1) << shift + for name, shift in [('left_scroll', 16), ('right_scroll', 24)]: + bits |= (values.get(name, 0) & 63) << shift + return bits.to_bytes(8, 'little') + + +class DecoderTests(unittest.TestCase): + def setUp(self): + self.d = TeslaInputDecoder(bus=1) + self.t = 1.0 + + def feed(self, data=None, address=0x3c2, bus=1, dt=.1): + self.t += dt + return self.d.feed(address, data or wheel(), bus, self.t) + + def test_defaults_and_all_wheel_entries(self): + # The right wheel's two nudges, their holds and its scroll: the only wheel controls StarPilot names. + self.assertEqual(sorted(k for k in INPUTS if '_wheel_' in k), + ['right_wheel_down', 'right_wheel_left', 'right_wheel_left_hold', 'right_wheel_right', + 'right_wheel_right_hold', 'right_wheel_up']) + self.assertFalse([k for k in INPUTS if k.startswith(('left_', 'indicator_', 'beam_', 'wiper_'))]) + self.assertEqual(self.feed(wheel(right_wheel_right=2)), []) + self.assertEqual(self.feed(), []) + self.assertEqual(self.feed(wheel(right_wheel_right=2)), []) + self.assertEqual(self.feed(wheel(right_wheel_right=2)), []) + self.assertEqual(self.feed(), ['right_wheel_right']) + self.assertEqual(self.feed(), []) + + def test_scroll_signed_magnitude_and_direction_change(self): + self.feed() + self.feed(wheel(right_scroll=-2)) + self.assertEqual(self.feed(), ['right_wheel_down']) + self.feed(wheel(right_scroll=1)) + self.feed(wheel(right_scroll=-1)) + self.assertEqual(self.feed(), []) + self.feed(wheel(left_scroll=1)) + self.assertEqual(self.feed(), ['left_wheel_up']) + + def test_mux_bus_length_fault_and_simultaneous(self): + self.feed() + for data, bus in [(wheel(right_wheel_right=2), 0), (bytes(8), 1), (bytes(7), 1)]: + self.assertEqual(self.feed(data, bus=bus), []) + self.feed() + self.feed(wheel(right_wheel_press=3)) + self.feed(wheel(right_wheel_right=2)) + self.assertEqual(self.feed(), []) + self.feed(wheel(left_wheel_left=2, right_wheel_right=2)) + self.assertEqual(self.feed(), []) + + def test_gap_reset_and_explicit_reset(self): + self.feed() + self.feed(wheel(right_wheel_right=2)) + self.assertEqual(self.feed(dt=1), []) + self.feed(wheel(right_wheel_right=2)) + self.d.reset() + self.assertEqual(self.feed(), []) + + def test_invalid_mux_discards_pending_but_body_mux_does_not(self): + for mux in (2, 3): + self.feed() + self.feed(wheel(right_wheel_press=2)) + self.feed(bytes([mux]) + bytes(7)) + self.assertEqual(self.feed(), []) + self.feed(wheel(right_wheel_press=2)) + self.feed(bytes(8)) + self.assertEqual(self.feed(), ['right_wheel_press']) + + def stalk(self, value, counter, address=0x229, length=3, shift=12): + return self.feed(((counter << 8) | (value << shift)).to_bytes(length, 'little'), address) + + def engage(self, counter): + """Cruise comes on, then the stalk rests in neutral for 0.6 s. The frames repeat `counter` (the last one sent), so + the counter sequence of the test carries on unchanged.""" + self.d.cruise_engaged = True + for _ in range(6): + self.assertEqual(self.stalk(0, counter), []) + + def test_right_stalk_stage_once_and_counter_gap(self): + self.stalk(0, 0) + self.stalk(1, 1) + self.stalk(2, 2) + self.assertEqual(self.stalk(0, 3), ['right_stalk_up_full']) + self.stalk(3, 4) + self.stalk(4, 6) + self.assertEqual(self.stalk(0, 7), []) + + def test_right_stalk_hold_replaces_the_down_press(self): + self.d = TeslaInputDecoder(bus=1, stalk_hold=True) + self.stalk(0, 0) + held = [name for counter in range(1, 10) for name in self.stalk(3, counter)] + self.assertEqual(held, ['right_stalk_down_hold'], 'once, while still held (0.8 s)') + self.assertEqual(self.stalk(0, 10), [], 'the release is not also a down press') + self.stalk(3, 11) + self.assertEqual(self.stalk(0, 12), ['right_stalk_down_half'], 'a tap is still a press') + self.stalk(3, 13) + self.stalk(4, 14) + self.assertEqual(self.stalk(0, 15), ['right_stalk_down_full']) + + def test_right_stalk_hold_needs_neutral_first_and_an_assignment(self): + self.d = TeslaInputDecoder(bus=1, stalk_hold=True) + self.assertEqual([n for c in range(10) for n in self.stalk(3, c)], [], 'already down when the decoder started') + self.d = TeslaInputDecoder(bus=1) + self.stalk(0, 0) + self.assertEqual([n for c in range(1, 12) for n in self.stalk(3, c)], []) + self.assertEqual(self.stalk(0, 12), ['right_stalk_down_half'], 'without a hold assignment a long press stays a press') + + def test_right_stalk_tap_while_engaged(self): + self.d = TeslaInputDecoder(bus=1, stalk_tap=True) + self.stalk(0, 0) + self.stalk(4, 1) + self.assertEqual(self.stalk(0, 2), ['right_stalk_down_full'], 'the press that engages cruise stays a press') + self.engage(2) + self.stalk(3, 3) + self.stalk(3, 4) + self.assertEqual(self.stalk(0, 5), ['right_stalk_down_tap_engaged']) + self.stalk(3, 6) + self.stalk(4, 7) + self.assertEqual(self.stalk(0, 8), ['right_stalk_down_full'], 'a full press while engaged is its own input') + for counter in range(9, 18): + self.stalk(3, counter % 16) + self.assertEqual(self.stalk(0, 2), ['right_stalk_down_half'], 'a long press is not a tap') + self.stalk(1, 3) + self.assertEqual(self.stalk(0, 4), ['right_stalk_up_half'], 'up is untouched') + + def test_full_press_while_engaged(self): + self.d = TeslaInputDecoder(bus=1, stalk_tap=True, stalk_tap_full=True) + self.engage(0) + self.stalk(0, 0) + self.stalk(3, 1) + self.stalk(4, 2) + self.assertEqual(self.stalk(0, 3), ['right_stalk_down_full_engaged']) + self.stalk(3, 4) + self.assertEqual(self.stalk(0, 5), ['right_stalk_down_tap_engaged']) + self.d = TeslaInputDecoder(bus=1, stalk_tap_full=True) + self.engage(0) + self.stalk(0, 0) + self.stalk(3, 1) + self.assertEqual(self.stalk(0, 2), ['right_stalk_down_half'], 'half press unassigned: a plain press') + + def test_tap_and_hold_together(self): + self.d = TeslaInputDecoder(bus=1, stalk_hold=True, stalk_tap=True) + self.engage(0) + self.stalk(0, 0) + self.assertEqual([n for c in range(1, 10) for n in self.stalk(3, c)], ['right_stalk_down_hold']) + self.assertEqual(self.stalk(0, 10), [], 'a hold is not also a tap') + self.stalk(3, 11) + self.assertEqual(self.stalk(0, 12), ['right_stalk_down_tap_engaged']) + self.d = TeslaInputDecoder(bus=1, stalk_hold=True) + self.engage(0) + self.stalk(0, 0) + self.stalk(3, 1) + self.assertEqual(self.stalk(0, 2), ['right_stalk_down_half'], 'tap unassigned: a plain press') + + def test_engaging_press_is_not_a_press_while_engaged(self): + # The car turns cruise on during the press that engages it, so the press's first frames already see cruise on. + for value in (3, 4): + self.d = TeslaInputDecoder(bus=1, stalk_tap=True, stalk_tap_full=True) + self.stalk(0, 0) + self.d.cruise_engaged = True + self.stalk(3, 1) + self.stalk(value, 2) + self.assertEqual(self.stalk(0, 3), ['right_stalk_down_half' if value == 3 else 'right_stalk_down_full']) + # Cruise came on a moment before the press started (under 0.5 s): still the engaging press. + self.d = TeslaInputDecoder(bus=1, stalk_tap=True) + self.stalk(0, 0) + self.d.cruise_engaged = True + self.stalk(0, 1) + self.stalk(0, 2) + self.stalk(3, 3) + self.assertEqual(self.stalk(0, 4), ['right_stalk_down_half']) + + def test_tap_one_second_after_engaging(self): + self.d = TeslaInputDecoder(bus=1, stalk_tap=True) + self.stalk(0, 0) + self.d.cruise_engaged = True + for c in range(1, 11): + self.stalk(0, c) + self.stalk(3, 11) + self.assertEqual(self.stalk(0, 12), ['right_stalk_down_tap_engaged']) + + def test_press_held_across_engagement_never_counts_as_engaged(self): + for hold in (False, True): + self.d = TeslaInputDecoder(bus=1, stalk_tap=True, stalk_tap_full=True, stalk_hold=hold) + self.stalk(0, 0) + self.stalk(3, 1) + self.d.cruise_engaged = True + out = [n for c in range(2, 12) for n in self.stalk(3 if c < 6 else 4, c)] + self.stalk(0, 12) + self.assertEqual(out, ['right_stalk_down_hold'] if hold else ['right_stalk_down_full']) + # A short press that started before cruise came on stays a plain press too. + self.d = TeslaInputDecoder(bus=1, stalk_tap=True) + self.stalk(0, 0) + self.stalk(3, 1) + self.d.cruise_engaged = True + for c in range(2, 4): + self.stalk(3, c) + self.assertEqual(self.stalk(0, 4), ['right_stalk_down_half']) + + def test_cruise_off_restarts_the_engaged_time(self): + self.d = TeslaInputDecoder(bus=1, stalk_tap=True) + self.engage(0) + self.d.cruise_engaged = False + self.stalk(0, 1) + self.d.cruise_engaged = True + self.stalk(3, 2) + self.assertEqual(self.stalk(0, 3), ['right_stalk_down_half'], 'cruise only just came back on') + + def test_left_stalk_is_not_decoded(self): + # Indicators, beams and wipers (0x249) are the car's own: the decoder holds no state for them. + self.assertEqual(sorted(self.d.groups), [0x229, 0x3c2, 0x3df]) + for length, half, full in [(3, 3, 4), (4, 6, 8)]: + out = [self.stalk(value, counter, 0x249, length, 16) for counter, value in enumerate((0, half, full, 0))] + self.assertEqual(out, [[], [], [], []]) + self.assertNotIn(0x249, self.d.last) + + def test_the_stalk_reader_takes_the_frame_bits_alone(self): + read = TeslaInputDecoder._stalk + self.assertEqual(read(0), []) + self.assertEqual([read(value << 12) for value in (1, 2, 3, 4)], + [[('right_stalk_up_half', 'right_stalk_up', 1)], [('right_stalk_up_full', 'right_stalk_up', 2)], + [('right_stalk_down_half', 'right_stalk_down', 1)], [('right_stalk_down_full', 'right_stalk_down', 2)]]) + self.assertEqual(read(1 << 16), [('park_press', 'park_press', 1)]) + self.assertEqual(read((3 << 12) | (1 << 16)), [('right_stalk_down_half', 'right_stalk_down', 1), ('park_press', 'park_press', 1)]) + for unreadable in (5 << 12, 7 << 12, 2 << 16, 3 << 16): + self.assertIsNone(read(unreadable)) + + def test_right_stalk_frames_of_another_length_are_dropped(self): + self.stalk(0, 0) + self.stalk(1, 1) + self.assertEqual(self.stalk(0, 2, length=4), []) + self.assertEqual(self.stalk(0, 3), [], 'the press before the odd frame is forgotten') + + def test_captured_park_event_reuses_periodic_counter(self): + self.feed(bytes.fromhex('8c0b00'), 0x229) + self.feed(bytes.fromhex('490c00'), 0x229) + self.feed(bytes.fromhex('c60d01'), 0x229, dt=0) + self.assertEqual(self.feed(bytes.fromhex('2f0d00'), 0x229), ['park_press']) + + def test_every_wheel_button_and_captured_frame(self): + # Every wheel switch is still read, so that doing two things at once can be told apart; only the right wheel's + # nudges are controls. + names = ['left_wheel_left', 'left_wheel_right', 'left_wheel_press', 'right_wheel_left', 'right_wheel_right', 'right_wheel_press'] + self.assertEqual([n for n in names if n in INPUTS], ['right_wheel_left', 'right_wheel_right']) + for name in names: + self.feed() + self.feed(wheel(**{name: 2})) + self.assertEqual(self.feed(), [name]) + self.feed(bytes.fromhex('2959000000000040')) + self.assertEqual(self.feed(bytes.fromhex('2955000000000040')), ['right_wheel_right']) + + def test_nudge_release_click_ends_the_nudge(self): + # A right-wheel nudge left can spring back with one scroll-up click in the release frame. The nudge's own action + # runs; the click is not a scroll. + self.feed() + self.feed(wheel(right_wheel_left=2)) + self.feed(wheel(right_wheel_left=2)) + self.assertEqual(self.feed(wheel(right_scroll=1)), ['right_wheel_left']) + self.assertEqual(self.feed(), []) + self.feed(wheel(right_scroll=1)) + self.assertEqual(self.feed(), ['right_wheel_up'], 'the next gesture works as normal') + self.feed() + self.feed(wheel(right_wheel_press=2)) + self.assertEqual(self.feed(wheel(right_scroll=-1)), ['right_wheel_press']) + + def test_nudge_followed_by_a_real_scroll_is_still_dropped(self): + self.feed() + self.feed(wheel(right_wheel_left=2)) + self.assertEqual(self.feed(wheel(right_scroll=2)), [], 'two clicks is a scroll, not a spring-back') + self.assertEqual(self.feed(), []) + self.feed(wheel(right_wheel_left=2)) + self.assertEqual(self.feed(wheel(left_scroll=1)), [], "the other wheel's click does not end this nudge") + self.assertEqual(self.feed(), []) + + def test_fast_scroll_is_two_or_more_clicks_in_one_frame_or_at_its_peak(self): + for frames, fast in (([1], False), ([2], True), ([1, 1], False), ([1, 3, 1], True), ([-1], False), ([-4, -1], True)): + self.d = TeslaInputDecoder(bus=1) + self.t += 5 + self.d.feed(0x3c2, wheel(), 1, self.t, details=True) + for ticks in frames: + self.t += .1 + self.assertEqual(self.d.feed(0x3c2, wheel(right_scroll=ticks), 1, self.t, details=True), []) + self.t += .1 + name = 'right_wheel_up' if frames[0] > 0 else 'right_wheel_down' + self.assertEqual(self.d.feed(0x3c2, wheel(), 1, self.t, details=True), [(name, fast)], frames) diff --git a/openpilot/starpilot/controllers/tests/test_tesla_keyed_lookup.py b/openpilot/starpilot/controllers/tests/test_tesla_keyed_lookup.py new file mode 100644 index 0000000000..e75470be6c --- /dev/null +++ b/openpilot/starpilot/controllers/tests/test_tesla_keyed_lookup.py @@ -0,0 +1,120 @@ +"""Tesla wheel nudges look up only their own mapped action. + +Building the full Favorites catalog checks every settings page (including the maps package), which can take seconds on +a cold first press: longer than a press stays fresh, so it would be dropped. A keyed lookup avoids that work. +""" +import json +from types import SimpleNamespace as NS + +import pytest + +from openpilot.starpilot.common.car_control_config import PARAM +from openpilot.starpilot.controllers.tesla_receiver import TeslaReceiver +from openpilot.starpilot.controllers.tests.test_tesla_decoder import wheel +from openpilot.starpilot.controllers.tests.tesla_worker_fixture import selected_rig + +LANE = 'LaneCentering' +PERSONALITY = '__starpilot_controller_action__:cycle_driving_personality' + + +@pytest.fixture +def setup(tmp_path): + return selected_rig(tmp_path) + + +def bind(s, **bindings): + s.doc['bindings'].update({name: {'key': key, 'value': None, 'label': key} for name, key in bindings.items()}) + s.params.put(PARAM, json.dumps(s.doc).encode(), block=True) + + +def keyed_receiver(s, keyed, full=None): + def full_catalog(): + if full is None: + raise AssertionError('full Favorites catalog must not be built for a wheel press') + return full + s.receiver = TeslaReceiver(s.params, full_catalog, lambda: s.cp, clock=lambda: s.clock[0], + messages=lambda: s.sm, channel_factory=lambda: s.channel, + speed_actions=lambda: s.actions, keyed_actions=keyed) + s.receiver.poll() # the first poll with a supported Tesla starts the worker + assert s.receiver.channel is s.channel + + +def press_nudge(s, name='right_wheel_left'): + s.feed(wheel(), dispatch=False) + s.feed(wheel(**{name: 2}), dispatch=False) + s.feed(wheel(), dispatch=False) + s.receiver.poll() + + +def test_nudge_uses_keyed_lookup_only(setup): + s = setup + bind(s, right_wheel_left=LANE, right_wheel_right=PERSONALITY) + calls, asked = [], [] + + def keyed(keys): + asked.append(set(keys)) + return {key: NS(available=True, invoke=lambda key=key: calls.append(key), invoke_value=None) for key in keys} + keyed_receiver(s, keyed) + press_nudge(s, 'right_wheel_left') + press_nudge(s, 'right_wheel_right') + assert asked == [{LANE}, {PERSONALITY}] + assert calls == [LANE, PERSONALITY] + + +def test_first_press_survives_when_only_full_catalog_is_slow(setup): + # The full catalog would take seconds (cold maps check); the keyed lookup is quick. + s = setup + bind(s, right_wheel_left=LANE) + calls = [] + + def keyed(keys): + s.clock[0] += .002 + return {LANE: NS(available=True, invoke=lambda: calls.append(LANE), invoke_value=None)} + keyed_receiver(s, keyed) + press_nudge(s) + assert calls == [LANE] + + +def test_slow_lookup_still_expires(setup): + # The 0.25 s freshness limit is unchanged: a press is never applied late. + s = setup + bind(s, right_wheel_left=LANE) + calls = [] + + def keyed(keys): + s.clock[0] += 2.3 + return {LANE: NS(available=True, invoke=lambda: calls.append(LANE), invoke_value=None)} + keyed_receiver(s, keyed) + press_nudge(s) + assert not calls + + +def test_unavailable_keyed_action_is_not_invoked(setup): + s = setup + bind(s, right_wheel_left=LANE) + calls = [] + keyed_receiver(s, lambda keys: {LANE: NS(available=False, invoke=lambda: calls.append(LANE), invoke_value=None)}) + press_nudge(s) + assert not calls + + +def test_speed_scroll_keeps_its_own_catalog(setup): + s = setup + + def keyed(keys): + raise AssertionError('speed must not use keyed lookup') + keyed_receiver(s, keyed) + s.feed(wheel(), dispatch=False) + s.feed(wheel(right_scroll=1), dispatch=False) + s.feed(wheel(), dispatch=False) + s.receiver.poll() + assert s.calls == [0] + + +def test_without_keyed_lookup_behavior_is_unchanged(setup): + s = setup + bind(s, right_wheel_left=LANE) + calls = [] + keyed_receiver(s, None, full={LANE: NS(available=True, invoke=lambda: calls.append(LANE), invoke_value=None)}) + press_nudge(s) + assert calls == [LANE] diff --git a/openpilot/starpilot/controllers/tests/test_tesla_screen_gesture.py b/openpilot/starpilot/controllers/tests/test_tesla_screen_gesture.py new file mode 100644 index 0000000000..e50e48c9ff --- /dev/null +++ b/openpilot/starpilot/controllers/tests/test_tesla_screen_gesture.py @@ -0,0 +1,66 @@ +"""The Tesla screen's three-finger tap, decoded from its touch-count frames: once, on complete release.""" +import unittest + +from openpilot.starpilot.controllers.tesla_controls import TeslaInputDecoder +from openpilot.starpilot.controllers.tests.test_tesla_decoder import wheel + + +def touch(count): + return bytes([0, 0, 0, count, 0, 0, 0, 0]) + + +class ScreenGestureTests(unittest.TestCase): + def sequence(self, counts, step=.08, bus=1, details=False): + decoder = TeslaInputDecoder(1) + result = [] + for i, count in enumerate(counts): + result += decoder.feed(0x3df, touch(count), bus, 1 + i * step, details=details) + return result + + def test_three_fingers_release_once_with_normal_ramp(self): + self.assertEqual(self.sequence([0, 1, 2, 3, 2, 1, 0, 0]), ['screen_three_finger_tap']) + self.assertEqual(self.sequence([0, 3, 2, 3, 0], details=True), [('screen_three_finger_tap', False)]) + + def test_held_boot_long_hold_other_counts_wrong_bus(self): + for sequence in ([3, 3, 0], [0, 1, 0], [0, 2, 0], [0, 3, 4, 3, 0]): + self.assertEqual(self.sequence(sequence), []) + self.assertEqual(self.sequence([0, 3, 0], step=2), []) + self.assertEqual(self.sequence([0, 3, 0], bus=0), []) + + def test_asynchronous_neutral_does_not_require_periodic_frame(self): + decoder = TeslaInputDecoder(1) + result = [] + for t, count in [(1, 0), (100, 3), (100.2, 0)]: + result += decoder.feed(0x3df, touch(count), 1, t) + self.assertEqual(result, ['screen_three_finger_tap']) + + def test_reset_malformed_and_time_reversal_discard(self): + for fault in ('reset', 'length', 'time'): + d = TeslaInputDecoder(1) + for t, count in [(1, 0), (1.1, 3)]: + d.feed(0x3df, touch(count), 1, t) + if fault == 'reset': + d.reset() + elif fault == 'length': + d.feed(0x3df, bytes(7), 1, 1.15) + else: + d.feed(0x3df, bytes(8), 1, .5) + self.assertEqual(d.feed(0x3df, bytes(8), 1, 1.2), [], fault) + + def test_existing_fast_scroll_threshold_is_preserved(self): + for ticks in (1, 2, 3, -1, -2, -3): + d = TeslaInputDecoder(1) + d.feed(0x3c2, wheel(), 1, 1, details=True) + d.feed(0x3c2, wheel(right_scroll=ticks), 1, 1.1, details=True) + self.assertEqual(d.feed(0x3c2, wheel(), 1, 1.2, details=True), + [('right_wheel_up' if ticks > 0 else 'right_wheel_down', abs(ticks) >= 2)]) + + def test_reset_preserves_observed_released_baseline_only(self): + d = TeslaInputDecoder(1) + d.feed(0x3df, bytes(8), 1, 1) + d.reset() + d.feed(0x3df, touch(3), 1, 2) + self.assertEqual(d.feed(0x3df, bytes(8), 1, 2.1), ['screen_three_finger_tap']) + d.feed(0x3df, touch(3), 1, 3) + d.reset() + self.assertEqual(d.feed(0x3df, bytes(8), 1, 3.1), []) diff --git a/openpilot/starpilot/controllers/tests/test_tesla_scroll_receipts.py b/openpilot/starpilot/controllers/tests/test_tesla_scroll_receipts.py new file mode 100644 index 0000000000..01267fd4b6 --- /dev/null +++ b/openpilot/starpilot/controllers/tests/test_tesla_scroll_receipts.py @@ -0,0 +1,553 @@ +"""The driver's own scroll, followed from the wheel to speed sync. + +The input worker reports where it saw the scroll on the car's bus, the screen attaches that to the comma step it asks +for, card records a receipt when it applies the step, and speed sync matches the receipt to the scroll it saw itself. +With the receipt it reads the comma's set speed again at once; without one it waits out its two-second window. +None of this metadata ever creates, repeats or alters a speed action. +""" +from dataclasses import replace +import json +import time +from types import SimpleNamespace as NS +from unittest.mock import patch + +import pytest +from opendbc.car.structs import car +from opendbc.car.tesla.speed_sync import MANUAL_COMPLETION_NS, ManualReceipt, SpeedSynchronizer, sync_controller +from openpilot.selfdrive.car.cruise import VCruiseHelper +from openpilot.starpilot.car.tesla_speed_sync_context import publish_context +from openpilot.starpilot.common.car_control_config import SPEED_DOWN, SPEED_UP +from openpilot.starpilot.controllers import cruise_action +from openpilot.starpilot.controllers.cruise_action import TESLA_RECEIPT_NS, CruiseActionConsumer, CruiseActionPublisher +from openpilot.starpilot.controllers.tesla_gesture_context import GestureSource, current_source, parse_source, source_from_event, source_scope +from openpilot.starpilot.controllers.tesla_input_protocol import decode_event, document_hash, encode_event +from openpilot.starpilot.controllers.tests.tesla_worker_fixture import build +from openpilot.starpilot.controllers.tests.test_cruise_action import Publisher +from openpilot.starpilot.controllers.tests.test_tesla_decoder import wheel +from openpilot.starpilot.controllers.wheel_actions import cp_fingerprint +from openpilot.starpilot.tests.tesla_set_speed_fixture import tesla + +MPH = 1.609344 +SESSION = '0123456789abcdef' * 2 +DOCUMENT, VEHICLE, DRIVE = 'a' * 64, 'b' * 64, 100_000_000 + + +def gesture(**changes): + values = {'worker_session': SESSION, 'sequence': 7, 'boot_ns': 5_000_000_000, 'frame_index': 3, 'name': 'right_wheel_up', + 'fast': False, 'document': DOCUMENT, 'vehicle': VEHICLE, 'drive': DRIVE} + values.update(changes) + return GestureSource(**values) + + +def event(source=None, **changes): + source = source or gesture() + value = {'version': 2, 'sequence': source.sequence, 'name': source.name, 'fast': source.fast, 'stamp': 5., 'drive': source.drive, + 'document': source.document, 'vehicle': source.vehicle, 'provenance': source.to_wire()} + value.update(changes) + return value + + +# The gesture's identity. + +@pytest.mark.parametrize('name,fast,step', [('right_wheel_up', False, 1), ('right_wheel_up', True, 5), + ('right_wheel_down', False, -1), ('right_wheel_down', True, -5)]) +def test_a_scroll_names_the_comma_step_it_produces(name, fast, step): + assert gesture(name=name, fast=fast).step == step + assert step in cruise_action.TESLA_STEPS + + +def test_the_wire_form_round_trips(): + source = gesture() + wire = source.to_wire() + assert wire == {'version': 1, 'workerSession': SESSION, 'sequence': 7, 'sourceCanBootTime': 5_000_000_000, + 'sourceCanFrameIndex': 3, 'name': 'right_wheel_up', 'fast': False, 'assignmentsHash': DOCUMENT, + 'vehicleHash': VEHICLE, 'driveStartMonoTime': DRIVE} + assert parse_source(wire) == source + assert not hasattr(source, 'matches'), 'no saved step sizes to compare with any more' + + +@pytest.mark.parametrize('change', [ + {'version': 2}, {'version': True}, {'workerSession': 'x' * 32}, {'workerSession': SESSION[:31]}, {'workerSession': None}, + {'sequence': 0}, {'sequence': 2**64}, {'sequence': 1.0}, {'sourceCanBootTime': 0}, {'sourceCanBootTime': -1}, + {'sourceCanFrameIndex': -1}, {'sourceCanFrameIndex': 4096}, {'sourceCanFrameIndex': True}, + {'name': 'right_wheel_left'}, {'name': 'left_wheel_up'}, {'name': 3}, {'fast': 1}, {'fast': None}, + {'assignmentsHash': 'A' * 64}, {'assignmentsHash': 'a' * 63}, {'vehicleHash': ''}, {'driveStartMonoTime': 0}, + {'extra': 1}, +]) +def test_a_malformed_wire_form_is_no_gesture(change): + wire = gesture().to_wire() + wire.update(change) + assert parse_source(wire) is None + + +@pytest.mark.parametrize('value', [None, [], 'gesture', 5, {}, {'version': 1}]) +def test_anything_else_is_no_gesture(value): + assert parse_source(value) is None + + +def test_an_event_carries_its_gesture_only_when_both_say_the_same(): + assert source_from_event(event()) == gesture() + for change in ({'sequence': 8}, {'name': 'right_wheel_down'}, {'fast': True}, {'document': 'c' * 64}, {'vehicle': 'c' * 64}, + {'drive': DRIVE + 1}, {'provenance': None}, {'provenance': {}}): + assert source_from_event(event(**change)) is None, change + plain = event() + del plain['provenance'] + assert source_from_event(plain) is None + + +def test_the_gesture_is_only_current_inside_its_scope(): + assert current_source() is None + with source_scope(event()): + assert current_source() == gesture() + with source_scope(event(name='right_wheel_down')): + assert current_source() is None, 'an event that does not match its own gesture carries none' + assert current_source() == gesture() + assert current_source() is None + with pytest.raises(RuntimeError): + with source_scope(event()): + raise RuntimeError('the action failed') + assert current_source() is None + + +# The worker's message. + +def test_the_protocol_carries_the_gesture_as_version_two(): + source = gesture() + packet = encode_event(7, 'right_wheel_up', False, 5., DRIVE, DOCUMENT, VEHICLE, provenance=source.to_wire()) + decoded = decode_event(packet, 5.1) + assert decoded['version'] == 2 and source_from_event(decoded) == source + plain = decode_event(encode_event(7, 'right_wheel_up', False, 5., DRIVE, DOCUMENT, VEHICLE), 5.1) + assert plain['version'] == 1 and 'provenance' not in plain and source_from_event(plain) is None + + +@pytest.mark.parametrize('change', [{'sequence': 8}, {'name': 'right_wheel_down'}, {'fast': True}, {'document': 'c' * 64}, + {'vehicle': 'c' * 64}, {'drive': DRIVE + 1}]) +def test_the_worker_cannot_encode_a_gesture_that_is_not_the_events_own(change): + arguments = {'sequence': 7, 'name': 'right_wheel_up', 'fast': False, 'drive': DRIVE, 'document': DOCUMENT, 'vehicle': VEHICLE} + arguments.update(change) + with pytest.raises(ValueError): + encode_event(arguments['sequence'], arguments['name'], arguments['fast'], 5., arguments['drive'], arguments['document'], + arguments['vehicle'], provenance=gesture().to_wire()) + + +@pytest.mark.parametrize('change', [{'version': 3}, {'version': 1}, {'provenance': None}, {'provenance': {}}, {'sequence': 8}, + {'name': 'right_wheel_down'}]) +def test_the_screen_refuses_a_message_whose_gesture_does_not_match(change): + value = event(**change) + assert decode_event(json.dumps(value).encode(), 5.1) is None + missing = event() + del missing['provenance'] + assert decode_event(json.dumps(missing).encode(), 5.1) is None, 'version two without its gesture' + + +@pytest.fixture +def rig(tmp_path): + """The worker and the screen's receiver for a Model 3 with the cable and the switch on.""" + return build(tmp_path, tesla(selected=True), comma=True) + + +def scroll(s, ticks=1): + """One scroll: neutral, the scroll, neutral. Returns the worker's packets, undelivered.""" + s.feed(wheel(), dispatch=False) + s.feed(wheel(right_scroll=ticks), dispatch=False) + s.feed(wheel(), dispatch=False) + packets = [json.loads(packet) for packet in s.channel.queue] + return packets + + +def test_the_worker_stamps_a_scroll_with_where_it_saw_it_on_the_bus(rig): + s = rig + assert s.pump.sync_provenance, 'speed sync is admitted on this car' + packet, = scroll(s, 3) + assert packet['version'] == 2 and packet['name'] == 'right_wheel_up' and packet['fast'] is True + source = source_from_event(packet) + assert source.boot_ns == round(s.clock[0] * 1e9), 'the CAN batch of the release frame, on the boot clock, to the nanosecond' + assert source.frame_index == 0 and source.worker_session == s.pump.worker_session and source.sequence == packet['sequence'] == 1 + assert source.document == document_hash((s.params.path / 'CarControlAssignments').read_bytes()) + assert source.vehicle == cp_fingerprint(s.cp) and source.drive == 100_000_000 and source.step == 5 + s.channel.queue.clear() + later, = scroll(s, -1) + assert source_from_event(later).sequence == 2 and source_from_event(later).step == -1 + + +def test_the_frame_index_is_the_position_inside_the_can_batch(rig): + from openpilot.cereal import messaging + s = rig + s.feed(wheel(), dispatch=False) + s.feed(wheel(right_scroll=1), dispatch=False) + s.clock[0] += .1 + s.sm.refresh(s.clock[0]) + batch = messaging.new_message('can', 4, valid=True, logMonoTime=round(s.clock[0] * 1e9)) + batch.can[0] = {'address': 0x286, 'dat': bytes(8), 'src': 0} + batch.can[1] = {'address': 0x3c2, 'dat': bytes(8), 'src': 1} # the wheel message's other half + batch.can[2] = {'address': 0x118, 'dat': bytes(8), 'src': 0} + batch.can[3] = {'address': 0x3c2, 'dat': wheel(), 'src': 1} # the release + s.frames.append(batch) + s.pump.poll(s.sm) + packet, = [json.loads(raw) for raw in s.channel.queue] + assert source_from_event(packet).frame_index == 3 + + +def test_only_scrolls_carry_a_gesture(rig): + s = rig + s.feed(wheel(), dispatch=False) + s.feed(wheel(right_wheel_left=2), dispatch=False) + s.feed(wheel(), dispatch=False) + packet, = [json.loads(raw) for raw in s.channel.queue] + assert packet['name'] == 'right_wheel_left' and packet['version'] == 1 and 'provenance' not in packet + + +def test_the_worker_sessions_differ_and_a_changed_car_resets_the_worker(rig, tmp_path): + s = rig + (tmp_path / 'other').mkdir() + other = build(tmp_path / 'other', tesla(selected=True), comma=True) + assert s.pump.worker_session != other.pump.worker_session and len(s.pump.worker_session) == 32 + s.feed(wheel(), dispatch=False) + assert s.pump.decoder is not None + unselected = s.cp.as_reader().as_builder() + unselected.safetyConfigs[0].safetyParam = 1 + s.pump.set_vehicle(unselected.as_reader()) + assert s.pump.decoder is None and not s.pump.sync_provenance, 'a car without the scroll frame reports no gestures' + s.pump.set_vehicle(None) + assert not s.pump.sync_provenance and s.pump.cp_hash is None + + +def test_can_stamped_ahead_of_the_boot_clock_or_too_old_is_not_decoded(rig): + from openpilot.cereal import messaging + s = rig + s.feed(wheel(), dispatch=False) + s.feed(wheel(right_scroll=1), dispatch=False) + for offset in (.01, -.3): + s.clock[0] += .1 + s.sm.refresh(s.clock[0]) + batch = messaging.new_message('can', 1, valid=True, logMonoTime=round((s.clock[0] + offset) * 1e9)) + batch.can[0] = {'address': 0x3c2, 'dat': wheel(), 'src': 1} + s.frames.append(batch) + s.pump.poll(s.sm) + assert not s.channel.queue, offset + s.feed(wheel(), dispatch=False) + assert not s.channel.queue, 'the decoder was reset: the held scroll is gone' + + +# The screen's request and card's receipt. + +class Boot: + """The boot clock card and the screen read, set by the test.""" + CLOCK_BOOTTIME = time.CLOCK_BOOTTIME + + def __init__(self, now): + self.now = now + + def clock_gettime_ns(self, clock): + assert clock == time.CLOCK_BOOTTIME + return self.now + + +class Card: + """Card's side for one selected Model 3 with the switch on: the cruise helper and the consumer of comma steps.""" + def __init__(self, cp, sm): + self.cp, self.sm = cp, sm + self.helper = VCruiseHelper(cp) + self.helper.tesla_set_speed = True + self.helper.v_cruise_kph = self.helper.v_cruise_cluster_kph = round(77 * MPH, 1) + self.consumer = CruiseActionConsumer() + + def apply(self, message, now_ns): + cs = car.CarState.new_message(canValid=True, cruiseState={'available': True, 'enabled': True}) + return self.consumer.apply(message, self.cp, cs, self.sm, self.helper, now_ns=now_ns, is_metric=False, enabled=True) + + @property + def shown(self): + return round(self.helper.v_cruise_kph / MPH) + + +class Drive: + """Everything between the wheel and speed sync, on one clock: the worker, the screen, card and the car controller.""" + def __init__(self, tmp_path): + self.s = build(tmp_path, tesla(selected=True), comma=True) + self.s.sm['carControl'] = NS(enabled=True, longActive=True) + self.s.sm['selfdriveState'] = NS(enabled=True) + self.boot = Boot(self.now_ns) + self.sender, self.publisher = CruiseActionPublisher(), Publisher() + self.card = Card(self.s.cp, self.s.sm) + self.sync = SpeedSynchronizer() + self.controller = NS(speed_sync=self.sync, speed_sync_authority=None) + self.host = NS(CI=NS(CC=self.controller), CP=self.s.cp, params=self.s.params, is_metric=False, sm=self.s.sm, + v_cruise_helper=self.card.helper, controller_cruise_consumer=self.card.consumer) + self.native, self.counter, self.sent, self.steps, self.attach = 77, 0, [], [], True + for key, sign in ((SPEED_UP, 1), (SPEED_DOWN, -1)): + self.s.actions[key] = NS(available=True, invoke=None, invoke_value=lambda fast, sign=sign: self.step(sign * (5 if fast else 1))) + + @property + def now_ns(self): + return round(self.s.clock[0] * 1e9) + + def step(self, units): + """The screen's comma-speed action: ask card for the step, then card applies it.""" + self.steps.append(units) + if not self.attach: + with source_scope({}): # as if the worker had reported no gesture + sent = self.sender.dispatch(units > 0, self.s.sm, self.s.cp, self.publisher, now_ns=self.now_ns, step_units=units) + else: + sent = self.sender.dispatch(units > 0, self.s.sm, self.s.cp, self.publisher, now_ns=self.now_ns, step_units=units) + return sent and self.card.apply(self.publisher.message, self.now_ns) + + def frame(self, data=None, *, publish=True): + """One 100 ms frame: the wheel frame reaches the worker and the car interface, then card and the controller run.""" + data = wheel() if data is None else data + with patch.object(cruise_action, 'time', self.boot): + self.boot.now = self.now_ns + 100_000_000 + self.s.feed(data) + now = self.now_ns + self.counter = (self.counter + 1) % 16 + bits = (self.counter << 8) | (2 << 12) | (round(self.native * 2) << 15) + di = bytearray(bits.to_bytes(8, 'little')) + di[0] = (0x88 + sum(di[1:])) & 255 + self.sync.observe([(now, [(0x3C2, data, 1)]), (now, [(0x286, bytes(di), 0)])]) + out = car.CarState.new_message(canValid=True, gearShifter='drive', cruiseState={'enabled': True, 'available': True}, + vCruise=self.card.helper.v_cruise_kph) + if publish: + publish_context(self.host, out, now_boot_ns=now) + else: + self.controller.speed_sync_authority = None + cc = car.CarControl.new_message(enabled=True, longActive=True).as_reader() + messages = sync_controller(self.controller, cc, NS(out=out, autopark=False), now) + self.sent += [(now, message) for message in messages] + return messages + + def frames(self, count, **kwargs): + return [message for _ in range(count) for message in self.frame(**kwargs)] + + def scroll(self, ticks=1): + self.frame(wheel(right_scroll=ticks)) + return self.frame() + + +@pytest.fixture +def drive(tmp_path): + d = Drive(tmp_path) + assert d.frames(12) == [] and d.sync.status == 'matched', 'settled: the Tesla and the comma both at 77 mph' + return d + + +def test_the_screen_attaches_the_gesture_to_the_step_it_asks_for(drive): + drive.card.apply = lambda message, now_ns: True # look at the request only + drive.frame(wheel(right_scroll=1)) + drive.frame() + request = drive.publisher.message.slcAction.controllerCruise + assert drive.steps == [1] and request.stepUnits == 1 + source = parse_source(request.sourceTeslaGesture.to_dict()) + assert source is not None and source.step == 1 and source.boot_ns == drive.now_ns and source.frame_index == 0 + assert source.vehicle == cp_fingerprint(drive.s.cp) and source.drive == 100_000_000 + + +@pytest.mark.parametrize('case', ['no gesture', 'another step', 'another drive', 'too old', 'from the future']) +def test_the_screen_attaches_nothing_that_is_not_this_steps_fresh_gesture(drive, case): + d = drive + source = gesture(boot_ns=d.now_ns, vehicle=cp_fingerprint(d.s.cp), drive=100_000_000) + if case == 'another step': + source = replace(source, fast=True) + if case == 'another drive': + source = replace(source, drive=100_000_001) + d.boot.now = d.now_ns + {'too old': 500_000_001, 'from the future': -1}.get(case, 0) + with patch.object(cruise_action, 'time', d.boot): + if case == 'no gesture': + assert d.sender.dispatch(True, d.s.sm, d.s.cp, d.publisher, now_ns=d.now_ns, step_units=1) + else: + with source_scope(event(source)): + assert d.sender.dispatch(True, d.s.sm, d.s.cp, d.publisher, now_ns=d.now_ns, step_units=1) + request = d.publisher.message.slcAction.controllerCruise + assert request.stepUnits == 1 and parse_source(request.sourceTeslaGesture.to_dict()) is None + assert d.card.apply(d.publisher.message, d.now_ns) and d.card.shown == 78, 'the step itself is applied all the same' + assert d.card.consumer.tesla_receipts == [] + + +def test_the_gesture_never_rides_on_an_ordinary_speed_action(drive): + d = drive + with patch.object(cruise_action, 'time', d.boot), source_scope(event(gesture(boot_ns=d.now_ns, drive=100_000_000))): + assert d.sender.dispatch(True, d.s.sm, d.s.cp, d.publisher, now_ns=d.now_ns) + assert d.publisher.message.slcAction.kind == 'cruiseIncrease' + assert parse_source(d.publisher.message.slcAction.controllerCruise.sourceTeslaGesture.to_dict()) is None + assert d.card.apply(d.publisher.message, d.now_ns) and d.card.consumer.tesla_receipts == [] + + +def test_card_records_a_receipt_for_the_step_it_applied(drive): + d = drive + d.frame(wheel(right_scroll=1)) + d.frame(publish=False) # the controller has not run yet: the receipt is still with card + assert d.card.shown == 78 + receipt, = d.card.consumer.tesla_receipts + assert isinstance(receipt, ManualReceipt) + assert (receipt.boot_ns, receipt.frame_index, receipt.name, receipt.fast) == (d.now_ns, 0, 'right_wheel_up', False) + assert receipt.worker_session == d.s.pump.worker_session and receipt.sequence == 1 and receipt.drive_start_ns == 100_000_000 + assert receipt.vehicle_hash == cp_fingerprint(d.s.cp) and len(receipt.document_hash) == 64 + assert receipt.processed_boot_ns == d.boot.now and receipt.target_kph == d.card.helper.v_cruise_kph + + +@pytest.mark.parametrize('case', ['another car', 'another drive', 'another step', 'too old', 'from the future']) +def test_card_records_no_receipt_for_metadata_that_does_not_fit_and_still_applies_the_step(drive, case): + d = drive + source = gesture(boot_ns=d.now_ns, vehicle=cp_fingerprint(d.s.cp), drive=100_000_000) + if case == 'another car': + source = replace(source, vehicle='c' * 64) + with patch.object(cruise_action, 'time', d.boot): + d.boot.now = d.now_ns + with source_scope(event(source)): + assert d.sender.dispatch(True, d.s.sm, d.s.cp, d.publisher, now_ns=d.now_ns, step_units=1) + message = d.publisher.message.as_builder() + if case == 'another drive': + message.slcAction.controllerCruise.sourceTeslaGesture.driveStartMonoTime = 100_000_001 + if case == 'another step': + message.slcAction.controllerCruise.sourceTeslaGesture.fast = True + d.boot.now = d.now_ns + {'too old': TESLA_RECEIPT_NS + 1, 'from the future': -1}.get(case, 0) + assert d.card.apply(message.as_reader(), d.now_ns) and d.card.shown == 78 + assert d.card.consumer.tesla_receipts == [] + + +def test_a_refused_step_leaves_no_receipt(drive): + d = drive + d.card.helper.tesla_set_speed = False # the switch went off + d.frame(wheel(right_scroll=1)) + d.frame(publish=False) + assert d.steps == [1] and d.card.shown == 77 and d.card.consumer.tesla_receipts == [] + + +def manual(now, index=0, **changes): + values = {'boot_ns': now, 'frame_index': index, 'name': 'right_wheel_up', 'fast': False, 'worker_session': SESSION, 'sequence': index + 1, + 'document_hash': DOCUMENT, 'vehicle_hash': VEHICLE, 'drive_start_ns': DRIVE, 'processed_boot_ns': now, 'target_kph': 125.} + values.update(changes) + return ManualReceipt(**values) + + +def test_receipts_are_offered_for_two_seconds_then_dropped(): + consumer = CruiseActionConsumer() + assert TESLA_RECEIPT_NS == MANUAL_COMPLETION_NS == 2_000_000_000, "the window in which speed sync can still match one" + first, second = manual(1_000_000_000), manual(2_000_000_000, 1) + consumer.tesla_receipts += [first, second] + assert consumer.peek_tesla_receipts(2_500_000_000) == (first, second) + assert consumer.peek_tesla_receipts(3_000_000_000) == (first, second), 'exactly two seconds old is still offered' + assert consumer.peek_tesla_receipts(3_000_000_001) == (second,) and consumer.tesla_receipts == [second] + assert consumer.peek_tesla_receipts(1_999_999_999) == (), 'a receipt from the future is dropped too' + assert consumer.tesla_receipts == [] + + +def test_only_the_receipts_speed_sync_took_are_discarded(): + consumer = CruiseActionConsumer() + receipts = [manual(1_000_000_000, index) for index in range(3)] + consumer.tesla_receipts += receipts + consumer.acknowledge_tesla_receipts((receipts[1], manual(9_000_000_000, 9))) + assert consumer.tesla_receipts == [receipts[0], receipts[2]] + for bad in ([receipts[0]], None, tuple(manual(1_000_000_000, index) for index in range(17))): + consumer.acknowledge_tesla_receipts(bad) + assert consumer.tesla_receipts == [receipts[0], receipts[2]], 'only a tuple of at most sixteen, as speed sync hands back' + consumer.acknowledge_tesla_receipts(()) + assert len(consumer.tesla_receipts) == 2 + + +def test_a_full_list_drops_the_newest_receipt_and_the_step_is_still_applied(drive): + d = drive + d.card.consumer.drive = 100_000_000 # this drive's receipts, not yet taken by speed sync + d.card.consumer.tesla_receipts += [manual(d.now_ns, index, vehicle_hash=cp_fingerprint(d.s.cp)) for index in range(16)] + before = list(d.card.consumer.tesla_receipts) + d.frame(wheel(right_scroll=1)) + d.frame(publish=False) + assert d.card.shown == 78, 'the step is applied' + assert d.card.consumer.tesla_receipts == before, 'no room: the new receipt is the one left out' + assert not hasattr(d.card.consumer, 'tesla_receipt_overflow') + + +def test_a_new_drive_forgets_the_receipts(drive): + d = drive + d.frame(wheel(right_scroll=1)) + d.frame(publish=False) + assert d.card.consumer.tesla_receipts + d.s.sm['deviceState'].startedMonoTime += 1 + assert not d.card.apply(d.publisher.message, d.now_ns) + assert d.card.consumer.tesla_receipts == [] + + +# End to end. + +def test_with_the_receipt_speed_sync_reads_the_comma_speed_again_at_once(drive): + d = drive + d.frame(wheel(right_scroll=1)) + d.native = 78 # the Tesla took the driver's scroll + d.frame() + assert d.steps == [1] and d.card.shown == 78, 'the comma took it too' + assert d.sync.manual_queue == [] and d.sync.blocked is None, 'matched to the scroll speed sync saw on the bus, the same frame' + assert d.controller.speed_sync_authority.manual_receipts == tuple(d.card.consumer.tesla_receipts) != () + d.frame() + assert d.card.consumer.tesla_receipts == [], 'handed back and dropped the frame after' + assert d.sync.status == 'matched' + assert d.frames(25) == [] and 'manual_action_unconfirmed' not in d.sync.noticed + assert not d.sync.manual_receipts and not d.sync.manual_receipt_acks + + +def test_with_the_receipt_a_tesla_that_moved_further_is_corrected_within_a_second(drive): + d = drive + d.frame(wheel(right_scroll=1)) + d.native = 80 # the Tesla jumped to its next multiple of five; the comma moved one + d.frame() + assert d.card.shown == 78 and d.sync.manual_queue == [] + sent = d.frames(9) + assert sent and sent[0][1][3] & 63 == 63, 'one click down, without waiting out the two-second window' + assert d.sent[0][0] - d.sync.driver_ns < 1_000_000_000 + + +def test_without_the_gesture_speed_sync_waits_out_its_window(drive): + d = drive + d.attach = False + d.frame(wheel(right_scroll=1)) + d.native = 80 + d.frame() + assert d.card.shown == 78 and d.card.consumer.tesla_receipts == [] + assert len(d.sync.manual_queue) == 1 + assert d.frames(19) == [] and d.sync.status == 'waiting_for_manual_processing' + sent = d.frames(8) + assert 'manual_action_unconfirmed' in d.sync.noticed and sent and sent[0][1][3] & 63 == 63, 'corrected after the window' + + +def test_a_fast_scroll_down_is_matched_too(drive): + d = drive + d.frame(wheel(right_scroll=-3)) + d.native = 75 + d.frame() + assert d.steps == [-5] and d.card.shown == 75 and d.sync.manual_queue == [] + assert d.frames(25) == [] and d.sync.status == 'matched' and 'manual_action_unconfirmed' not in d.sync.noticed + + +def test_a_receipt_is_still_matched_at_the_end_of_its_two_seconds(drive): + d = drive + d.frame(wheel(right_scroll=1)) + d.native = 78 + d.frame(publish=False) # card's admission does not reach the controller + assert len(d.card.consumer.tesla_receipts) == 1 + for _ in range(19): + d.frame(publish=False) + assert len(d.card.consumer.tesla_receipts) == 1, 'kept while nobody asks' + d.frame() # 2.0 s after the scroll: still offered, and still inside speed sync's window + assert d.sync.manual_queue == [] and 'manual_action_unconfirmed' not in d.sync.noticed + + +def test_a_receipt_speed_sync_never_takes_expires_with_card(drive): + d = drive + d.frame(wheel(right_scroll=1)) + d.native = 78 + for _ in range(22): + d.frame(publish=False) + assert len(d.card.consumer.tesla_receipts) == 1 + d.frame() # 2.2 s after: card drops it instead of offering it + assert d.card.consumer.tesla_receipts == [] and d.controller.speed_sync_authority.manual_receipts == () + assert 'manual_action_unconfirmed' in d.sync.noticed and d.sync.blocked is None, 'the scroll was dropped after its window' + assert d.frames(10) == [] and d.sync.status == 'matched' + + +def test_seventeen_scrolls_that_are_never_taken_keep_sixteen_receipts(drive): + d = drive + for count in range(1, 18): + d.frame(wheel(right_scroll=-1), publish=False) + d.native -= 1 + d.frame(publish=False) + assert len(d.card.consumer.tesla_receipts) == min(count, 16) + assert d.card.shown == 77 - 17, 'every step was applied' + assert [receipt.sequence for receipt in d.card.consumer.tesla_receipts] == list(range(1, 17)), 'the seventeenth was left out' diff --git a/openpilot/starpilot/controllers/tests/test_tesla_scroll_speed.py b/openpilot/starpilot/controllers/tests/test_tesla_scroll_speed.py new file mode 100644 index 0000000000..0836b976a5 --- /dev/null +++ b/openpilot/starpilot/controllers/tests/test_tesla_scroll_speed.py @@ -0,0 +1,520 @@ +"""Tesla right scroll wheel speed: while the comma owns the set speed (Comma can set speed on Tesla dashboard is on), a +scroll moves it by one display unit and a fast scroll to the next multiple of five, as the Tesla's own cruise steps. + +The car's parameters only say that it may (the scroll frame was admitted at startup); card's cruise helper carries the +saved switch, and with it off the Tesla's own set speed is the set speed exactly as before.""" +from types import SimpleNamespace as NS +from unittest.mock import Mock, patch + +import pytest +from openpilot.cereal import messaging +from openpilot.common.params import Params +from opendbc.car.structs import car +from openpilot.selfdrive.car.cruise import V_CRUISE_MAX, V_CRUISE_MIN, V_CRUISE_UNSET, VCruiseHelper +from openpilot.starpilot.controllers.cruise_action import (TESLA_STEPS, CruiseActionConsumer, CruiseActionPublisher, eligible, tesla_set_speed, + ui_authority) +from openpilot.starpilot.controllers.tests.test_cruise_action import State, Publisher, cp as mock_cp +from openpilot.starpilot.tests.tesla_set_speed_fixture import tesla + +MPH = 1.609344 +NOW = 5_000_000_000 +MODELS = ('TESLA_MODEL_3', 'TESLA_MODEL_Y') + + +def state(mph=25, enabled=True): + return car.CarState.new_message(canValid=True, vEgo=20, cruiseState={ + 'available': True, 'enabled': enabled, 'speed': mph * .44704, 'speedCluster': mph * .44704}) + + +def owned(cp, *, switch=True): + """Card's cruise helper as tesla_set_speed_card.refresh keeps it: owning the set speed while the switch is on.""" + helper = VCruiseHelper(cp) + assert helper.tesla_set_speed is False, 'never owned before the switch has been read' + helper.tesla_set_speed = bool(switch and tesla_set_speed(cp)) + return helper + + +def expected_step(displayed, step): + if abs(step) == 1: + return displayed + step + return (displayed // 5 + 1) * 5 if step > 0 else ((displayed - 1) // 5) * 5 + + +class Rig: + """One selected Tesla, the UI publisher and card's consumer; every step is a fresh message 200 ms after the last.""" + def __init__(self, cp=None, *, metric=False, start=50): + self.cp = tesla(selected=True) if cp is None else cp + self.metric = metric + self.now = NOW + self.sm = State(self.now) + self.helper = owned(self.cp) + self.set(start) + self.sender, self.consumer = CruiseActionPublisher(), CruiseActionConsumer() + + def set(self, displayed): + self.helper.v_cruise_kph = self.helper.v_cruise_cluster_kph = float(displayed if self.metric else round(displayed * MPH, 1)) + + @property + def displayed(self): + return round(self.helper.v_cruise_kph / (1 if self.metric else MPH)) + + def message(self, step): + self.now += 200_000_000 + self.sm = State(self.now) + publisher = Publisher() + assert self.sender.dispatch(step > 0, self.sm, self.cp, publisher, now_ns=self.now, step_units=step) + return publisher.message + + def apply(self, msg, **changes): + arguments = {'now_ns': self.now, 'is_metric': self.metric, 'enabled': True} + arguments.update(changes) + return self.consumer.apply(msg, self.cp, state(), self.sm, self.helper, **arguments) + + def step(self, step): + return self.apply(self.message(step)) + + +def test_the_steps_are_one_unit_or_one_fast_step_each_way(): + assert TESLA_STEPS == (-5, -1, 1, 5) + + +@pytest.mark.parametrize('model', MODELS) +def test_only_a_selected_tesla_may_own_its_set_speed_beside_the_car_cruise(model): + selected, plain = tesla(model, selected=True), tesla(model) + assert selected.pcmCruise and plain.pcmCruise + assert tesla_set_speed(selected) and eligible(selected) + assert not tesla_set_speed(plain) and not eligible(plain), 'started without the scroll frame: a plain car-cruise car' + assert not tesla_set_speed(tesla(model, cable=False, selected=True)) and not tesla_set_speed(tesla(model, long=False, selected=True)) + assert not tesla_set_speed(None) and not tesla_set_speed(mock_cp()) and not tesla_set_speed(mock_cp(True)) + assert eligible(mock_cp()) and not eligible(mock_cp(True)) and not eligible(None), 'other cars: unchanged' + sm = State(NOW) + assert ui_authority(sm, selected, NOW) and not ui_authority(sm, plain, NOW) + + +@pytest.mark.parametrize('metric,start,step,expected', [ + (False, 50, 1, 51), (False, 50, -1, 49), (False, 50, 5, 55), (False, 50, -5, 45), + (False, 52, 5, 55), (False, 52, -5, 50), (False, 54, 5, 55), (False, 56, -5, 55), (False, 51, -5, 50), (False, 49, 5, 50), + (True, 83, 1, 84), (True, 83, -1, 82), (True, 83, 5, 85), (True, 83, -5, 80), (True, 80, 5, 85), (True, 80, -5, 75), +]) +def test_a_step_moves_one_unit_and_a_fast_step_snaps_to_the_next_multiple_of_five(metric, start, step, expected): + r = Rig(metric=metric, start=start) + before = r.helper.v_cruise_kph + assert r.step(step) + assert r.displayed == expected + assert r.helper.v_cruise_kph == pytest.approx(expected * (1 if metric else MPH), abs=.05) + assert r.helper.v_cruise_cluster_kph == r.helper.v_cruise_kph + assert r.helper.slc_cruise_change == (pytest.approx(before / 3.6), pytest.approx(r.helper.v_cruise_kph / 3.6), + 'accel' if step > 0 else 'decel', False) + + +@pytest.mark.parametrize('metric', [False, True]) +def test_every_display_speed_and_every_step_lands_exactly_or_is_refused_at_the_limits(metric): + unit = 1 if metric else MPH + low, high = (8, 145) if metric else (5, 90) + assert (low - 1) * unit < V_CRUISE_MIN <= low * unit and high * unit <= V_CRUISE_MAX < (high + 1) * unit + for start in range(low, high + 1): + for step in TESLA_STEPS: + r = Rig(metric=metric, start=start) + assert r.displayed == start + target = expected_step(start, step) + applied = r.step(step) + if low <= target <= high: + assert applied and r.displayed == target, (start, step) + else: + assert not applied and r.displayed == start, (start, step) + assert r.helper.slc_cruise_change is None + + +@pytest.mark.parametrize('metric,start,step,applied,expected', [ + (False, 5, -1, False, 5), (False, 5, -5, False, 5), (False, 6, -5, True, 5), (False, 9, -5, True, 5), (False, 10, -5, True, 5), + (False, 90, 1, False, 90), (False, 90, 5, False, 90), (False, 89, 1, True, 90), (False, 86, 5, True, 90), (False, 85, 5, True, 90), + (True, 8, -1, False, 8), (True, 8, -5, False, 8), (True, 9, -5, False, 9), (True, 10, -5, False, 10), (True, 11, -5, True, 10), + (True, 145, 1, False, 145), (True, 145, 5, False, 145), (True, 144, 1, True, 145), (True, 141, 5, True, 145), (True, 140, 5, True, 145), +]) +def test_boundaries(metric, start, step, applied, expected): + r = Rig(metric=metric, start=start) + assert r.step(step) is applied + assert r.displayed == expected + assert V_CRUISE_MIN <= r.helper.v_cruise_kph <= V_CRUISE_MAX + + +@pytest.mark.parametrize('metric', [False, True]) +def test_steps_do_not_drift_across_the_range(metric): + low, high = (8, 145) if metric else (5, 90) + r = Rig(metric=metric, start=low) + for expected in range(low + 1, high + 1): + assert r.step(1) and r.displayed == expected + for expected in range(high - 1, low - 1, -1): + assert r.step(-1) and r.displayed == expected + r.set(low + 2) + seen = [] + while r.step(5): + seen.append(r.displayed) + first = (low + 2) // 5 * 5 + 5 + assert seen == list(range(first, high + 1, 5)) + seen = [] + while r.step(-5): + seen.append(r.displayed) + assert seen == list(range(seen[0], (low + 4) // 5 * 5 - 1, -5)) and seen[-1] == (low + 4) // 5 * 5 + + +def test_a_step_starts_from_the_speed_shown_not_from_stored_rounding(): + # Seeded from the car's own 53 mph (85.295 km/h, not yet rounded to a tenth). + r = Rig() + r.helper.v_cruise_kph = 53 * MPH + assert r.step(1) and r.helper.v_cruise_kph == pytest.approx(round(54 * MPH, 1)) + r.helper.v_cruise_kph = 53 * MPH + assert r.step(5) and r.helper.v_cruise_kph == pytest.approx(round(55 * MPH, 1)) + # Speed Limit Controller left 60 km/h on an mph car: 37.28 mph shows as 37. + r.helper.v_cruise_kph = 60. + assert r.step(-1) and r.displayed == 36 + r.helper.v_cruise_kph = 60. + assert r.step(5) and r.displayed == 40 + + +def test_an_unset_speed_is_never_stepped(): + r = Rig() + r.helper.v_cruise_kph = V_CRUISE_UNSET + assert not r.helper.v_cruise_initialized + for step in TESLA_STEPS: + assert not r.step(step) and r.helper.v_cruise_kph == V_CRUISE_UNSET + + +@pytest.mark.parametrize('step', [0, 2, 3, 4, -2, 6, 10, -10, 99, 1.0, 5.0, True, '1']) +def test_the_publisher_refuses_any_other_step(step): + r = Rig() + publisher = Publisher() + assert not r.sender.dispatch(True, r.sm, r.cp, publisher, now_ns=NOW, step_units=step) + assert not hasattr(publisher, 'message') and r.sender.sequence == 0 + + +def test_the_publisher_refuses_a_step_together_with_a_target(): + r = Rig() + assert not r.sender.dispatch(True, r.sm, r.cp, Publisher(), now_ns=NOW, step_units=1, target_mps=25.) + + +@pytest.mark.parametrize('case', ['tesla without the switch', 'tesla without the cable', 'model s', 'software cruise car', + 'car cruise car', 'no car']) +def test_the_publisher_refuses_a_step_for_any_other_car(case): + cp = {'tesla without the switch': tesla, 'tesla without the cable': lambda: tesla(cable=False, selected=True), + 'model s': lambda: tesla('TESLA_MODEL_S_HW1', selected=True), 'software cruise car': mock_cp, + 'car cruise car': lambda: mock_cp(True), 'no car': lambda: None}[case]() + sender, publisher = CruiseActionPublisher(), Publisher() + for step in TESLA_STEPS: + assert not sender.dispatch(step > 0, State(NOW), cp, publisher, now_ns=NOW, step_units=step) + assert not hasattr(publisher, 'message') + + +def test_a_step_message_carries_the_step_and_nothing_else_new(): + r = Rig() + msg = r.message(-5) + assert msg.slcAction.kind == 'cruiseStep' and msg.valid + request = msg.slcAction.controllerCruise + assert request.stepUnits == -5 and request.targetSpeedMps == 0 and request.carFingerprint == r.cp.carFingerprint + assert request.validUntilMonoTime - request.observedMonoTime == 250_000_000 + plain = Publisher() + assert r.sender.dispatch(True, r.sm, r.cp, plain, now_ns=r.now + 1) + assert plain.message.slcAction.kind == 'cruiseIncrease' and plain.message.slcAction.controllerCruise.stepUnits == 0 + + +@pytest.mark.parametrize('case', ['tesla with the switch off', 'tesla started without the frame', 'software cruise car', + 'car cruise car']) +def test_card_refuses_a_step_on_any_car_that_does_not_own_its_set_speed(case): + r = Rig() + msg = r.message(1) + other = {'tesla with the switch off': lambda: tesla(selected=True), 'tesla started without the frame': tesla, + 'software cruise car': mock_cp, 'car cruise car': lambda: mock_cp(True)}[case]() + other.carFingerprint = r.cp.carFingerprint + helper = owned(other, switch=False) + helper.v_cruise_kph = 80. + consumer = CruiseActionConsumer() + assert not consumer.apply(msg, other, state(), r.sm, helper, now_ns=r.now, is_metric=False, enabled=True) + assert helper.v_cruise_kph == 80. and not consumer.tesla_receipts + + +def test_card_follows_the_switch_from_one_message_to_the_next(): + r = Rig() + assert r.step(1) and r.displayed == 51 + r.helper.tesla_set_speed = False # the owner turned the switch off (card's settings thread, within a second) + assert not r.step(1) and r.displayed == 51 + publisher = Publisher() + r.now += 200_000_000 + r.sm = State(r.now) + assert r.sender.dispatch(True, r.sm, r.cp, publisher, now_ns=r.now), 'the screen may still ask' + assert not r.apply(publisher.message) and r.displayed == 51, 'an ordinary speed action is refused too' + r.helper.tesla_set_speed = True + assert r.step(5) and r.displayed == 55 + + +@pytest.mark.parametrize('step', [0, 2, -3, 10, -10, 127, -128]) +def test_card_refuses_a_message_with_any_other_step(step): + r = Rig() + msg = r.message(1).as_builder() + msg.slcAction.controllerCruise.stepUnits = step + assert not r.apply(msg.as_reader()) + assert r.displayed == 50 + + +@pytest.mark.parametrize('fault', ['expired', 'replayed', 'too soon', 'not enabled', 'can invalid', 'cruise unavailable', 'other drive', + 'other car', 'button event']) +def test_card_applies_a_step_only_fresh_once_and_while_engaged(fault): + r = Rig() + msg = r.message(1) + cs = state() + arguments = {'now_ns': r.now, 'is_metric': False, 'enabled': True} + if fault == 'expired': + arguments['now_ns'] += 250_000_001 + if fault == 'replayed': + assert r.apply(msg) + r.now += 150_000_000 + arguments['now_ns'] = r.now + r.set(50) + if fault == 'too soon': + assert r.apply(msg) + msg = r.message(1) + arguments['now_ns'] = r.now = r.now - 150_000_000 + r.set(50) + if fault == 'not enabled': + arguments['enabled'] = False + if fault == 'can invalid': + cs.canValid = False + if fault == 'cruise unavailable': + cs.cruiseState.available = False + if fault == 'other drive': + r.sm['deviceState'].startedMonoTime += 1 + if fault == 'other car': + r.cp.carFingerprint = 'TESLA_MODEL_Y' + if fault == 'button event': + cs.buttonEvents = [{'type': 'accelCruise', 'pressed': True}] + assert not r.consumer.apply(msg, r.cp, cs, r.sm, r.helper, **arguments) + assert r.displayed == 50 + + +def test_a_selected_tesla_also_takes_the_ordinary_speed_actions(): + # Favorites and controller buttons use these: the same card-owned set speed. + r = Rig() + publisher = Publisher() + r.now += 200_000_000 + r.sm = State(r.now) + assert r.sender.dispatch(True, r.sm, r.cp, publisher, now_ns=r.now) + assert r.apply(publisher.message) and r.displayed == 51 + r.now += 200_000_000 + r.sm = State(r.now) + assert r.sender.dispatch(False, r.sm, r.cp, publisher, now_ns=r.now, target_mps=30 * .44704) + assert publisher.message.slcAction.kind == 'cruiseSet' + assert r.apply(publisher.message) and r.displayed == 30 + + +# The set speed itself (selfdrive/car/cruise.py). + +def run(helper, frames, *, metric=False): + out = [] + for mph, engaged in frames: + cs = state(mph, engaged) if mph is not None else car.CarState.new_message(canValid=True) + helper.update_v_cruise(cs, engaged, metric) + out.append((helper.v_cruise_kph, helper.v_cruise_cluster_kph)) + return out + + +@pytest.mark.parametrize('model', MODELS) +def test_with_the_switch_on_a_tesla_keeps_its_own_set_speed_seeded_from_the_car_while_not_engaged(model): + h = owned(tesla(model, selected=True)) + assert h.tesla_set_speed and not h.v_cruise_initialized + out = run(h, [(50, False), (55, False), (55, True), (60, True), (40, True), (40, False), (45, True)]) + shown = [round(kph / MPH, 3) for kph, _ in out] + assert shown == [50, 55, 55, 55, 55, 40, 40], "follows the Tesla until engaged, then is the comma's own" + assert all(kph == cluster for kph, cluster in out) + assert h.slc_cruise_change is None and not h.slc_pcm + + +def test_with_the_switch_on_a_tesla_starts_from_the_car_if_it_engages_before_any_speed_was_seen(): + h = owned(tesla(selected=True)) + assert [round(kph / MPH, 3) for kph, _ in run(h, [(62, True), (70, True)])] == [62, 62] + + +def test_with_the_switch_on_a_tesla_has_no_set_speed_without_cruise_or_a_car_speed(): + h = owned(tesla(selected=True)) + assert run(h, [(50, True), (None, False)])[-1] == (V_CRUISE_UNSET, V_CRUISE_UNSET), 'cruise not available' + assert run(h, [(0, False)])[-1] == (V_CRUISE_UNSET, V_CRUISE_UNSET), 'the car has no set speed' + assert run(h, [(50, False), (0, True)])[-1][0] == pytest.approx(50 * MPH), 'engaged: the comma keeps its own' + + +def test_engaging_with_the_switch_on_keeps_the_seeded_speed(): + h = owned(tesla(selected=True)) + run(h, [(50, False)]) + for resume in (None, False, True): + assert h.initialize_v_cruise(state(50), False, resume=resume) is False + assert h.v_cruise_kph == pytest.approx(50 * MPH) + assert h.initialize_v_cruise(state(50), False, slc_target_mps=30., is_metric=False) is False, 'no live Speed Limit Controller' + assert h.v_cruise_kph == pytest.approx(50 * MPH) + + +def test_the_switch_changes_who_owns_the_set_speed_without_a_jump(): + h = owned(tesla(selected=True), switch=False) + assert [round(kph / MPH, 3) for kph, _ in run(h, [(50, False), (50, True), (52, True)])] == [50, 50, 52], "off: the Tesla's own" + h.tesla_set_speed = True # card's settings thread read the switch on + assert [round(kph / MPH, 3) for kph, _ in run(h, [(52, True), (60, True)])] == [52, 52], 'on: it starts from that same speed' + h.tesla_set_speed = False + assert [round(kph / MPH, 3) for kph, _ in run(h, [(60, True)])] == [60], "off again: the Tesla's own at once" + + +def car_cruise_car(brand, fingerprint): + return car.CarParams.new_message(pcmCruise=True, brand=brand, carFingerprint=fingerprint, openpilotLongitudinalControl=True) + + +WITHOUT_OWNERSHIP = { + 'tesla with the switch off': lambda: tesla(selected=True), + 'model y with the switch off': lambda: tesla('TESLA_MODEL_Y', selected=True), + 'tesla started without the frame': tesla, + 'tesla without the cable': lambda: tesla(cable=False, selected=True), + 'tesla without longitudinal control': lambda: tesla(long=False, selected=True), + 'model s': lambda: tesla('TESLA_MODEL_S_HW1', selected=True), + 'mock toyota': lambda: mock_cp(True, 'toyota'), + 'toyota': lambda: car_cruise_car('toyota', 'TOYOTA_RAV4_TSS2'), + 'hyundai': lambda: car_cruise_car('hyundai', 'HYUNDAI_IONIQ_5'), + 'honda': lambda: car_cruise_car('honda', 'HONDA_CIVIC_BOSCH'), +} + + +@pytest.mark.parametrize('case', WITHOUT_OWNERSHIP) +def test_a_tesla_with_the_switch_off_and_any_car_cruise_car_mirror_the_car_as_before(case): + h = VCruiseHelper(WITHOUT_OWNERSHIP[case]()) + assert h.tesla_set_speed is False, 'a new helper never owns the set speed: card turns it on from the saved switch' + frames = [(50, False), (55, False), (55, True), (60, True), (40, True), (40, False), (45, True), (0, True), (0, False)] + out = run(h, frames) + for (mph, _), (kph, cluster) in zip(frames, out, strict=True): + expected = mph * .44704 * 3.6 if mph else V_CRUISE_UNSET + assert kph == pytest.approx(expected) and cluster == pytest.approx(expected) + cs = car.CarState.new_message(canValid=True, cruiseState={'available': True, 'speed': -1, 'speedCluster': -1}) + h.update_v_cruise(cs, True, False) + assert (h.v_cruise_kph, h.v_cruise_cluster_kph) == (-1, -1) + cs = car.CarState.new_message(canValid=True, cruiseState={'available': True, 'speed': 20., 'speedCluster': 21.}) + h.update_v_cruise(cs, True, False) + assert (h.v_cruise_kph, h.v_cruise_cluster_kph) == (pytest.approx(72.), pytest.approx(75.6)), 'the cluster speed stays its own' + assert run(h, [(None, False)])[-1] == (V_CRUISE_UNSET, V_CRUISE_UNSET) + assert h.initialize_v_cruise(state(50), False, slc_target_mps=30.) is False + up = car.CarState.ButtonEvent.Type.accelCruise + run(h, [(50, True)]) + assert h.adjust_v_cruise(up, state(50), False) is False and h.v_cruise_kph == pytest.approx(50 * MPH) + assert not h.slc_pcm + + +def test_software_cruise_cars_are_unchanged(): + h = VCruiseHelper(mock_cp()) + assert not h.tesla_set_speed + h.v_cruise_kph = 80 + h.update_v_cruise(state(50), True, True) + assert h.v_cruise_kph == 80, "never taken from the car's own cruise" + assert h.adjust_v_cruise(car.CarState.ButtonEvent.Type.accelCruise, state(50), True) and h.v_cruise_kph == 81 + + +def test_speed_limit_controller_ownership_is_only_marked_while_the_comma_owns_the_set_speed(): + for cp, switch, expected in ((tesla(selected=True), True, True), (tesla(selected=True), False, False), (tesla(), True, False), + (mock_cp(True), True, False), (mock_cp(), True, False)): + h = owned(cp, switch=switch) + h.update_v_cruise(state(50), True, False, slc_enabled=True) + assert h.slc_pcm is expected + h.update_v_cruise(state(50), True, False, slc_enabled=False) + assert h.slc_pcm is False + + +# The real card loop. + +def card_instance(tmp_path, cp, helper, sm, cs): + from openpilot.selfdrive.car import card + instance = card.Car.__new__(card.Car) + instance.CP = cp + vars(instance)['sm'] = sm + instance.CC_prev = car.CarControl(enabled=True) + instance.CS_prev = cs + vars(instance)['CI'] = NS(CC=None, CS=NS(), update=lambda packets: cs) + vars(instance)['RI'] = NS(update=lambda packets: None) + instance.car_gps_publisher = card.CarGpsPublisher() + instance.params = Params(str(tmp_path)) + vars(instance)['can_sock'] = object() + instance.can_rcv_cum_timeout_counter = 0 + instance.ioniq6_long_prearmed = False + instance.conditional_replay = instance.slc_replay = instance.curve_replay = False + instance.switchback_button_tracker = instance.switchback_settings_owner = None + instance.wheel_publisher = card.WheelPublisher(instance.params) + instance.aol_card_intent = None + instance.is_metric = False + instance.experimental_mode = False + instance.v_cruise_helper = helper + instance.slc_command_sock = None + instance.controller_cruise_sock = object() + instance.controller_cruise_consumer = CruiseActionConsumer() + return card, instance + + +def card_step(tmp_path, cp, request, *, now, switch=True, safe_mode=False): + """One real card state update: the saved switch is read as card's settings thread reads it, then a request arrives.""" + from openpilot.starpilot.speed_limits import tesla_set_speed_card + sm = State(now) + cs = state(60) # the Tesla's own set speed has moved to 60 mph since engaging at 50 + helper = VCruiseHelper(cp) + card, instance = card_instance(tmp_path, cp, helper, sm, cs) + instance.params.put_bool('TeslaSpeedSync', switch, block=True) + instance.params.put_bool('SafeMode', safe_mode, block=True) + tesla_set_speed_card.refresh(instance) + helper.update_v_cruise(state(50, False), False, False) + with (patch.object(instance, 'pm', NS(send=Mock()), create=True), + patch.object(card.messaging, 'drain_sock_raw', return_value=[messaging.new_message('can', 1).to_bytes()]), + patch.object(card.messaging, 'recv_one_or_none', side_effect=[request, None]), + patch.object(card.time, 'monotonic_ns', return_value=now)): + selected, _ = instance.state_update() + return selected, helper, instance + + +@pytest.mark.parametrize('step,expected', [(1, 51), (-1, 49), (5, 55), (-5, 45)]) +def test_actual_card_applies_a_step_to_its_own_set_speed_with_the_switch_on(tmp_path, step, expected): + r = Rig() + selected, helper, _ = card_step(tmp_path, r.cp, r.message(step), now=r.now) + assert helper.tesla_set_speed + assert selected.vCruise == pytest.approx(round(expected * MPH, 1)) + assert selected.vCruiseCluster == selected.vCruise + assert list(selected.buttonEvents) == [] + assert helper.slc_cruise_change is not None and helper.slc_cruise_change[2] == ('accel' if step > 0 else 'decel') + + +def test_actual_card_keeps_the_comma_speed_when_no_step_arrives(tmp_path): + r = Rig() + selected, _, _ = card_step(tmp_path, r.cp, None, now=r.now) + assert selected.vCruise == pytest.approx(50 * MPH), "not the Tesla's 60" + + +def test_actual_card_ignores_a_step_in_safe_mode(tmp_path): + r = Rig() + selected, helper, _ = card_step(tmp_path, r.cp, r.message(1), now=r.now, safe_mode=True) + assert not helper.tesla_set_speed, 'Safe Mode turns the switch off' + assert selected.vCruise == pytest.approx(60 * MPH), "the Tesla's own set speed" + + +@pytest.mark.parametrize('admitted,switch', [(True, False), (False, True), (False, False)]) +def test_actual_card_ignores_a_step_with_the_switch_off_or_on_a_tesla_started_without_the_frame(tmp_path, admitted, switch): + r = Rig() + selected, helper, _ = card_step(tmp_path, tesla(selected=admitted), r.message(1), now=r.now, switch=switch) + assert not helper.tesla_set_speed + assert selected.vCruise == pytest.approx(60 * MPH), "the Tesla's own set speed, as before" + + +def test_card_reads_the_switch_only_for_a_car_that_may_own_its_set_speed(tmp_path): + from openpilot.starpilot.speed_limits import tesla_set_speed_card + for index, (cp, expected) in enumerate(((tesla(selected=True), True), (tesla('TESLA_MODEL_Y', selected=True), True), (tesla(), False), + (tesla(cable=False, selected=True), False), (car_cruise_car('hyundai', 'HYUNDAI_IONIQ_5'), False), + (mock_cp(), False))): + path = tmp_path / str(index) + path.mkdir() + params = Params(str(path)) + params.put_bool('TeslaSpeedSync', True, block=True) + reads = [] + saved = NS(get_param_path=lambda key='', params=params, reads=reads: reads.append(key) or params.get_param_path(key)) + helper = VCruiseHelper(cp) + owner = NS(CP=cp, params=saved, v_cruise_helper=helper, slc_transport_available=False) + tesla_set_speed_card.refresh(owner) + assert helper.tesla_set_speed is expected + assert bool(reads) is expected, 'nothing is read for any other car' + assert tesla_set_speed_card.attach(owner) is None and not tesla_set_speed_card.rule(owner) + params.put_bool('TeslaSpeedSync', False, block=True) + tesla_set_speed_card.refresh(owner) + assert helper.tesla_set_speed is False diff --git a/openpilot/starpilot/controllers/tests/test_tesla_wheel_hold.py b/openpilot/starpilot/controllers/tests/test_tesla_wheel_hold.py new file mode 100644 index 0000000000..9f7200e1e8 --- /dev/null +++ b/openpilot/starpilot/controllers/tests/test_tesla_wheel_hold.py @@ -0,0 +1,259 @@ +"""The right scroll wheel nudged left or right and held: its own control, apart from the plain nudge. +Wheel frames arrive every 0.1 s.""" +import json +from types import SimpleNamespace as NS + +import pytest + +from openpilot.starpilot.common.car_control_config import ACTIVE_INPUTS, INPUTS, PARAM, WHEEL_HOLDS, effective_bindings, parse_assignments +from openpilot.starpilot.controllers.tesla_controls import TeslaInputDecoder, WHEEL_FRAME_GAP_SECONDS, WHEEL_HOLD_SECONDS, WheelHold +from openpilot.starpilot.controllers.tests.test_tesla_decoder import wheel +from openpilot.starpilot.controllers.tests.tesla_worker_fixture import selected_rig +from openpilot.starpilot.favorites.actions import BOOKMARK + +UP = wheel() +SWITCHES = ('right_wheel_left', 'right_wheel_right') +HOLDS = tuple(WHEEL_HOLDS.values()) +HOLD_FRAMES = round(WHEEL_HOLD_SECONDS / .1) + 1 # the first pressed frame, then 0.6 s of them + + +@pytest.fixture +def setup(tmp_path): + return selected_rig(tmp_path) + + +def on(switch, **more): + return wheel(**{switch: 2}, **more) + + +class Feed: + def __init__(self, *holds): + self.decoder = TeslaInputDecoder(bus=1, wheel_holds=frozenset(holds)) + self.t = 1.0 + self.out = [] + + def __call__(self, *frames, dt=.1): + result = [] + for frame in frames: + self.t += dt + result += self.decoder.feed(0x3c2, frame, 1, self.t) + self.out += result + return result + + +def test_the_inputs_exist_and_act(): + assert WHEEL_HOLDS == {'right_wheel_left': 'right_wheel_left_hold', 'right_wheel_right': 'right_wheel_right_hold'} + assert INPUTS['right_wheel_left_hold'] == ('Right scroll wheel', 'Nudge left — hold') + assert INPUTS['right_wheel_right_hold'] == ('Right scroll wheel', 'Nudge right — hold') + assert set(HOLDS) <= ACTIVE_INPUTS + document = parse_assignments(json.dumps({'version': 1, 'vehicle': 'TESLA_MODEL_3', 'bindings': { + 'right_wheel_left_hold': {'key': BOOKMARK, 'value': None, 'label': 'Bookmark'}}})) + assert effective_bindings(document)['right_wheel_left_hold']['key'] == BOOKMARK + + +def test_holds_only_and_nudges_only(): + # No double nudge, and no hold or double of the inward press. + wheel_inputs = {name for name in INPUTS if '_wheel_' in name} + assert not [name for name in wheel_inputs if 'double' in name] + assert {name for name in wheel_inputs if name.endswith('_hold')} == set(HOLDS) + assert 'right_wheel_press' not in ACTIVE_INPUTS and not [name for name in ACTIVE_INPUTS if name.startswith('left_wheel_')] + for name in ('right_wheel_press_hold', 'right_wheel_left_double', 'right_wheel_press_double', 'left_wheel_left_hold'): + assert parse_assignments(json.dumps({'version': 1, 'vehicle': 'TESLA_MODEL_3', 'bindings': { + name: {'key': BOOKMARK, 'value': None, 'label': 'Bookmark'}}})) is None, name + + +@pytest.mark.parametrize('switch', SWITCHES) +def test_hold_fires_once_while_still_held(switch): + hold = WHEEL_HOLDS[switch] + feed = Feed(hold) + feed(UP) + assert feed(*[on(switch)] * (HOLD_FRAMES - 1)) == [], 'held for 0.5 s: not yet' + assert feed(on(switch)) == [hold], 'the frame 0.6 s after the first one' + assert feed(*[on(switch)] * 10) == [], 'once per hold' + assert feed(UP, UP) == [], 'the release is part of the hold: the plain nudge does not also act' + assert feed(*[on(switch)] * HOLD_FRAMES) == [hold], 'the next hold works' + + +@pytest.mark.parametrize('switch', SWITCHES) +def test_release_after_a_hold_gives_nothing(switch): + feed = Feed(*HOLDS) + feed(UP) + assert feed(*[on(switch)] * 13, UP, UP, UP) == [WHEEL_HOLDS[switch]], 'a 1.3 s hold reads as thirteen frames' + assert switch not in feed.out + + +@pytest.mark.parametrize('switch', SWITCHES) +def test_a_quick_nudge_with_the_hold_assigned_still_acts_at_once(switch): + feed = Feed(WHEEL_HOLDS[switch]) + feed(UP) + for frames in (1, 2, 4, HOLD_FRAMES - 1): + assert feed(*[on(switch)] * frames) == [] + assert feed(UP) == [switch], f'{frames} frames: on the release frame, with no wait' + assert feed(UP) == [] + + +def test_each_side_is_assigned_separately(): + feed = Feed('right_wheel_left_hold') + feed(UP) + assert feed(*[on('right_wheel_right')] * 10, UP) == ['right_wheel_right'], 'nudge right has no hold: a long one is a nudge' + assert feed(*[on('right_wheel_left')] * 10, UP) == ['right_wheel_left_hold'] + assert feed(*[on('right_wheel_press')] * 10, UP) == ['right_wheel_press'], 'the inward press never has a hold' + feed = Feed(*HOLDS) + feed(UP) + assert feed(*[on('right_wheel_press')] * 10, UP) == ['right_wheel_press'] + assert feed(*[on('left_wheel_left')] * 10, UP) == ['left_wheel_left'], 'the left wheel has no holds' + + +def test_unknown_or_unassigned_hold_names_are_ignored(): + for names in ((), ('right_wheel_press_hold',), ('right_wheel_left',), ('left_wheel_left_hold',)): + decoder = TeslaInputDecoder(bus=1, wheel_holds=frozenset(names)) + assert decoder.wheel_holds == {} + assert TeslaInputDecoder(bus=1, wheel_holds=frozenset(HOLDS)).wheel_holds == WHEEL_HOLDS + + +def test_unassigned_changes_nothing(): + script = ([UP, on('right_wheel_left'), UP, on('right_wheel_left'), on('right_wheel_left'), UP, UP] + + [on('right_wheel_right')] * 9 + [UP, on('right_wheel_press'), UP, on('right_wheel_press'), UP, + wheel(right_scroll=2), UP, on('right_wheel_left'), wheel(right_scroll=1), UP]) + plain, assigned = TeslaInputDecoder(bus=1), Feed() + t, expected = 1.0, [] + for frame in script: + t += .1 + expected.append(plain.feed(0x3c2, frame, 1, t)) + assert [assigned(frame) for frame in script] == expected + assert not set(assigned.out) & set(HOLDS) + assert assigned.out.count('right_wheel_left') == 3 and assigned.out.count('right_wheel_right') == 1 + + +def test_only_an_assigned_hold_changes_what_the_other_frames_give(): + # With one side's hold assigned, everything but that side's long nudge decodes exactly as with none assigned. + script = ([UP, on('right_wheel_left'), UP] + [on('right_wheel_right')] * 9 + [UP, on('right_wheel_press'), UP, + wheel(right_scroll=2), UP, wheel(left_scroll=-1), UP, on('right_wheel_left'), wheel(right_scroll=1), UP]) + plain, assigned = Feed(), Feed('right_wheel_left_hold') + assert [assigned(frame) for frame in script] == [plain(frame) for frame in script] + + +def test_a_nudge_that_ends_with_a_stray_scroll_click_still_counts(): + feed = Feed(*HOLDS) + nudge = on('right_wheel_left') + feed(UP) + assert feed(nudge, wheel(right_scroll=1)) == ['right_wheel_left'], 'the click ends the nudge and is not a scroll' + assert feed(UP) == [] + # A click while the wheel is still tilted does not stop the hold from counting. + assert feed(nudge, on('right_wheel_left', right_scroll=1), *[nudge] * (HOLD_FRAMES - 2)) == ['right_wheel_left_hold'] + assert feed(UP, UP) == [] + # A hold whose release frame carries the click gives the hold alone. + assert feed(*[nudge] * HOLD_FRAMES, wheel(right_scroll=-1), UP) == ['right_wheel_left_hold'] + + +def test_doing_two_things_with_the_right_wheel_at_once_is_not_a_hold(): + feed = Feed(*HOLDS) + feed(UP) + both = wheel(right_wheel_press=2, right_wheel_left=2) + assert feed(on('right_wheel_left'), on('right_wheel_left'), both, *[on('right_wheel_left')] * 8) == [], 'needs a release first' + feed(UP, UP) + both = wheel(right_wheel_left=2, right_wheel_right=2) + assert feed(on('right_wheel_left'), both, *[on('right_wheel_left')] * 8) == [] + feed(UP, UP) + assert feed(on('right_wheel_left'), on('right_wheel_left', right_scroll=2), *[on('right_wheel_left')] * 8) == [], 'a real scroll' + feed(UP, UP) + # The left wheel is its own business: a hold on the right still counts while the left one scrolls or is pressed. + frames = [on('right_wheel_right')] * 3 + [on('right_wheel_right', left_scroll=3), on('right_wheel_right', left_wheel_press=2)] + assert feed(*frames, *[on('right_wheel_right')] * (HOLD_FRAMES - 5)) == ['right_wheel_right_hold'] + + +def test_already_down_at_the_start_or_after_lost_frames_does_not_count(): + feed = Feed(*HOLDS) + nudge = on('right_wheel_left') + assert feed(*[nudge] * 10) == [], 'never seen released' + feed(UP) + assert feed(*[nudge] * 4) == [] + assert feed(*[nudge] * 8, dt=.5) == [], 'frames went missing mid-hold' + feed(UP, dt=.1) + assert feed(*[nudge] * HOLD_FRAMES) == ['right_wheel_left_hold'] + feed(UP) + feed.decoder.reset() + assert feed(*[nudge] * 10) == [], 'a reset decoder must see the wheel released first' + + +def test_two_lost_frames_are_bridged_and_three_are_not(): + assert .3 < WHEEL_FRAME_GAP_SECONDS < .4 + hold = WheelHold() + assert not hold.update(False, 1.0) and not hold.update(True, 1.1) + assert not hold.update(True, 1.4), 'two frames lost: still the same nudge' + assert hold.update(True, 1.7), 'held 0.6 s since it was first seen' + assert not hold.update(True, 1.8) + hold = WheelHold() + hold.update(False, 1.0) + hold.update(True, 1.1) + assert not hold.update(True, 1.5) and not hold.update(True, 1.9), 'three lost: start again, from a release' + assert not hold.armed + hold = WheelHold() + hold.update(False, 1.0) + hold.update(True, 1.1) + assert not hold.update(True, 1.05) and not hold.armed, 'time going backward starts again' + + +def test_frame_time_jitter_does_not_delay_a_hold(): + hold = WheelHold() + hold.update(False, 1.0) + hold.update(True, 1.1004) + for i in range(1, 6): + assert not hold.update(True, 1.1 + i * .1) + assert hold.update(True, 1.6996), 'six frames after the first, a few ms early' + + +def test_unreadable_switches_start_again(): + feed = Feed(*HOLDS) + nudge = on('right_wheel_right') + feed(UP) + assert feed(nudge, nudge, wheel(right_wheel_right=3), *[nudge] * 8) == [], 'a faulted switch frame' + feed(UP) + assert feed(nudge, nudge, wheel(left_wheel_left=0), *[nudge] * 8) == [], 'any unreadable switch in the frame' + feed(UP) + assert feed(*[nudge] * HOLD_FRAMES) == ['right_wheel_right_hold'], 'works again after a release' + + +def test_other_mux_frames_between_wheel_frames_do_not_break_a_hold(): + feed = Feed(*HOLDS) + nudge = on('right_wheel_left') + feed(UP) + out = [] + for _ in range(HOLD_FRAMES): + out += feed(nudge, dt=.1) + out += feed(bytes(8), dt=0.) # the message's other multiplexed half, sent in between + assert out == ['right_wheel_left_hold'] + + +def test_the_worker_sends_an_assigned_hold(setup): + calls = [] + names = {'right_wheel_left': 'single', 'right_wheel_left_hold': 'hold', 'right_wheel_right': 'other'} + setup.doc['bindings'] = {name: {'key': action, 'value': None, 'label': action} for name, action in names.items()} + setup.params.put(PARAM, json.dumps(setup.doc).encode(), block=True) + for action in names.values(): + setup.actions[action] = NS(available=True, invoke=lambda action=action: calls.append(action), invoke_value=None) + nudge = on('right_wheel_left') + setup.feed(UP) + for _ in range(HOLD_FRAMES): + setup.feed(nudge) + assert calls == ['hold'] + for frame in (UP, UP, nudge, UP): + setup.feed(frame) + assert calls == ['hold', 'single'] + for frame in [on('right_wheel_right')] * 10 + [UP]: + setup.feed(frame) + assert calls == ['hold', 'single', 'other'], 'the unassigned hold on the other side stays a plain nudge' + assert setup.pump.decoder.wheel_holds == {'right_wheel_left': 'right_wheel_left_hold'} + + +def test_the_worker_treats_an_explicitly_unassigned_hold_as_unassigned(setup): + calls = [] + setup.doc['bindings'] = {'right_wheel_left': {'key': 'single', 'value': None, 'label': 'single'}, + 'right_wheel_left_hold': {'key': '__starpilot_controller_action__:none', 'value': None, 'label': 'Unassigned'}} + setup.params.put(PARAM, json.dumps(setup.doc).encode(), block=True) + setup.actions['single'] = NS(available=True, invoke=lambda: calls.append('single'), invoke_value=None) + setup.feed(UP) + for _ in range(10): + setup.feed(on('right_wheel_left')) + setup.feed(UP) + assert calls == ['single'] and setup.pump.decoder.wheel_holds == {} diff --git a/openpilot/starpilot/controllers/tests/test_tesla_worker.py b/openpilot/starpilot/controllers/tests/test_tesla_worker.py new file mode 100644 index 0000000000..1390f0abf2 --- /dev/null +++ b/openpilot/starpilot/controllers/tests/test_tesla_worker.py @@ -0,0 +1,711 @@ +"""Tesla input worker and its receiver in the UI: messages, lifecycle and hand-off of one decoded control at a time.""" +import json +import os +import shutil +import time +from types import SimpleNamespace as NS + +import pytest +from openpilot.cereal import messaging +from openpilot.common.prefix import OpenpilotPrefix +from opendbc.car.structs import car +from opendbc.car.tesla.values import TeslaFlags +from openpilot.starpilot.common.car_control_config import (NO_LIMIT_REASON, PARAM, SPEED_DOWN, SPEED_RESUME, SPEED_UP, STALK_HOLD, STALK_TAP, + comma_speed, vehicle_supported) +from openpilot.starpilot.controllers.tesla_receiver import TeslaReceiver, WorkerChannel +from openpilot.starpilot.controllers.tesla_input_protocol import encode_event, decode_event, MAX_PACKET +from openpilot.starpilot.controllers.tests.tesla_worker_fixture import CUSTOM, Channel, Messages, build, save, selected_rig, stalk +from openpilot.starpilot.controllers.tests.test_tesla_decoder import wheel +from openpilot.starpilot.tests.port_settings_fixture import Saved +from openpilot.starpilot.tests.tesla_set_speed_fixture import switch, tesla + + +@pytest.fixture +def setup(tmp_path): + return selected_rig(tmp_path) + + +@pytest.mark.parametrize('ticks', [1, 2, 3, 6]) +def test_end_to_end_release_preserves_speed_action(setup, ticks): + s = setup + s.feed(wheel()) + s.feed(wheel(right_scroll=ticks)) + assert not s.calls + s.feed(wheel()) + s.feed(wheel()) + assert s.calls == [0 if ticks == 1 else 1] + + +def test_scroll_down_runs_the_decrease_action(setup): + s = setup + s.actions[SPEED_DOWN] = NS(available=True, invoke_value=lambda fast: s.calls.append(('down', fast)), invoke=None) + s.feed(wheel()) + s.feed(wheel(right_scroll=-1)) + s.feed(wheel()) + s.feed(wheel(right_scroll=-3)) + s.feed(wheel()) + assert s.calls == [('down', 0), ('down', 1)] + + +@pytest.mark.parametrize('saved', [None, SPEED_DOWN, CUSTOM, '__starpilot_controller_action__:none']) +def test_scroll_is_never_assignable(setup, saved): + # Whatever was saved for the scroll (an old build could save one), a selected car's scroll sets the comma speed. + s = setup + if saved is not None: + s.doc['bindings']['right_wheel_up'] = {'key': saved, 'value': None, 'label': 'Saved'} + save(s) + s.actions[SPEED_DOWN] = NS(available=True, invoke_value=lambda fast: s.calls.append('down'), invoke=None) + s.feed(wheel()) + s.feed(wheel(right_scroll=1)) + s.feed(wheel()) + assert s.calls == [0] + + +@pytest.mark.parametrize('selected,comma', [(True, False), (False, True), (False, False)]) +@pytest.mark.parametrize('saved', [None, SPEED_UP, CUSTOM]) +def test_without_the_switch_the_scroll_is_left_to_the_tesla(tmp_path, selected, comma, saved): + # The switch off, or on for a car that started without the scroll frame admitted: the scroll is the Tesla's own. + s = build(tmp_path, tesla(selected=selected), comma=comma) + assert vehicle_supported(s.cp) and not comma_speed(s.params, s.cp) + if saved is not None: + s.doc['bindings']['right_wheel_up'] = {'key': saved, 'value': None, 'label': 'Saved'} + save(s) + for ticks in (1, 3, -1, -3): + s.feed(wheel()) + s.feed(wheel(right_scroll=ticks)) + s.feed(wheel()) + assert not s.calls and not s.channel.queue, 'the worker sends nothing for a scroll' + s.feed(wheel(right_wheel_left=2)) + s.feed(wheel()) + assert s.calls == [CUSTOM], 'the other controls still work' + + +def test_the_switch_is_followed_within_a_second_without_a_restart(tmp_path): + s = build(tmp_path, tesla(selected=True), comma=False) + + def scroll(): + s.feed(wheel()) + s.feed(wheel(right_scroll=1)) + s.feed(wheel()) + s.feed(wheel()) + scroll() + assert s.calls == [] + switch(s.params, True) + for _ in range(4): + scroll() # the worker reads the switch at most once a second + assert s.calls and set(s.calls) == {0}, 'now the scroll sets the comma speed' + taken = len(s.calls) + switch(s.params, False) + s.feed(wheel()) + s.feed(wheel(right_scroll=1)) + s.feed(wheel(), dispatch=False) + queued = len(s.channel.queue) + s.receiver.poll() + assert len(s.calls) == taken, 'the screen reads the switch at once: an event the worker still sent is not acted on' + for _ in range(4): + scroll() + assert len(s.calls) == taken and queued <= 1 and not s.channel.queue + + +def test_safe_mode_turns_the_comma_scroll_off_like_the_switch(setup): + s = setup + s.params.put('SafeMode', b'1', block=True) + for _ in range(4): + s.feed(wheel()) + s.feed(wheel(right_scroll=1)) + s.feed(wheel()) + assert s.calls == [] + + +def test_end_to_end_stalk_hold_runs_its_action_instead_of_the_press(setup): + s = setup + s.doc['bindings'][STALK_HOLD] = {'key': SPEED_RESUME, 'value': None, 'label': 'Resume Speed Limit + Offset'} + s.doc['bindings']['right_stalk_down_half'] = {'key': SPEED_UP, 'value': None, 'label': 'Up'} + save(s) + s.actions[SPEED_RESUME] = NS(available=True, invoke=lambda: s.calls.append('resume'), invoke_value=None) + s.feed(stalk(0, 0), address=0x229) + for counter in range(1, 10): + s.feed(stalk(3, counter), address=0x229) + assert s.calls == ['resume'] + s.feed(stalk(0, 10), address=0x229) + assert s.calls == ['resume'], 'the release is not also a down press' + s.feed(stalk(3, 11), address=0x229) + s.feed(stalk(0, 12), address=0x229) + assert s.calls == ['resume'], 'a plain down press (the engage press) has no action of its own' + + +def test_stalk_hold_is_fixed_whatever_is_saved_for_it(setup): + s = setup + s.doc['bindings'][STALK_HOLD] = {'key': CUSTOM, 'value': None, 'label': 'Custom'} + save(s) + s.actions[SPEED_RESUME] = NS(available=True, invoke=lambda: s.calls.append('resume'), invoke_value=None) + s.feed(stalk(0, 0), address=0x229) + for counter in range(1, 10): + s.feed(stalk(3, counter), address=0x229) + assert s.calls == ['resume'] + + +def test_end_to_end_tap_while_engaged(setup): + s = setup + s.doc['bindings'][STALK_TAP] = {'key': SPEED_RESUME, 'value': None, 'label': 'Resume Speed Limit + Offset'} + s.doc['bindings']['right_stalk_down_full'] = {'key': SPEED_UP, 'value': None, 'label': 'Up'} + save(s) + s.actions[SPEED_RESUME] = NS(available=True, invoke=lambda: s.calls.append('resume'), invoke_value=None) + s.feed(stalk(0, 0), address=0x229) + s.feed(stalk(4, 1), address=0x229) + s.feed(stalk(0, 2), address=0x229) + assert s.calls == [], 'the press that engages has no action of its own' + s.sm.engaged = True + s.feed(stalk(3, 3), address=0x229) + s.feed(stalk(0, 4), address=0x229) + assert s.calls == [], 'cruise only just came on: still part of engaging' + for _ in range(6): + s.feed(stalk(0, 4), address=0x229) # cruise on for 0.6 s + s.feed(stalk(3, 5), address=0x229) + s.feed(stalk(0, 6), address=0x229) + assert s.calls == ['resume'] + + +def test_engaging_press_runs_no_action_while_engaged(setup): + # The car turns cruise on during the press that engages it, so the press's first frames already see cruise on. + s = setup + s.doc['bindings'][STALK_TAP] = {'key': SPEED_RESUME, 'value': None, 'label': 'Resume Speed Limit + Offset'} + save(s) + s.actions[SPEED_RESUME] = NS(available=True, invoke=lambda: s.calls.append('resume'), invoke_value=None) + s.feed(stalk(0, 0), address=0x229) + s.sm.engaged = True + s.feed(stalk(3, 1), address=0x229) + s.feed(stalk(0, 2), address=0x229) + assert s.calls == [] + for _ in range(6): + s.feed(stalk(0, 2), address=0x229) + s.feed(stalk(3, 3), address=0x229) + s.feed(stalk(0, 4), address=0x229) + assert s.calls == ['resume'] + + +def test_hold_and_half_press_work_with_nothing_saved(setup): + # 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 + s.actions[SPEED_RESUME] = NS(available=True, invoke=lambda: s.calls.append('resume'), invoke_value=None) + s.sm.engaged = True + for _ in range(6): + s.feed(stalk(0, 0), address=0x229) # cruise already on for 0.6 s + s.feed(stalk(3, 1), address=0x229) + s.feed(stalk(0, 2), address=0x229) + assert s.calls == ['resume'] + for counter in range(3, 12): + s.feed(stalk(3, counter), address=0x229) + assert s.calls == ['resume', 'resume'] + + +@pytest.mark.parametrize('fault', ['safe', 'config', 'invalid', 'wrong_bus', 'offroad', 'vehicle', 'stale']) +def test_held_gesture_cannot_cross_context(setup, fault): + s = setup + s.feed(wheel()) + s.feed(wheel(right_scroll=2)) + if fault == 'safe': + s.params.put('SafeMode', b'1', block=True) + if fault == 'config': + s.doc['bindings']['right_wheel_left']['label'] = 'Changed' + save(s) + if fault == 'vehicle': + s.cp.mass = 1234. + s.pump.set_vehicle(s.cp) + if fault == 'offroad': + s.sm.refresh(s.clock[0], started=False) + s.pump.poll(s.sm) + s.feed(wheel(), valid=fault != 'invalid', bus=0 if fault == 'wrong_bus' else 1, + delta=1 if fault == 'stale' else .1) + assert not s.calls + + +@pytest.mark.parametrize('fault', ['safe', 'config', 'vehicle', 'offroad', 'stale', 'can_invalid', 'availability', 'unselected']) +def test_ui_revalidates_worker_event(setup, fault): + s = setup + s.feed(wheel()) + s.feed(wheel(right_scroll=2)) + s.feed(wheel(), dispatch=False) + assert len(s.channel.queue) == 1 + if fault == 'safe': + s.params.put('SafeMode', b'1', block=True) + if fault == 'config': + s.doc['bindings']['right_wheel_left']['label'] = 'New' + save(s) + if fault == 'vehicle': + s.cp.mass = 1234. + if fault == 'offroad': + s.sm['deviceState'].started = False + if fault == 'stale': + s.clock[0] += .251 + if fault == 'can_invalid': + s.sm['carState'].canValid = False + if fault == 'availability': + s.actions[SPEED_UP].available = False + if fault == 'unselected': + s.cp.safetyConfigs[0].safetyParam = 1 # the comma no longer owns the set speed + s.receiver.poll() + assert not s.calls + + +def test_revalidation_after_action_discovery(setup): + s = setup + s.feed(wheel()) + s.feed(wheel(right_scroll=2)) + s.feed(wheel(), dispatch=False) + + def actions(): + s.params.put('SafeMode', b'1', block=True) + return s.actions + s.receiver.actions = actions + s.receiver.poll() + assert not s.calls + + +def test_duplicate_event_does_not_repeat(setup): + s = setup + s.feed(wheel()) + s.feed(wheel(right_scroll=2)) + s.feed(wheel(), dispatch=False) + packet = s.channel.queue[0] + s.channel.queue.append(packet) + s.receiver.poll() + assert s.calls == [1] + + +def test_no_can_or_settings_work_without_event(setup): + # An idle poll only asks which car this is and drains the worker's channel. + s = setup + + def forbidden(*a, **kw): + raise AssertionError('idle UI accessed source context') + s.receiver.params = NS(get_param_path=forbidden) + s.receiver.messages = s.receiver.actions = forbidden + for _ in range(1000): + s.receiver.poll() + assert s.channel.receives == 1000 + + +def test_backlog_is_bounded_and_discarded(setup): + s = setup + s.channel.queue.extend([b'{}'] * 500) + s.receiver.poll() + assert s.channel.receives == 5 + assert s.channel.closed + assert not s.calls + # Never immediately replay a discarded backlog. Recovery has a backoff. + s.receiver.poll() + assert s.receiver.channel is None + + +@pytest.mark.parametrize('patch', [ + {'stamp': float('nan')}, {'stamp': float('inf')}, {'stamp': 1.3}, {'stamp': .7}, + {'sequence': True}, {'sequence': 0}, {'version': True}, {'version': 2}, {'fast': 1}, {'drive': 0}, + {'document': 'x' * 64}, {'vehicle': None}, {'extra': 'field'}, {'name': 3}, +]) +def test_protocol_rejects_malformed_or_stale(patch): + d = json.loads(encode_event(1, 'right_wheel_up', True, 1., 100_000_000, 'a' * 64, 'b' * 64)) + d.update(patch) + assert decode_event(json.dumps(d).encode(), 1.) is None + + +def test_protocol_size_and_boundary(): + packet = encode_event(1, 'right_wheel_up', True, 1., 100_000_000, 'a' * 64, 'b' * 64) + assert decode_event(packet, 1.25) is not None + assert decode_event(packet, 1.250001) is None + assert decode_event(b' ' * (MAX_PACKET + 1), 1) is None + + +def test_protocol_carries_exactly_the_event_and_its_context(): + packet = encode_event(7, 'right_wheel_down', False, 1., 100_000_000, 'a' * 64, 'b' * 64) + assert decode_event(packet, 1.1) == {'version': 1, 'sequence': 7, 'name': 'right_wheel_down', 'fast': False, 'stamp': 1., + 'drive': 100_000_000, 'document': 'a' * 64, 'vehicle': 'b' * 64} + + +def test_unrelated_frames_never_convert_payload(setup): + s = setup + + class Payload: + def __bytes__(self): + raise AssertionError('unrelated payload converted') + s.frames.append(NS(valid=True, logMonoTime=int(s.clock[0] * 1e9), + can=[NS(src=0, address=0x3c2, dat=Payload()), + NS(src=1, address=0x555, dat=Payload())])) + s.pump.poll(s.sm) + assert not s.calls + + +def test_worker_tick_is_bounded(setup): + s = setup + s.frames.extend(NS(valid=True, logMonoTime=int(s.clock[0] * 1e9), can=[]) for _ in range(1000)) + s.pump.poll(s.sm) + assert len(s.frames) == 744 + + +def test_transport_overflow_fails_without_replay(setup): + s = setup + s.feed(wheel()) + s.feed(wheel(right_scroll=2)) + + def fail(_): + raise BlockingIOError() + s.pump.send = fail + with pytest.raises(BlockingIOError): + s.feed(wheel()) + assert s.pump.decoder is None + assert not s.calls + + +def test_worker_real_process_lifecycle(): + channel = WorkerChannel() + try: + # Real imports, isolated Params/MSGQ, scheduler reset and socket closure. + deadline = time.monotonic() + 15 + while time.monotonic() < deadline: + assert channel.receive() is None + if channel.ready: + break + time.sleep(.01) + assert channel.ready, "worker did not complete native startup" + pid = channel.process.pid + assert pid != os.getpid() + assert os.sched_getscheduler(pid) == os.SCHED_OTHER + assert os.getpriority(os.PRIO_PROCESS, pid) == 10 + assert os.sched_getaffinity(pid).issubset({0, 1, 2, 3}) + finally: + channel.close() + assert channel.process.poll() is not None + + +def test_lost_telemetry_does_not_relaunch_failed_worker(setup): + s = setup + s.receiver.close() + s.receiver.next_start = 0 + s.sm['carState'].canValid = False + s.receiver.poll() + assert s.receiver.channel is None + s.sm.refresh(s.clock[0], started=False) + s.receiver.poll() + assert s.receiver.channel is s.channel + + +@pytest.mark.parametrize('value', [None, 0, 2.5]) +def test_generic_assigned_actions_keep_value_semantics(setup, value): + s = setup + s.doc['bindings']['right_wheel_left'] = {'key': CUSTOM, 'value': value, 'label': 'Action'} + save(s) + s.actions[CUSTOM] = NS(available=True, invoke=lambda: s.calls.append('invoke'), invoke_value=s.calls.append) + s.feed(wheel()) + s.feed(wheel(right_wheel_left=2)) + s.feed(wheel()) + assert s.calls == ['invoke' if value is None else value] + + +def test_peer_close_stops_worker_without_gesture(): + channel = WorkerChannel() + try: + deadline = time.monotonic() + 15 + while time.monotonic() < deadline and not channel.ready: + assert channel.receive() is None + time.sleep(.01) + assert channel.ready + channel.socket.close() + assert channel.process.wait(timeout=5) == 0 + finally: + channel.close() + + +@pytest.mark.parametrize('published', [True, False]) +def test_real_worker_can_to_ui_dispatch(tmp_path, monkeypatch, published): + # Explicit private Params root; the child inherits it. No live device settings. + # published False: the worker starts mid-drive, between card's broadcasts of the car's parameters, and reads this + # drive's saved copy. + from openpilot.common.params import Params + root = tmp_path / 'native-params' + root.mkdir() + monkeypatch.setenv('PARAMS_ROOT', str(root)) + cp = tesla(selected=True) + # Its own messaging and settings namespace, which the worker inherits: nothing is shared with another test. + prefix = OpenpilotPrefix(clean_dirs_on_exit=False) + with prefix: + params = Params(str(root)) + params.put(PARAM, {'version': 1, 'vehicle': 'TESLA_MODEL_3', 'bindings': {}}, block=True) + params.put_bool('TeslaSpeedSync', True, block=True) + if not published: + params.put('CarParams', cp.as_reader().as_builder().to_bytes(), block=True) + pm = messaging.PubMaster(['deviceState', 'carState', 'carParams', 'can']) + channel = WorkerChannel() + sm = Messages() + calls = [] + receiver = TeslaReceiver(params, lambda: {SPEED_UP: NS(available=True, invoke=None, invoke_value=calls.append)}, + lambda: cp, messages=lambda: sm, channel_factory=lambda: channel) + try: + deadline = time.monotonic() + 15 + while time.monotonic() < deadline and not channel.ready: + receiver.poll() + time.sleep(.01) + assert channel.ready and receiver.channel is channel + start = time.monotonic() + drive = int((start - 1) * 1e9) + # Fresh telemetry and real CAN neutral -> scroll -> neutral across processes. + while time.monotonic() - start < 1.2: + now = time.monotonic() + elapsed = now - start + stamp = int(now * 1e9) + sm.refresh(now) + sm['deviceState'].startedMonoTime = drive + state = messaging.new_message('deviceState', valid=True, logMonoTime=stamp) + state.deviceState.started = True + state.deviceState.startedMonoTime = drive + pm.send('deviceState', state) + state = messaging.new_message('carState', valid=True, logMonoTime=stamp) + state.carState.canValid = True + pm.send('carState', state) + # Publish CP only during startup, not continually resetting a held gesture. + if published and elapsed < .2: + state = messaging.new_message('carParams', valid=True, logMonoTime=stamp) + state.carParams = cp + pm.send('carParams', state) + # CAN is stamped on the boot clock, which the worker translates to its own. + event = messaging.new_message('can', 1, valid=True, logMonoTime=time.clock_gettime_ns(time.CLOCK_BOOTTIME)) + event.can[0] = {'address': 0x3c2, 'src': 1, 'dat': wheel(right_scroll=2 if .4 <= elapsed < .6 else 0)} + pm.send('can', event) + receiver.poll() + time.sleep(.01) + assert calls == [1] + finally: + receiver.close() + shutil.rmtree(prefix.msgq_path, ignore_errors=True) + + +def test_stalk_resume_comes_from_the_comma_speed_lookup(setup): + # Resume comes from the same quick lookup as the scroll wheel's comma-speed steps, not from the favorites catalog. + s = setup + s.doc['bindings'][STALK_TAP] = {'key': SPEED_RESUME, 'value': None, 'label': 'Resume Speed Limit + Offset'} + save(s) + resume = NS(available=True, invoke=lambda: s.calls.append('resume') or True, invoke_value=None) + s.receiver.speed_actions = lambda: {SPEED_RESUME: resume} + s.receiver.keyed_actions = lambda keys: {} + s.sm.engaged = True + for _ in range(6): + s.feed(stalk(0, 0), address=0x229) # cruise already on for 0.6 s + s.feed(stalk(3, 1), address=0x229) + s.feed(stalk(0, 2), address=0x229) + assert s.calls == ['resume'] + + +def _resume_during_dropout(s): + """A half press while engaged bound to Resume, whose speed limit is missing until s.limit is set True.""" + s.doc['bindings'][STALK_TAP] = {'key': SPEED_RESUME, 'value': None, 'label': 'Resume Speed Limit + Offset'} + save(s) + s.limit = False + s.reason = NO_LIMIT_REASON + + def lookup(): + return {SPEED_RESUME: NS(available=s.limit, reason='' if s.limit else s.reason, + invoke=lambda: s.calls.append('resume') or True, invoke_value=None)} + s.receiver.speed_actions = lookup + s.receiver.keyed_actions = lambda keys: {} + s.sm.engaged = True + for _ in range(6): + s.feed(stalk(0, 0), address=0x229) + s.feed(stalk(3, 1), address=0x229) + s.feed(stalk(0, 2), address=0x229) # the press, while the limit is missing + assert s.calls == [] + + +def test_resume_during_a_limit_dropout_runs_once_the_limit_is_back(setup): + s = setup + _resume_during_dropout(s) + for _ in range(10): + s.feed(stalk(0, 2), address=0x229) # 1 s without a limit + assert s.calls == [] + s.limit = True + s.feed(stalk(0, 2), address=0x229) + assert s.calls == ['resume'] + for _ in range(30): + s.feed(stalk(0, 2), address=0x229) + assert s.calls == ['resume'], 'once only' + + +def test_resume_is_refused_when_the_limit_stays_away(setup): + s = setup + _resume_during_dropout(s) + for _ in range(21): + s.feed(stalk(0, 2), address=0x229) # 2.1 s without a limit + s.limit = True + for _ in range(10): + s.feed(stalk(0, 2), address=0x229) + assert s.calls == [] + + +@pytest.mark.parametrize('change', ['reason', 'assignments', 'safe']) +def test_waiting_resume_is_dropped_when_things_change(setup, change): + s = setup + _resume_during_dropout(s) + if change == 'reason': + s.reason = 'Speed Limit Controller is not running' + elif change == 'assignments': + s.doc['bindings']['right_wheel_left']['label'] = 'Changed' + save(s) + else: + s.params.put('SafeMode', b'1', block=True) + s.feed(stalk(0, 2), address=0x229) + s.limit = True + for _ in range(10): + s.feed(stalk(0, 2), address=0x229) + assert s.calls == [] + + +def test_two_presses_during_one_dropout_resume_once(setup): + s = setup + _resume_during_dropout(s) + s.feed(stalk(3, 3), address=0x229) + s.feed(stalk(0, 4), address=0x229) # a second press, still without a limit, replaces the first + s.limit = True + for _ in range(10): + s.feed(stalk(0, 4), address=0x229) + assert s.calls == ['resume'] + + +def _refusing_scroll(s, results): + """Increase Comma Set Speed whose UI checks refuse the step (nothing published) for each False in results.""" + attempts = [] + + def step(fast): + attempts.append(fast) + applied = results.pop(0) if results else True + if applied: + s.calls.append(fast) + return applied + s.actions[SPEED_UP] = NS(available=True, invoke_value=step, invoke=None) + s.feed(wheel()) + s.feed(wheel(right_scroll=1)) + s.feed(wheel(), dispatch=False) + return attempts + + +def test_a_refused_scroll_step_is_tried_once_more_on_the_next_frame(setup): + s = setup + attempts = _refusing_scroll(s, [False]) + s.receiver.poll() + assert attempts == [0] + s.feed(wheel()) + assert attempts == [0, 0] and s.calls == [0], 'one retry, one step' + for _ in range(5): + s.feed(wheel()) + assert s.calls == [0] + + +def test_a_scroll_step_is_retried_only_once(setup): + s = setup + attempts = _refusing_scroll(s, [False, False]) + s.receiver.poll() + for _ in range(5): + s.feed(wheel()) + assert attempts == [0, 0] and s.calls == [] + + +def test_an_expired_scroll_step_is_not_retried(setup): + s = setup + attempts = _refusing_scroll(s, [False]) + s.receiver.poll() + s.clock[0] += .3 + s.sm.refresh(s.clock[0]) + s.receiver.poll() + assert attempts == [0] and s.calls == [] + + +# The worker only runs on a supported Tesla: a Model 3/Y whose CAN add-on cable was detected. + +def other_car(brand='hyundai', fingerprint='HYUNDAI_IONIQ_5'): + return car.CarParams.new_message(carFingerprint=fingerprint, brand=brand, flags=int(TeslaFlags.HAS_VEHICLE_BUS), + pcmCruise=True, openpilotLongitudinalControl=True) + + +UNSUPPORTED = { + 'no car yet': lambda: None, + 'hyundai': other_car, + 'toyota': lambda: other_car('toyota', 'TOYOTA_RAV4_TSS2'), + 'another brand with a tesla name': lambda: other_car('mock', 'TESLA_MODEL_3'), + 'model s': lambda: tesla('TESLA_MODEL_S_HW1'), + 'model x': lambda: tesla('TESLA_MODEL_X'), + 'model 3 without the cable': lambda: tesla(cable=False), + 'model y without the cable': lambda: tesla('TESLA_MODEL_Y', cable=False), + 'dashcam': lambda: car.CarParams.new_message(carFingerprint='TESLA_MODEL_3', brand='tesla', dashcamOnly=True, + flags=int(TeslaFlags.HAS_VEHICLE_BUS)), + 'passive': lambda: car.CarParams.new_message(carFingerprint='TESLA_MODEL_3', brand='tesla', passive=True, + flags=int(TeslaFlags.HAS_VEHICLE_BUS)), + 'not a car': lambda: car.CarParams.new_message(carFingerprint='TESLA_MODEL_3', brand='tesla', notCar=True, + flags=int(TeslaFlags.HAS_VEHICLE_BUS)), +} + + +def counting_receiver(tmp_path, vehicle): + started = [] + + def factory(): + started.append(Channel()) + return started[-1] + sm = Messages() + sm.refresh(1.) + receiver = TeslaReceiver(Saved(tmp_path), dict, vehicle, clock=lambda: 1., messages=lambda: sm, channel_factory=factory) + return receiver, started + + +@pytest.mark.parametrize('case', UNSUPPORTED) +def test_no_worker_is_ever_started_for_an_unsupported_car(tmp_path, case): + cp = UNSUPPORTED[case]() + assert not vehicle_supported(cp) + receiver, started = counting_receiver(tmp_path, lambda: cp) + assert receiver.channel is None and not started, 'creating the receiver starts nothing' + for _ in range(50): + receiver.poll() + assert receiver.channel is None and not started + receiver.close() + + +@pytest.mark.parametrize('candidate', ['TESLA_MODEL_3', 'TESLA_MODEL_Y']) +@pytest.mark.parametrize('selected', [False, True]) +def test_the_worker_starts_once_a_supported_tesla_is_known(tmp_path, candidate, selected): + # The cable is enough: the stalk, nudges and screen tap work with or without the set-speed switch. + current = [None] + receiver, started = counting_receiver(tmp_path, lambda: current[0]) + for _ in range(5): + receiver.poll() + assert not started, 'no car parameters yet' + current[0] = tesla(candidate, selected=selected) + receiver.poll() + assert len(started) == 1 and receiver.channel is started[0] + for _ in range(20): + receiver.poll() + assert len(started) == 1, 'one worker' + + +def test_the_worker_is_closed_when_the_car_is_no_longer_a_supported_tesla(tmp_path): + current = [tesla()] + receiver, started = counting_receiver(tmp_path, lambda: current[0]) + receiver.poll() + assert receiver.channel is started[0] and not started[0].closed + current[0] = other_car() + receiver.poll() + assert receiver.channel is None and started[0].closed + for _ in range(20): + receiver.poll() + assert len(started) == 1 + current[0] = None + receiver.poll() + assert receiver.channel is None and len(started) == 1 + + +def test_the_real_worker_process_is_not_spawned_for_another_car(tmp_path, monkeypatch): + from openpilot.starpilot.controllers import tesla_receiver + spawned = [] + monkeypatch.setattr(tesla_receiver.subprocess, 'Popen', lambda *a, **kw: spawned.append(a) or NS(poll=lambda: 0)) + cp = other_car() + receiver = TeslaReceiver(Saved(tmp_path), dict, lambda: cp) + for _ in range(10): + receiver.poll() + receiver.close() + assert not spawned and receiver.channel is None diff --git a/openpilot/starpilot/galaxy/setting_descriptions.py b/openpilot/starpilot/galaxy/setting_descriptions.py index 1fbe128f48..9fd42e3b55 100644 --- a/openpilot/starpilot/galaxy/setting_descriptions.py +++ b/openpilot/starpilot/galaxy/setting_descriptions.py @@ -117,7 +117,6 @@ DESCRIPTIONS = { 'GMLongitudinalTune': 'Selects the supported vehicle speed-control response tune.', 'TruckTuning': 'Softens small acceleration requests, reduces grade correction and smooths light braking on supported GM trucks.', 'EVTuning': 'Selects EV acceleration curves for inherited acceleration presets.', - 'TeslaAOLScreenTap': 'Lets a three-finger tap on a supported Tesla screen toggle Always On Lateral.', 'TeslaAOLDisengageOnBrake': 'Disarms Tesla Always On Lateral when you press the brake, with either harness.', 'RemoteStartBootsComma': 'Wakes comma during GM remote start.', 'HKGRemoteStartBootsComma': 'Wakes comma during Hyundai, Kia or Genesis remote climate operation.', @@ -216,7 +215,6 @@ INITIALIZATION = { 'VoltOnePedalMode': ('First enable requires the next vehicle startup to configure the braking safety ' + 'permission. An already admitted mode can be disabled live.'), 'VoltSNG': 'Applies when the vehicle controller next starts: its fresh resume-plan input is created for the selected stop-and-go mode.', - 'TeslaAOLScreenTap': 'Requires the next vehicle startup to configure the screen-button CAN source and matching safety permission.', 'TeslaAOLDisengageOnBrake': 'Requires the next vehicle startup to configure the Tesla brake/disarm safety permission.', 'RemoteStartBootsComma': 'Requires a device restart to load the matching Panda ignition firmware.', 'HKGRemoteStartBootsComma': 'Requires a device restart to load the matching Panda ignition firmware.', diff --git a/openpilot/starpilot/galaxy/settings.py b/openpilot/starpilot/galaxy/settings.py index 62d881e330..4b9bad0294 100644 --- a/openpilot/starpilot/galaxy/settings.py +++ b/openpilot/starpilot/galaxy/settings.py @@ -422,6 +422,8 @@ def _projection(row: FeatureRow) -> dict: **({"coordinateLocked": row.coordinate_locked} if row.coordinate_locked is not None else {}), **({"learningEligible": row.learning_eligible} if row.learning_eligible is not None else {}), "heading": is_heading(row.key), "collapsed": bool(row.collapsed), + **({"status": True} if row.status else {}), + **({"links": [{"label": label, "url": url} for label, url in row.links if url.startswith("https://")]} if row.links else {}), **({"previewSound": row.key} if row.key in SOUND_SPECS else {})} diff --git a/openpilot/starpilot/galaxy/tests/description-key-inventory.json b/openpilot/starpilot/galaxy/tests/description-key-inventory.json index 06a4a18e32..3e3363ba8a 100644 --- a/openpilot/starpilot/galaxy/tests/description-key-inventory.json +++ b/openpilot/starpilot/galaxy/tests/description-key-inventory.json @@ -127,7 +127,6 @@ "SteerLatAccel", "StockConfidenceBallWidget", "TeslaAOLDisengageOnBrake", - "TeslaAOLScreenTap", "TeslaWakeOnCAN", "ToyotaAutoHold", "TrafficFollow", diff --git a/openpilot/starpilot/galaxy/tests/test_tesla_screen_settings.py b/openpilot/starpilot/galaxy/tests/test_tesla_screen_settings.py index 9077173714..1fbea80526 100644 --- a/openpilot/starpilot/galaxy/tests/test_tesla_screen_settings.py +++ b/openpilot/starpilot/galaxy/tests/test_tesla_screen_settings.py @@ -33,7 +33,10 @@ class TestTeslaScreenSettings(unittest.TestCase): def page(self, page='vehicle'): return self.gateway.page(page, 'session', b'generation') - def intent(self, *, key='Three-Finger AOL Tap', value='On', reset=False): + def tap(self): + return next(row for row in self.page('wheel')['rows'] if row['label'] == 'Tesla screen / Three-finger tap') + + def intent(self, *, key='Disengage AOL on Brake', value='On', reset=False): page = self.page() index = next(i for i, row in enumerate(page['rows']) if row['label'] == key) return self.gateway.preview(page['view'], index, 0, 'session', b'generation', @@ -44,22 +47,29 @@ class TestTeslaScreenSettings(unittest.TestCase): def test_detected_harness_exposes_preferences_without_granting_native_permission(self): page = self.page() - self.assertEqual({row['label'] for row in page['rows']}, {'Three-Finger AOL Tap', 'Disengage AOL on Brake', 'Alpha Longitudinal', 'Tesla Co-op Steering'}) - self.assertTrue(all(row['available'] and row['value'] == 'Off' and row['defaultValue'] == 'Off' for row in page['rows'])) + set_speed = {'Tesla CAN add-on cable', 'Comma can set speed on Tesla dashboard'} + self.assertEqual({row['label'] for row in page['rows']}, + {'Disengage AOL on Brake', 'Alpha Longitudinal', 'Tesla Co-op Steering'} | set_speed) + self.assertTrue(all(row['available'] and row['value'] == 'Off' and row['defaultValue'] == 'Off' + for row in page['rows'] if row['label'] not in set_speed)) + cable, sync = (next(row for row in page['rows'] if row['label'] == label) for label in sorted(set_speed, reverse=True)) + self.assertEqual((cable['value'], cable['status'], [link['label'] for link in cable['links']]), + ('Detected', True, ['Buy the cable', 'Install guide'])) + # Alpha Longitudinal is off on this car, so the switch shows grayed with the reason. + self.assertEqual((sync['value'], sync['available'], sync['defaultValue']), ('Off', False, 'Off')) self.assertIn('Vehicle Settings', {row['label'] for row in self.page('hub')['rows']}) master = next(row for row in self.page('aol')['rows'] if row['label'] == 'Enable Always On Lateral') self.assertTrue(master['available'], 'The user must be able to enable AOL before requesting screen gestures') - for key in ('Three-Finger AOL Tap', 'Disengage AOL on Brake'): - intent = self.intent(key=key) - self.assertIn('next startup', intent['question']) - self.assertTrue(self.confirm(intent)) - self.assertTrue(self.params.get_bool('TeslaAOLScreenTap')) + self.assertIn('Always On Lateral on/off', self.tap()['choices'], 'the three-finger tap is chosen in Wheel Controls') + intent = self.intent() + self.assertIn('next startup', intent['question']) + self.assertTrue(self.confirm(intent)) self.assertTrue(self.params.get_bool('TeslaAOLDisengageOnBrake')) + self.assertIsNone(self.params.get('TeslaAOLScreenTap'), 'the brake preference does not touch the tap') self.assertEqual(self.context.cp.safetyConfigs[0].safetyParam, 0, 'Saving preferences does not mutate live native authority') self.gateway = SettingsGateway(self.params, self, clock=lambda: 100.0) self.assertTrue(self.confirm(self.intent(reset=True))) - self.assertFalse(self.params.get_bool('TeslaAOLScreenTap')) - self.assertTrue(self.params.get_bool('TeslaAOLDisengageOnBrake')) + self.assertFalse(self.params.get_bool('TeslaAOLDisengageOnBrake')) def test_absent_wrong_bus_or_unqualified_car_hides_screen_controls(self): for options in ({'harness': False}, {'marker': False}, {'bus': 0}, {'length': 7}): @@ -69,13 +79,14 @@ class TestTeslaScreenSettings(unittest.TestCase): labels = {row['label'] for row in self.page()['rows']} self.assertNotIn('Three-Finger AOL Tap', labels) self.assertEqual('Disengage AOL on Brake' in labels, options != {'marker': False}) + self.assertNotIn('Always On Lateral on/off', self.tap()['choices']) def test_stale_vehicle_or_onroad_change_rejects_saved_intent(self): intent = self.intent() - before = self.params.get('TeslaAOLScreenTap') + before = self.params.get('TeslaAOLDisengageOnBrake') self.context = replace(self.context, parked=False) self.assertFalse(self.confirm(intent)) - self.assertEqual(self.params.get('TeslaAOLScreenTap'), before) + self.assertEqual(self.params.get('TeslaAOLDisengageOnBrake'), before) self.assertFalse(any(row['available'] for row in self.page()['rows'])) self.context = replace(self.context, parked=True) intent = self.intent() @@ -83,4 +94,4 @@ class TestTeslaScreenSettings(unittest.TestCase): self.context = AuthorityContext(True, cp, cp.to_bytes()) with self.assertRaises(SettingsChanged): self.confirm(intent) - self.assertFalse(self.params.get_bool('TeslaAOLScreenTap')) + self.assertFalse(self.params.get_bool('TeslaAOLDisengageOnBrake')) diff --git a/openpilot/starpilot/galaxy/web/css/settings.css b/openpilot/starpilot/galaxy/web/css/settings.css index 3d92dd9f8d..2266973dfb 100644 --- a/openpilot/starpilot/galaxy/web/css/settings.css +++ b/openpilot/starpilot/galaxy/web/css/settings.css @@ -23,6 +23,7 @@ .gx-switch input:focus-visible + .gx-switch__track { outline: 2px solid var(--secondary); outline-offset: 4px; } input[type="range"].gx-slider:focus-visible { outline: 2px solid var(--secondary); outline-offset: 6px; } input[type="range"].gx-slider:disabled { cursor: default; opacity: .4; } +.gx-row__links { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 10px; } .gx-row .gx-btn { flex-shrink: 0; } .gx-settings-tabs { display: flex; flex-wrap: wrap; gap: var(--sp-2); } .gx-layout__favorite-display { display: grid; gap: 8px; } diff --git a/openpilot/starpilot/galaxy/web/js/galaxy-setting-row.js b/openpilot/starpilot/galaxy/web/js/galaxy-setting-row.js index 01d0c46567..2aa4bd2b25 100644 --- a/openpilot/starpilot/galaxy/web/js/galaxy-setting-row.js +++ b/openpilot/starpilot/galaxy/web/js/galaxy-setting-row.js @@ -93,7 +93,8 @@ export const GalaxySettingRow = { return { ...bounds, numericMax, max: Number((numericMax + bounds.step).toFixed(8)), auto: true } }, locked() { return this.busy || this.updating || this.dimmed }, - dimmed() { return this.disabled || !this.row.available || (!this.row.action && !this.row.page) }, + // A status row has nothing to change, so it is never shown grayed. + dimmed() { return !this.row.status && (this.disabled || !this.row.available || (!this.row.action && !this.row.page)) }, currentValue() { return this.preview !== undefined ? this.preview : this.presentedRow.value }, sliderValue() { return this.currentValue === "Auto" && this.bounds?.auto ? this.bounds.max : this.currentValue }, displayValue() { @@ -237,6 +238,7 @@ export const GalaxySettingRow = { {{ ' ' + presentedRow.reason.replace('https://firestar.link/discord', '') }} StarPilot Discord + {{ link.label }} {{ presentedRow.value }}