mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-12-02 10:53:45 +08:00
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 <noreply@anthropic.com>
This commit is contained in:
@@ -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)
|
||||
|
||||
@@ -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"])
|
||||
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
@@ -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]
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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'
|
||||
@@ -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() == ()
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -85,8 +85,10 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> 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"}},
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<uint16_t>(word)) == expected);
|
||||
auto tesla = status();
|
||||
tesla.safety_mode = 10U;
|
||||
tesla.safety_param = static_cast<uint16_t>(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<uint16_t>(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;
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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
|
||||
+76
@@ -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": {
|
||||
|
||||
@@ -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)
|
||||
@@ -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')
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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}'
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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))
|
||||
@@ -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)
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
@@ -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()
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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)})
|
||||
@@ -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
|
||||
@@ -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)
|
||||
|
||||
@@ -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]
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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]
|
||||
@@ -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), [])
|
||||
@@ -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'
|
||||
@@ -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
|
||||
@@ -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 == {}
|
||||
@@ -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
|
||||
@@ -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.',
|
||||
|
||||
@@ -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 {})}
|
||||
|
||||
|
||||
|
||||
@@ -127,7 +127,6 @@
|
||||
"SteerLatAccel",
|
||||
"StockConfidenceBallWidget",
|
||||
"TeslaAOLDisengageOnBrake",
|
||||
"TeslaAOLScreenTap",
|
||||
"TeslaWakeOnCAN",
|
||||
"ToyotaAutoHold",
|
||||
"TrafficFollow",
|
||||
|
||||
@@ -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'))
|
||||
|
||||
@@ -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; }
|
||||
|
||||
@@ -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 = {
|
||||
<span v-if="presentedRow.reason && !row.heading && !compact" class="gx-row__desc">{{ ' ' + presentedRow.reason.replace('https://firestar.link/discord', '') }}</span>
|
||||
<template v-if="compact && presentedRow.reason && !row.heading"><span class="gx-row__desc">{{ presentedRow.reason.split('. ')[0] + (presentedRow.reason.includes('. ') ? '.' : '') }}</span><details class="gx-row__help"><summary>What this changes</summary><p>{{ presentedRow.reason }}</p></details></template>
|
||||
<a v-if="presentedRow.reason?.includes('https://firestar.link/discord')" class="gx-btn gx-btn--tonal" href="https://firestar.link/discord" target="_blank" rel="noopener">StarPilot Discord</a>
|
||||
<span v-if="row.links?.length" class="gx-row__links"><a v-for="link in row.links" :key="link.url" class="gx-btn gx-btn--tonal" :href="link.url" target="_blank" rel="noopener noreferrer"><i class="bi bi-box-arrow-up-right" aria-hidden="true"></i> {{ link.label }}</a></span>
|
||||
<span v-if="control === 'group' || control === 'action'" class="gx-row__desc">{{ presentedRow.value }}</span>
|
||||
</div>
|
||||
<button v-if="control !== 'slider' && showDefault && !row.heading" type="button"
|
||||
|
||||
@@ -11,5 +11,9 @@ after a restart. It never creates a fresh source observation or accepts a pendin
|
||||
proposal. Current vehicle coordinates and system-longitudinal authority remain
|
||||
required. There is no separate SLC override reducer or retained pedal target.
|
||||
|
||||
The one exception is the [Tesla set-speed rule](README.md#tesla-set-speed-rule). With
|
||||
`Frame.set_speed_rule`, `composition.step` supplies no ceiling and runs `overrides.step`
|
||||
instead, which holds a SET the driver chose until the accepted limit changes.
|
||||
|
||||
Lead following, curves, stopping, cruise profiles and actuator restrictions retain
|
||||
their existing owners. See the [controller contract](README.md).
|
||||
|
||||
@@ -2,13 +2,47 @@
|
||||
|
||||
SLC supplies a speed-limit cap beneath the driver's cruise SET. The planner uses
|
||||
the lower of SET and the accepted limit plus its configured offset, converted into
|
||||
physical-speed coordinates once. Accepting a limit never rewrites SET. Native PCM
|
||||
physical-speed coordinates once. Accepting a limit never rewrites SET (one exception:
|
||||
the [Tesla set-speed rule](#tesla-set-speed-rule)). Native PCM
|
||||
cruise owns its setpoint; non-PCM software cruise and the dedicated Subaru software
|
||||
cruise mode retain their existing owners. Automatic SLC requires system longitudinal
|
||||
control. Lead, curve, stop and actuator safety constraints retain their existing owners.
|
||||
SLC works with either the StarPilot or upstream longitudinal planner. The StarPilot planner
|
||||
eases braking after an overshoot past the cap; the upstream planner keeps its native response.
|
||||
|
||||
## Tesla set-speed rule
|
||||
|
||||
One car is different. On a Tesla Model 3 or Model Y where **Comma can set speed on Tesla dashboard**
|
||||
is on (`openpilot/starpilot/car/tesla/set_speed.py`, followed within a second of a change), StarPilot
|
||||
owns a software SET that is mirrored to the car, and SLC writes that SET instead of capping beneath it:
|
||||
|
||||
- Engaging starts SET at the current limit plus offset. Each newly accepted limit is written to SET.
|
||||
The runtime issues one `slcCruiseCommand`; card applies it only while the planner state, the source
|
||||
and SET are still what the planner saw (`physical_actions.command_applicable`), and answers with a
|
||||
`commandApplied` or `commandRejected` cruise event. An unanswered or refused command is issued
|
||||
again while SET has not moved.
|
||||
- No planner cap is published (`hasCeiling` stays false). The sign's green outline means SET equals
|
||||
the accepted limit plus offset.
|
||||
- A SET change by the driver holds until the accepted limit changes (`overrides.py`) and shows as
|
||||
OVERRIDE. A higher limit that is still below the driver's SET leaves it alone. A source gap leaves
|
||||
SET where it is.
|
||||
- **After an accelerator override** is applied by card, which owns SET here
|
||||
(`tesla_set_speed_card.pedal_hold`). With **Hold the speed you reached**, lifting off above both SET
|
||||
and the accepted limit plus offset makes the highest speed reached the new SET, as the driver's own
|
||||
change, so it holds until the limit changes like a scroll. The other two choices return to SET.
|
||||
- The adopt action puts SET back to the current limit plus offset. Accepting a pending limit writes it.
|
||||
- A written SET is felt at once, so automatic adoption waits 3 seconds and a different limit from
|
||||
another source must hold for 2 seconds first (`acceptance.AUTOMATIC_ADOPTION_NS`, `SOURCE_SWITCH_NS`).
|
||||
An explicit adopt skips both waits.
|
||||
- **Adopt limits early** writes SET early. An early Maps preview is offered the chosen number of
|
||||
seconds ahead, so it is adopted when offered, without the 3 second wait, and written like any
|
||||
accepted limit. Card binds that command to Maps and the upcoming boundary instead of the road's
|
||||
current limit. If the preview is withdrawn before the car reaches it, acceptance returns to the
|
||||
road's limit and that is written back.
|
||||
|
||||
With the switch off, and on every other car, none of this applies: SLC caps beneath SET as the
|
||||
rest of this document describes.
|
||||
|
||||
## New limits and adoption
|
||||
|
||||
**Match Speed Limit on Engage** is Off by default. When enabled, a new software SET
|
||||
@@ -269,8 +303,8 @@ and the numeric cap before applying the lower speed.
|
||||
`SlcState.hasCeiling` and `effectiveCap` report the active physical-speed constraint;
|
||||
`isLimitingMaxSet` identifies when it is below the driver's ceiling. Observations,
|
||||
accepted limits and the effective constraint remain separate. The existing custom
|
||||
wire layout and historical command fields remain reserved for compatibility; live
|
||||
SLC no longer publishes or consumes `slcCruiseCommand`. Official vehicle schemas
|
||||
wire layout and historical command fields remain reserved for compatibility; outside the
|
||||
Tesla set-speed rule, live SLC no longer publishes or consumes `slcCruiseCommand`. Official vehicle schemas
|
||||
are unchanged. Shared curve, conditional-mode and controller messages remain intact.
|
||||
|
||||
## Numeric comparison investigation
|
||||
|
||||
@@ -8,6 +8,10 @@ from dataclasses import dataclass, replace
|
||||
from enum import Enum
|
||||
|
||||
CONFIRMATION_NS = 30_000_000_000
|
||||
# Where SLC writes SET (Tesla set-speed rule): automatic adoption waits this long, and a limit from a different
|
||||
# source must hold this long before it counts. Every other car keeps the Policy defaults of 0.
|
||||
AUTOMATIC_ADOPTION_NS = 3_000_000_000
|
||||
SOURCE_SWITCH_NS = 2_000_000_000
|
||||
|
||||
|
||||
class ObservationKind(Enum):
|
||||
@@ -81,6 +85,8 @@ class Policy:
|
||||
confirm_lower: bool = True
|
||||
confirm_higher: bool = True
|
||||
display_only: bool = False
|
||||
automatic_adoption_ns: int = 0 # wait before an automatic adoption; 0 adopts at once
|
||||
source_switch_ns: int = 0 # how long another source's different limit must hold; 0 switches at once
|
||||
|
||||
|
||||
class ActionKind(Enum):
|
||||
@@ -149,6 +155,10 @@ class State:
|
||||
presentation: Presentation | None = None
|
||||
next_presentation_id: int = 1
|
||||
received_speed_mps: float | None = None
|
||||
# Only tracked with Policy.source_switch_ns: the last received limit's source and a switch still settling.
|
||||
received_source: str | None = None
|
||||
switch_candidate: Candidate | None = None
|
||||
switch_started_ns: int | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -272,6 +282,14 @@ def _state_errors(state: State) -> list[str]:
|
||||
errors.append("invalid state clock")
|
||||
if state.received_speed_mps is not None and not number(state.received_speed_mps, positive=True):
|
||||
errors.append("invalid received speed")
|
||||
if state.received_source is not None and not token(state.received_source):
|
||||
errors.append("invalid received source")
|
||||
if state.switch_candidate is not None:
|
||||
if (not _candidate_valid(state.switch_candidate, state.session_id) or not integer(state.switch_started_ns) or
|
||||
state.last_timestamp_ns is None or state.switch_started_ns > state.last_timestamp_ns):
|
||||
errors.append("invalid source switch")
|
||||
elif state.switch_started_ns is not None:
|
||||
errors.append("source switch lacks candidate")
|
||||
if not integer(state.last_action_sequence, -1) or not integer(state.next_decision_id, 1) or not integer(state.next_presentation_id, 1):
|
||||
errors.append("invalid state sequence")
|
||||
if type(state.timer_running) is not bool:
|
||||
@@ -366,7 +384,8 @@ def step(state: State, observation: Observation, authority: Authority, policy: P
|
||||
if not observation_is_valid(observation, session_id=state.session_id):
|
||||
errors.append("invalid observation")
|
||||
if not isinstance(policy, Policy) or any(type(v) is not bool for v in (
|
||||
policy.confirm_lower, policy.confirm_higher, policy.display_only)):
|
||||
policy.confirm_lower, policy.confirm_higher, policy.display_only)) or any(
|
||||
not integer(v) or v > CONFIRMATION_NS for v in (policy.automatic_adoption_ns, policy.source_switch_ns)):
|
||||
errors.append("invalid policy")
|
||||
if not integer(now_ns) or (state.last_timestamp_ns is not None and now_ns < state.last_timestamp_ns):
|
||||
errors.append("invalid or reversed monotonic clock")
|
||||
@@ -454,6 +473,16 @@ def step(state: State, observation: Observation, authority: Authority, policy: P
|
||||
explicit_adopt = (adopt is not None and adopt_receipt is not None and adopt_receipt.status == 'seen' and
|
||||
old.presentation is not None and old.presentation.presentation_id == adopt.presentation_id and
|
||||
old.presentation.candidate == candidate == adopt.candidate)
|
||||
if policy.source_switch_ns:
|
||||
if (new_limit and state.received_source is not None and candidate.source != state.received_source and
|
||||
authority.can_control and not explicit_adopt and confirmation_started_ns is None):
|
||||
switching = state.switch_candidate
|
||||
if switching is None or (switching.source, switching.speed_mps) != (candidate.source, candidate.speed_mps):
|
||||
state = replace(state, switch_candidate=candidate, switch_started_ns=now_ns)
|
||||
assert state.switch_started_ns is not None
|
||||
if now_ns - state.switch_started_ns < policy.source_switch_ns:
|
||||
return unavailable('source_switch_pending')
|
||||
state = replace(state, received_source=candidate.source, switch_candidate=None, switch_started_ns=None)
|
||||
if new_limit:
|
||||
state = replace(state, received_speed_mps=candidate.speed_mps, pending=None, timer_running=False)
|
||||
if adopt_receipt is not None and adopt_receipt.status == "seen":
|
||||
@@ -494,7 +523,7 @@ def step(state: State, observation: Observation, authority: Authority, policy: P
|
||||
state = replace(state, pending=pending, timer_running=True)
|
||||
|
||||
if pending.automatic:
|
||||
if authority.can_control or authority.fully_disengaged:
|
||||
if pending.active_elapsed_ns >= policy.automatic_adoption_ns and (authority.can_control or authority.fully_disengaged):
|
||||
state, history = _accept(state, candidate, now_ns)
|
||||
return finish("accepted" if authority.can_control else "disengaged_accept",
|
||||
target=candidate.speed_mps if authority.can_control else None, history=history)
|
||||
|
||||
@@ -6,6 +6,7 @@ from dataclasses import dataclass, replace
|
||||
from openpilot.starpilot.longitudinal.cruise_ceiling import CruiseCeiling
|
||||
from openpilot.starpilot.speed_limits import acceptance as acc
|
||||
from openpilot.starpilot.speed_limits import action_arbitration as arb
|
||||
from openpilot.starpilot.speed_limits import overrides as ov
|
||||
from openpilot.starpilot.speed_limits import selection as sel
|
||||
from openpilot.starpilot.speed_limits import speed_domain as sd
|
||||
from openpilot.starpilot.speed_limits.runtime_settings import PedalOverride
|
||||
@@ -46,6 +47,10 @@ class Frame:
|
||||
wheel_override_blocked: bool = False
|
||||
wheel_override_since_ns: int = 0
|
||||
filtered_ego_delta_mps: float | None = None
|
||||
# Tesla set-speed rule: SLC writes SET through card, a driver's SET change holds through the override module, and
|
||||
# no planner ceiling is supplied. set_speed_ready: card's last SLC command receipt has reached carState.
|
||||
set_speed_rule: bool = False
|
||||
set_speed_ready: bool = True
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -58,6 +63,7 @@ class State:
|
||||
pedal_blocked_until_release: bool = False
|
||||
wheel_override_metric: bool | None = None
|
||||
wheel_override_since_ns: int = 0
|
||||
override: ov.State | None = None # Tesla set-speed rule only
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -70,6 +76,7 @@ class Result:
|
||||
ceiling: CruiseCeiling | None = None
|
||||
status: str = "none"
|
||||
errors: tuple[str, ...] = ()
|
||||
override: ov.Decision | None = None # Tesla set-speed rule only
|
||||
|
||||
|
||||
def _state_valid(state: object) -> bool:
|
||||
@@ -79,7 +86,8 @@ def _state_valid(state: object) -> bool:
|
||||
acc.number(state.pedal_target_mps) and (state.last_now_ns is None or acc.integer(state.last_now_ns)) and
|
||||
type(state.reset_required) is bool and type(state.pedal_blocked_until_release) is bool and
|
||||
(state.wheel_override_metric is None or type(state.wheel_override_metric) is bool) and
|
||||
acc.integer(state.wheel_override_since_ns))
|
||||
acc.integer(state.wheel_override_since_ns) and
|
||||
(state.override is None or isinstance(state.override, ov.State) and state.override.session_id == state.session_id))
|
||||
|
||||
|
||||
def _host_valid(host: object) -> bool:
|
||||
@@ -119,7 +127,8 @@ def step(state: State, frame: Frame) -> Result:
|
||||
frame.wheel_override_enabled, frame.wheel_override_blocked)) or
|
||||
not isinstance(frame.selected_kind, sd.DomainStatus) or not isinstance(frame.ego_pair, sd.SpeedPair) or
|
||||
(frame.filtered_ego_delta_mps is not None and not acc.number(frame.filtered_ego_delta_mps)) or
|
||||
(frame.is_metric is not None and type(frame.is_metric) is not bool)):
|
||||
(frame.is_metric is not None and type(frame.is_metric) is not bool) or
|
||||
type(frame.set_speed_rule) is not bool or type(frame.set_speed_ready) is not bool):
|
||||
return Result(replace(state, reset_required=True), status="invalid_frame", errors=("invalid frame or clock",))
|
||||
host = frame.host
|
||||
selected_initialized = host.driver_v_cruise_kph > 0 and host.driver_v_cruise_kph != 255.0
|
||||
@@ -154,7 +163,7 @@ def step(state: State, frame: Frame) -> Result:
|
||||
ego = frame.ego_pair
|
||||
candidate = selected.observation.candidate
|
||||
matches_set = False
|
||||
if (active_path and candidate is not None and frame.selected_kind is sd.DomainStatus.VALID and
|
||||
if (active_path and frame.set_speed_ready and candidate is not None and frame.selected_kind is sd.DomainStatus.VALID and
|
||||
ego.status is sd.DomainStatus.VALID and ego.session_id == state.session_id and ego.timestamp_ns == frame.now_ns and
|
||||
acc.number(ego.raw_mps) and acc.number(ego.cluster_mps)):
|
||||
assert ego.raw_mps is not None and ego.cluster_mps is not None
|
||||
@@ -177,6 +186,8 @@ def step(state: State, frame: Frame) -> Result:
|
||||
pair = sd.SpeedPair(frame.selected_kind)
|
||||
else:
|
||||
pair = sd.SpeedPair(sd.DomainStatus.ABSENT)
|
||||
if frame.set_speed_rule:
|
||||
return _set_speed_rule(base, frame, selected, acceptance, pair, active_path)
|
||||
domain = sd.resolve(acceptance, frame.offset_schedule, pair, frame.ego_pair)
|
||||
if domain.status is sd.DomainStatus.INVALID:
|
||||
return Result(replace(base, reset_required=True), selected, acceptance, domain,
|
||||
@@ -243,3 +254,45 @@ def step(state: State, frame: Frame) -> Result:
|
||||
return Result(base, selected, acceptance, domain, coordinate,
|
||||
ceiling=CruiseCeiling(coordinate.cap_mps, frame.authority),
|
||||
status=acceptance.basis)
|
||||
|
||||
|
||||
def _override_evidence(kind: sd.DomainStatus) -> ov.EvidenceKind:
|
||||
return {sd.DomainStatus.VALID: ov.EvidenceKind.VALID, sd.DomainStatus.ABSENT: ov.EvidenceKind.ABSENT,
|
||||
sd.DomainStatus.STALE: ov.EvidenceKind.STALE}.get(kind, ov.EvidenceKind.UNKNOWN)
|
||||
|
||||
|
||||
def _set_speed_rule(base: State, frame: Frame, selected: sel.Selection, acceptance: acc.Decision,
|
||||
pair: sd.SpeedPair, active_path: bool) -> Result:
|
||||
"""Tesla set-speed rule: the accepted limit plus offset becomes SET through card, and a driver's own SET change
|
||||
holds until the limit changes. A cap beneath SET would hold the car under a SET the driver raised, so none is supplied."""
|
||||
if acceptance.control_target_mps is not None and acceptance.state.observation.kind is not acc.ObservationKind.VALID:
|
||||
# A source gap carries no target: SET stays where it is until a current reading returns.
|
||||
acceptance = replace(acceptance, control_target_mps=None)
|
||||
domain = sd.resolve(acceptance, frame.offset_schedule, pair, frame.ego_pair)
|
||||
ego = frame.ego_pair
|
||||
ego_valid = ego.status is sd.DomainStatus.VALID
|
||||
change = frame.classified_cruise.change if frame.classified_cruise is not None else None
|
||||
override = ov.step(base.override if base.override is not None else ov.new_session(base.session_id),
|
||||
acceptance, frame.authority, frame.acceptance_policy,
|
||||
ov.SelectedEvidence(_override_evidence(pair.status), pair.raw_mps if pair.status is sd.DomainStatus.VALID else None),
|
||||
ov.PedalEvidence(_override_evidence(ego.status), frame.pedal_pressed if ego_valid else None,
|
||||
ego.raw_mps if ego_valid else None),
|
||||
now_ns=frame.now_ns, change=change, domain=domain)
|
||||
base = replace(base, override=override.state)
|
||||
if override.errors or domain.status is sd.DomainStatus.INVALID:
|
||||
return Result(replace(base, reset_required=True), selected, acceptance, domain, override=override,
|
||||
status="invalid_domain_or_override", errors=override.errors or (domain.reason,))
|
||||
if not active_path or domain.status is not sd.DomainStatus.VALID:
|
||||
return Result(base, selected, acceptance, domain, override=override,
|
||||
status=acceptance.basis if acceptance.basis == 'source_switch_pending' else 'inactive_or_unavailable')
|
||||
context = domain.context
|
||||
if (context is None or override.state.last_timestamp_ns != frame.now_ns or
|
||||
override.state.accepted_mps != context.accepted_raw_mps or
|
||||
override.state.effective_target_mps != context.effective_cluster_mps):
|
||||
return Result(replace(base, reset_required=True), selected, acceptance, domain, override=override,
|
||||
status="invalid_join", errors=("override and speed domain mismatch",))
|
||||
coordinate = sd.override_planner_coordinate(context, override.contribution_mps)
|
||||
if coordinate.cap_mps is None:
|
||||
return Result(replace(base, reset_required=True), selected, acceptance, domain, coordinate, override=override,
|
||||
status="invalid_coordinate", errors=("planner coordinate unavailable",))
|
||||
return Result(base, selected, acceptance, domain, coordinate, override=override, status=acceptance.basis)
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
"""Where SLC writes SET: a driver's own SET change holds until the accepted limit changes.
|
||||
|
||||
Pure state for the Tesla set-speed rule only. It proposes a held SET, never an actuator or stock-button command.
|
||||
"""
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass, replace
|
||||
from enum import Enum
|
||||
|
||||
from openpilot.starpilot.speed_limits import acceptance as acc
|
||||
from openpilot.starpilot.speed_limits import action_arbitration as arb
|
||||
from openpilot.starpilot.speed_limits import speed_domain as sd
|
||||
|
||||
|
||||
class EvidenceKind(Enum):
|
||||
VALID = "valid"
|
||||
ABSENT = "absent"
|
||||
UNKNOWN = "unknown"
|
||||
STALE = "stale"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SelectedEvidence:
|
||||
kind: EvidenceKind
|
||||
speed_mps: float | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PedalEvidence:
|
||||
kind: EvidenceKind
|
||||
pressed: bool | None = None
|
||||
ego_mps: float | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Context:
|
||||
context_id: str
|
||||
issued_at_ns: int
|
||||
accepted_target_mps: float
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class State:
|
||||
session_id: str
|
||||
persistent_selected_mps: float | None = None # the driver's held SET; None while SET follows the limit
|
||||
accepted_mps: float | None = None
|
||||
context: Context | None = None
|
||||
next_context_id: int = 1
|
||||
active: bool = False
|
||||
mode: acc.Mode | None = None
|
||||
owner: acc.LongitudinalOwner | None = None
|
||||
last_effect_id: int = -1
|
||||
last_adoption_sequence: int = -1
|
||||
last_timestamp_ns: int | None = None
|
||||
reset_required: bool = False
|
||||
effective_target_mps: float | None = None
|
||||
applied_selected_mps: float | None = None # the rounded SET card wrote for the accepted limit
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EventReceipt:
|
||||
effect_id: int
|
||||
acknowledged: bool
|
||||
consumed: bool
|
||||
status: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Decision:
|
||||
state: State
|
||||
contribution_mps: float | None = None
|
||||
basis: str = "none"
|
||||
context: Context | None = None
|
||||
event_receipt: EventReceipt | None = None
|
||||
errors: tuple[str, ...] = ()
|
||||
|
||||
|
||||
def explicit_adoption(decision: acc.Decision) -> int | None:
|
||||
"""The sequence of an explicit adopt this decision consumed with speed-control authority, else None."""
|
||||
receipt = decision.adoption_receipt
|
||||
if decision.basis != 'driver_adopt' or decision.control_target_mps is None or receipt is None or not receipt.consumed:
|
||||
return None
|
||||
return receipt.sequence_id
|
||||
|
||||
|
||||
def _state_valid(state: object) -> bool:
|
||||
if not isinstance(state, State) or not acc.token(state.session_id):
|
||||
return False
|
||||
if any(v is not None and not acc.number(v, positive=True) for v in (
|
||||
state.persistent_selected_mps, state.accepted_mps, state.effective_target_mps, state.applied_selected_mps)):
|
||||
return False
|
||||
if (not acc.integer(state.next_context_id, 1) or type(state.active) is not bool or
|
||||
not acc.integer(state.last_effect_id, -1) or not acc.integer(state.last_adoption_sequence, -1) or
|
||||
type(state.reset_required) is not bool or
|
||||
(state.last_timestamp_ns is not None and not acc.integer(state.last_timestamp_ns))):
|
||||
return False
|
||||
if (state.mode is not None and not isinstance(state.mode, acc.Mode)) or (
|
||||
state.owner is not None and not isinstance(state.owner, acc.LongitudinalOwner)):
|
||||
return False
|
||||
if (state.mode is None) != (state.owner is None) or (state.mode is not None and state.last_timestamp_ns is None):
|
||||
return False
|
||||
if state.reset_required and (state.persistent_selected_mps is not None or state.active or state.context is not None):
|
||||
return False
|
||||
# Held intent is raw selected speed; a negative offset can put it below the raw accepted limit.
|
||||
if state.context is not None:
|
||||
c = state.context
|
||||
if (not isinstance(c, Context) or not acc.token(c.context_id) or not acc.integer(c.issued_at_ns) or
|
||||
not acc.number(c.accepted_target_mps, positive=True) or state.last_timestamp_ns is None or
|
||||
c.issued_at_ns > state.last_timestamp_ns or not state.active or state.accepted_mps != c.accepted_target_mps or
|
||||
state.next_context_id <= 1 or c.context_id != f"override:{state.next_context_id - 1}" or
|
||||
state.mode not in (acc.Mode.LONGITUDINAL_ONLY, acc.Mode.COMBINED) or state.owner is not acc.LongitudinalOwner.SYSTEM):
|
||||
return False
|
||||
return not state.active or (state.context is not None and state.effective_target_mps is not None)
|
||||
|
||||
|
||||
def new_session(session_id: str) -> State:
|
||||
state = State(session_id)
|
||||
if not _state_valid(state):
|
||||
raise ValueError("invalid session ID")
|
||||
return state
|
||||
|
||||
|
||||
def _selected_valid(selected: object) -> bool:
|
||||
return isinstance(selected, SelectedEvidence) and isinstance(selected.kind, EvidenceKind) and (
|
||||
acc.number(selected.speed_mps, positive=True) if selected.kind is EvidenceKind.VALID else selected.speed_mps is None)
|
||||
|
||||
|
||||
def _pedal_valid(pedal: object) -> bool:
|
||||
if not isinstance(pedal, PedalEvidence) or not isinstance(pedal.kind, EvidenceKind):
|
||||
return False
|
||||
if pedal.kind is not EvidenceKind.VALID:
|
||||
return pedal.pressed is None and pedal.ego_mps is None
|
||||
return type(pedal.pressed) is bool and (acc.number(pedal.ego_mps) or pedal.ego_mps is None and not pedal.pressed)
|
||||
|
||||
|
||||
def _change_valid(change: object) -> bool:
|
||||
return (isinstance(change, arb.ClassifiedChange) and acc.token(change.session_id) and acc.integer(change.effect_id) and
|
||||
(change.action_id is None or acc.integer(change.action_id)) and
|
||||
(change.context_id is None or acc.token(change.context_id)) and
|
||||
(change.started_at_ns is None or acc.integer(change.started_at_ns)) and
|
||||
(change.previous_mps is None or acc.number(change.previous_mps, positive=True)) and
|
||||
acc.number(change.selected_mps, positive=True) and isinstance(change.disposition, arb.Disposition))
|
||||
|
||||
|
||||
def _acceptance_valid(decision: object, authority: object, policy: object, session_id: str, now_ns: int) -> bool:
|
||||
if (not isinstance(decision, acc.Decision) or not isinstance(decision.state, acc.State) or decision.errors or
|
||||
decision.state.session_id != session_id or decision.state.last_timestamp_ns != now_ns or
|
||||
not isinstance(authority, acc.Authority) or not isinstance(policy, acc.Policy) or
|
||||
decision.authority != authority or decision.policy != policy or
|
||||
not acc.observation_is_valid(decision.state.observation, session_id=session_id)):
|
||||
return False
|
||||
if policy.display_only or not authority.can_control:
|
||||
return decision.control_target_mps is None
|
||||
if decision.control_target_mps is None:
|
||||
return True
|
||||
accepted = decision.state.accepted
|
||||
if (accepted is None or not acc.token(accepted.session_id) or not acc.number(accepted.candidate.speed_mps, positive=True) or
|
||||
decision.control_target_mps != accepted.candidate.speed_mps):
|
||||
return False
|
||||
return decision.state.observation.kind is acc.ObservationKind.VALID
|
||||
|
||||
|
||||
def _failed(state: State) -> State:
|
||||
return replace(state, persistent_selected_mps=None, context=None, active=False, reset_required=True)
|
||||
|
||||
|
||||
def step(state: State, acceptance: acc.Decision, authority: acc.Authority, policy: acc.Policy,
|
||||
selected: SelectedEvidence, pedal: PedalEvidence, *, now_ns: int,
|
||||
change: arb.ClassifiedChange | None = None, domain: sd.DomainResolution | None = None) -> Decision:
|
||||
"""Hold or release the driver's own SET against this frame's acceptance decision."""
|
||||
if not _state_valid(state):
|
||||
return Decision(state, errors=("invalid override state",))
|
||||
if state.reset_required:
|
||||
return Decision(state, basis="session_reset_required", errors=("new session required",))
|
||||
if (not acc.integer(now_ns) or (state.last_timestamp_ns is not None and now_ns < state.last_timestamp_ns) or
|
||||
not _selected_valid(selected) or not _pedal_valid(pedal) or
|
||||
(change is not None and not _change_valid(change)) or
|
||||
(domain is not None and (not isinstance(domain, sd.DomainResolution) or not isinstance(domain.status, sd.DomainStatus)))):
|
||||
return Decision(_failed(state), basis="session_reset_required", errors=("invalid evidence or monotonic clock",))
|
||||
old = state
|
||||
state = replace(state, last_timestamp_ns=now_ns)
|
||||
receipt = None
|
||||
if change is not None:
|
||||
if change.session_id != state.session_id:
|
||||
receipt = EventReceipt(change.effect_id, True, False, "foreign_session")
|
||||
elif change.effect_id <= state.last_effect_id:
|
||||
receipt = EventReceipt(change.effect_id, True, False, "already_seen")
|
||||
else:
|
||||
state = replace(state, last_effect_id=change.effect_id)
|
||||
receipt = EventReceipt(change.effect_id, True, False, "ineligible")
|
||||
|
||||
if not _acceptance_valid(acceptance, authority, policy, state.session_id, now_ns):
|
||||
return Decision(_failed(state), basis="session_reset_required", event_receipt=receipt,
|
||||
errors=("acceptance authority, policy, target or clock mismatch",))
|
||||
|
||||
accepted = acceptance.state.accepted
|
||||
accepted_speed = accepted.candidate.speed_mps if accepted is not None else None
|
||||
domain_unavailable = False
|
||||
selected_delta = 0.0
|
||||
effective_target = (old.effective_target_mps if acceptance.control_target_mps is None and accepted_speed == old.accepted_mps
|
||||
else acceptance.control_target_mps)
|
||||
if domain is not None:
|
||||
if domain.status is sd.DomainStatus.INVALID or (domain.status is not sd.DomainStatus.VALID and domain.context is not None):
|
||||
return Decision(_failed(state), basis="session_reset_required", event_receipt=receipt, errors=("invalid speed domain",))
|
||||
if domain.status is not sd.DomainStatus.VALID:
|
||||
domain_unavailable = True
|
||||
else:
|
||||
c = domain.context
|
||||
if (not isinstance(c, sd.DomainContext) or not sd.context_is_valid(c) or
|
||||
c.session_id != state.session_id or c.timestamp_ns != now_ns or
|
||||
c.accepted_raw_mps != acceptance.control_target_mps or selected.speed_mps != c.selected_raw_mps or
|
||||
(pedal.pressed and pedal.ego_mps != c.ego_raw_mps)):
|
||||
return Decision(_failed(state), basis="session_reset_required", event_receipt=receipt, errors=("speed domain mismatch",))
|
||||
selected_delta = c.selected_delta_mps
|
||||
effective_target = c.effective_cluster_mps
|
||||
mode_changed = old.mode is not None and (old.mode != authority.mode or old.owner != authority.owner)
|
||||
if acceptance.history_write is not None and (old.accepted_mps is None or accepted_speed is None or
|
||||
abs(accepted_speed - old.accepted_mps) >= .1):
|
||||
# A higher limit keeps a held SET that is still above it; any other new limit releases the hold.
|
||||
keep_manual = (old.accepted_mps is not None and accepted_speed is not None and
|
||||
accepted_speed > old.accepted_mps and state.persistent_selected_mps is not None and
|
||||
effective_target is not None and
|
||||
state.persistent_selected_mps + selected_delta > effective_target + .1)
|
||||
state = replace(state, persistent_selected_mps=state.persistent_selected_mps if keep_manual else None,
|
||||
applied_selected_mps=None)
|
||||
comparison_target = state.applied_selected_mps + selected_delta if state.applied_selected_mps is not None else effective_target
|
||||
# SET back on the limit's own value (as card rounded it) is no longer a hold.
|
||||
if (not domain_unavailable and state.persistent_selected_mps is not None and effective_target is not None and
|
||||
comparison_target is not None and selected.speed_mps is not None and
|
||||
math.isclose(comparison_target, selected.speed_mps + selected_delta, abs_tol=0.001, rel_tol=0)):
|
||||
state = replace(state, persistent_selected_mps=None)
|
||||
state = replace(state, accepted_mps=accepted_speed, effective_target_mps=effective_target,
|
||||
mode=authority.mode, owner=authority.owner)
|
||||
|
||||
adopted = explicit_adoption(acceptance)
|
||||
adopted_now = adopted is not None and adopted > state.last_adoption_sequence
|
||||
if adopted_now:
|
||||
assert adopted is not None
|
||||
state = replace(state, persistent_selected_mps=None, last_adoption_sequence=adopted)
|
||||
|
||||
eligible = (authority.can_control and not policy.display_only and accepted_speed is not None and effective_target is not None and
|
||||
selected.kind is EvidenceKind.VALID and pedal.kind is EvidenceKind.VALID and
|
||||
(not domain_unavailable or acceptance.control_target_mps is None))
|
||||
if not eligible:
|
||||
state = replace(state, active=False, context=None)
|
||||
return Decision(state, basis="display_only" if policy.display_only else "inactive_or_missing_evidence", event_receipt=receipt)
|
||||
|
||||
assert accepted_speed is not None and selected.speed_mps is not None
|
||||
rotate = (not old.active or old.context is None or old.context.accepted_target_mps != accepted_speed or
|
||||
old.effective_target_mps != effective_target or mode_changed or adopted_now)
|
||||
if rotate:
|
||||
context = Context(f"override:{state.next_context_id}", now_ns, accepted_speed)
|
||||
state = replace(state, context=context, next_context_id=state.next_context_id + 1, active=True)
|
||||
else:
|
||||
state = replace(state, active=True)
|
||||
|
||||
if receipt is not None and receipt.status == "ineligible" and change is not None:
|
||||
if (change.disposition is arb.Disposition.DRIVER_INTENT and change.action_id is not None and
|
||||
change.previous_mps is not None and change.previous_mps != change.selected_mps and
|
||||
old.active and old.context is not None and not rotate and change.context_id == old.context.context_id and
|
||||
change.started_at_ns is not None and old.context.issued_at_ns <= change.started_at_ns <= now_ns and
|
||||
change.selected_mps == selected.speed_mps):
|
||||
# A change back onto the limit's own SET releases the hold; any other value becomes the held SET.
|
||||
held = comparison_target is not None and not math.isclose(
|
||||
change.selected_mps + selected_delta, comparison_target, abs_tol=0.001, rel_tol=0)
|
||||
state = replace(state, persistent_selected_mps=change.selected_mps if held else None)
|
||||
receipt = replace(receipt, consumed=True, status="driver_intent")
|
||||
else:
|
||||
receipt = replace(receipt, status="unqualified_effect")
|
||||
|
||||
if state.persistent_selected_mps is not None:
|
||||
return Decision(state, state.persistent_selected_mps, "persistent", state.context, receipt)
|
||||
return Decision(state, basis="adoption_clear" if adopted_now else "none", context=state.context, event_receipt=receipt)
|
||||
@@ -57,6 +57,51 @@ def _current_state(sm, now_ns: int):
|
||||
str(state.source) in tuple(Source) and number(state.speedLimit, positive=True) and adoption_speed(state) is not None) else None
|
||||
|
||||
|
||||
def state_current(sm, observation, producer_session: str, now_ns: int):
|
||||
"""Tesla set-speed rule: the planner's current limit; a dashboard reading must still be this card's own."""
|
||||
state = _current_state(sm, now_ns)
|
||||
if (state is not None and not state.upcomingBoundaryId and str(state.source) == 'dashboard' and
|
||||
(observation is None or not source_matches(state, observation, producer_session, now_ns))):
|
||||
return None
|
||||
return state
|
||||
|
||||
|
||||
def command_applicable(command, state, observation, producer_session: str, now_ns: int, selected_mps: float, *,
|
||||
long_active: bool, button_event: bool) -> bool:
|
||||
"""Tesla set-speed rule: whether card may write this SLC command's target into software SET now."""
|
||||
if state is None or button_event or not long_active or not state.hasAccepted:
|
||||
return False
|
||||
# Adopt limits early: the accepted limit is the upcoming Maps boundary's, not the road's current one, so the command
|
||||
# is bound to Maps (which has no producer episode) and to that boundary instead of the current source.
|
||||
preview = bool(state.acceptedIsPreview)
|
||||
if preview and (str(state.acceptedSource) != 'map' or not str(state.upcomingBoundaryId) or adoption_speed(state) is None or
|
||||
abs(float(state.acceptedSpeedLimit) - float(state.upcomingSpeedLimit)) > 0.02):
|
||||
return False
|
||||
bound = ('map', 0, '', 0, 0) if preview else (str(state.source), int(state.sourceEpisode), str(state.sourceProducerSessionId),
|
||||
int(state.sourceObservedMonoTime), int(state.sourceValidUntilMonoTime))
|
||||
if (str(command.kind) != 'adoptAcceptedLimit' or not str(command.sessionId) or
|
||||
str(command.sessionId) != str(state.sessionId) or int(command.commandId) <= 0 or int(command.presentationId) <= 0 or
|
||||
int(command.commandId) != int(state.commandId) or
|
||||
int(command.presentationId) != int(state.presentationId) or
|
||||
(str(command.source), int(command.sourceEpisode), str(command.sourceProducerSessionId),
|
||||
int(command.sourceObservedMonoTime), int(command.sourceValidUntilMonoTime)) != bound or
|
||||
(not preview and str(state.source) == 'dashboard' and
|
||||
(observation is None or not source_matches(state, observation, producer_session, now_ns)))):
|
||||
return False
|
||||
issued, expires = int(command.issuedMonoTime), int(command.expiresMonoTime)
|
||||
if not 0 < issued <= now_ns <= expires <= issued + STATE_MAX_AGE_NS:
|
||||
return False
|
||||
expected, target = float(command.expectedSelectedMps), float(command.targetMps)
|
||||
# SET must still be where the planner saw it, and the target must be the accepted limit plus its offset: the road's
|
||||
# current limit, or the early preview checked above.
|
||||
# Float32 transport can round a legal boundary just outside its double-precision value.
|
||||
return (number(expected, positive=True) and number(target, positive=True) and number(selected_mps, positive=True) and
|
||||
abs(expected - selected_mps) <= 0.1 and
|
||||
(preview or abs(float(state.acceptedSpeedLimit) - float(state.speedLimit)) <= 0.02) and
|
||||
abs(target - (float(state.acceptedSpeedLimit) + float(state.offset))) <= 0.1 and
|
||||
V_CRUISE_MIN / 3.6 - 1e-5 <= target <= V_CRUISE_MAX / 3.6 + 1e-5)
|
||||
|
||||
|
||||
def active_ceiling(sm, now_ns: int, *, after_ns: int = 0) -> float | None:
|
||||
state = _state(sm, now_ns)
|
||||
if state is None or int(state.frameMonoTime) <= after_ns or not state.hasCeiling:
|
||||
@@ -100,8 +145,11 @@ def engagement_state(sm, observation, producer_session: str, now_ns: int, *, aft
|
||||
return state if number(target, positive=True) and V_CRUISE_MIN / 3.6 - 1e-5 <= target <= V_CRUISE_MAX / 3.6 + 1e-5 else None
|
||||
|
||||
|
||||
def engagement_target(sm, observation, producer_session: str, now_ns: int, *, after_ns: int = 0):
|
||||
def engagement_target(sm, observation, producer_session: str, now_ns: int, *, after_ns: int = 0, current_only: bool = False):
|
||||
current = engagement_state(sm, observation, producer_session, now_ns, after_ns=after_ns)
|
||||
if current_only:
|
||||
# Tesla set-speed rule: engaging starts SET at the road's current limit, never at an earlier acceptance.
|
||||
return (float(current.presentationAdjustedLimit), current) if current is not None else (None, None)
|
||||
state = current if current is not None else _state(sm, now_ns)
|
||||
if state is None or int(state.frameMonoTime) <= after_ns:
|
||||
return None, None
|
||||
|
||||
@@ -5,6 +5,8 @@ import secrets
|
||||
import time
|
||||
from dataclasses import replace
|
||||
|
||||
from opendbc.car.tesla.speed_sync import selected as tesla_set_speed_selected
|
||||
from openpilot.starpilot.car.tesla import set_speed as tesla_set_speed
|
||||
from openpilot.cereal import messaging
|
||||
from openpilot.cereal.services import SERVICE_LIST
|
||||
from openpilot.starpilot.feature_runtime import enabled as feature_enabled, slc_runtime_settings, vision_control_enabled
|
||||
@@ -15,7 +17,9 @@ from openpilot.starpilot.speed_limits.runtime_settings import read_params as rea
|
||||
|
||||
ACTION_MAX_AGE_NS = int(2e9 / SERVICE_LIST['modelV2'].frequency)
|
||||
SLC_ACTIONS = ('accept', 'reject', 'adopt')
|
||||
SLC_CRUISE_EVENTS = ('driverChange', 'confirmationAccept', 'confirmationReject', 'engagementAdopt')
|
||||
# commandApplied/commandRejected: card's answers to the Tesla set-speed rule's commands; no other car sends them.
|
||||
SLC_CRUISE_EVENTS = ('driverChange', 'confirmationAccept', 'confirmationReject', 'engagementAdopt',
|
||||
'commandApplied', 'commandRejected')
|
||||
|
||||
|
||||
class SavedSlcLifecycle:
|
||||
@@ -26,6 +30,8 @@ class SavedSlcLifecycle:
|
||||
self.runtime = None
|
||||
self.configuration = None
|
||||
self.last_refresh_ns = None
|
||||
# Tesla set-speed rule: SLC's set-speed commands for card, from whichever planner hosts this lifecycle.
|
||||
self.command_sock = messaging.pub_sock('slcCruiseCommand') if tesla_set_speed_selected(cp) else None
|
||||
|
||||
def source_services(self):
|
||||
services = ['slcDashboardObservation', 'slcVisionObservation', 'mapdOut']
|
||||
@@ -42,6 +48,10 @@ class SavedSlcLifecycle:
|
||||
saved_slc = read_slc_settings(self.params)
|
||||
admitted = feature_enabled(self.params, self.cp, 'slc', self.environment, saved_slc=saved_slc)
|
||||
settings = slc_runtime_settings(self.params, self.cp, self.environment, saved_slc=saved_slc)
|
||||
if self.command_sock is not None and tesla_set_speed.active(self.params, self.cp):
|
||||
# Tesla set-speed rule: SLC writes SET through card. Early adoption writes SET early (runtime._command), and the
|
||||
# accelerator-override choice is applied by card, which owns SET (tesla_set_speed_card.pedal_hold).
|
||||
settings = replace(settings, set_speed_rule=True)
|
||||
vision = admitted and feature_enabled(self.params, self.cp, 'vision', self.environment, saved_slc=saved_slc)
|
||||
configuration = (admitted and not settings.errors, settings, vision,
|
||||
vision_control_enabled(self.params, self.cp, saved_slc=saved_slc),
|
||||
@@ -50,7 +60,9 @@ class SavedSlcLifecycle:
|
||||
if configuration == self.configuration:
|
||||
return self.runtime, False
|
||||
previous_runtime = self.runtime
|
||||
continuing_control = bool(self.runtime is not None and self.runtime.settings.enabled and settings.enabled and configuration[0])
|
||||
# Who owns SET changed (the Tesla switch): start a new session rather than carry cap or command state across.
|
||||
continuing_control = bool(self.runtime is not None and self.runtime.settings.enabled and settings.enabled and configuration[0] and
|
||||
self.runtime.settings.set_speed_rule == settings.set_speed_rule)
|
||||
timing_only = False
|
||||
preserve_runtime = continuing_control
|
||||
if self.runtime is not None and self.configuration is not None:
|
||||
@@ -111,6 +123,8 @@ class SavedSlcLifecycle:
|
||||
accepted = runtime.history_limit
|
||||
if accepted != previous_accepted:
|
||||
self.params.put("SLCQualifiedHistory", json.loads(history.encode(accepted, time.time_ns())) if accepted is not None else {})
|
||||
if output.command is not None and self.command_sock is not None:
|
||||
self.command_sock.send(output.command.to_bytes())
|
||||
return output
|
||||
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import math
|
||||
import uuid
|
||||
from dataclasses import dataclass, replace
|
||||
|
||||
from opendbc.car.tesla.speed_sync import selected as tesla_set_speed_selected
|
||||
import openpilot.cereal.messaging as messaging
|
||||
from openpilot.cereal.services import SERVICE_LIST
|
||||
from openpilot.selfdrive.car.cruise import V_CRUISE_MIN, V_CRUISE_MAX
|
||||
@@ -12,6 +13,7 @@ from openpilot.starpilot.controllers.wheel_actions import LIFETIME_NS as WHEEL_A
|
||||
from openpilot.starpilot.speed_limits import acceptance as acc
|
||||
from openpilot.starpilot.speed_limits import action_arbitration as arb
|
||||
from openpilot.starpilot.speed_limits import composition as comp
|
||||
from openpilot.starpilot.speed_limits import overrides as ov
|
||||
from openpilot.starpilot.speed_limits import selection as sel
|
||||
from openpilot.starpilot.speed_limits import speed_domain as sd
|
||||
from openpilot.starpilot.speed_limits.runtime_settings import ADVANCE_SECONDS, Settings
|
||||
@@ -108,6 +110,7 @@ class Output:
|
||||
result: comp.Result
|
||||
message: object
|
||||
action_result: arb.Result | None = None
|
||||
command: object | None = None # Tesla set-speed rule: an slcCruiseCommand for card
|
||||
|
||||
|
||||
class Runtime:
|
||||
@@ -125,6 +128,10 @@ class Runtime:
|
||||
# driver confirmation remain independent requirements for each episode.
|
||||
self.vision_control_qualified = vision_enabled and vision_control_qualified
|
||||
self.vision_display_qualified = bool(vision_enabled and vision_display_qualified and settings.display and not settings.enabled)
|
||||
# Tesla set-speed rule (see step): SLC writes SET through card. A reset keeps this deadline, because the
|
||||
# previous session's command may still be in flight.
|
||||
self.set_speed_rule = False
|
||||
self.set_speed_after_ns = 0
|
||||
self._start_session(session_id or uuid.uuid4().hex, previous_limit)
|
||||
|
||||
def reset(self) -> None:
|
||||
@@ -157,12 +164,27 @@ class Runtime:
|
||||
self._ego_delta_key: tuple[str, str] | None = None
|
||||
self._ego_delta_mps = 0.0
|
||||
self._ego_sample_ns = 0
|
||||
# Tesla set-speed rule: the one command card is asked to apply, and what became of it.
|
||||
self.last_command_id = 0
|
||||
self.command_status = ''
|
||||
self.command_interrupted = False
|
||||
self.command_issued_ns = 0
|
||||
self.command_expiry_ns = 0
|
||||
self.command_expected_mps = 0.0
|
||||
self.command_target_mps = 0.0
|
||||
self.command_card_producer = ''
|
||||
self.commanded_acceptance: acc.AcceptedLimit | None = None
|
||||
|
||||
def update_offsets(self, offsets: sd.OffsetSchedule, *, is_metric: bool | None = None) -> None:
|
||||
if is_metric is not None:
|
||||
if type(is_metric) is not bool:
|
||||
raise ValueError('SLC display units must be Boolean')
|
||||
self.is_metric = is_metric
|
||||
if offsets != self.settings.offsets:
|
||||
# A new offset is a new SET target for the same accepted limit; display units alone are not.
|
||||
self.command_status = ''
|
||||
self.command_interrupted = False
|
||||
self.commanded_acceptance = None
|
||||
self.settings = replace(self.settings, offsets=offsets)
|
||||
# Renew actions for new offsets/units without forgetting driver choices.
|
||||
acceptance = replace(self.state.acceptance, observation=acc.Observation(acc.ObservationKind.UNKNOWN),
|
||||
@@ -203,7 +225,14 @@ class Runtime:
|
||||
return None
|
||||
self._mark_event(event)
|
||||
action_id = self.ledger.last_action_id + 1
|
||||
begun = arb.step(self.ledger, arb.BeginAction(self.session_id, action_id, arb.Origin.DRIVER_CRUISE, 'driver-set'), now_ns=now_ns)
|
||||
context_id = 'driver-set'
|
||||
if self.set_speed_rule and self.state.override is not None:
|
||||
# A SET change older than the current override context answers an earlier limit.
|
||||
context = self.state.override.context
|
||||
if context is not None and context.issued_at_ns > event.observed_ns:
|
||||
return None
|
||||
context_id = context.context_id if context is not None else 'no-slc-context'
|
||||
begun = arb.step(self.ledger, arb.BeginAction(self.session_id, action_id, arb.Origin.DRIVER_CRUISE, context_id), now_ns=now_ns)
|
||||
self.ledger = begun.state
|
||||
if begun.errors or begun.status != 'begun':
|
||||
return None
|
||||
@@ -255,6 +284,32 @@ class Runtime:
|
||||
kind = acc.ActionKind.ACCEPT if event.kind == 'confirmationAccept' else acc.ActionKind.REJECT
|
||||
return acc.DriverAction(self.session_id, action_id, pending.decision_id, kind, event.observed_ns), None, action_id
|
||||
|
||||
def _command_receipt(self, event: CruiseEvent, sm, now_ns: int) -> None:
|
||||
"""Card's answer to the command this session issued; anything else is ignored."""
|
||||
if event.kind not in ('commandApplied', 'commandRejected') or not self._event_current(event, sm, now_ns):
|
||||
return
|
||||
self._mark_event(event)
|
||||
if (event.session_id != self.session_id or event.command_id != self.last_command_id or
|
||||
event.producer_session != self.command_card_producer or self.command_status not in ('issued', 'expired') or
|
||||
not self.command_issued_ns <= event.observed_ns <= self.command_expiry_ns):
|
||||
return
|
||||
if event.kind == 'commandRejected':
|
||||
self.command_status = 'rejected'
|
||||
self.set_speed_after_ns = event.observed_ns
|
||||
return
|
||||
# Card rounds the target to whole display units, at most half a mph away.
|
||||
if (not acc.number(event.previous_mps, positive=True) or abs(event.previous_mps - self.command_expected_mps) > 0.1 or
|
||||
not acc.number(event.selected_mps, positive=True) or abs(event.selected_mps - self.command_target_mps) > 0.5):
|
||||
return
|
||||
self.command_status = 'applied'
|
||||
self.set_speed_after_ns = event.observed_ns
|
||||
if self.commanded_acceptance == self.state.acceptance.accepted and self.state.override is not None:
|
||||
self.state = replace(self.state, override=replace(self.state.override, applied_selected_mps=event.selected_mps))
|
||||
|
||||
def _set_speed_ready(self, sm) -> bool:
|
||||
# Trust SET only once carState is newer than card's answer to the last command (or that command's expiry).
|
||||
return int(sm.logMonoTime.get('carState', 0)) > self.set_speed_after_ns
|
||||
|
||||
@property
|
||||
def _maps_selected(self) -> bool:
|
||||
policy = self.settings.selection
|
||||
@@ -469,7 +524,9 @@ class Runtime:
|
||||
if shown is None or shown.presentation_id != request.presentation_id:
|
||||
return None, None, None
|
||||
action_id = self.ledger.last_action_id + 1
|
||||
begun = arb.step(self.ledger, arb.BeginAction(self.session_id, action_id, arb.Origin.DRIVER_OTHER, 'slc-presentation'),
|
||||
context = self.state.override.context if self.set_speed_rule and self.state.override is not None else None
|
||||
context_id = context.context_id if context is not None else 'slc-presentation'
|
||||
begun = arb.step(self.ledger, arb.BeginAction(self.session_id, action_id, arb.Origin.DRIVER_OTHER, context_id),
|
||||
now_ns=now_ns)
|
||||
self.ledger = begun.state
|
||||
if begun.errors:
|
||||
@@ -482,7 +539,15 @@ class Runtime:
|
||||
|
||||
def step(self, sm, CP, *, now_ns: int, now_boot_ns: int | None = None, request: Action | None = None,
|
||||
cruise_event: CruiseEvent | None = None, confirmation_grace_ns: int = 0, wheel_override_blocked: bool = False) -> Output:
|
||||
# Tesla set-speed rule: on a Model 3/Y whose software SET is mirrored to the car, SLC writes SET (limit plus
|
||||
# offset) through card instead of capping beneath it. The planner host follows the saved switch.
|
||||
self.set_speed_rule = bool(self.settings.set_speed_rule and tesla_set_speed_selected(CP))
|
||||
old_pending = self.state.acceptance.pending
|
||||
if self.command_status == 'issued' and now_ns > self.command_expiry_ns:
|
||||
self.command_status = 'expired'
|
||||
classified = self._cruise(cruise_event, sm, now_ns) if request is None else None
|
||||
if self.set_speed_rule and cruise_event is not None and request is None:
|
||||
self._command_receipt(cruise_event, sm, now_ns)
|
||||
action, adopt, action_id = self._action(request, now_ns)
|
||||
if cruise_event is not None and request is None:
|
||||
action, adopt, action_id = self._physical_action(cruise_event, sm, now_ns)
|
||||
@@ -503,6 +568,16 @@ class Runtime:
|
||||
wheel_since = cruise_event.wheel_override_since_ns
|
||||
frame = self._frame(sm, CP, now_ns, now_boot_ns, action, adopt, classified, wheel_override_blocked=wheel_override_blocked)
|
||||
frame = replace(frame, confirmation_grace_ns=confirmation_grace_ns, wheel_override_since_ns=wheel_since)
|
||||
if self.set_speed_rule:
|
||||
# A written SET is felt at once, so automatic adoption waits and a new source must hold before it counts. An early
|
||||
# Maps preview is offered the chosen number of seconds ahead, so it is adopted when offered, without the wait.
|
||||
wait = 0 if frame.confirmation_started_ns is not None else acc.AUTOMATIC_ADOPTION_NS
|
||||
frame = replace(frame, set_speed_rule=True, set_speed_ready=self._set_speed_ready(sm),
|
||||
acceptance_policy=replace(frame.acceptance_policy, automatic_adoption_ns=wait,
|
||||
source_switch_ns=acc.SOURCE_SWITCH_NS))
|
||||
if frame.preview_reverted and self.state.override is not None:
|
||||
# The withdrawn preview's SET is no longer the accepted limit's own value.
|
||||
self.state = replace(self.state, override=replace(self.state.override, applied_selected_mps=None))
|
||||
result = comp.step(self.state, frame)
|
||||
self.state = result.state
|
||||
self.advance.observe(result)
|
||||
@@ -529,6 +604,7 @@ class Runtime:
|
||||
self.ledger = action_result.state
|
||||
completed = arb.step(self.ledger, arb.CompleteAction(self.session_id, action_id), now_ns=now_ns)
|
||||
self.ledger = completed.state
|
||||
command = self._command(result, frame, sm, now_ns, old_pending, action, adopt) if self.set_speed_rule else None
|
||||
result = replace(result, state=self.state)
|
||||
message = self._message(now_ns, result, sm, frame)
|
||||
if action_result is not None and action_result.status == 'resolved':
|
||||
@@ -542,7 +618,86 @@ class Runtime:
|
||||
receipt = self._ui_receipt
|
||||
if receipt is not None:
|
||||
message.slcState.actionSequenceId, message.slcState.actionStatus = receipt
|
||||
return Output(result, message, action_result)
|
||||
return Output(result, message, action_result, command)
|
||||
|
||||
def _command(self, result: comp.Result, frame: comp.Frame, sm, now_ns: int, old_pending: acc.PendingDecision | None,
|
||||
action: acc.DriverAction | None, adopt: acc.AdoptRequest | None):
|
||||
"""Ask card to write the accepted limit plus offset into SET: once per accepted limit, again after an explicit
|
||||
adopt, and again while an unanswered or refused command still finds SET where it was."""
|
||||
decision = result.acceptance
|
||||
override = result.state.override
|
||||
if result.errors or decision is None or override is None:
|
||||
return None
|
||||
accepted = decision.state.accepted
|
||||
if (decision.state.pending is not None and self.commanded_acceptance == accepted and
|
||||
self.command_status in ('issued', 'expired', 'rejected')):
|
||||
# Another candidate interrupted this command; only a new acceptance or an explicit adopt may issue again.
|
||||
self.command_interrupted = True
|
||||
current = result.selection.observation.candidate if result.selection is not None else None
|
||||
if (decision.basis not in ('accepted', 'driver_accept', 'driver_adopt') or accepted is None or
|
||||
decision.state.pending is not None or decision.authority is None or not decision.authority.can_control or
|
||||
result.coordinate is None or result.domain is None or result.domain.context is None or current is None or
|
||||
current.speed_mps != accepted.candidate.speed_mps or override.persistent_selected_mps is not None):
|
||||
return None
|
||||
# An accepted early Maps preview (Adopt limits early) is written like any accepted limit. If it is withdrawn before
|
||||
# the car reaches it, acceptance returns to the road's limit, which is then a different acceptance and is written back.
|
||||
target = result.domain.context.effective_cluster_mps
|
||||
selected_kph = float(sm['carState'].vCruise)
|
||||
if (not acc.number(selected_kph, positive=True) or selected_kph >= 255 or
|
||||
not V_CRUISE_MIN / 3.6 <= target <= V_CRUISE_MAX / 3.6):
|
||||
return None
|
||||
if sd.set_speed_matches(target, selected_kph, float(sm['carState'].vCruiseCluster), self.is_metric):
|
||||
if not self._set_speed_ready(sm):
|
||||
return None
|
||||
self.commanded_acceptance = accepted
|
||||
self.command_status = 'applied'
|
||||
self.state = replace(self.state, override=replace(override, applied_selected_mps=selected_kph / 3.6))
|
||||
return None
|
||||
if (self.commanded_acceptance == accepted and ov.explicit_adoption(decision) is None and
|
||||
(self.command_interrupted or self.command_status in ('issued', 'applied') or
|
||||
abs(selected_kph / 3.6 - self.command_expected_mps) > 0.1)):
|
||||
return None
|
||||
source = result.selection.selected_source
|
||||
evidence = sm['slcDashboardObservation']
|
||||
expiry = now_ns + int(2e9 / SERVICE_LIST['slcState'].frequency)
|
||||
if source is sel.Source.VISION:
|
||||
evidence = sm['slcVisionObservation'].vision
|
||||
if source in (sel.Source.DASHBOARD, sel.Source.VISION):
|
||||
expiry = min(expiry, int(evidence.validUntilMonoTime))
|
||||
if expiry <= now_ns:
|
||||
return None
|
||||
self.commanded_acceptance = accepted
|
||||
self.last_command_id += 1
|
||||
self.command_status = 'issued'
|
||||
self.command_interrupted = False
|
||||
self.command_issued_ns = now_ns
|
||||
self.command_expiry_ns = expiry
|
||||
self.set_speed_after_ns = max(self.set_speed_after_ns, expiry)
|
||||
self.command_expected_mps = selected_kph / 3.6
|
||||
self.command_target_mps = target
|
||||
self.command_card_producer = str(sm['slcDashboardObservation'].producerSessionId)
|
||||
command = messaging.new_message('slcCruiseCommand')
|
||||
command.valid = True
|
||||
command.logMonoTime = now_ns
|
||||
record = command.slcCruiseCommand
|
||||
record.kind = 'adoptAcceptedLimit'
|
||||
record.source = source.value
|
||||
record.sessionId = self.session_id
|
||||
record.commandId = self.last_command_id
|
||||
record.actionId = action.sequence_id if action is not None else adopt.sequence_id if adopt is not None else 0
|
||||
record.decisionId = old_pending.decision_id if old_pending is not None else 0
|
||||
shown = self.state.acceptance.presentation
|
||||
record.presentationId = shown.presentation_id if shown is not None else 0
|
||||
if source in (sel.Source.DASHBOARD, sel.Source.VISION):
|
||||
record.sourceProducerSessionId = str(evidence.producerSessionId)
|
||||
record.sourceEpisode = int(evidence.episode)
|
||||
record.sourceObservedMonoTime = int(evidence.observedMonoTime)
|
||||
record.sourceValidUntilMonoTime = int(evidence.validUntilMonoTime)
|
||||
record.issuedMonoTime = now_ns
|
||||
record.expiresMonoTime = expiry
|
||||
record.expectedSelectedMps = selected_kph / 3.6
|
||||
record.targetMps = target
|
||||
return command
|
||||
|
||||
def _message(self, now_ns: int, result: comp.Result, sm, frame: comp.Frame):
|
||||
message = messaging.new_message("slcState")
|
||||
@@ -593,6 +748,10 @@ class Runtime:
|
||||
state.hasCeiling = True
|
||||
state.effectiveCap = result.ceiling.speed_mps
|
||||
state.isLimitingMaxSet = context is not None and sd.limit_caps_set(context, self.is_metric)
|
||||
elif self.set_speed_rule and context is not None and accepted is not None:
|
||||
# No cap is published; the limit is in use while SET is the value card writes for it.
|
||||
state.isLimitingMaxSet = sd.set_speed_matches(context.effective_cluster_mps, frame.host.driver_v_cruise_kph,
|
||||
frame.host.selected_cluster_kph, self.is_metric)
|
||||
pending = result.state.acceptance.pending
|
||||
# Only an already-captured response can finish an expired presentation.
|
||||
if pending is not None and not pending.automatic and pending.active_elapsed_ns >= acc.CONFIRMATION_NS:
|
||||
@@ -606,9 +765,17 @@ class Runtime:
|
||||
state.pendingSinceMonoTime = now_ns - pending.active_elapsed_ns
|
||||
wheel_active = result.coordinate is not None and result.coordinate.basis == 'wheel'
|
||||
state.wheelOverrideSince = result.state.wheel_override_since_ns if not result.errors else 0
|
||||
state.driverOverrideActive = wheel_active or result.ceiling is not None and result.state.pedal_target_mps > 0.
|
||||
state.overrideBasis = 'wheel' if wheel_active else (
|
||||
('pedal' if frame.pedal_pressed else 'persistent') if state.driverOverrideActive else 'none')
|
||||
if self.set_speed_rule and result.state.override is not None:
|
||||
# An override here is the driver's own held SET; the accelerator never makes one.
|
||||
state.driverOverrideActive = result.state.override.persistent_selected_mps is not None
|
||||
state.overrideBasis = 'persistent' if state.driverOverrideActive else 'none'
|
||||
state.retainedOverride = state.driverOverrideActive
|
||||
state.commandId = self.last_command_id
|
||||
state.commandStatus = self.command_status
|
||||
else:
|
||||
state.driverOverrideActive = wheel_active or result.ceiling is not None and result.state.pedal_target_mps > 0.
|
||||
state.overrideBasis = 'wheel' if wheel_active else (
|
||||
('pedal' if frame.pedal_pressed else 'persistent') if state.driverOverrideActive else 'none')
|
||||
shown = result.state.acceptance.presentation
|
||||
ego = frame.ego_pair
|
||||
ego_delta = ego.delta_mps if ego.status is sd.DomainStatus.VALID else 0.0
|
||||
|
||||
@@ -47,6 +47,9 @@ class Settings:
|
||||
advance_lower_seconds: int = 0
|
||||
pedal_override: PedalOverride = PedalOverride.OFF
|
||||
wheel_override: bool = False
|
||||
# Tesla set-speed rule: SLC writes SET on this car (Comma can set speed on Tesla dashboard is on). The planner host
|
||||
# reads the switch; nothing saved under SLC's own keys sets it.
|
||||
set_speed_rule: bool = False
|
||||
|
||||
|
||||
def _bool(values: Mapping[str, object], key: str, default: bool = False) -> bool:
|
||||
|
||||
@@ -227,3 +227,14 @@ def to_planner_coordinate(context: DomainContext, *, override_mps: float = 0.) -
|
||||
if not acc.number(cap, positive=True):
|
||||
return PlannerCoordinate(None, "nonpositive", cluster_target, context.ego_delta_mps)
|
||||
return PlannerCoordinate(cap, 'none', cluster_target, context.ego_delta_mps)
|
||||
|
||||
|
||||
def override_planner_coordinate(context: DomainContext, held_raw_mps: float | None) -> PlannerCoordinate:
|
||||
"""Where SLC writes SET, cruise targets SET itself: the limit plus offset, or the SET the driver holds instead."""
|
||||
if not context_is_valid(context) or (held_raw_mps is not None and not acc.number(held_raw_mps, positive=True)):
|
||||
return PlannerCoordinate(None, "invalid")
|
||||
cluster_target = context.effective_cluster_mps if held_raw_mps is None else held_raw_mps + context.selected_delta_mps
|
||||
cap = cluster_target - context.ego_delta_mps
|
||||
if not acc.number(cap, positive=True):
|
||||
return PlannerCoordinate(None, "nonpositive", cluster_target, context.ego_delta_mps)
|
||||
return PlannerCoordinate(cap, 'none' if held_raw_mps is None else 'persistent', cluster_target, context.ego_delta_mps)
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
"""Card side of the Tesla set-speed rule: the saved switch decides who owns SET, and SLC's qualified commands become
|
||||
software SET.
|
||||
|
||||
Only a Model 3/Y selected by opendbc.car.tesla.speed_sync gets a receiver or reads the switch. Every other car has
|
||||
neither, so nothing here subscribes, reads or writes for it.
|
||||
"""
|
||||
import math
|
||||
from collections import deque
|
||||
|
||||
from opendbc.car.tesla.speed_sync import selected
|
||||
from openpilot.cereal import messaging
|
||||
from openpilot.common.constants import CV
|
||||
from openpilot.selfdrive.car.cruise import slc_target_kph
|
||||
from openpilot.starpilot.car.tesla import set_speed
|
||||
from openpilot.starpilot.saved_source import read_saved
|
||||
from openpilot.starpilot.speed_limits import physical_actions
|
||||
from openpilot.starpilot.speed_limits.runtime_settings import PEDAL_OVERRIDE_KEY, PedalOverride
|
||||
|
||||
PEDAL_HOLD = str(int(PedalOverride.SPEED_REACHED)).encode()
|
||||
|
||||
|
||||
class Receiver:
|
||||
def __init__(self, sock):
|
||||
self.sock = sock
|
||||
self.commands = deque(maxlen=8)
|
||||
self.session = ''
|
||||
self.last_id = 0
|
||||
self.pedal_peak_mps = 0. # the highest speed reached during this accelerator press
|
||||
|
||||
|
||||
def refresh(card) -> None:
|
||||
"""Follow the saved switch (card's settings thread, once a second). SET changes owner at once: it is the car's own
|
||||
set speed on that frame either way, so nothing jumps."""
|
||||
if selected(card.CP):
|
||||
card.v_cruise_helper.tesla_set_speed = set_speed.active(card.params, card.CP)
|
||||
# After an accelerator override: card applies "Hold the speed you reached", because card owns SET here.
|
||||
card.v_cruise_helper.tesla_pedal_hold = read_saved(card.params, PEDAL_OVERRIDE_KEY, 1) == (PEDAL_HOLD, True)
|
||||
|
||||
|
||||
def attach(card) -> Receiver | None:
|
||||
"""Read the switch, and return the command receiver for a car where SLC may write SET, else None."""
|
||||
refresh(card)
|
||||
if not (card.slc_transport_available and selected(card.CP)):
|
||||
return None
|
||||
return Receiver(messaging.sub_sock('slcCruiseCommand', conflate=False))
|
||||
|
||||
|
||||
def rule(card) -> bool:
|
||||
"""SLC writes SET on this car now."""
|
||||
return bool(getattr(card, 'slc_set_speed', None) is not None and card.v_cruise_helper.tesla_set_speed)
|
||||
|
||||
|
||||
def pedal_hold(card, CS, now_ns: int) -> bool:
|
||||
"""After an accelerator override, Hold the speed you reached: on lifting off, the highest speed reached above SET
|
||||
becomes SET as the driver's own change, so SLC holds it until the limit changes, as it does a scroll. The other two
|
||||
choices return to SET, which is the limit plus offset or the speed the driver scrolled to."""
|
||||
receiver, helper = card.slc_set_speed, card.v_cruise_helper
|
||||
speed = float(CS.vEgoCluster) if CS.vEgoCluster > 0 else float(CS.vEgo)
|
||||
if not (helper.tesla_pedal_hold and helper.slc_pcm and helper.v_cruise_initialized and CS.cruiseState.enabled and
|
||||
CS.canValid and not CS.canTimeout and not CS.standstill and math.isfinite(speed)):
|
||||
receiver.pedal_peak_mps = 0.
|
||||
return False
|
||||
if CS.gasPressed:
|
||||
receiver.pedal_peak_mps = max(receiver.pedal_peak_mps, speed)
|
||||
return False
|
||||
peak, receiver.pedal_peak_mps = receiver.pedal_peak_mps, 0.
|
||||
previous_kph = float(helper.v_cruise_kph)
|
||||
unit = 1. if card.is_metric else CV.MPH_TO_KPH
|
||||
# An override of the limit: SLC has an accepted limit in force and the speed reached is above it.
|
||||
limit = physical_actions.accepted_target(card.sm, now_ns)
|
||||
# Compare as shown: SET moves only when the speed reached rounds to a higher whole unit.
|
||||
if (peak <= 0. or limit is None or peak <= limit or
|
||||
round(slc_target_kph(peak, card.is_metric) / unit) <= round(previous_kph / unit)):
|
||||
return False
|
||||
helper.apply_slc_target(peak, card.is_metric)
|
||||
card.slc_receipts.append(('driverChange', (previous_kph / 3.6, float(helper.v_cruise_kph / 3.6), 'accel', False),
|
||||
previous_kph / 3.6, float(helper.v_cruise_kph / 3.6), now_ns))
|
||||
return True
|
||||
|
||||
|
||||
def apply_commands(card, CS, observation, now_ns: int, *, long_active: bool, after_ns: int = 0) -> None:
|
||||
"""Write each new qualified command's target into software SET and answer it with a receipt."""
|
||||
receiver = getattr(card, 'slc_set_speed', None)
|
||||
if receiver is None:
|
||||
return
|
||||
helper = card.v_cruise_helper
|
||||
for _ in range(8):
|
||||
message = messaging.recv_one_or_none(receiver.sock)
|
||||
if message is None:
|
||||
break
|
||||
if card.slc_replay and message.valid:
|
||||
receiver.commands.append(message)
|
||||
if not helper.tesla_set_speed:
|
||||
receiver.commands.clear() # the switch is off: the car owns SET
|
||||
receiver.pedal_peak_mps = 0.
|
||||
return
|
||||
held = pedal_hold(card, CS, now_ns)
|
||||
for _ in range(len(receiver.commands)):
|
||||
message = receiver.commands.popleft()
|
||||
command = message.slcCruiseCommand
|
||||
issued, expires = int(command.issuedMonoTime), int(command.expiresMonoTime)
|
||||
if issued <= after_ns:
|
||||
continue # issued before the SLC settings last changed
|
||||
if now_ns < issued:
|
||||
if now_ns <= expires:
|
||||
receiver.commands.append(message)
|
||||
continue
|
||||
state = physical_actions.state_current(card.sm, observation, card.slc_producer_session, now_ns)
|
||||
# Wait for the planner state published with this command.
|
||||
if (state is None or int(card.sm.logMonoTime['slcState']) < issued) and now_ns < expires:
|
||||
receiver.commands.append(message)
|
||||
continue
|
||||
if state is not None and str(state.sessionId) != receiver.session:
|
||||
receiver.session, receiver.last_id = str(state.sessionId), 0
|
||||
if not receiver.session:
|
||||
receiver.session = str(command.sessionId)
|
||||
if str(command.sessionId) != receiver.session or int(command.commandId) <= receiver.last_id:
|
||||
continue
|
||||
receiver.last_id = int(command.commandId)
|
||||
previous_mps = float(helper.v_cruise_kph / 3.6)
|
||||
# The driver's own SET change in this frame wins; the planner sees it and decides again.
|
||||
driver_input = held or helper.slc_cruise_change is not None or len(CS.buttonEvents) > 0 or any(helper.button_timers.values())
|
||||
applicable = physical_actions.command_applicable(
|
||||
command, state, observation, card.slc_producer_session, now_ns, previous_mps,
|
||||
long_active=long_active, button_event=driver_input)
|
||||
if applicable:
|
||||
helper.apply_slc_target(float(command.targetMps), card.is_metric)
|
||||
card.slc_receipts.append(('commandApplied' if applicable else 'commandRejected', command,
|
||||
previous_mps, float(helper.v_cruise_kph / 3.6), now_ns))
|
||||
|
||||
|
||||
def write_receipt(record, kind: str, detail) -> None:
|
||||
"""Card's answer to a command; the runtime matches it to the one it issued."""
|
||||
if kind in ('commandApplied', 'commandRejected'):
|
||||
record.sessionId = str(detail.sessionId)
|
||||
record.commandId = int(detail.commandId)
|
||||
record.decisionId = int(detail.decisionId)
|
||||
record.presentationId = int(detail.presentationId)
|
||||
@@ -0,0 +1,395 @@
|
||||
"""Tesla set-speed rule: a held SET needs the acceptance decision and the causal ledger together."""
|
||||
|
||||
import unittest
|
||||
from dataclasses import replace
|
||||
|
||||
from openpilot.starpilot.speed_limits import acceptance as acc
|
||||
from openpilot.starpilot.speed_limits import action_arbitration as arb
|
||||
from openpilot.starpilot.speed_limits import overrides as ov
|
||||
|
||||
SESSION = "drive"
|
||||
HIGH = acc.Candidate("dashboard", acc.ObservationIdentity(acc.IdentityKind.SESSION_VALUE, session_id=SESSION), 20.0)
|
||||
LOW = acc.Candidate("map", acc.ObservationIdentity(acc.IdentityKind.GEOGRAPHIC, value="road-2"), 15.0)
|
||||
SAME = acc.Candidate("map", acc.ObservationIdentity(acc.IdentityKind.GEOGRAPHIC, value="road-3"), 20.0)
|
||||
ACTIVE = acc.Authority(acc.Mode.LONGITUDINAL_ONLY, acc.LongitudinalOwner.SYSTEM, False, True, False, False)
|
||||
# The rule's policy: automatic adoption waits 3 s and another source must hold 2 s (the Policy defaults are 0).
|
||||
POLICY = acc.Policy(confirm_lower=False, confirm_higher=False, automatic_adoption_ns=acc.AUTOMATIC_ADOPTION_NS,
|
||||
source_switch_ns=acc.SOURCE_SWITCH_NS)
|
||||
PEDAL_OFF = ov.PedalEvidence(ov.EvidenceKind.VALID, False)
|
||||
PAUSE_NS = 750_000_000
|
||||
|
||||
|
||||
def observation(candidate=HIGH):
|
||||
return acc.Observation(acc.ObservationKind.VALID, candidate)
|
||||
|
||||
|
||||
def rule(decision):
|
||||
# As composition does on the rule: a source gap carries no control target.
|
||||
if decision.control_target_mps is not None and decision.state.observation.kind is not acc.ObservationKind.VALID:
|
||||
return replace(decision, control_target_mps=None)
|
||||
return decision
|
||||
|
||||
|
||||
class OverrideTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
state = replace(acc.new_session(SESSION, acc.AcceptedLimit(HIGH, SESSION, 0)), received_speed_mps=HIGH.speed_mps)
|
||||
self.accepted = acc.step(state, observation(), ACTIVE, POLICY, now_ns=0)
|
||||
self.state = ov.new_session(SESSION)
|
||||
self.selected = ov.SelectedEvidence(ov.EvidenceKind.VALID, 20.0)
|
||||
self.first = self.reduce(0)
|
||||
|
||||
def decision(self, now, *, candidate=HIGH, authority=ACTIVE, policy=POLICY, source=None, adopt=None):
|
||||
obs = observation(candidate) if source is None else acc.Observation(source)
|
||||
result = rule(acc.step(self.accepted.state, obs, authority, policy, now_ns=now, adopt=adopt))
|
||||
self.accepted = result
|
||||
return result
|
||||
|
||||
def reduce(self, now, *, acceptance=None, authority=ACTIVE, policy=POLICY, selected=None, pedal=PEDAL_OFF, change=None):
|
||||
result = ov.step(self.state, self.accepted if acceptance is None else acceptance, authority, policy,
|
||||
self.selected if selected is None else selected, pedal, now_ns=now, change=change)
|
||||
self.state = result.state
|
||||
return result
|
||||
|
||||
def classified(self, *, effect=1, now=2, previous=20.0, chosen=25.0, context=None, disposition=arb.Disposition.DRIVER_INTENT):
|
||||
ledger = arb.new_ledger(SESSION)
|
||||
context = self.first.context if context is None else context
|
||||
ledger = arb.step(ledger, arb.BeginAction(SESSION, 1, arb.Origin.DRIVER_CRUISE, context.context_id), now_ns=1).state
|
||||
ledger = arb.step(ledger, arb.ResolveAction(SESSION, 1, disposition), now_ns=1).state
|
||||
result = arb.step(ledger, arb.CruiseChange(SESSION, effect, 1, previous, chosen), now_ns=now)
|
||||
return result.change
|
||||
|
||||
def arm(self, now=2, chosen=25.0):
|
||||
change = self.classified(now=now, chosen=chosen)
|
||||
self.decision(now)
|
||||
return self.reduce(now, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, chosen), change=change)
|
||||
|
||||
def test_fresh_causal_intent_persists_and_scalar_does_not_rearm(self):
|
||||
armed = self.arm()
|
||||
self.assertEqual(armed.contribution_mps, 25.0)
|
||||
self.assertEqual(armed.event_receipt.status, "driver_intent")
|
||||
self.assertTrue(armed.event_receipt.consumed)
|
||||
self.decision(3)
|
||||
self.assertEqual(self.reduce(3, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0)).contribution_mps, 25.0)
|
||||
self.decision(4, candidate=replace(LOW, source=HIGH.source))
|
||||
# Automatic adoption waits AUTOMATIC_ADOPTION_NS on the rule.
|
||||
self.assertEqual(self.reduce(4, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0)).contribution_mps, 25.)
|
||||
self.decision(4 + acc.AUTOMATIC_ADOPTION_NS, candidate=replace(LOW, source=HIGH.source))
|
||||
self.assertIsNone(self.reduce(4 + acc.AUTOMATIC_ADOPTION_NS, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0)).contribution_mps)
|
||||
self.decision(5 + acc.AUTOMATIC_ADOPTION_NS, candidate=LOW)
|
||||
self.assertIsNone(self.reduce(5 + acc.AUTOMATIC_ADOPTION_NS, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0)).contribution_mps)
|
||||
|
||||
def test_decrease_only_reduces_an_existing_override(self):
|
||||
for existing, previous, chosen, expected in (
|
||||
(False, 30.0, 29.0, 29.0), (False, 30.0, 20.0, None), (False, 30.0, 19.0, 19.0),
|
||||
(True, 25.0, 24.0, 24.0), (True, 25.0, 20.0, None), (True, 25.0, 19.0, 19.0),
|
||||
(True, 30.0, 29.0, 29.0), (True, 30.0, 25.0, 25.0),
|
||||
):
|
||||
with self.subTest(existing=existing, chosen=chosen):
|
||||
self.setUp()
|
||||
if existing:
|
||||
self.arm()
|
||||
self.decision(2)
|
||||
self.reduce(2, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, previous))
|
||||
self.decision(3)
|
||||
result = self.reduce(3, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, chosen),
|
||||
change=self.classified(effect=2, now=3, previous=previous, chosen=chosen))
|
||||
self.assertFalse(result.errors)
|
||||
self.assertTrue(result.event_receipt.consumed)
|
||||
self.assertEqual(result.state.persistent_selected_mps, expected)
|
||||
self.assertEqual(result.contribution_mps, expected)
|
||||
self.assertEqual(self.accepted.control_target_mps, HIGH.speed_mps)
|
||||
|
||||
def test_manual_raise_survives_higher_limit_below_it_but_lower_limit_clears(self):
|
||||
self.arm(chosen=25.)
|
||||
self.decision(3, candidate=SAME)
|
||||
self.assertEqual(self.reduce(3, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.)).contribution_mps, 25.)
|
||||
mid = replace(SAME, speed_mps=22.)
|
||||
self.decision(4, candidate=mid)
|
||||
self.assertEqual(self.reduce(4, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.)).contribution_mps, 25.)
|
||||
self.decision(3_000_000_004, candidate=mid)
|
||||
self.assertEqual(self.reduce(3_000_000_004, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.)).contribution_mps, 25.)
|
||||
self.decision(3_000_000_005, candidate=LOW)
|
||||
self.reduce(3_000_000_005, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.))
|
||||
self.decision(6_000_000_005, candidate=LOW)
|
||||
self.assertIsNone(self.reduce(6_000_000_005, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.)).contribution_mps)
|
||||
|
||||
def test_pedal_tracks_current_ego_and_release_restores_persistence(self):
|
||||
self.arm()
|
||||
self.decision(3)
|
||||
self.assertEqual(self.reduce(3, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0),
|
||||
pedal=ov.PedalEvidence(ov.EvidenceKind.VALID, True, 28.0)).contribution_mps, 25.0)
|
||||
self.decision(4)
|
||||
self.assertEqual(self.reduce(4, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0),
|
||||
pedal=ov.PedalEvidence(ov.EvidenceKind.VALID, True, 23.0)).contribution_mps, 25.0)
|
||||
self.decision(5)
|
||||
self.assertEqual(self.reduce(5, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0)).contribution_mps, 25.0)
|
||||
|
||||
def test_temporary_inactivity_invalidates_origin_and_grace_expires(self):
|
||||
self.arm()
|
||||
paused = replace(ACTIVE, longitudinal_active=False)
|
||||
self.decision(3, authority=paused)
|
||||
self.assertIsNone(self.reduce(3, authority=paused, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0)).context)
|
||||
self.decision(3 + PAUSE_NS - 1, authority=paused)
|
||||
self.reduce(3 + PAUSE_NS - 1, authority=paused, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0))
|
||||
self.decision(3 + PAUSE_NS - 1)
|
||||
resumed = self.reduce(3 + PAUSE_NS - 1, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0))
|
||||
self.assertEqual(resumed.contribution_mps, 25.0)
|
||||
self.assertNotEqual(resumed.context.context_id, self.first.context.context_id)
|
||||
self.decision(PAUSE_NS + 10, authority=paused)
|
||||
self.reduce(PAUSE_NS + 10, authority=paused, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0))
|
||||
self.decision(2 * PAUSE_NS + 10)
|
||||
self.assertEqual(self.reduce(2 * PAUSE_NS + 10, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0)).contribution_mps, 25.)
|
||||
|
||||
def test_stale_missing_and_display_only_suppress_output_and_watermark(self):
|
||||
self.arm()
|
||||
change = self.classified(effect=2, now=3, chosen=26.0)
|
||||
self.decision(3, source=acc.ObservationKind.STALE)
|
||||
stale = self.reduce(3, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 26.0), change=change)
|
||||
self.assertEqual(stale.contribution_mps, 26.)
|
||||
self.assertEqual(stale.state.last_effect_id, 2)
|
||||
self.decision(4)
|
||||
self.assertEqual(self.reduce(4, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0), change=change).event_receipt.status, "already_seen")
|
||||
display = acc.Policy(confirm_lower=False, confirm_higher=False, display_only=True)
|
||||
self.decision(5, policy=display)
|
||||
self.assertIsNone(self.reduce(5, policy=display, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0)).contribution_mps)
|
||||
|
||||
def test_source_gaps_preserve_the_manual_choice(self):
|
||||
for kind in (acc.ObservationKind.ABSENT, acc.ObservationKind.UNKNOWN, acc.ObservationKind.STALE):
|
||||
with self.subTest(kind=kind):
|
||||
self.setUp()
|
||||
self.arm()
|
||||
self.decision(3, source=kind)
|
||||
result = self.reduce(3, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0))
|
||||
self.assertEqual(result.contribution_mps, 25.0)
|
||||
self.assertEqual(result.context, self.first.context)
|
||||
|
||||
def test_delayed_acceptance_consumed_effect_cannot_arm_after_release(self):
|
||||
pending_policy = acc.Policy(confirm_lower=True, confirm_higher=True)
|
||||
state = replace(acc.new_session(SESSION, acc.AcceptedLimit(HIGH, SESSION, 0)), received_speed_mps=HIGH.speed_mps)
|
||||
pending = acc.step(state, observation(LOW), ACTIVE, pending_policy, now_ns=0)
|
||||
action = acc.DriverAction(SESSION, 1, pending.state.pending.decision_id, acc.ActionKind.ACCEPT)
|
||||
ledger = arb.step(arb.new_ledger(SESSION), arb.BeginAction(SESSION, 1, arb.Origin.DRIVER_CRUISE,
|
||||
self.first.context.context_id), now_ns=1).state
|
||||
accepted = acc.step(pending.state, observation(LOW), ACTIVE, pending_policy, now_ns=2, action=action)
|
||||
ledger = arb.resolve_acceptance(ledger, 1, accepted, now_ns=2).state
|
||||
delayed = arb.step(ledger, arb.CruiseChange(SESSION, 1, 1, 20.0, 25.0), now_ns=60_000_000_000).change
|
||||
self.assertEqual(delayed.disposition, arb.Disposition.SLC_CONSUMED)
|
||||
self.decision(60_000_000_000)
|
||||
result = self.reduce(60_000_000_000, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0), change=delayed)
|
||||
self.assertIsNone(result.contribution_mps)
|
||||
self.assertEqual(result.state.last_effect_id, 1)
|
||||
|
||||
def test_adoption_clears_once_and_current_pedal_still_contributes(self):
|
||||
self.arm()
|
||||
shown = self.decision(3, candidate=LOW)
|
||||
adopt = acc.AdoptRequest(SESSION, 2, shown.state.presentation.presentation_id, LOW)
|
||||
adopted = self.decision(4, candidate=LOW, adopt=adopt)
|
||||
result = self.reduce(4, acceptance=adopted, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0),
|
||||
pedal=ov.PedalEvidence(ov.EvidenceKind.VALID, True, 27.0))
|
||||
self.assertIsNone(result.state.persistent_selected_mps)
|
||||
self.assertIsNone(result.contribution_mps)
|
||||
self.assertNotEqual(result.context.context_id, self.first.context.context_id)
|
||||
duplicate = self.reduce(4, acceptance=adopted, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0))
|
||||
self.assertEqual(duplicate.context, result.context)
|
||||
|
||||
def test_mismatched_snapshot_and_inactive_origin_fail_closed(self):
|
||||
change = self.classified()
|
||||
self.decision(2)
|
||||
mismatch = self.reduce(2, policy=replace(POLICY, confirm_lower=True), change=change)
|
||||
self.assertTrue(mismatch.errors)
|
||||
self.assertEqual(mismatch.state.last_effect_id, 1)
|
||||
self.assertTrue(mismatch.state.reset_required)
|
||||
self.decision(3)
|
||||
self.assertIsNone(self.reduce(3).context)
|
||||
self.state = ov.new_session(SESSION)
|
||||
old = self.reduce(3).context
|
||||
paused = replace(ACTIVE, longitudinal_active=False)
|
||||
self.decision(4, authority=paused)
|
||||
self.reduce(4, authority=paused)
|
||||
self.decision(5)
|
||||
late = replace(change, effect_id=2, context_id=old.context_id, started_at_ns=4)
|
||||
result = self.reduce(5, change=late, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0))
|
||||
self.assertIsNone(result.contribution_mps)
|
||||
self.assertEqual(result.event_receipt.status, "unqualified_effect")
|
||||
|
||||
def test_pending_lower_and_rejection_keep_accepted_target_and_intent(self):
|
||||
self.arm()
|
||||
confirmation = acc.Policy(confirm_lower=True, confirm_higher=True)
|
||||
lower = replace(LOW, source=HIGH.source)
|
||||
pending = self.decision(3, candidate=lower, policy=confirmation)
|
||||
self.assertEqual(pending.basis, "pending")
|
||||
self.assertEqual(self.reduce(3, policy=confirmation, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0)).contribution_mps, 25.0)
|
||||
action = acc.DriverAction(SESSION, 2, pending.state.pending.decision_id, acc.ActionKind.REJECT)
|
||||
rejected = acc.step(pending.state, observation(lower), ACTIVE, confirmation, now_ns=4, action=action)
|
||||
self.accepted = rejected
|
||||
self.assertEqual(self.reduce(4, policy=confirmation, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0)).contribution_mps, 25.0)
|
||||
self.assertEqual(rejected.state.rejected, lower)
|
||||
|
||||
def test_provider_flapping_preserves_override_until_the_new_limit_qualifies(self):
|
||||
self.arm()
|
||||
for now, candidate in ((3, LOW), (4, HIGH), (5, LOW)):
|
||||
self.decision(now, candidate=candidate)
|
||||
retained = self.reduce(now, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.))
|
||||
self.assertEqual(retained.contribution_mps, 25.)
|
||||
now = 5 + acc.SOURCE_SWITCH_NS
|
||||
self.decision(now, candidate=LOW)
|
||||
now += acc.AUTOMATIC_ADOPTION_NS # then the automatic-adoption wait
|
||||
self.decision(now, candidate=LOW)
|
||||
adopted = self.reduce(now, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.))
|
||||
self.assertIsNone(adopted.contribution_mps)
|
||||
|
||||
def test_mode_owner_change_suppresses_output_without_forgetting_manual_choice(self):
|
||||
self.arm()
|
||||
stock = acc.Authority(acc.Mode.LONGITUDINAL_ONLY, acc.LongitudinalOwner.STOCK, False, False, True, False)
|
||||
self.decision(3, authority=stock)
|
||||
self.reduce(3, authority=stock, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0))
|
||||
self.assertEqual(self.state.persistent_selected_mps, 25.)
|
||||
self.decision(4)
|
||||
self.assertEqual(self.reduce(4, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0)).contribution_mps, 25.)
|
||||
|
||||
def test_previous_session_history_does_not_arm_overrides_without_a_live_limit(self):
|
||||
prior = acc.AcceptedLimit(acc.Candidate("map", acc.ObservationIdentity(acc.IdentityKind.GEOGRAPHIC, value="road"), 20.0),
|
||||
"prior-drive", 0)
|
||||
policy = acc.Policy()
|
||||
decision = rule(acc.step(acc.new_session(SESSION, prior), acc.Observation(acc.ObservationKind.ABSENT), ACTIVE, policy, now_ns=1))
|
||||
result = ov.step(ov.new_session(SESSION), decision, ACTIVE, policy, self.selected, PEDAL_OFF, now_ns=1)
|
||||
self.assertFalse(result.errors)
|
||||
self.assertIsNone(result.context)
|
||||
|
||||
def test_automatic_foreign_and_completed_effects_are_watermarked_without_intent(self):
|
||||
self.decision(2)
|
||||
automatic = replace(self.classified(now=2), disposition=arb.Disposition.AUTOMATIC)
|
||||
got = self.reduce(2, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0), change=automatic)
|
||||
self.assertIsNone(got.contribution_mps)
|
||||
self.assertEqual(got.state.last_effect_id, 1)
|
||||
self.decision(3)
|
||||
foreign = replace(automatic, session_id="other", effect_id=2, disposition=arb.Disposition.DRIVER_INTENT)
|
||||
self.assertEqual(self.reduce(3, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0), change=foreign).event_receipt.status,
|
||||
"foreign_session")
|
||||
self.decision(4)
|
||||
completed = replace(automatic, effect_id=2, action_id=1, context_id=None, disposition=arb.Disposition.UNRESOLVED)
|
||||
result = self.reduce(4, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0), change=completed)
|
||||
self.assertIsNone(result.contribution_mps)
|
||||
self.assertEqual(result.state.last_effect_id, 2)
|
||||
|
||||
def test_inconsistent_acceptance_target_and_reversed_clock_fail_closed(self):
|
||||
self.decision(2)
|
||||
forged = replace(self.accepted, control_target_mps=21.0)
|
||||
bad = self.reduce(2, acceptance=forged)
|
||||
self.assertTrue(bad.errors)
|
||||
self.assertIsNone(bad.contribution_mps)
|
||||
self.assertTrue(bad.state.reset_required)
|
||||
reversed_clock = self.reduce(1)
|
||||
self.assertTrue(reversed_clock.errors)
|
||||
|
||||
def test_zero_ego_speed_is_valid_but_negative_bool_and_nan_are_not(self):
|
||||
self.arm()
|
||||
for now, pressed in ((3, True), (4, False)):
|
||||
self.decision(now)
|
||||
zero = self.reduce(now, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0),
|
||||
pedal=ov.PedalEvidence(ov.EvidenceKind.VALID, pressed, 0.0))
|
||||
self.assertFalse(zero.errors)
|
||||
self.assertEqual(zero.contribution_mps, 25.0)
|
||||
for invalid in (-0.1, True, float("nan")):
|
||||
with self.subTest(invalid=invalid):
|
||||
self.decision(5)
|
||||
bad = ov.step(self.state, self.accepted, ACTIVE, POLICY, ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0),
|
||||
ov.PedalEvidence(ov.EvidenceKind.VALID, True, invalid), now_ns=5)
|
||||
self.assertTrue(bad.errors)
|
||||
self.assertTrue(bad.state.reset_required)
|
||||
|
||||
def test_malformed_effect_latches_session_and_cannot_replay_after_repair(self):
|
||||
self.arm()
|
||||
fresh = self.classified(effect=2, now=4, chosen=26.0)
|
||||
self.decision(3)
|
||||
malformed = replace(fresh, selected_mps=float("nan"))
|
||||
bad = self.reduce(3, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 26.0), change=malformed)
|
||||
self.assertTrue(bad.state.reset_required)
|
||||
self.assertIsNone(bad.state.persistent_selected_mps)
|
||||
self.assertIsNone(bad.state.context)
|
||||
self.decision(4)
|
||||
retry = self.reduce(4, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 26.0), change=fresh)
|
||||
self.assertIsNone(retry.contribution_mps)
|
||||
self.assertEqual(retry.basis, "session_reset_required")
|
||||
next_candidate = acc.Candidate("map", acc.ObservationIdentity(acc.IdentityKind.GEOGRAPHIC, value="new-road"), 20.0)
|
||||
next_acceptance = acc.step(acc.new_session("next-drive"), observation(next_candidate), ACTIVE, POLICY, now_ns=0)
|
||||
next_state = ov.step(ov.new_session("next-drive"), next_acceptance, ACTIVE, POLICY, self.selected, PEDAL_OFF, now_ns=0)
|
||||
next_acceptance = acc.step(next_acceptance.state, observation(next_candidate), ACTIVE, POLICY, now_ns=1)
|
||||
replay = ov.step(next_state.state, next_acceptance, ACTIVE, POLICY, ov.SelectedEvidence(ov.EvidenceKind.VALID, 26.0),
|
||||
PEDAL_OFF, now_ns=1, change=fresh)
|
||||
self.assertIsNone(replay.contribution_mps)
|
||||
self.assertEqual(replay.event_receipt.status, "foreign_session")
|
||||
|
||||
def test_malformed_state_is_inert(self):
|
||||
forged = replace(self.state, context=replace(self.first.context, context_id="caller-proof"))
|
||||
self.decision(2)
|
||||
result = ov.step(forged, self.accepted, ACTIVE, POLICY, self.selected, PEDAL_OFF, now_ns=2)
|
||||
self.assertTrue(result.errors)
|
||||
self.assertIsNone(result.contribution_mps)
|
||||
self.assertIs(result.state, forged)
|
||||
|
||||
def test_reversed_clock_clears_previously_armed_state_and_stays_latched(self):
|
||||
self.arm()
|
||||
bad = self.reduce(1)
|
||||
self.assertTrue(bad.state.reset_required)
|
||||
self.assertIsNone(bad.state.persistent_selected_mps)
|
||||
self.assertIsNone(bad.context)
|
||||
self.decision(3)
|
||||
recovered_input = self.reduce(3)
|
||||
self.assertEqual(recovered_input.basis, "session_reset_required")
|
||||
self.assertIsNone(recovered_input.contribution_mps)
|
||||
|
||||
def test_target_change_requires_new_action_from_the_new_eligible_context(self):
|
||||
self.arm()
|
||||
old_effect = self.classified(effect=2, now=3, chosen=26.0)
|
||||
self.decision(3, candidate=replace(LOW, source=HIGH.source))
|
||||
self.decision(3 + acc.AUTOMATIC_ADOPTION_NS, candidate=replace(LOW, source=HIGH.source))
|
||||
lower = self.reduce(3 + acc.AUTOMATIC_ADOPTION_NS, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 26.0), change=old_effect)
|
||||
self.assertIsNone(lower.contribution_mps)
|
||||
self.assertFalse(lower.event_receipt.consumed)
|
||||
self.assertNotEqual(lower.context, self.first.context)
|
||||
|
||||
ledger = arb.step(arb.new_ledger(SESSION), arb.BeginAction(SESSION, 2, arb.Origin.DRIVER_CRUISE,
|
||||
lower.context.context_id), now_ns=3_000_000_004).state
|
||||
ledger = arb.step(ledger, arb.ResolveAction(SESSION, 2, arb.Disposition.DRIVER_INTENT), now_ns=3_000_000_004).state
|
||||
fresh = arb.step(ledger, arb.CruiseChange(SESSION, 3, 2, 26.0, 27.0), now_ns=3_000_000_005).change
|
||||
self.decision(3_000_000_005, candidate=LOW)
|
||||
rearmed = self.reduce(3_000_000_005, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 27.0), change=fresh)
|
||||
self.assertTrue(rearmed.event_receipt.consumed)
|
||||
self.assertEqual(rearmed.contribution_mps, 27.0)
|
||||
|
||||
def test_missing_selected_or_pedal_evidence_suppresses_output(self):
|
||||
self.arm()
|
||||
for now, selected, pedal in (
|
||||
(3, ov.SelectedEvidence(ov.EvidenceKind.STALE), PEDAL_OFF),
|
||||
(4, ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0), ov.PedalEvidence(ov.EvidenceKind.UNKNOWN)),
|
||||
(5, ov.SelectedEvidence(ov.EvidenceKind.ABSENT), PEDAL_OFF),
|
||||
):
|
||||
self.decision(now)
|
||||
result = self.reduce(now, selected=selected, pedal=pedal)
|
||||
self.assertIsNone(result.contribution_mps)
|
||||
self.assertIsNone(result.context)
|
||||
|
||||
def test_same_value_adoption_rotates_once_and_delayed_effect_is_consumed(self):
|
||||
self.arm()
|
||||
shown = self.decision(3)
|
||||
request = acc.AdoptRequest(SESSION, 2, shown.state.presentation.presentation_id, HIGH)
|
||||
ledger = arb.step(arb.new_ledger(SESSION), arb.BeginAction(SESSION, 2, arb.Origin.DRIVER_CRUISE,
|
||||
self.first.context.context_id), now_ns=3).state
|
||||
adopted = self.decision(4, adopt=request)
|
||||
ledger = arb.resolve_acceptance(ledger, 2, adopted, now_ns=4).state
|
||||
result = self.reduce(4, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0))
|
||||
self.assertIsNone(result.state.persistent_selected_mps)
|
||||
self.assertNotEqual(result.context.context_id, self.first.context.context_id)
|
||||
again = self.reduce(4, acceptance=adopted, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0))
|
||||
self.assertEqual(again.context, result.context)
|
||||
delayed = arb.step(ledger, arb.CruiseChange(SESSION, 3, 2, 25.0, 20.0), now_ns=10_000_000_000).change
|
||||
self.assertEqual(delayed.disposition, arb.Disposition.SLC_CONSUMED)
|
||||
self.decision(10_000_000_000)
|
||||
no_rearm = self.reduce(10_000_000_000, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 20.0), change=delayed)
|
||||
self.assertIsNone(no_rearm.contribution_mps)
|
||||
self.assertEqual(no_rearm.event_receipt.status, "unqualified_effect")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,217 @@
|
||||
"""After an accelerator override, on a Tesla where SLC writes SET (Comma can set speed on Tesla dashboard is on).
|
||||
|
||||
SET there is the limit plus offset, so nothing sits above it for the planner to hold. Card owns SET, so card applies
|
||||
"Hold the speed you reached": on lifting off, the highest speed reached above SET becomes SET as the driver's own
|
||||
change, and SLC holds it until the limit changes, as it does a scroll. The other two choices return to SET.
|
||||
"""
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from opendbc.car.structs import car
|
||||
from openpilot.cereal import messaging
|
||||
from openpilot.common.constants import CV
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.starpilot.speed_limits import tesla_set_speed_card
|
||||
from openpilot.starpilot.speed_limits.runtime import Runtime
|
||||
from openpilot.starpilot.speed_limits.runtime_settings import PEDAL_OVERRIDE_CHOICES, PEDAL_OVERRIDE_KEY, PedalOverride
|
||||
from openpilot.starpilot.speed_limits.tesla_set_speed_card import Receiver, pedal_hold, refresh
|
||||
from openpilot.starpilot.speed_limits.tests.test_runtime_replay import ReplaySM
|
||||
from openpilot.starpilot.speed_limits.tests.test_tesla_set_speed import (AUTOMATIC, START, adopt_automatically, owned_helper, parse,
|
||||
rule_cp, scene, set_change, tick)
|
||||
|
||||
NOW = START + 5_000_000_000
|
||||
|
||||
|
||||
def car_state(speed_kph, *, gas=False, enabled=True, standstill=False, valid=True, cluster=None):
|
||||
state = car.CarState.new_message()
|
||||
state.vEgo = speed_kph / 3.6
|
||||
state.vEgoCluster = (speed_kph if cluster is None else cluster) / 3.6
|
||||
state.gasPressed = gas
|
||||
state.cruiseState.enabled = enabled
|
||||
state.standstill = standstill
|
||||
state.canValid = valid
|
||||
return state
|
||||
|
||||
|
||||
def planner_state(limit_kph):
|
||||
"""What card sees of the planner: SLC live with this accepted limit plus offset in force (None: no limit yet)."""
|
||||
message = messaging.new_message('slcState')
|
||||
state = message.slcState
|
||||
state.enabled, state.sessionId, state.frameMonoTime = True, 'drive', NOW
|
||||
if limit_kph is not None:
|
||||
state.hasAcceptedAdjustedLimit, state.acceptedAdjustedLimit = True, limit_kph / 3.6
|
||||
return ReplaySM({'slcState': state}, NOW)
|
||||
|
||||
|
||||
def make_card(*, set_kph=90., limit_kph=90., metric=True, hold=True, slc=True, switch=True):
|
||||
"""Card as it is with the switch on, SLC live, its limit plus offset at limit_kph and SET at set_kph."""
|
||||
helper = owned_helper(rule_cp(), switch=switch)
|
||||
helper.v_cruise_kph = helper.v_cruise_cluster_kph = set_kph
|
||||
helper.tesla_pedal_hold = hold
|
||||
helper.slc_pcm = bool(slc and switch)
|
||||
return SimpleNamespace(slc_set_speed=Receiver(None), v_cruise_helper=helper, is_metric=metric, slc_receipts=[],
|
||||
sm=planner_state(limit_kph))
|
||||
|
||||
|
||||
def press_and_release(card, speeds_kph, **state):
|
||||
for speed in speeds_kph:
|
||||
assert not pedal_hold(card, car_state(speed, gas=True, **state), NOW)
|
||||
assert card.slc_receipts == [], 'nothing changes while the accelerator is pressed'
|
||||
return pedal_hold(card, car_state(speeds_kph[-1], **state), NOW)
|
||||
|
||||
|
||||
def test_the_choices_are_the_stock_ones():
|
||||
assert PEDAL_OVERRIDE_CHOICES == ('Resume the adjusted limit', 'Hold the speed you reached', 'Use your SET speed')
|
||||
assert tesla_set_speed_card.PEDAL_HOLD == b'1' and int(PedalOverride.SPEED_REACHED) == 1
|
||||
|
||||
|
||||
def test_lifting_off_above_set_makes_the_highest_speed_reached_the_set_speed():
|
||||
card = make_card(set_kph=90.)
|
||||
assert press_and_release(card, [88., 95., 104.4, 101.])
|
||||
assert card.v_cruise_helper.v_cruise_kph == 104. and card.v_cruise_helper.v_cruise_cluster_kph == 104.
|
||||
kind, detail, previous, selected, observed = card.slc_receipts[0]
|
||||
assert kind == 'driverChange' and detail == (pytest.approx(25.), pytest.approx(104 / 3.6), 'accel', False)
|
||||
assert (previous, selected, observed) == (pytest.approx(25.), pytest.approx(104 / 3.6), NOW)
|
||||
assert len(card.slc_receipts) == 1
|
||||
assert not pedal_hold(card, car_state(101.), NOW) and len(card.slc_receipts) == 1, 'once per press'
|
||||
|
||||
|
||||
def test_the_speed_is_rounded_to_the_units_shown():
|
||||
card = make_card(set_kph=60 * CV.MPH_TO_KPH, limit_kph=60 * CV.MPH_TO_KPH, metric=False)
|
||||
assert press_and_release(card, [66.4 * CV.MPH_TO_KPH])
|
||||
assert card.v_cruise_helper.v_cruise_kph == pytest.approx(66 * CV.MPH_TO_KPH, abs=.05)
|
||||
again = make_card(set_kph=60 * CV.MPH_TO_KPH, limit_kph=60 * CV.MPH_TO_KPH, metric=False)
|
||||
assert not press_and_release(again, [60.4 * CV.MPH_TO_KPH]), 'less than half a unit over SET is still SET'
|
||||
assert again.slc_receipts == []
|
||||
|
||||
|
||||
def test_the_dashboard_speed_is_the_speed_reached():
|
||||
card = make_card(set_kph=90.)
|
||||
for speed in (95., 100.):
|
||||
pedal_hold(card, car_state(speed, gas=True, cluster=speed + 2), NOW)
|
||||
assert pedal_hold(card, car_state(100., cluster=102.), NOW) and card.v_cruise_helper.v_cruise_kph == 102.
|
||||
|
||||
|
||||
@pytest.mark.parametrize('speeds', [[60., 80., 89.], [90.4], [0.]])
|
||||
def test_a_press_that_stays_at_or_below_set_changes_nothing(speeds):
|
||||
card = make_card(set_kph=90.)
|
||||
assert not press_and_release(card, speeds)
|
||||
assert card.v_cruise_helper.v_cruise_kph == 90. and card.slc_receipts == []
|
||||
|
||||
|
||||
def test_it_is_an_override_of_the_limit_not_of_a_lower_set_speed():
|
||||
# SET scrolled down to 70 under a 90 limit: 80 is above SET but not above the limit, so lifting off returns to SET.
|
||||
card = make_card(set_kph=70., limit_kph=90.)
|
||||
assert not press_and_release(card, [80.]) and card.v_cruise_helper.v_cruise_kph == 70. and card.slc_receipts == []
|
||||
assert press_and_release(card, [96.]) and card.v_cruise_helper.v_cruise_kph == 96.
|
||||
# SET scrolled up to 100 over the 90 limit: a speed above both becomes the new held SET.
|
||||
above = make_card(set_kph=100., limit_kph=90.)
|
||||
assert not press_and_release(above, [95.]) and press_and_release(above, [108.])
|
||||
assert above.v_cruise_helper.v_cruise_kph == 108.
|
||||
|
||||
|
||||
def test_without_a_limit_in_force_the_accelerator_changes_nothing():
|
||||
card = make_card(set_kph=90., limit_kph=None)
|
||||
assert not press_and_release(card, [100., 110.])
|
||||
assert card.v_cruise_helper.v_cruise_kph == 90. and card.slc_receipts == []
|
||||
stale = make_card(set_kph=90.)
|
||||
stale.sm = ReplaySM({'slcState': stale.sm['slcState']}, NOW + 10_000_000_000) # the planner stopped publishing
|
||||
for speed in (100., 110.):
|
||||
pedal_hold(stale, car_state(speed, gas=True), NOW + 10_000_000_000)
|
||||
assert not pedal_hold(stale, car_state(110.), NOW + 10_000_000_000) and stale.slc_receipts == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize('case', ['another choice', 'SLC off', 'switch off'])
|
||||
def test_only_hold_the_speed_you_reached_with_slc_writing_set(case):
|
||||
card = make_card(hold=case != 'another choice', slc=case != 'SLC off', switch=case != 'switch off')
|
||||
assert not press_and_release(card, [100., 110.])
|
||||
assert card.v_cruise_helper.v_cruise_kph == 90. and card.slc_receipts == []
|
||||
assert card.slc_set_speed.pedal_peak_mps == 0.
|
||||
|
||||
|
||||
@pytest.mark.parametrize('state', [{'enabled': False}, {'standstill': True}, {'valid': False}])
|
||||
def test_a_press_while_cruise_is_off_stopped_or_unreadable_is_forgotten(state):
|
||||
card = make_card()
|
||||
assert not press_and_release(card, [100., 110.], **state)
|
||||
assert card.v_cruise_helper.v_cruise_kph == 90. and card.slc_receipts == []
|
||||
# and it does not carry into a later release
|
||||
assert not pedal_hold(card, car_state(95.), NOW) and card.v_cruise_helper.v_cruise_kph == 90.
|
||||
|
||||
|
||||
def test_the_speed_reached_before_cruise_dropped_does_not_count_after_it_returns():
|
||||
card = make_card()
|
||||
pedal_hold(card, car_state(120., gas=True), NOW)
|
||||
pedal_hold(card, car_state(120., gas=True, enabled=False), NOW)
|
||||
assert press_and_release(card, [96.]) and card.v_cruise_helper.v_cruise_kph == 96.
|
||||
|
||||
|
||||
def test_set_never_goes_above_the_most_cruise_allows():
|
||||
from openpilot.selfdrive.car.cruise import V_CRUISE_MAX
|
||||
card = make_card(set_kph=140., limit_kph=130.)
|
||||
assert press_and_release(card, [V_CRUISE_MAX + 40.])
|
||||
assert card.v_cruise_helper.v_cruise_kph == V_CRUISE_MAX
|
||||
|
||||
|
||||
@pytest.mark.parametrize('saved,expected', [(b'1', True), (b'0', False), (b'2', False), (None, False), (b'x', False)])
|
||||
def test_card_reads_the_saved_choice(tmp_path, saved, expected):
|
||||
params = Params(str(tmp_path))
|
||||
params.put_bool('TeslaSpeedSync', True, block=True)
|
||||
if saved is not None:
|
||||
Path(params.get_param_path(PEDAL_OVERRIDE_KEY)).write_bytes(saved)
|
||||
cp = rule_cp()
|
||||
card = SimpleNamespace(CP=cp, params=params, v_cruise_helper=owned_helper(cp, switch=False))
|
||||
refresh(card)
|
||||
assert card.v_cruise_helper.tesla_set_speed and card.v_cruise_helper.tesla_pedal_hold is expected
|
||||
|
||||
|
||||
def test_another_car_never_gets_the_choice(tmp_path):
|
||||
from openpilot.selfdrive.car.cruise import VCruiseHelper
|
||||
params = Params(str(tmp_path))
|
||||
params.put_bool('TeslaSpeedSync', True, block=True)
|
||||
Path(params.get_param_path(PEDAL_OVERRIDE_KEY)).write_bytes(b'1')
|
||||
cp = rule_cp(admitted=False)
|
||||
card = SimpleNamespace(CP=cp, params=params, v_cruise_helper=VCruiseHelper(cp))
|
||||
refresh(card)
|
||||
assert card.v_cruise_helper.tesla_pedal_hold is False and card.v_cruise_helper.tesla_set_speed is False
|
||||
|
||||
|
||||
def test_a_command_in_the_same_frame_gives_way_to_the_held_speed():
|
||||
from unittest.mock import patch
|
||||
card = make_card(set_kph=90.)
|
||||
card.slc_replay, card.slc_producer_session = True, 'card-producer'
|
||||
pedal_hold(card, car_state(104., gas=True), NOW)
|
||||
command = SimpleNamespace(valid=True, slcCruiseCommand=SimpleNamespace(issuedMonoTime=NOW - 1, expiresMonoTime=NOW + 10**8,
|
||||
sessionId='s', commandId=1, targetMps=25.))
|
||||
state = SimpleNamespace(sessionId='s')
|
||||
seen = {}
|
||||
|
||||
def applicable(command, state, observation, producer, now, previous, *, long_active, button_event):
|
||||
seen['driver'] = button_event
|
||||
return not button_event
|
||||
|
||||
with patch.object(tesla_set_speed_card.messaging, 'recv_one_or_none', side_effect=[command, None]), \
|
||||
patch.object(tesla_set_speed_card.physical_actions, 'state_current', return_value=state), \
|
||||
patch.object(tesla_set_speed_card.physical_actions, 'command_applicable', side_effect=applicable):
|
||||
tesla_set_speed_card.apply_commands(card, car_state(104.), None, NOW, long_active=True)
|
||||
assert seen == {'driver': True} and card.v_cruise_helper.v_cruise_kph == 104.
|
||||
assert [receipt[0] for receipt in card.slc_receipts] == ['driverChange', 'commandRejected']
|
||||
|
||||
|
||||
def test_the_planner_holds_the_speed_reached_until_the_limit_changes():
|
||||
sm, cp = scene(rule_cp())
|
||||
runtime = Runtime(parse(AUTOMATIC), is_metric=True)
|
||||
adopt_automatically(runtime, sm, cp) # the 25 m/s limit, SET 90 km/h
|
||||
card = make_card(set_kph=90.)
|
||||
assert press_and_release(card, [97., 104.])
|
||||
_, detail, previous, selected, _ = card.slc_receipts[0]
|
||||
sm['carState'].vCruise = sm['carState'].vCruiseCluster = card.v_cruise_helper.v_cruise_kph
|
||||
held = tick(runtime, sm, cp, 3.1, cruise_event=set_change(2, 3.1, previous * 3.6, selected * 3.6))
|
||||
assert held.result.override.event_receipt.consumed and detail[2] == 'accel'
|
||||
assert held.message.slcState.driverOverrideActive and held.message.slcState.overrideBasis == 'persistent'
|
||||
assert held.command is None
|
||||
assert all(tick(runtime, sm, cp, 3.2 + n * .05).command is None for n in range(40)), 'SLC leaves the held speed alone'
|
||||
sm['slcDashboardObservation'].speedMps = 18.
|
||||
tick(runtime, sm, cp, 5.3)
|
||||
adopted = tick(runtime, sm, cp, 8.4)
|
||||
assert adopted.command.slcCruiseCommand.targetMps == pytest.approx(18.) and not adopted.message.slcState.driverOverrideActive
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,18 @@
|
||||
"""Small shared persisted-setting fixture for ported Tesla and map controls."""
|
||||
from openpilot.starpilot.ui.feature_settings_state import FeatureSettingsRequest
|
||||
|
||||
class Saved:
|
||||
def __init__(self, path):
|
||||
self.path = path/'params'
|
||||
self.path.mkdir()
|
||||
self.writes = []
|
||||
def get_param_path(self, key=''):
|
||||
return str(self.path/key)
|
||||
def put(self, key, data, block=False):
|
||||
assert block, '7.0 persistence must finish before confirmation'
|
||||
self.writes.append((key, data))
|
||||
(self.path/key).write_bytes(data)
|
||||
|
||||
def request(row, value):
|
||||
return FeatureSettingsRequest(row.key, row.source, value, confirmation=True,
|
||||
vehicle_fingerprint=row.vehicle_fingerprint, dependencies=row.dependencies, display_unit=row.display_unit)
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Tesla Model 3/Y car parameters and the saved switch for the set-speed and car-control tests."""
|
||||
from pathlib import Path
|
||||
|
||||
from opendbc.car import gen_empty_fingerprint
|
||||
from opendbc.car.tesla.interface import CarInterface
|
||||
from opendbc.car.tesla.speed_sync import prepare
|
||||
from opendbc.car.tesla.values import CAR, CANBUS
|
||||
|
||||
SWITCH = 'TeslaSpeedSync'
|
||||
|
||||
|
||||
def tesla(candidate=CAR.TESLA_MODEL_3, *, cable=True, long=True, selected=False):
|
||||
"""Car parameters built by the real car interface. cable: the CAN add-on cable was detected when the car started.
|
||||
long: StarPilot longitudinal control. selected: startup admitted the scroll frame (it only lands on an eligible car);
|
||||
whether the comma then owns the set speed follows the saved switch."""
|
||||
fingerprint = gen_empty_fingerprint()
|
||||
fingerprint[CANBUS.autopilot_party][0x489] = 8
|
||||
if cable:
|
||||
fingerprint[CANBUS.vehicle][0x3DF] = 8
|
||||
return prepare(CarInterface.get_params(candidate, fingerprint, [], long, False, False), selected)
|
||||
|
||||
|
||||
def save(params, key, value):
|
||||
"""Write a saved setting as its file, as the settings store leaves it: True/False, raw bytes, or None to remove."""
|
||||
path = Path(params.get_param_path(key))
|
||||
if value is None:
|
||||
path.unlink(missing_ok=True)
|
||||
else:
|
||||
path.write_bytes(value if isinstance(value, bytes) else b'1' if value else b'0')
|
||||
|
||||
|
||||
def switch(params, on=True):
|
||||
"""Save Comma can set speed on Tesla dashboard."""
|
||||
save(params, SWITCH, on)
|
||||
return params
|
||||
@@ -148,7 +148,8 @@ class TestTeslaScreenIntegration(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)
|
||||
|
||||
@@ -60,10 +60,10 @@ from openpilot.starpilot.ui.traffic_feature import TrafficFeature, EDIT_KEYS as
|
||||
from openpilot.starpilot.ui.lane_change_feature import LaneChangeFeature, KEYS as LANE_CHANGE_KEYS
|
||||
from openpilot.starpilot.ui.conditional_feature import BUTTON_PREFIX, ConditionalFeature
|
||||
from openpilot.starpilot.saved_source import read_saved
|
||||
from openpilot.starpilot.ui.wheel_feature import WheelFeature, PREFIX as WHEEL_PREFIX
|
||||
from openpilot.starpilot.ui.wheel_feature import PREFIX as WHEEL_PREFIX
|
||||
from openpilot.starpilot.longitudinal.output_max import KEY as OUTPUT_MAX_KEY
|
||||
from openpilot.starpilot.ui.tesla_coop_feature import TeslaCoopFeature
|
||||
from openpilot.starpilot.ui.tesla_screen_feature import TeslaScreenFeature, KEYS as TESLA_SCREEN_KEYS
|
||||
from openpilot.starpilot.ui.tesla_rows import TeslaVehicleRows, TeslaWheelRows, KEYS as TESLA_SCREEN_KEYS
|
||||
from openpilot.starpilot.ui.ford_bluepilot_feature import FordBluePilotFeature, KEYS as FORD_BLUEPILOT_KEYS
|
||||
from openpilot.starpilot.ui.ford_cluster_feature import FordClusterFeature
|
||||
from openpilot.starpilot.ui.ford_rear_fog_feature import FordRearFogFeature
|
||||
@@ -185,7 +185,7 @@ class FeatureSettingsOwner:
|
||||
repair_parked=lambda: self.authority("parked_preferences"),
|
||||
configuration_longitudinal=self.configuration_longitudinal)
|
||||
self.long_profiles = LongProfileFeature(self)
|
||||
self.tesla_screen = TeslaScreenFeature(self)
|
||||
self.tesla_screen = TeslaVehicleRows(self)
|
||||
self.tesla_coop = TeslaCoopFeature(self)
|
||||
from openpilot.starpilot.ui.gm_cancel_remap_feature import GmCancelRemapFeature
|
||||
self.gm_cancel_remap = GmCancelRemapFeature(self)
|
||||
@@ -202,7 +202,7 @@ class FeatureSettingsOwner:
|
||||
self.lane_changes = LaneChangeFeature(params, authority, vehicle_fingerprint, self.vehicle_params,
|
||||
configuration_longitudinal=self.configuration_longitudinal)
|
||||
self.conditional = ConditionalFeature(self)
|
||||
self.wheel = WheelFeature(self)
|
||||
self.wheel = TeslaWheelRows(self)
|
||||
|
||||
def _source_capability(self) -> tuple[bool, bool]:
|
||||
return bool(self.vision_development()), bool(self.maps_available())
|
||||
@@ -1183,7 +1183,7 @@ class FeatureSettingsOwner:
|
||||
title = "Wheel Controls"
|
||||
if self.show_cruise_intervals or toyota_cruise_capability(self.vehicle_params()) is not None:
|
||||
rows.extend(self._cruise_rows(configurable))
|
||||
rows.extend(self.wheel.rows())
|
||||
rows = self.wheel.page(rows)
|
||||
elif page == FeaturePage.SLC:
|
||||
cp = self.vehicle_params()
|
||||
button_cruise = hyundai_software_cruise.slc_configurable(cp, self.params)
|
||||
|
||||
@@ -115,6 +115,8 @@ class FeatureRow:
|
||||
actions: tuple[tuple[str, bool], ...] = ()
|
||||
presets: tuple[tuple[str, str], ...] = ()
|
||||
default_reset_available: bool = False
|
||||
status: bool = False # a read-only status: Galaxy shows it normally instead of grayed
|
||||
links: tuple[tuple[str, str], ...] = () # (label, https URL) buttons shown in Galaxy
|
||||
collapsed: bool = False # a heading whose rows are hidden until it is opened
|
||||
learned_value: str = field(default='', compare=False, repr=False)
|
||||
accepted_finding_value: float | None = None
|
||||
|
||||
@@ -72,7 +72,7 @@ from openpilot.starpilot.ui.presentation import BitmapFonts, FontRole, Profile,
|
||||
from openpilot.starpilot.ui.startup import slc_action_transport_enabled, validate_artwork, validate_fonts
|
||||
from openpilot.starpilot.speed_limits.vision_gate import diagnostic_choice_enabled
|
||||
from openpilot.starpilot.ui.bluetooth_status import BluetoothStatusSource
|
||||
from openpilot.starpilot.ui.runtime_snapshot import RuntimeSnapshotAdapter, current_message, display_message
|
||||
from openpilot.starpilot.ui.runtime_snapshot import RuntimeSnapshotAdapter, current_message, display_message, input_message
|
||||
from openpilot.starpilot.ui.runtime_software import deliver_software
|
||||
from openpilot.starpilot.ui.network_panel import NetworkPanelBridge
|
||||
from openpilot.starpilot.ui.slc_action_dispatch import SlcActionDispatcher
|
||||
@@ -89,6 +89,7 @@ from openpilot.starpilot.controllers.mode_actions import ModeActionPublisher, pr
|
||||
from openpilot.starpilot.favorites.actions import (BOOKMARK, CYCLE_PERSONALITY, EXPERIMENTAL, INCREASE_SPEED, DECREASE_SPEED, SET_SPEED,
|
||||
FORCE_COAST, PULSE_GLIDE, DISENGAGE, TRAFFIC, SWITCHBACK, SCREEN_OFF, mapped_actions)
|
||||
from openpilot.starpilot.favorites.state import FavoriteAction
|
||||
from openpilot.starpilot.ui.tesla_speed_actions import TeslaSpeedActions
|
||||
from openpilot.starpilot.favorites.layout_actions import layout_actions
|
||||
from openpilot.starpilot.saved_source import read_saved
|
||||
from openpilot.starpilot.feature_runtime import enabled as feature_enabled
|
||||
@@ -156,7 +157,7 @@ def visual_border_state(state: OnroadState, signals: Signals) -> OnroadState:
|
||||
border.left_blindspot or signals.vasm_left, border.right_blindspot or signals.vasm_right))
|
||||
|
||||
|
||||
class StarShellSession:
|
||||
class StarShellSession(TeslaSpeedActions):
|
||||
"""Own native shell resources and one request/router boundary per app."""
|
||||
|
||||
def __init__(self, profile: Profile, camera_owner: Any, *, network_layer: Any = None, settings_layer: Any = None):
|
||||
@@ -249,9 +250,12 @@ class StarShellSession:
|
||||
self.display_page = "system"
|
||||
self.display_edit_key: str | None = None
|
||||
self.slc_actions: SlcActionDispatcher | None = None
|
||||
self.slc_car_actions: SlcActionDispatcher | None = None
|
||||
if slc_action_transport_enabled(os.environ, ui_state.params):
|
||||
try:
|
||||
self.slc_actions = SlcActionDispatcher(_slc_action_publisher(), self._live_slc_message)
|
||||
# A car button (Tesla stalk or wheel) reads the car's messages with the scroll wheel's age limit.
|
||||
self.slc_car_actions = SlcActionDispatcher(_slc_action_publisher(), lambda now_ns: self._live_slc_message(now_ns, car_input=True))
|
||||
except (OSError, RuntimeError):
|
||||
pass # The shell stays readable and reports action unavailability.
|
||||
self.input = ShellInput(profile, self._emit,
|
||||
@@ -492,7 +496,7 @@ class StarShellSession:
|
||||
self.mode_actions.dispatch(mode, ui_state.sm, ui_state.CP, _slc_action_publisher(), now_ns=time.monotonic_ns()))
|
||||
actions[key] = FavoriteAction(key, label, available=allowed, token=repr((drive, mode, allowed)),
|
||||
reason="Fresh onroad control required", invoke=apply_mode)
|
||||
if ui_state.CP is not None and not ui_state.CP.pcmCruise:
|
||||
if ui_state.CP is not None and (not ui_state.CP.pcmCruise or self._tesla_set_speed(ui_state.CP)):
|
||||
current = self._favorite_authority() and cruise_action_authority(ui_state.sm, ui_state.CP, time.monotonic_ns())
|
||||
def change_speed(increase):
|
||||
return bool(not ui_state.params.get_bool("SafeMode") and self.cruise_actions.dispatch(
|
||||
@@ -515,7 +519,7 @@ class StarShellSession:
|
||||
target_mps=float(value) * (1 / 3.6 if metric else 0.44704)))
|
||||
actions[SET_SPEED] = FavoriteAction(SET_SPEED, "Set Speed To", available=current and not ui_state.params.get_bool("SafeMode"),
|
||||
reason="Active software cruise required; speed uses device units", token=repr((drive, current)), invoke_value=set_speed)
|
||||
return actions
|
||||
return self._tesla_favorite_actions(actions, drive)
|
||||
|
||||
def _poll_projection_bookmark(self, now_ns):
|
||||
receiver = getattr(self, '_projection_bookmarks', None)
|
||||
@@ -1364,7 +1368,7 @@ class StarShellSession:
|
||||
self.feature_request(replace(request, confirmation=True))
|
||||
gui_app.push_widget(ConfirmDialog(question, "Save", callback=confirmed))
|
||||
|
||||
def _live_slc_message(self, now_ns: int) -> Any | None:
|
||||
def _live_slc_message(self, now_ns: int, *, car_input: bool = False) -> Any | None:
|
||||
ui = self.adapter.ui_state
|
||||
if not ui.started:
|
||||
return None
|
||||
@@ -1374,11 +1378,12 @@ class StarShellSession:
|
||||
not any(p.ignitionLine or p.ignitionCan for p in pandas)):
|
||||
return None
|
||||
after = ui.started_frame
|
||||
# plannerd revalidates actions.
|
||||
car = display_message(ui.sm, "carState", now_ns, after_frame=after)
|
||||
control = display_message(ui.sm, "carControl", now_ns, after_frame=after)
|
||||
controls = display_message(ui.sm, "controlsState", now_ns, after_frame=after)
|
||||
selfdrive = display_message(ui.sm, "selfdriveState", now_ns, after_frame=after)
|
||||
# plannerd revalidates actions. A car button reads with the scroll wheel's age limit.
|
||||
read = input_message if car_input else display_message
|
||||
car = read(ui.sm, "carState", now_ns, after_frame=after)
|
||||
control = read(ui.sm, "carControl", now_ns, after_frame=after)
|
||||
controls = read(ui.sm, "controlsState", now_ns, after_frame=after)
|
||||
selfdrive = read(ui.sm, "selfdriveState", now_ns, after_frame=after)
|
||||
cp = ui.CP
|
||||
if (car is None or not getattr(car, "canValid", False) or getattr(car, "canTimeout", True) or
|
||||
control is None or controls is None or selfdrive is None or cp is None):
|
||||
@@ -1828,7 +1833,7 @@ class StarShellSession:
|
||||
source.close()
|
||||
self.home_stats_source = None
|
||||
self.drive_state.physical.close()
|
||||
self.slc_actions = None
|
||||
self.slc_actions = self.slc_car_actions = None
|
||||
self.galaxy_flow.close()
|
||||
if getattr(self, 'model_manager', None) is not None:
|
||||
self.model_manager.close()
|
||||
|
||||
@@ -128,6 +128,19 @@ def current_message(sm: Any, service: str, now_ns: int, *, after_frame: int = 0,
|
||||
return _message_at_age(sm, service, now_ns, after_frame, max_age_ns)
|
||||
|
||||
|
||||
# Car buttons (wheel, stalk) are handled part-way through a screen frame, after the frame's other work. The same age the
|
||||
# scroll wheel's comma-speed actions allow (conditional_mode.ui_action.SOURCE_MAX_AGE_NS).
|
||||
INPUT_MAX_AGE_NS = 250_000_000
|
||||
|
||||
|
||||
def input_message(sm: Any, service: str, now_ns: int, *, after_frame: int = 0) -> Any | None:
|
||||
"""current_message for a car button: the same checks, with the age stretched to INPUT_MAX_AGE_NS for fast services
|
||||
(two periods of a 100 Hz message is 20 ms, less than the work done in the frame before the button is handled)."""
|
||||
frequency = SERVICE_LIST[service].frequency
|
||||
max_age_ns = max(int(2e9 / frequency) if frequency else 1_000_000_000, INPUT_MAX_AGE_NS)
|
||||
return _message_at_age(sm, service, now_ns, after_frame, max_age_ns)
|
||||
|
||||
|
||||
def display_message(sm: Any, service: str, now_ns: int, *, after_frame: int = 0) -> Any | None:
|
||||
"""Allow a bounded UI frame gap without extending control-action freshness."""
|
||||
max_age_ns = 200_000_000
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Resume Speed Limit + Offset: the SLC action a car button (wheel, stalk) or a favorite can run."""
|
||||
import time
|
||||
|
||||
from openpilot.starpilot.common.car_control_config import NO_LIMIT_REASON, SPEED_RESUME
|
||||
from openpilot.starpilot.favorites.state import FavoriteAction
|
||||
from openpilot.starpilot.ui.onroad_state import SlcActionKind, SlcUiRequest
|
||||
|
||||
|
||||
def resume_action(shell, ui_state, drive, *, require_display: bool) -> FavoriteAction:
|
||||
"""Adopt the current limit + offset, or accept a limit waiting for confirmation.
|
||||
|
||||
A car button is handled part-way through a screen frame, so the car's messages are read with the scroll wheel's age
|
||||
limit (shell._live_slc_message(..., car_input=True)), both here and when shell.slc_car_actions checks again before
|
||||
sending.
|
||||
require_display (a favorite) also needs the screen's own authority."""
|
||||
def read(now_ns):
|
||||
return shell._live_slc_message(now_ns, car_input=True)
|
||||
|
||||
def blocked():
|
||||
return bool(ui_state.params.get_bool('SafeMode') or getattr(ui_state, 'replay_clock', None) is not None or
|
||||
getattr(shell, 'slc_car_actions', None) is None or require_display and not shell._favorite_authority())
|
||||
|
||||
def invoke():
|
||||
live = None if blocked() else read(time.monotonic_ns())
|
||||
if live is None:
|
||||
return False
|
||||
kind = SlcActionKind.ACCEPT if live.hasPending and not live.automaticAdoptionPending else SlcActionKind.ADOPT
|
||||
request = SlcUiRequest(kind, str(live.sessionId), int(live.decisionId), int(live.presentationId), float(live.speedLimit))
|
||||
return shell.slc_car_actions.dispatch(request)
|
||||
|
||||
live = None if blocked() else read(time.monotonic_ns())
|
||||
available = bool(live is not None and live.enabled and live.observationKind == 'valid')
|
||||
reason = ('Unavailable in this context' if available or live is None and blocked() else
|
||||
'Speed Limit Controller is not running' if live is None or not live.enabled else NO_LIMIT_REASON)
|
||||
token = repr((drive, str(live.sessionId) if live is not None else '', int(live.presentationId) if live is not None else 0))
|
||||
return FavoriteAction(SPEED_RESUME, 'Resume Speed Limit + Offset', available=available, reason=reason, token=token,
|
||||
invoke=invoke)
|
||||
@@ -0,0 +1,161 @@
|
||||
"""Vehicle input assignments shared by native settings and Galaxy."""
|
||||
import json
|
||||
from openpilot.starpilot.common.car_control_config import (PARAM, MAX_ASSIGNMENT_BYTES, INPUTS, MODELS, SPEED_SET, SPEED_RESUME, STALK_HOLD, STALK_TAP,
|
||||
STALK_TAP_FULL, WHEEL_HOLDS, DEFAULT_BINDINGS, FIXED_BINDINGS, NO_ACTION, comma_speed, effective_bindings, parse_assignments,
|
||||
vehicle_supported, screen_reserved)
|
||||
from openpilot.starpilot.favorites.actions import (BOOKMARK, CYCLE_PERSONALITY, EXPERIMENTAL, FORCE_COAST, PULSE_GLIDE, DISENGAGE, SELFIE,
|
||||
SCREEN_OFF, TRAFFIC, SWITCHBACK, FEATURE_KEYS, APPEARANCE_KEYS)
|
||||
from openpilot.starpilot.saved_source import read_saved
|
||||
from openpilot.starpilot.saved_document import commit_exact
|
||||
from openpilot.starpilot.ui.feature_settings_state import FeatureRow
|
||||
|
||||
PREFIX = 'tesla_input:'
|
||||
SCREEN = 'screen_three_finger_tap'
|
||||
# Always On Lateral on/off is only offered on the three-finger tap: the panda's own safety check watches that tap, and the
|
||||
# choice is set up when the car starts (TeslaAOLScreenTap, saved on by default). This row is the only place it is chosen.
|
||||
AOL_ACTION = 'Always On Lateral on/off'
|
||||
AOL_KEY = 'TeslaAOLScreenTap'
|
||||
# The Wheel Controls rows carry no description: the title says what the control is. A row only says what stops it
|
||||
# acting as shown, and a scroll row how far it moves the set speed.
|
||||
AOL_NOTE = 'Always On Lateral on/off applies after the next startup'
|
||||
AOL_PENDING = 'Always On Lateral on/off stays on this tap until the next startup'
|
||||
# A Tesla shows only the controls StarPilot can use: the rest steer, signal, light, wipe or shift the car. The right
|
||||
# scroll wheel's scroll always changes the set speed and the right stalk's plain down and up engage and disengage, so
|
||||
# they show grayed; the stalk's hold is fixed (FIXED_BINDINGS).
|
||||
TESLA_INPUTS = ('right_wheel_left', WHEEL_HOLDS['right_wheel_left'], 'right_wheel_right', WHEEL_HOLDS['right_wheel_right'],
|
||||
STALK_TAP, STALK_TAP_FULL, STALK_HOLD, SCREEN)
|
||||
# What each scroll does to the set speed, and by how much in the units shown: one unit, or on to the next multiple of
|
||||
# five for a fast scroll, as the Tesla's own cruise steps (cruise_action.TESLA_STEPS).
|
||||
SCROLL_INFO = (('Scroll up', 'Increase set speed', 'By 1 {unit}'), ('Fast scroll up', 'Increase set speed', 'To the next 5 {unit}'),
|
||||
('Scroll down', 'Decrease set speed', 'By 1 {unit}'), ('Fast scroll down', 'Decrease set speed', 'To the next 5 {unit}'))
|
||||
STALK_INFO = (('Down', 'Engage StarPilot'), ('Up', 'Disengage StarPilot'))
|
||||
SET_SPEED_NEEDS = 'Set Speed To needs Comma can set speed on Tesla dashboard turned on in Vehicle Settings'
|
||||
# Every settings key these rows use (each control, and its speed when it is on Set Speed To).
|
||||
KEYS = frozenset(PREFIX + name + suffix for name in TESLA_INPUTS for suffix in ('', ':speed'))
|
||||
OPTIONS = {'Unassigned': '', 'Set Speed To': SPEED_SET, 'Resume Speed Limit + Offset': SPEED_RESUME, 'Cycle Driving Personality': CYCLE_PERSONALITY,
|
||||
'Bookmark': BOOKMARK, 'Experimental Mode': EXPERIMENTAL, 'Force Coasting': FORCE_COAST, 'Pulse and Glide': PULSE_GLIDE,
|
||||
'Disengage Openpilot': DISENGAGE, 'Take Comma Selfie': SELFIE, 'Toggle Screen Off': SCREEN_OFF, 'Traffic Mode': TRAFFIC, 'Switchback Mode': SWITCHBACK}
|
||||
for key in (*[k for keys in FEATURE_KEYS.values() for k in keys], *APPEARANCE_KEYS):
|
||||
if key not in OPTIONS.values():
|
||||
OPTIONS['Toggle ' + key] = key
|
||||
|
||||
|
||||
class TeslaControlsFeature:
|
||||
def __init__(self, owner):
|
||||
self.owner = owner
|
||||
|
||||
def context(self):
|
||||
cp = self.owner.vehicle_params()
|
||||
raw, readable = read_saved(self.owner.params, PARAM, MAX_ASSIGNMENT_BYTES)
|
||||
doc = parse_assignments(raw) if readable else None
|
||||
valid = bool(doc is not None and (not doc['vehicle'] or cp is not None and doc['vehicle'] == cp.carFingerprint))
|
||||
return cp, raw, doc, valid
|
||||
|
||||
def allowed(self):
|
||||
return self.owner.authority('parked_preferences') and self.owner.authority('preferences') and vehicle_supported(self.owner.vehicle_params())
|
||||
|
||||
def aol_supported(self, cp):
|
||||
from opendbc.car.tesla.screen_button import screen_tap_supported
|
||||
return screen_tap_supported(cp)
|
||||
|
||||
def rows(self):
|
||||
cp, raw, doc, valid = self.context()
|
||||
if cp is None or cp.carFingerprint not in MODELS:
|
||||
return []
|
||||
from openpilot.starpilot.ui.tesla_set_speed_feature import CABLE_MISSING, addon_cable
|
||||
missing = [] if addon_cable(cp) is not False else [CABLE_MISSING]
|
||||
rows = []
|
||||
metric, ok = read_saved(self.owner.params, 'IsMetric', 8)
|
||||
units_valid = ok and metric in (None, b'0', b'1')
|
||||
metric_on = metric == b'1'
|
||||
bindings = effective_bindings(doc) if valid else {}
|
||||
owned = comma_speed(self.owner.params, cp)
|
||||
for control, value, amount in SCROLL_INFO:
|
||||
amount = amount.format(unit='km/h' if metric_on else 'mph')
|
||||
rows.append(FeatureRow('', 'Right scroll wheel / ' + control, value, reason='.\n'.join((*missing, amount))))
|
||||
for name in TESLA_INPUTS:
|
||||
group, label = INPUTS[name]
|
||||
if name == STALK_TAP:
|
||||
for control, value in STALK_INFO:
|
||||
rows.append(FeatureRow('', 'Right stalk / ' + control, value, reason='.\n'.join(missing)))
|
||||
reserved = name == SCREEN and screen_reserved(cp)
|
||||
aol = name == SCREEN and self.aol_supported(cp)
|
||||
aol_on = aol and read_saved(self.owner.params, AOL_KEY, 8) == (b'1', True)
|
||||
fixed = name in FIXED_BINDINGS
|
||||
binding = bindings.get(name, {})
|
||||
key = binding.get('key', '')
|
||||
choice = next((name for name, value in OPTIONS.items() if value == key), 'Unavailable saved action')
|
||||
if aol_on:
|
||||
choice = AOL_ACTION
|
||||
notes = [*missing, *([SET_SPEED_NEEDS] if key == SPEED_SET and not owned else []),
|
||||
*([AOL_PENDING] if reserved and not aol_on else [AOL_NOTE] if aol else [])]
|
||||
help_text = '.\n'.join(notes)
|
||||
rows.append(FeatureRow(PREFIX + name, group + ' / ' + label, choice if valid else 'Invalid or other-vehicle assignments', raw,
|
||||
tuple(OPTIONS) + ((AOL_ACTION,) if aol else ()), available=self.allowed() and valid and not fixed, reason=help_text,
|
||||
vehicle_fingerprint=self.owner.vehicle_fingerprint()))
|
||||
if key == SPEED_SET:
|
||||
value = binding.get('value')
|
||||
low, high = (8, 145) if metric_on else (5, 90)
|
||||
rows.append(FeatureRow(PREFIX + name + ':speed', group + ' / ' + label + ': set speed', str(value), raw, step=1., minimum=low, maximum=high,
|
||||
unit='km/h' if metric_on else 'mph', display_unit='km/h' if metric_on else 'mph',
|
||||
dependencies=(('IsMetric', metric),), available=self.allowed() and units_valid and not reserved,
|
||||
vehicle_fingerprint=self.owner.vehicle_fingerprint()))
|
||||
return rows
|
||||
|
||||
def apply(self, request):
|
||||
cp, raw, doc, valid = self.context()
|
||||
name = request.key.removeprefix(PREFIX)
|
||||
numeric = name.endswith(':speed')
|
||||
if numeric:
|
||||
name = name[:-6]
|
||||
if not self.allowed() or not valid or name not in TESLA_INPUTS or name in FIXED_BINDINGS or request.expected != raw:
|
||||
return False
|
||||
fingerprint = self.owner.vehicle_fingerprint()
|
||||
if not request.vehicle_fingerprint or request.vehicle_fingerprint != fingerprint:
|
||||
return False
|
||||
updated = {**doc, 'vehicle': str(cp.carFingerprint), 'bindings': dict(doc['bindings'])}
|
||||
if numeric:
|
||||
metric, ok = read_saved(self.owner.params, 'IsMetric', 8)
|
||||
unit = 'km/h' if metric == b'1' else 'mph'
|
||||
low, high = (8, 145) if metric == b'1' else (5, 90)
|
||||
binding = updated['bindings'].get(name)
|
||||
if not ok or metric not in (None, b'0', b'1') or request.display_unit != unit or request.dependencies != (('IsMetric', metric),):
|
||||
return False
|
||||
try:
|
||||
value = float(request.value)
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
if not low <= value <= high or binding is None or binding['key'] != SPEED_SET:
|
||||
return False
|
||||
updated['bindings'][name] = {**binding, 'value': value}
|
||||
else:
|
||||
aol = name == SCREEN and request.value == AOL_ACTION
|
||||
if aol and not self.aol_supported(cp):
|
||||
return False
|
||||
if (request.value not in OPTIONS and not aol) or request.dependencies or request.display_unit:
|
||||
return False
|
||||
key = '' if aol else OPTIONS[request.value]
|
||||
if key:
|
||||
updated['bindings'][name] = {'key': key, 'value': 30 if key == SPEED_SET else None, 'label': request.value}
|
||||
elif name in DEFAULT_BINDINGS:
|
||||
updated['bindings'][name] = {'key': NO_ACTION, 'value': None, 'label': 'Unassigned'}
|
||||
else:
|
||||
updated['bindings'].pop(name, None)
|
||||
|
||||
def authorized():
|
||||
return (self.allowed() and self.owner.vehicle_fingerprint() == fingerprint and
|
||||
(not numeric or read_saved(self.owner.params, 'IsMetric', 8) == (metric, True)))
|
||||
result = commit_exact(self.owner.params, key=PARAM, max_bytes=MAX_ASSIGNMENT_BYTES, expected=raw,
|
||||
raw=json.dumps(updated, separators=(',', ':'), allow_nan=False).encode(), authorized=authorized, temp_prefix='.tesla-input-')
|
||||
if not (result.committed and result.verified):
|
||||
return False
|
||||
if name == SCREEN and not numeric:
|
||||
# The tap's Always On Lateral on/off is its own saved switch, read when the car starts. It is on by default, so
|
||||
# another choice always saves it off.
|
||||
current, readable = read_saved(self.owner.params, AOL_KEY, 8)
|
||||
wanted = b'1' if request.value == AOL_ACTION else b'0'
|
||||
if readable and current != wanted:
|
||||
aol = commit_exact(self.owner.params, key=AOL_KEY, max_bytes=8, expected=current, raw=wanted, authorized=authorized,
|
||||
temp_prefix='.tesla-screen-')
|
||||
return aol.committed and aol.verified
|
||||
return True
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Tesla Model 3/Y settings rows, joined to the features the settings owner already builds.
|
||||
|
||||
feature_settings_owner.py sits at the repository's 120 KiB file limit, so the Tesla rows come in through these two
|
||||
subclasses rather than new branches there. Vehicle Settings gets the CAN add-on cable and Comma can set speed on Tesla
|
||||
dashboard above the existing Tesla screen rows; Wheel Controls gets the Tesla controls below the wheel buttons. Other
|
||||
cars get exactly the rows they had: both additions are empty unless the car is a Tesla Model 3 or Model Y.
|
||||
"""
|
||||
from openpilot.starpilot.ui.tesla_controls_feature import KEYS as CONTROL_KEYS, TeslaControlsFeature
|
||||
from openpilot.starpilot.ui.tesla_screen_feature import KEYS as SCREEN_KEYS, TeslaScreenFeature
|
||||
from openpilot.starpilot.ui.tesla_set_speed_feature import KEYS as SET_SPEED_KEYS, TeslaSetSpeedFeature
|
||||
from openpilot.starpilot.ui.wheel_feature import WheelFeature
|
||||
|
||||
# Every key the owner hands to TeslaVehicleRows.apply.
|
||||
KEYS = SCREEN_KEYS | SET_SPEED_KEYS | CONTROL_KEYS
|
||||
# The set-speed steps of a short press and a hold of a cruise button (feature_settings_owner._cruise_rows).
|
||||
CRUISE_STEP_KEYS = ('CustomCruise', 'CustomCruiseLong')
|
||||
|
||||
|
||||
class TeslaVehicleRows(TeslaScreenFeature):
|
||||
def __init__(self, owner):
|
||||
super().__init__(owner)
|
||||
self.set_speed = TeslaSetSpeedFeature(owner)
|
||||
self.controls = TeslaControlsFeature(owner)
|
||||
|
||||
def rows(self, parked):
|
||||
return (*self.set_speed.rows(parked), *super().rows(parked))
|
||||
|
||||
def apply(self, request):
|
||||
if request.key in SET_SPEED_KEYS:
|
||||
return self.set_speed.apply(request)
|
||||
if request.key in CONTROL_KEYS:
|
||||
return self.controls.apply(request)
|
||||
return super().apply(request)
|
||||
|
||||
|
||||
class TeslaWheelRows(WheelFeature):
|
||||
def __init__(self, owner):
|
||||
super().__init__(owner)
|
||||
self.tesla = TeslaControlsFeature(owner)
|
||||
|
||||
def rows(self):
|
||||
return [*super().rows(), *self.tesla.rows()]
|
||||
|
||||
def page(self, rows):
|
||||
"""The Wheel Controls page: the rows above the wheel's, then the wheel's and the Tesla's. StarPilot never steps a
|
||||
Model 3/Y's set speed from cruise buttons, so the two step rows (Short press, Hold) are left out there."""
|
||||
tesla = self.tesla.rows()
|
||||
if tesla:
|
||||
rows = [row for row in rows if row.key not in CRUISE_STEP_KEYS]
|
||||
return [*rows, *super().rows(), *tesla]
|
||||
@@ -4,11 +4,9 @@ from openpilot.starpilot.saved_source import read_saved
|
||||
from openpilot.starpilot.ui.feature_settings_state import FeatureRow
|
||||
|
||||
|
||||
KEYS = frozenset(('TeslaAOLScreenTap', 'TeslaAOLDisengageOnBrake'))
|
||||
# The three-finger tap's Always On Lateral on/off is chosen on the tap's own row in Wheel Controls (tesla_controls_feature.py).
|
||||
KEYS = frozenset(('TeslaAOLDisengageOnBrake',))
|
||||
ROWS = (
|
||||
('TeslaAOLScreenTap', 'Three-Finger AOL Tap',
|
||||
'Touch the Tesla screen with three fingers to toggle Always On Lateral. Requires Always On Lateral and the detected Vehicle CAN add-on cable. ' +
|
||||
'Does not engage or cancel cruise control. Applies after the next startup.'),
|
||||
('TeslaAOLDisengageOnBrake', 'Disengage AOL on Brake',
|
||||
'Pressing the brake disarms Always On Lateral. ' +
|
||||
'Turn off to keep steering armed during braking. Applies after the next startup.'),
|
||||
@@ -36,10 +34,7 @@ class TeslaScreenFeature:
|
||||
if capability is None:
|
||||
return ()
|
||||
rows = []
|
||||
from opendbc.car.tesla.screen_button import screen_tap_supported
|
||||
for key, label, reason in ROWS:
|
||||
if key == 'TeslaAOLScreenTap' and not screen_tap_supported(self.vehicle_params()):
|
||||
continue
|
||||
raw, readable = read_saved(self.params, key, 8)
|
||||
valid = readable and raw in (None, b'0', b'1')
|
||||
rows.append(FeatureRow(key, label, ('On' if raw == b'1' else 'Off') if valid else 'Invalid saved choice',
|
||||
@@ -57,8 +52,7 @@ class TeslaScreenFeature:
|
||||
def authorized():
|
||||
return (self.authority('parked_preferences') and bool(request.vehicle_fingerprint) and
|
||||
self.vehicle_fingerprint() == request.vehicle_fingerprint and request.capability is not None and
|
||||
self.capability() == request.capability and
|
||||
(request.key != 'TeslaAOLScreenTap' or any(row.key == request.key for row in self.rows(True))))
|
||||
self.capability() == request.capability)
|
||||
|
||||
result = commit_exact(self.params, key=request.key, max_bytes=8, expected=request.expected,
|
||||
raw=b'1' if request.value == 'On' else b'0', authorized=authorized, temp_prefix='.tesla-screen-')
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Tesla Model 3/Y vehicle settings: the CAN add-on cable status and Comma can set speed on Tesla dashboard.
|
||||
|
||||
Shared by native settings and Galaxy. The cable (Vehicle CAN) is detected when the car starts; the switch takes effect
|
||||
within a second of being changed (openpilot/starpilot/car/tesla/set_speed.py).
|
||||
"""
|
||||
from openpilot.starpilot.car.tesla import set_speed
|
||||
from openpilot.starpilot.saved_document import commit_exact
|
||||
from openpilot.starpilot.saved_source import read_saved
|
||||
from openpilot.starpilot.ui.feature_settings_state import FeatureRow
|
||||
|
||||
SYNC = set_speed.PARAM
|
||||
KEYS = frozenset((SYNC,))
|
||||
MODELS = ('TESLA_MODEL_3', 'TESLA_MODEL_Y')
|
||||
CABLE_MISSING = 'Needs the Tesla CAN add-on cable'
|
||||
LONG_MISSING = 'Needs Alpha Longitudinal turned on'
|
||||
RESTART_NEEDED = 'Available after the next startup'
|
||||
CABLE_LINKS = (('Buy the cable', 'https://xnor.shop/products/model-3-y-hw3-hw4-vehicle-can-addon-cable'),
|
||||
('Install guide', 'https://wiki.xnor.shop/docs/tesla/hw3-hw4/vehicle-can-bus-addon/'))
|
||||
CABLE_HELP = ('Adds the right scroll wheel, right stalk and three-finger screen tap as controls, and lets the comma set the ' +
|
||||
"speed on the Tesla's dashboard. Model 3 and Model Y, HW3 or HW4. Checked when the car starts.")
|
||||
SYNC_LABEL = 'Comma can set speed on Tesla dashboard'
|
||||
SYNC_HELP = ("StarPilot keeps its own set speed and scrolls the Tesla's set speed to match, so the dashboard shows the same " +
|
||||
"speed. The Tesla's can lag a second or two behind. The comma and the Tesla must use the same units. Experimental.")
|
||||
|
||||
|
||||
def addon_cable(cp) -> bool | None:
|
||||
"""True/False for a Tesla Model 3/Y (cable detected at startup or not); None for other cars."""
|
||||
try:
|
||||
from opendbc.car.tesla.values import TeslaFlags
|
||||
if cp is None or cp.brand != 'tesla' or cp.carFingerprint not in MODELS:
|
||||
return None
|
||||
return bool(cp.flags & TeslaFlags.HAS_VEHICLE_BUS)
|
||||
except (AttributeError, TypeError, ImportError):
|
||||
return None
|
||||
|
||||
|
||||
class TeslaSetSpeedFeature:
|
||||
def __init__(self, owner):
|
||||
self.params = owner.params
|
||||
self.authority = owner.authority
|
||||
self.vehicle_params = owner.vehicle_params
|
||||
self.vehicle_fingerprint = owner.vehicle_fingerprint
|
||||
|
||||
def capability(self):
|
||||
cp = self.vehicle_params()
|
||||
if addon_cable(cp) is None:
|
||||
return None
|
||||
return (str(cp.carFingerprint), str(cp.brand), int(cp.flags), bool(cp.openpilotLongitudinalControl), bool(cp.pcmCruise),
|
||||
tuple(int(config.safetyParam) for config in cp.safetyConfigs))
|
||||
|
||||
def active(self) -> bool:
|
||||
"""The comma owns the set speed on this car now."""
|
||||
return set_speed.active(self.params, self.vehicle_params())
|
||||
|
||||
def unavailable(self, cp) -> str:
|
||||
"""Why the switch cannot be used on this car as it started, or ''."""
|
||||
if not addon_cable(cp):
|
||||
return CABLE_MISSING
|
||||
if not cp.openpilotLongitudinalControl or not cp.pcmCruise:
|
||||
return LONG_MISSING
|
||||
if read_saved(self.params, 'IsReleaseBranch', 8) not in ((None, True), (b'0', True)):
|
||||
return 'Not available on release builds'
|
||||
if not set_speed.selected(cp):
|
||||
return RESTART_NEEDED # the car started without the scroll frame admitted (Safe Mode, or settings changed since)
|
||||
return ''
|
||||
|
||||
def rows(self, parked):
|
||||
capability = self.capability()
|
||||
if capability is None:
|
||||
return ()
|
||||
cp = self.vehicle_params()
|
||||
cable = addon_cable(cp)
|
||||
raw, readable = read_saved(self.params, SYNC, 8)
|
||||
valid = readable and raw in (None, b'0', b'1')
|
||||
grayed = self.unavailable(cp)
|
||||
return (
|
||||
FeatureRow('', 'Tesla CAN add-on cable', 'Detected' if cable else 'Not detected', reason=CABLE_HELP, status=True,
|
||||
links=CABLE_LINKS),
|
||||
FeatureRow(SYNC, SYNC_LABEL, ('On' if raw == b'1' else 'Off') if valid else 'Invalid saved choice', source=raw,
|
||||
choices=('Off', 'On') if valid else (), default_value='Off',
|
||||
available=parked and self.authority('parked_preferences') and valid and not grayed,
|
||||
reason=(grayed + '.\n' + SYNC_HELP if grayed else SYNC_HELP) if valid else 'Invalid saved choice',
|
||||
capability=capability),
|
||||
)
|
||||
|
||||
def apply(self, request):
|
||||
if (request.key not in KEYS or request.value not in ('Off', 'On') or not request.confirmation or
|
||||
request.expected not in (None, b'0', b'1') or request.dependencies or request.related_source is not None or
|
||||
request.display_unit or request.direction):
|
||||
return False
|
||||
|
||||
def authorized():
|
||||
cp = self.vehicle_params()
|
||||
return (self.authority('parked_preferences') and bool(request.vehicle_fingerprint) and
|
||||
self.vehicle_fingerprint() == request.vehicle_fingerprint and request.capability is not None and
|
||||
self.capability() == request.capability and (request.value == 'Off' or not self.unavailable(cp)))
|
||||
|
||||
result = commit_exact(self.params, key=request.key, max_bytes=8, expected=request.expected,
|
||||
raw=b'1' if request.value == 'On' else b'0', authorized=authorized, temp_prefix='.tesla-set-speed-')
|
||||
return result.committed and result.verified
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Tesla Model 3/Y speed actions for the car's own controls (Wheel Controls).
|
||||
|
||||
Kept apart from runtime_app so that file stays small. The session mixes this in; every action still passes the
|
||||
publisher's and card's own driving-authority checks.
|
||||
"""
|
||||
import time
|
||||
|
||||
|
||||
class TeslaSpeedActions:
|
||||
def _comma_speed_actions(self):
|
||||
"""The right scroll wheel's steps where the comma owns the set speed (one display unit, or to the next multiple of
|
||||
five for a fast scroll), and Resume Speed Limit + Offset, which the right stalk runs by default. Looked up apart
|
||||
from the favorites catalog, so a car button never expires while unrelated settings pages are built."""
|
||||
from openpilot.starpilot.ui.runtime_app import ui_state, _slc_action_publisher, cruise_action_authority
|
||||
from openpilot.starpilot.favorites.state import FavoriteAction
|
||||
from openpilot.starpilot.common.car_control_config import SPEED_UP, SPEED_DOWN, SPEED_RESUME
|
||||
from openpilot.starpilot.ui.slc_resume_action import resume_action
|
||||
|
||||
def blocked():
|
||||
return bool(ui_state.params.get_bool('SafeMode') or getattr(ui_state, 'replay_clock', None) is not None)
|
||||
|
||||
actions = {}
|
||||
drive = (ui_state.started_frame, getattr(ui_state.CP, 'carFingerprint', None))
|
||||
for key, label, sign in ((SPEED_UP, 'Increase Comma Set Speed', 1), (SPEED_DOWN, 'Decrease Comma Set Speed', -1)):
|
||||
def comma_step(fast=0., sign=sign):
|
||||
if fast not in (0, 1) or blocked():
|
||||
return False
|
||||
return self.cruise_actions.dispatch(sign > 0, ui_state.sm, ui_state.CP, _slc_action_publisher(),
|
||||
now_ns=time.monotonic_ns(), step_units=sign * (5 if fast else 1))
|
||||
allowed = not blocked() and cruise_action_authority(ui_state.sm, ui_state.CP, time.monotonic_ns())
|
||||
actions[key] = FavoriteAction(key, label, available=allowed, token=repr((drive, allowed)),
|
||||
invoke=lambda action=comma_step: action(), invoke_value=comma_step)
|
||||
actions[SPEED_RESUME] = resume_action(self, ui_state, drive, require_display=False)
|
||||
return actions
|
||||
|
||||
def _tesla_set_speed(self, cp):
|
||||
"""Comma can set speed on Tesla dashboard is on for this car (read at most once a second)."""
|
||||
from openpilot.starpilot.ui.runtime_app import ui_state
|
||||
from openpilot.starpilot.car.tesla.set_speed import Polled
|
||||
polled = getattr(self, '_tesla_set_speed_polled', None)
|
||||
if polled is None:
|
||||
polled = self._tesla_set_speed_polled = Polled(ui_state.params)
|
||||
return polled(cp)
|
||||
|
||||
def _tesla_favorite_actions(self, actions, drive):
|
||||
"""Resume Speed Limit + Offset as an assignable action on a Tesla Model 3/Y with the CAN add-on cable (the car's
|
||||
controls that can run it). Other cars keep the catalog as built."""
|
||||
from openpilot.starpilot.ui.runtime_app import ui_state
|
||||
from openpilot.starpilot.common.car_control_config import SPEED_RESUME, vehicle_supported
|
||||
if vehicle_supported(ui_state.CP):
|
||||
from openpilot.starpilot.ui.slc_resume_action import resume_action
|
||||
actions[SPEED_RESUME] = resume_action(self, ui_state, drive, require_display=True)
|
||||
return actions
|
||||
@@ -0,0 +1,244 @@
|
||||
"""Resume Speed Limit + Offset from a car button (Tesla right stalk, wheel) or a favorite.
|
||||
|
||||
A car button is handled part-way through a screen frame, so by then a 100 Hz message is older than the screen's own
|
||||
age limit and the action would almost never be available. A car button reads the car's messages with the scroll
|
||||
wheel's 250 ms limit instead, through its own dispatcher.
|
||||
"""
|
||||
import atexit
|
||||
import tempfile
|
||||
from types import SimpleNamespace as NS
|
||||
from typing import Any
|
||||
from unittest.mock import patch
|
||||
|
||||
from openpilot.cereal import messaging
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.starpilot.common.car_control_config import NO_LIMIT_REASON, SPEED_RESUME
|
||||
from openpilot.starpilot.ui.onroad_state import SlcActionKind
|
||||
from openpilot.starpilot.ui.runtime_snapshot import INPUT_MAX_AGE_NS, current_message, input_message
|
||||
from openpilot.starpilot.ui.slc_action_dispatch import SlcActionDispatcher
|
||||
from openpilot.starpilot.ui.slc_resume_action import resume_action
|
||||
from openpilot.starpilot.ui.tests.test_runtime_snapshot import BOOT_OFFSET_NS, NOW, ui_fake
|
||||
|
||||
_param_dir = tempfile.TemporaryDirectory(prefix="starpilot-resume-test-")
|
||||
atexit.register(_param_dir.cleanup)
|
||||
_original_params_init = Params.__init__
|
||||
with patch.object(Params, "__init__", lambda self, d="": _original_params_init(self, _param_dir.name)):
|
||||
from openpilot.starpilot.ui import runtime_app
|
||||
|
||||
CAR_SERVICES = ("carState", "carControl", "controlsState", "selfdriveState")
|
||||
|
||||
|
||||
class SavedParams:
|
||||
def __init__(self, safe=False):
|
||||
self.safe = safe
|
||||
|
||||
def get_bool(self, key):
|
||||
return self.safe if key == 'SafeMode' else False
|
||||
|
||||
|
||||
def live(**changes):
|
||||
state = {'enabled': True, 'observationKind': 'valid', 'hasPending': False, 'automaticAdoptionPending': False,
|
||||
'sessionId': 's1', 'decisionId': 3, 'presentationId': 7, 'speedLimit': 22.35}
|
||||
state.update(changes)
|
||||
return NS(**state)
|
||||
|
||||
|
||||
class Shell:
|
||||
def __init__(self, state, display=True, accepted=True):
|
||||
self.state, self.display, self.accepted = state, display, accepted
|
||||
self.reads, self.sent, self.screen_sent = [], [], []
|
||||
self.slc_car_actions: Any = NS(dispatch=self.dispatch)
|
||||
self.slc_actions = NS(dispatch=self.screen_sent.append)
|
||||
|
||||
def _live_slc_message(self, now_ns, *, car_input=False):
|
||||
self.reads.append(car_input)
|
||||
return self.state
|
||||
|
||||
def _favorite_authority(self):
|
||||
return self.display
|
||||
|
||||
def dispatch(self, request):
|
||||
self.sent.append(request)
|
||||
return self.accepted
|
||||
|
||||
|
||||
def ui(safe=False):
|
||||
return NS(params=SavedParams(safe), replay_clock=None)
|
||||
|
||||
|
||||
def press(action):
|
||||
"""Run the action as a car button or a favorite would."""
|
||||
assert action.invoke is not None
|
||||
return action.invoke()
|
||||
|
||||
|
||||
def test_car_button_adopts_the_limit_reading_with_the_button_age():
|
||||
shell = Shell(live())
|
||||
action = resume_action(shell, ui(), 'drive', require_display=False)
|
||||
assert action.available and action.label == 'Resume Speed Limit + Offset' and action.key == SPEED_RESUME
|
||||
assert press(action) is True
|
||||
request, = shell.sent
|
||||
assert request.kind is SlcActionKind.ADOPT
|
||||
assert (request.session_id, request.decision_id, request.presentation_id, request.candidate_speed_mps) == ('s1', 3, 7, 22.35)
|
||||
assert shell.reads and all(shell.reads), 'every read is a car-button read'
|
||||
assert not shell.screen_sent, "sent through the car-button dispatcher, never the screen's"
|
||||
|
||||
|
||||
def test_a_limit_waiting_for_confirmation_is_accepted():
|
||||
shell = Shell(live(hasPending=True))
|
||||
assert press(resume_action(shell, ui(), 'drive', require_display=False)) is True
|
||||
assert shell.sent[0].kind is SlcActionKind.ACCEPT
|
||||
automatic = Shell(live(hasPending=True, automaticAdoptionPending=True))
|
||||
assert press(resume_action(automatic, ui(), 'drive', require_display=False)) is True
|
||||
assert automatic.sent[0].kind is SlcActionKind.ADOPT, 'a limit about to be adopted by itself is adopted, not confirmed'
|
||||
|
||||
|
||||
def test_the_result_is_what_the_dispatcher_decided():
|
||||
shell = Shell(live(), accepted=False)
|
||||
assert press(resume_action(shell, ui(), 'drive', require_display=False)) is False
|
||||
assert len(shell.sent) == 1
|
||||
|
||||
|
||||
def test_a_car_button_does_not_need_the_screen_but_a_favorite_does():
|
||||
shell = Shell(live(), display=False)
|
||||
assert resume_action(shell, ui(), 'drive', require_display=False).available
|
||||
favorite = resume_action(shell, ui(), 'drive', require_display=True)
|
||||
assert not favorite.available and press(favorite) is False and not shell.sent
|
||||
shell.display = True
|
||||
favorite = resume_action(shell, ui(), 'drive', require_display=True)
|
||||
assert favorite.available and press(favorite) is True and len(shell.sent) == 1
|
||||
|
||||
|
||||
def test_safe_mode_replay_and_no_limit_block_it():
|
||||
assert not resume_action(Shell(live()), ui(safe=True), 'drive', require_display=False).available
|
||||
replay = NS(params=SavedParams(), replay_clock=object())
|
||||
assert not resume_action(Shell(live()), replay, 'drive', require_display=False).available
|
||||
no_limit = resume_action(Shell(live(observationKind='absent')), ui(), 'drive', require_display=False)
|
||||
assert not no_limit.available and no_limit.reason == NO_LIMIT_REASON == 'No current speed limit'
|
||||
off = resume_action(Shell(None), ui(), 'drive', require_display=False)
|
||||
assert not off.available and off.reason == 'Speed Limit Controller is not running'
|
||||
disabled = resume_action(Shell(live(enabled=False)), ui(), 'drive', require_display=False)
|
||||
assert not disabled.available and disabled.reason == 'Speed Limit Controller is not running'
|
||||
|
||||
|
||||
def test_without_the_car_button_dispatcher_it_is_unavailable_and_sends_nothing():
|
||||
shell = Shell(live())
|
||||
shell.slc_car_actions = None
|
||||
action = resume_action(shell, ui(), 'drive', require_display=False)
|
||||
assert not action.available and press(action) is False
|
||||
del shell.slc_car_actions # the action transport never started
|
||||
action = resume_action(shell, ui(), 'drive', require_display=False)
|
||||
assert not action.available and press(action) is False
|
||||
assert not shell.sent and not shell.screen_sent, "the screen's dispatcher is not a fallback"
|
||||
|
||||
|
||||
def test_things_that_change_after_the_lookup_are_checked_again_at_the_press():
|
||||
state = ui()
|
||||
shell = Shell(live())
|
||||
action = resume_action(shell, state, 'drive', require_display=False)
|
||||
state.params.safe = True
|
||||
assert press(action) is False and not shell.sent
|
||||
state.params.safe = False
|
||||
shell.state = None
|
||||
assert press(action) is False and not shell.sent
|
||||
|
||||
|
||||
def test_the_token_changes_with_the_drive_and_the_limit_shown():
|
||||
tokens = {resume_action(Shell(live()), ui(), drive, require_display=False).token for drive in ('a', 'b')}
|
||||
tokens.add(resume_action(Shell(live(presentationId=8)), ui(), 'a', require_display=False).token)
|
||||
tokens.add(resume_action(Shell(live(sessionId='s2')), ui(), 'a', require_display=False).token)
|
||||
tokens.add(resume_action(Shell(None), ui(), 'a', require_display=False).token)
|
||||
assert len(tokens) == 5
|
||||
|
||||
|
||||
class Publisher:
|
||||
def __init__(self):
|
||||
self.sent = []
|
||||
|
||||
def send(self, topic, message):
|
||||
self.sent.append((topic, messaging.log_from_bytes(message.to_bytes())))
|
||||
|
||||
|
||||
def test_the_real_dispatcher_checks_the_limit_again_with_the_car_button_reader():
|
||||
state = live(frameMonoTime=NOW - 50_000_000, source='dashboard', pendingSpeedLimit=0., actionSequenceId=0)
|
||||
shell = Shell(state)
|
||||
publisher = Publisher()
|
||||
shell.slc_car_actions = SlcActionDispatcher(publisher, lambda now_ns: shell._live_slc_message(now_ns, car_input=True), clock=lambda: NOW)
|
||||
action = resume_action(shell, ui(), 'drive', require_display=False)
|
||||
assert press(action) is True
|
||||
(topic, message), = publisher.sent
|
||||
assert topic == 'slcAction' and message.slcAction.kind == 'adopt'
|
||||
assert (message.slcAction.sessionId, message.slcAction.decisionId, message.slcAction.presentationId) == ('s1', 3, 7)
|
||||
assert all(shell.reads) and len(shell.reads) >= 3, 'the lookup, the press and the dispatcher each read as a car button'
|
||||
assert press(action) is False and len(publisher.sent) == 1, 'the same limit is not adopted twice'
|
||||
|
||||
|
||||
def test_the_real_dispatcher_refuses_a_press_whose_limit_has_changed_or_gone_stale():
|
||||
def dispatcher(current):
|
||||
return SlcActionDispatcher(Publisher(), lambda now_ns: current, clock=lambda: NOW)
|
||||
fresh = {"frameMonoTime": NOW - 50_000_000, "source": 'dashboard', "pendingSpeedLimit": 0., "actionSequenceId": 0}
|
||||
for current in (live(speedLimit=25., **fresh), live(presentationId=8, **fresh), live(sessionId='s2', **fresh),
|
||||
live(enabled=False, **fresh), live(**{**fresh, 'frameMonoTime': NOW - 100_000_001}), None):
|
||||
shell = Shell(live()) # what the press read
|
||||
shell.slc_car_actions = dispatcher(current)
|
||||
assert press(resume_action(shell, ui(), 'drive', require_display=False)) is False
|
||||
assert not shell.slc_car_actions.publisher.sent
|
||||
|
||||
|
||||
def test_a_car_button_reads_fast_messages_up_to_a_quarter_second_old():
|
||||
assert INPUT_MAX_AGE_NS == 250_000_000
|
||||
fake = ui_fake()
|
||||
for age, button, screen in ((10_000_000, True, True), (150_000_000, True, False), (250_000_000, True, False), (250_000_001, False, False)):
|
||||
fake.sm.put("carState", fake.sm.messages["carState"], age_ns=age)
|
||||
assert (input_message(fake.sm, "carState", NOW) is not None) is button, age
|
||||
assert (current_message(fake.sm, "carState", NOW) is not None) is screen, age
|
||||
fake.sm.put("carState", fake.sm.messages["carState"], age_ns=10_000_000)
|
||||
assert input_message(fake.sm, "carState", NOW, after_frame=3) is None, 'still needs a message received since the drive started'
|
||||
fake.sm.valid["carState"] = False
|
||||
assert input_message(fake.sm, "carState", NOW) is None
|
||||
fake.sm.valid["carState"] = True
|
||||
fake.sm.alive["carState"] = False
|
||||
assert input_message(fake.sm, "carState", NOW) is None
|
||||
fake.sm.alive["carState"] = True
|
||||
fake.sm.logMonoTime["carState"] = NOW + 1
|
||||
assert input_message(fake.sm, "carState", NOW) is None, 'never a message from the future'
|
||||
|
||||
|
||||
def test_a_slow_service_keeps_its_own_longer_limit_for_a_car_button():
|
||||
fake = ui_fake()
|
||||
fake.sm.put("deviceState", fake.sm.messages["deviceState"], age_ns=900_000_000) # 2 Hz: two periods is one second
|
||||
assert input_message(fake.sm, "deviceState", NOW) is not None and current_message(fake.sm, "deviceState", NOW) is not None
|
||||
|
||||
|
||||
def test_live_state_for_a_car_button_allows_a_message_a_frame_old():
|
||||
# The real reader: 100 Hz messages 150 ms old pass for a car button; past its limit they are refused for both.
|
||||
fake = ui_fake()
|
||||
fake.CP = NS(carFingerprint="TESLA_MODEL_3", openpilotLongitudinalControl=True, pcmCruise=True)
|
||||
fake.sm.messages["carState"].canValid = True
|
||||
fake.sm.messages["carState"].canTimeout = False
|
||||
fake.sm.put("controlsState", NS(longControlState="pid"))
|
||||
for service in CAR_SERVICES:
|
||||
fake.sm.put(service, fake.sm.messages[service], age_ns=150_000_000)
|
||||
session = runtime_app.StarShellSession.__new__(runtime_app.StarShellSession)
|
||||
session.adapter = runtime_app.RuntimeSnapshotAdapter(fake)
|
||||
with patch("openpilot.starpilot.ui.runtime_snapshot._clock_pair", return_value=(NOW, NOW + BOOT_OFFSET_NS, BOOT_OFFSET_NS)):
|
||||
assert session._live_slc_message(NOW, car_input=True) is fake.sm["slcState"]
|
||||
for service in CAR_SERVICES:
|
||||
fake.sm.put(service, fake.sm.messages[service], age_ns=230_000_000)
|
||||
assert session._live_slc_message(NOW) is None, "past the screen's own limit"
|
||||
assert session._live_slc_message(NOW, car_input=True) is fake.sm["slcState"]
|
||||
for service in CAR_SERVICES:
|
||||
fake.sm.put(service, fake.sm.messages[service], age_ns=300_000_000)
|
||||
assert session._live_slc_message(NOW, car_input=True) is None, 'still refused past the button limit'
|
||||
assert session._live_slc_message(NOW) is None
|
||||
for service in CAR_SERVICES:
|
||||
fake.sm.put(service, fake.sm.messages[service], age_ns=10_000_000)
|
||||
fake.sm.messages["carState"].canValid = False
|
||||
assert session._live_slc_message(NOW, car_input=True) is None, 'the longer age limit changes nothing else'
|
||||
|
||||
|
||||
def test_the_shell_gives_car_buttons_their_own_dispatcher():
|
||||
source = open(runtime_app.__file__).read()
|
||||
assert "self.slc_car_actions = SlcActionDispatcher(_slc_action_publisher(), lambda now_ns: self._live_slc_message(now_ns, car_input=True))" in source
|
||||
assert "self.slc_actions = SlcActionDispatcher(_slc_action_publisher(), self._live_slc_message)" in source
|
||||
assert issubclass(runtime_app.StarShellSession, runtime_app.TeslaSpeedActions)
|
||||
@@ -0,0 +1,386 @@
|
||||
"""Tesla Model 3/Y Vehicle Settings: the CAN add-on cable status and the one switch, Comma can set speed on Tesla
|
||||
dashboard. The switch takes effect within a second, without a restart, and is shown grayed with the reason when the car
|
||||
as it started cannot use it."""
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
import pytest
|
||||
|
||||
from opendbc.car.structs import car
|
||||
from opendbc.car.tesla.speed_sync import selected
|
||||
from opendbc.car.tesla.values import CAR
|
||||
from openpilot.common.params import Params, UnknownKeyName
|
||||
from openpilot.starpilot.car.tesla import set_speed
|
||||
from openpilot.starpilot.galaxy.settings import AuthorityContext, SettingsChanged, SettingsGateway, _projection
|
||||
from openpilot.starpilot.tests.tesla_set_speed_fixture import tesla
|
||||
from openpilot.starpilot.ui.feature_settings_owner import FeatureSettingsOwner
|
||||
from openpilot.starpilot.ui.feature_settings_state import FeaturePage, FeatureRow, FeatureSettingsRequest, FeatureUiAction, value_request
|
||||
from openpilot.starpilot.ui.tesla_set_speed_feature import (CABLE_HELP, CABLE_LINKS, CABLE_MISSING, KEYS, LONG_MISSING, RESTART_NEEDED,
|
||||
SYNC, SYNC_HELP, SYNC_LABEL, TeslaSetSpeedFeature, addon_cable)
|
||||
from openpilot.starpilot.ui.vehicle_bool import VEHICLE_BOOL_KEYS, confirmation_question
|
||||
from openpilot.starpilot.vehicle_preferences import VehicleStartupPreferences
|
||||
|
||||
CABLE_LABEL = 'Tesla CAN add-on cable'
|
||||
RELEASE = 'Not available on release builds'
|
||||
REMOVED_ROWS = ('Independent set speed', 'Override Tesla set-speed changes', "Match the Tesla's set speed", 'Gentle slowing',
|
||||
'Short scroll', 'Fast scroll')
|
||||
MODELS = (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y)
|
||||
|
||||
|
||||
def started(candidate=CAR.TESLA_MODEL_3, **changes):
|
||||
"""A Model 3/Y as it normally starts: startup admits the scroll frame whenever the car is eligible."""
|
||||
return tesla(candidate, selected=True, **changes)
|
||||
|
||||
|
||||
def other_car(brand, fingerprint):
|
||||
return car.CarParams.new_message(brand=brand, carFingerprint=fingerprint, pcmCruise=True, openpilotLongitudinalControl=True, flags=8)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODELS)
|
||||
def test_the_cable_is_a_startup_fact_of_model_3_and_y(candidate):
|
||||
assert addon_cable(tesla(candidate)) is True and addon_cable(tesla(candidate, cable=False)) is False
|
||||
assert addon_cable(tesla(candidate, long=False)) is True, 'the cable does not depend on longitudinal control'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('make', [lambda: None, lambda: other_car('hyundai', 'HYUNDAI_IONIQ_5'),
|
||||
lambda: other_car('toyota', 'TOYOTA_RAV4_TSS2'), lambda: other_car('mock', 'TESLA_MODEL_3'),
|
||||
lambda: tesla(CAR.TESLA_MODEL_X), lambda: tesla(CAR.TESLA_MODEL_S_HW1),
|
||||
lambda: tesla(CAR.TESLA_MODEL_S_PREAP)])
|
||||
def test_other_cars_have_no_cable_status_and_no_rows(tmp_path, make):
|
||||
cp = make()
|
||||
assert addon_cable(cp) is None
|
||||
owner = FeatureSettingsOwner(Params(str(tmp_path)), lambda group: True,
|
||||
vehicle_fingerprint=lambda: getattr(cp, 'carFingerprint', None), vehicle_params=lambda: cp)
|
||||
feature = TeslaSetSpeedFeature(owner)
|
||||
assert feature.capability() is None and feature.rows(True) == () and not feature.active()
|
||||
labels = [row.label for row in owner.snapshot(FeaturePage.VEHICLE, parked=True, system_long=True, lateral_context=False, metric=False).rows]
|
||||
assert CABLE_LABEL not in labels and SYNC_LABEL not in labels
|
||||
|
||||
|
||||
def test_something_that_is_not_car_parameters_has_no_cable_status():
|
||||
assert addon_cable(object()) is None
|
||||
|
||||
|
||||
class TeslaSettings(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temporary = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temporary.cleanup)
|
||||
self.params = Params(temporary.name)
|
||||
self.use(started())
|
||||
|
||||
def use(self, cp, parked=True):
|
||||
self.context = AuthorityContext(parked, cp, cp.as_reader().as_builder().to_bytes())
|
||||
self.gateway = SettingsGateway(self.params, self, clock=lambda: 100.0)
|
||||
|
||||
def sample(self):
|
||||
return self.context
|
||||
|
||||
def rows(self, page='vehicle'):
|
||||
return {row['label']: row for row in self.gateway.page(page, 'session', b'generation')['rows']}
|
||||
|
||||
def labels(self, page='vehicle'):
|
||||
return [row['label'] for row in self.gateway.page(page, 'session', b'generation')['rows']]
|
||||
|
||||
def intent(self, label, value, page='vehicle'):
|
||||
view = self.gateway.page(page, 'session', b'generation')
|
||||
index = next(i for i, row in enumerate(view['rows']) if row['label'] == label)
|
||||
return self.gateway.preview(view['view'], index, 0, 'session', b'generation', value=value)
|
||||
|
||||
def save(self, label, value, page='vehicle'):
|
||||
return self.gateway.confirm(self.intent(label, value, page)['intent'], 'session', b'generation')
|
||||
|
||||
def write_raw(self, key, raw):
|
||||
Path(self.params.get_param_path(key)).write_bytes(raw)
|
||||
|
||||
def test_rows_defaults_and_cable_status(self):
|
||||
rows = self.rows()
|
||||
cable = rows[CABLE_LABEL]
|
||||
assert cable['value'] == 'Detected' and cable['status'] is True and cable['reason'] == CABLE_HELP, 'a status, shown normally'
|
||||
assert not cable['available'], 'nothing to change'
|
||||
assert [(link['label'], link['url']) for link in cable['links']] == list(CABLE_LINKS)
|
||||
assert [label for label, _ in CABLE_LINKS] == ['Buy the cable', 'Install guide']
|
||||
assert all(link['url'].startswith('https://') for link in cable['links'])
|
||||
sync = rows[SYNC_LABEL]
|
||||
assert SYNC_LABEL == 'Comma can set speed on Tesla dashboard'
|
||||
assert (sync['value'], sync['available'], sync['defaultValue']) == ('Off', True, 'Off')
|
||||
assert sync['reason'] == SYNC_HELP and 'links' not in sync and 'status' not in sync
|
||||
|
||||
def test_the_help_says_what_the_switch_does_now(self):
|
||||
assert 'startup' not in SYNC_HELP and 'restart' not in SYNC_HELP, 'it applies at once'
|
||||
assert 'lag a second or two' in SYNC_HELP and 'must use the same units' in SYNC_HELP
|
||||
assert SYNC_HELP.startswith('StarPilot keeps its own set speed') and SYNC_HELP.endswith('Experimental.')
|
||||
assert len(SYNC_HELP) < 240 and len(CABLE_HELP) < 220, 'short enough to read at a glance'
|
||||
assert RESTART_NEEDED == 'Available after the next startup'
|
||||
|
||||
def test_only_the_cable_row_is_a_status_for_galaxy(self):
|
||||
for page in ('vehicle', 'wheel', 'slc', 'hub'):
|
||||
for row in self.gateway.page(page, 'session', b'generation')['rows']:
|
||||
assert ('status' in row) is (row['label'] == CABLE_LABEL), (page, row['label'])
|
||||
assert ('links' in row) is (row['label'] == CABLE_LABEL), (page, row['label'])
|
||||
|
||||
def test_the_cable_and_the_switch_come_first_of_the_tesla_rows(self):
|
||||
labels = self.labels()
|
||||
start = labels.index(CABLE_LABEL)
|
||||
assert labels[start:start + 4] == [CABLE_LABEL, SYNC_LABEL, 'Disengage AOL on Brake', 'Tesla Co-op Steering']
|
||||
assert 'Three-Finger AOL Tap' not in labels, 'the tap is chosen on its own row in Wheel Controls'
|
||||
|
||||
def test_it_is_the_only_set_speed_setting(self):
|
||||
assert KEYS == frozenset(('TeslaSpeedSync',)) and SYNC == set_speed.PARAM == 'TeslaSpeedSync'
|
||||
for page in ('vehicle', 'wheel', 'slc'):
|
||||
labels = self.labels(page)
|
||||
for removed in REMOVED_ROWS:
|
||||
assert removed not in labels, (page, removed)
|
||||
for key in ('TeslaIndependentSetSpeed', 'TeslaOverrideSetSpeed', 'TeslaGentleSlowing'):
|
||||
with self.assertRaises(UnknownKeyName):
|
||||
self.params.get(key)
|
||||
|
||||
def test_saving_on_and_off_takes_effect_without_a_restart(self):
|
||||
cp = self.context.cp
|
||||
assert selected(cp) and not set_speed.active(self.params, cp)
|
||||
intent = self.intent(SYNC_LABEL, 'On')
|
||||
assert intent['proposed'] == 'On' and 'comma can set speed on tesla dashboard' in intent['question'].lower()
|
||||
assert self.gateway.confirm(intent['intent'], 'session', b'generation') and self.params.get_bool(SYNC)
|
||||
assert self.rows()[SYNC_LABEL]['value'] == 'On'
|
||||
assert set_speed.active(self.params, cp), 'the comma owns the set speed on this car now'
|
||||
assert cp.safetyConfigs[0].safetyParam == 4097, "the car's parameters never change with the switch"
|
||||
assert self.save(SYNC_LABEL, 'Off') and not self.params.get_bool(SYNC)
|
||||
assert self.rows()[SYNC_LABEL]['value'] == 'Off' and not set_speed.active(self.params, cp)
|
||||
|
||||
def test_startup_admits_the_scroll_frame_whatever_is_saved(self):
|
||||
for saved in (False, True):
|
||||
self.params.put_bool(SYNC, saved, block=True)
|
||||
cp = tesla()
|
||||
VehicleStartupPreferences.read(self.params, enabled=True).prepare(cp)
|
||||
assert selected(cp)
|
||||
self.use(cp)
|
||||
sync = self.rows()[SYNC_LABEL]
|
||||
assert sync['available'] and sync['value'] == ('On' if saved else 'Off') and sync['reason'] == SYNC_HELP
|
||||
|
||||
def test_a_car_that_started_without_the_scroll_frame_needs_a_restart(self):
|
||||
# Safe Mode at startup, or settings changed since: the cable and longitudinal control are there, the bit is not.
|
||||
self.use(tesla())
|
||||
rows = self.rows()
|
||||
assert rows[CABLE_LABEL]['value'] == 'Detected'
|
||||
sync = rows[SYNC_LABEL]
|
||||
assert not sync['available'] and sync['reason'] == RESTART_NEEDED + '.\n' + SYNC_HELP
|
||||
with self.assertRaises(SettingsChanged):
|
||||
self.intent(SYNC_LABEL, 'On')
|
||||
self.params.put_bool(SYNC, True, block=True)
|
||||
assert self.rows()[SYNC_LABEL]['value'] == 'On' and not set_speed.active(self.params, self.context.cp), 'saved on, not in effect'
|
||||
|
||||
def test_without_the_cable_it_is_grayed_with_the_reason(self):
|
||||
self.use(started(cable=False))
|
||||
rows = self.rows()
|
||||
assert rows[CABLE_LABEL]['value'] == 'Not detected' and rows[CABLE_LABEL]['status'] is True
|
||||
sync = rows[SYNC_LABEL]
|
||||
assert not sync['available'] and sync['value'] == 'Off'
|
||||
assert sync['reason'] == CABLE_MISSING + '.\n' + SYNC_HELP
|
||||
with self.assertRaises(SettingsChanged):
|
||||
self.intent(SYNC_LABEL, 'On')
|
||||
assert not self.params.get_bool(SYNC)
|
||||
|
||||
def test_without_alpha_longitudinal_it_is_grayed_with_the_reason(self):
|
||||
self.use(started(long=False))
|
||||
rows = self.rows()
|
||||
assert rows[CABLE_LABEL]['value'] == 'Detected'
|
||||
sync = rows[SYNC_LABEL]
|
||||
assert not sync['available'] and sync['reason'] == LONG_MISSING + '.\n' + SYNC_HELP
|
||||
assert LONG_MISSING == 'Needs Alpha Longitudinal turned on'
|
||||
with self.assertRaises(SettingsChanged):
|
||||
self.intent(SYNC_LABEL, 'On')
|
||||
|
||||
def test_on_a_release_build_it_is_grayed_with_the_reason(self):
|
||||
self.params.put_bool('IsReleaseBranch', True, block=True)
|
||||
sync = self.rows()[SYNC_LABEL]
|
||||
assert not sync['available'] and sync['reason'] == RELEASE + '.\n' + SYNC_HELP
|
||||
with self.assertRaises(SettingsChanged):
|
||||
self.intent(SYNC_LABEL, 'On')
|
||||
self.params.put_bool('IsReleaseBranch', False, block=True)
|
||||
assert self.rows()[SYNC_LABEL]['available']
|
||||
self.write_raw('IsReleaseBranch', b'unreadable')
|
||||
assert not self.rows()[SYNC_LABEL]['available'], 'an unreadable release marker counts as a release build'
|
||||
|
||||
def test_the_first_missing_thing_is_the_reason_shown(self):
|
||||
self.params.put_bool('IsReleaseBranch', True, block=True)
|
||||
self.use(tesla(cable=False, long=False))
|
||||
assert self.rows()[SYNC_LABEL]['reason'].startswith(CABLE_MISSING + '.')
|
||||
self.use(tesla(long=False))
|
||||
assert self.rows()[SYNC_LABEL]['reason'].startswith(LONG_MISSING + '.')
|
||||
self.use(tesla())
|
||||
assert self.rows()[SYNC_LABEL]['reason'].startswith(RELEASE + '.')
|
||||
self.params.put_bool('IsReleaseBranch', False, block=True)
|
||||
assert self.rows()[SYNC_LABEL]['reason'].startswith(RESTART_NEEDED + '.')
|
||||
self.use(started())
|
||||
assert self.rows()[SYNC_LABEL]['reason'] == SYNC_HELP
|
||||
|
||||
def test_a_choice_saved_earlier_still_shows_while_grayed(self):
|
||||
assert self.save(SYNC_LABEL, 'On')
|
||||
self.use(started(cable=False))
|
||||
sync = self.rows()[SYNC_LABEL]
|
||||
assert sync['value'] == 'On' and not sync['available'] and sync['reason'].startswith(CABLE_MISSING)
|
||||
assert not set_speed.active(self.params, self.context.cp)
|
||||
|
||||
def test_an_invalid_saved_choice_is_shown_cannot_be_changed_and_is_off(self):
|
||||
self.write_raw(SYNC, b'2')
|
||||
sync = self.rows()[SYNC_LABEL]
|
||||
assert (sync['value'], sync['available'], sync['reason']) == ('Invalid saved choice', False, 'Invalid saved choice')
|
||||
assert not set_speed.requested(self.params) and not set_speed.active(self.params, self.context.cp)
|
||||
|
||||
def test_it_can_only_be_changed_while_parked(self):
|
||||
intent = self.intent(SYNC_LABEL, 'On')
|
||||
self.context = replace(self.context, parked=False)
|
||||
assert not self.gateway.confirm(intent['intent'], 'session', b'generation'), 'confirmed after driving off: refused'
|
||||
assert not self.params.get_bool(SYNC)
|
||||
rows = self.rows()
|
||||
with self.assertRaises(SettingsChanged):
|
||||
self.intent(SYNC_LABEL, 'On')
|
||||
assert not rows[SYNC_LABEL]['available'] and rows[CABLE_LABEL]['value'] == 'Detected' and rows[CABLE_LABEL]['status'] is True
|
||||
|
||||
def test_a_confirmation_does_not_survive_a_changed_car(self):
|
||||
intent = self.intent(SYNC_LABEL, 'On')
|
||||
self.use(started(cable=False))
|
||||
with self.assertRaises(SettingsChanged):
|
||||
self.gateway.confirm(intent['intent'], 'session', b'generation')
|
||||
assert not self.params.get_bool(SYNC)
|
||||
|
||||
def test_model_y_has_the_same_rows(self):
|
||||
self.use(started(CAR.TESLA_MODEL_Y))
|
||||
rows = self.rows()
|
||||
assert rows[CABLE_LABEL]['value'] == 'Detected' and rows[SYNC_LABEL]['available']
|
||||
assert self.save(SYNC_LABEL, 'On') and self.params.get_bool(SYNC)
|
||||
assert set_speed.active(self.params, self.context.cp)
|
||||
|
||||
|
||||
def test_galaxy_passes_on_a_status_and_only_https_links():
|
||||
links = (('Plain', 'http://example.com'), ('Script', 'javascript:alert(1)'), ('Safe', 'https://example.com/a'))
|
||||
projected = _projection(FeatureRow('', 'Status', 'Detected', status=True, links=links))
|
||||
assert projected['status'] is True and projected['links'] == [{'label': 'Safe', 'url': 'https://example.com/a'}]
|
||||
plain = _projection(FeatureRow('Key', 'Label', 'Off'))
|
||||
assert 'status' not in plain and 'links' not in plain, 'every other row is projected exactly as before'
|
||||
|
||||
|
||||
class Owner:
|
||||
"""The settings owner as the feature sees it, with a real saved-settings folder."""
|
||||
def __init__(self, path, cp):
|
||||
self.params = Params(str(path))
|
||||
self.cp, self.parked = cp, True
|
||||
|
||||
def authority(self, group):
|
||||
return self.parked and group == 'parked_preferences'
|
||||
|
||||
def vehicle_params(self):
|
||||
return self.cp
|
||||
|
||||
def vehicle_fingerprint(self):
|
||||
return getattr(self.cp, 'carFingerprint', None)
|
||||
|
||||
|
||||
def sync_request(feature, value='On', **changes):
|
||||
row = next(row for row in feature.rows(True) if row.key == SYNC)
|
||||
request = FeatureSettingsRequest(SYNC, row.source, value, confirmation=True, vehicle_fingerprint=feature.vehicle_fingerprint(),
|
||||
capability=row.capability)
|
||||
return replace(request, **changes)
|
||||
|
||||
|
||||
def test_feature_rows_are_the_cable_status_then_the_switch(tmp_path):
|
||||
feature = TeslaSetSpeedFeature(Owner(tmp_path, started()))
|
||||
cable, sync = feature.rows(True)
|
||||
assert (cable.key, cable.label, cable.value, cable.status, cable.links, cable.available) == ('', CABLE_LABEL, 'Detected', True, CABLE_LINKS, False)
|
||||
assert (sync.key, sync.label, sync.value, sync.choices, sync.default_value, sync.available) == (SYNC, SYNC_LABEL, 'Off', ('Off', 'On'), 'Off', True)
|
||||
assert sync.capability == ('TESLA_MODEL_3', 'tesla', int(started().flags), True, True, (4097,)) and not sync.status and not sync.links
|
||||
assert not feature.rows(False)[1].available, 'not parked'
|
||||
|
||||
|
||||
def test_the_feature_says_when_the_comma_owns_the_set_speed(tmp_path):
|
||||
owner = Owner(tmp_path, started())
|
||||
feature = TeslaSetSpeedFeature(owner)
|
||||
assert not feature.active()
|
||||
assert feature.apply(sync_request(feature)) and feature.active()
|
||||
owner.params.put_bool('SafeMode', True, block=True)
|
||||
assert not feature.active()
|
||||
owner.params.put_bool('SafeMode', False, block=True)
|
||||
owner.cp = tesla()
|
||||
assert not feature.active(), 'saved on, but the car started without the scroll frame'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('changes', [{'confirmation': False}, {'value': 'Auto'}, {'value': ''}, {'key': 'TeslaCoopSteering'},
|
||||
{'expected': b'1'}, {'expected': b'x'}, {'dependencies': (('IsMetric', None),)},
|
||||
{'related_source': b''}, {'display_unit': 'mph'}, {'direction': 1},
|
||||
{'vehicle_fingerprint': None}, {'vehicle_fingerprint': 'TESLA_MODEL_Y'}, {'capability': None},
|
||||
{'capability': ('TESLA_MODEL_3', 'tesla', 4, True, True, (4097,))},
|
||||
{'capability': ('TESLA_MODEL_3', 'tesla', 12, True, True, (1,))}])
|
||||
def test_apply_refuses_any_request_that_is_not_exactly_the_row_shown(tmp_path, changes):
|
||||
owner = Owner(tmp_path, started())
|
||||
feature = TeslaSetSpeedFeature(owner)
|
||||
assert not feature.apply(sync_request(feature, **changes))
|
||||
assert not owner.params.get_bool(SYNC)
|
||||
assert feature.apply(sync_request(feature)) and owner.params.get_bool(SYNC), 'the unchanged request saves'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reason', ['driving', 'cable', 'longitudinal', 'release', 'restart needed', 'other car'])
|
||||
def test_apply_refuses_on_when_the_car_or_build_cannot_use_it(tmp_path, reason):
|
||||
owner = Owner(tmp_path, started())
|
||||
feature = TeslaSetSpeedFeature(owner)
|
||||
request = sync_request(feature)
|
||||
if reason == 'driving':
|
||||
owner.parked = False
|
||||
if reason in ('cable', 'longitudinal', 'restart needed'):
|
||||
owner.cp = {'cable': lambda: started(cable=False), 'longitudinal': lambda: started(long=False), 'restart needed': tesla}[reason]()
|
||||
request = replace(request, capability=feature.capability())
|
||||
if reason == 'release':
|
||||
owner.params.put_bool('IsReleaseBranch', True, block=True)
|
||||
if reason == 'other car':
|
||||
owner.cp = other_car('hyundai', 'HYUNDAI_IONIQ_5')
|
||||
assert not feature.apply(request)
|
||||
assert not owner.params.get_bool(SYNC)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reason', ['cable', 'longitudinal', 'release', 'restart needed'])
|
||||
def test_apply_still_lets_a_saved_on_be_turned_off_when_grayed(tmp_path, reason):
|
||||
owner = Owner(tmp_path, started())
|
||||
feature = TeslaSetSpeedFeature(owner)
|
||||
assert feature.apply(sync_request(feature))
|
||||
if reason == 'release':
|
||||
owner.params.put_bool('IsReleaseBranch', True, block=True)
|
||||
else:
|
||||
owner.cp = {'cable': lambda: started(cable=False), 'longitudinal': lambda: started(long=False), 'restart needed': tesla}[reason]()
|
||||
row = feature.rows(True)[1]
|
||||
assert row.value == 'On' and not row.available
|
||||
request = FeatureSettingsRequest(SYNC, row.source, 'Off', confirmation=True, vehicle_fingerprint=feature.vehicle_fingerprint(),
|
||||
capability=row.capability)
|
||||
assert feature.apply(request) and not owner.params.get_bool(SYNC)
|
||||
|
||||
|
||||
def device_tap(tmp_path, value):
|
||||
"""The request a tap on the switch row makes on the device's own screen, and its owner."""
|
||||
params = Params(str(tmp_path))
|
||||
params.put_bool(SYNC, value == 'Off', block=True)
|
||||
cp = started()
|
||||
owner = FeatureSettingsOwner(params, lambda group: True, vehicle_fingerprint=lambda: cp.carFingerprint, vehicle_params=lambda: cp)
|
||||
state = owner.snapshot(FeaturePage.VEHICLE, parked=True, system_long=True, lateral_context=False, metric=False)
|
||||
row = next(row for row in state.rows if row.key == SYNC)
|
||||
assert row.available
|
||||
request = value_request(state, FeatureUiAction('change', row))
|
||||
assert request is not None and request.value == value and request.key == SYNC and not request.confirmation
|
||||
return params, owner, request
|
||||
|
||||
|
||||
@pytest.mark.parametrize('value', ['On', 'Off'])
|
||||
def test_a_confirmed_tap_on_the_device_screen_changes_the_switch(tmp_path, value):
|
||||
params, owner, request = device_tap(tmp_path, value)
|
||||
assert owner.apply(replace(request, confirmation=True))
|
||||
assert params.get_bool(SYNC) is (value == 'On')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('value', ['On', 'Off'])
|
||||
def test_the_switch_can_be_changed_on_the_device_screen(tmp_path, value):
|
||||
# What runtime_app and feature_settings_compact do with a tapped row: keys in VEHICLE_BOOL_KEYS get a confirmation
|
||||
# dialog (and are then sent confirmed); every other key is sent as tapped.
|
||||
params, owner, request = device_tap(tmp_path, value)
|
||||
if request.key in VEHICLE_BOOL_KEYS:
|
||||
assert confirmation_question(request)
|
||||
request = replace(request, confirmation=True)
|
||||
assert owner.apply(request)
|
||||
assert params.get_bool(SYNC) is (value == 'On')
|
||||
@@ -0,0 +1,301 @@
|
||||
"""How the Tesla Model 3/Y rows join the settings owner: through two subclasses of features it already builds, so every
|
||||
other car's Vehicle Settings, Wheel Controls and Speed Limit Controller pages stay exactly as they were, and each Tesla
|
||||
key reaches its own feature."""
|
||||
from dataclasses import replace
|
||||
import json
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from opendbc.car.car_helpers import interfaces
|
||||
from opendbc.car.values import BRANDS
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.starpilot.common.car_control_config import PARAM
|
||||
from openpilot.starpilot.favorites.actions import BOOKMARK
|
||||
from openpilot.starpilot.galaxy.settings import AuthorityContext, SettingsGateway
|
||||
from openpilot.starpilot.speed_limits.runtime_settings import ADVANCE_KEYS, PEDAL_OVERRIDE_KEY
|
||||
from openpilot.starpilot.tests.tesla_set_speed_fixture import tesla
|
||||
from openpilot.starpilot.ui import feature_settings_owner
|
||||
from openpilot.starpilot.ui.feature_settings_owner import FeatureSettingsOwner
|
||||
from openpilot.starpilot.ui.feature_settings_state import FeaturePage, FeatureSettingsRequest
|
||||
from openpilot.starpilot.ui.tesla_controls_feature import KEYS as CONTROL_KEYS, TeslaControlsFeature
|
||||
from openpilot.starpilot.ui.tesla_rows import KEYS, TeslaVehicleRows, TeslaWheelRows
|
||||
from openpilot.starpilot.ui.tesla_screen_feature import KEYS as SCREEN_KEYS, TeslaScreenFeature
|
||||
from openpilot.starpilot.ui.tesla_set_speed_feature import KEYS as SET_SPEED_KEYS, SYNC_LABEL, TeslaSetSpeedFeature
|
||||
from openpilot.starpilot.ui.wheel_feature import WheelFeature
|
||||
|
||||
MODELS = ('TESLA_MODEL_3', 'TESLA_MODEL_Y')
|
||||
# One platform of every brand, and every Tesla that is not a Model 3 or Model Y.
|
||||
OTHER_CARS = sorted({str(next(iter(brand))) for brand in BRANDS if str(next(iter(brand))) not in MODELS} |
|
||||
{'TESLA_MODEL_X', 'TESLA_MODEL_S_HW1', 'TESLA_MODEL_S_PREAP', 'HYUNDAI_IONIQ_5', 'TOYOTA_RAV4_TSS2'})
|
||||
PAGES = (FeaturePage.VEHICLE, FeaturePage.WHEEL, FeaturePage.SLC)
|
||||
CABLE_LABEL = 'Tesla CAN add-on cable'
|
||||
RULE_KEYS = (*ADVANCE_KEYS, PEDAL_OVERRIDE_KEY)
|
||||
|
||||
|
||||
class ScreenRowsBefore(TeslaScreenFeature):
|
||||
"""The Tesla screen rows as the owner built them before the set-speed rows joined."""
|
||||
|
||||
|
||||
class WheelBefore(WheelFeature):
|
||||
"""The wheel rows as the owner added them before the Tesla rows joined: after whatever the page already had."""
|
||||
def page(self, rows):
|
||||
return [*rows, *self.rows()]
|
||||
|
||||
|
||||
def other(platform):
|
||||
return None if platform is None else interfaces[platform].get_non_essential_params(platform)
|
||||
|
||||
|
||||
def switch_on(params):
|
||||
params.put_bool('TeslaSpeedSync', True, block=True)
|
||||
return params
|
||||
|
||||
|
||||
def build_owner(params, cp, *, before=False):
|
||||
"""The settings owner for `cp`; before=True wires the two features the owner built before the Tesla rows were added."""
|
||||
owner = FeatureSettingsOwner(params, lambda group: True, vehicle_fingerprint=lambda: getattr(cp, 'carFingerprint', None),
|
||||
vehicle_params=lambda: cp)
|
||||
if before:
|
||||
vars(owner).update(tesla_screen=ScreenRowsBefore(owner), wheel=WheelBefore(owner))
|
||||
return owner
|
||||
|
||||
|
||||
def pages(owner):
|
||||
return {(page, parked, long): owner.snapshot(page, parked=parked, system_long=long, lateral_context=False, metric=False)
|
||||
for page in PAGES for parked in (True, False) for long in (True, False)}
|
||||
|
||||
|
||||
class Context:
|
||||
def __init__(self, cp):
|
||||
self.context = AuthorityContext(True, cp, None if cp is None else cp.as_reader().as_builder().to_bytes())
|
||||
|
||||
def sample(self):
|
||||
return self.context
|
||||
|
||||
|
||||
def galaxy_rows(params, cp, page):
|
||||
gateway = SettingsGateway(params, Context(cp), clock=lambda: 100.0)
|
||||
return json.dumps(gateway.page(page, 'session', b'generation')['rows'], sort_keys=True).encode()
|
||||
|
||||
|
||||
def test_the_owner_builds_the_two_tesla_subclasses_in_place_of_the_features_it_had(tmp_path):
|
||||
owner = build_owner(Params(str(tmp_path)), tesla(selected=True))
|
||||
assert type(owner.tesla_screen) is TeslaVehicleRows and isinstance(owner.tesla_screen, TeslaScreenFeature)
|
||||
assert type(owner.wheel) is TeslaWheelRows and isinstance(owner.wheel, WheelFeature)
|
||||
assert type(owner.tesla_screen.set_speed) is TeslaSetSpeedFeature and type(owner.tesla_screen.controls) is TeslaControlsFeature
|
||||
assert type(owner.wheel.tesla) is TeslaControlsFeature
|
||||
assert not hasattr(owner, 'tesla_set_speed') and not hasattr(owner, 'tesla_controls')
|
||||
assert KEYS == SCREEN_KEYS | SET_SPEED_KEYS | CONTROL_KEYS == feature_settings_owner.TESLA_SCREEN_KEYS
|
||||
assert SET_SPEED_KEYS == {'TeslaSpeedSync'} and SCREEN_KEYS == {'TeslaAOLDisengageOnBrake'}
|
||||
assert not SCREEN_KEYS & SET_SPEED_KEYS and not SCREEN_KEYS & CONTROL_KEYS and not SET_SPEED_KEYS & CONTROL_KEYS
|
||||
|
||||
|
||||
@pytest.mark.parametrize('platform', [None, *OTHER_CARS])
|
||||
def test_vehicle_wheel_and_speed_limit_pages_are_unchanged_for_other_cars_and_for_no_car(tmp_path, platform):
|
||||
params = switch_on(Params(str(tmp_path))) # the switch saved on by a Tesla owner means nothing to another car
|
||||
for name in RULE_KEYS:
|
||||
params.put(name, 1, block=True)
|
||||
now = pages(build_owner(params, other(platform)))
|
||||
before = pages(build_owner(params, other(platform), before=True))
|
||||
assert now == before
|
||||
assert repr(now).encode() == repr(before).encode(), 'byte for byte'
|
||||
for state in now.values():
|
||||
assert not any(row.status or row.links or row.key in KEYS or row.key.startswith('tesla_input:') for row in state.rows)
|
||||
assert CABLE_LABEL not in [row.label for row in state.rows] and SYNC_LABEL not in [row.label for row in state.rows]
|
||||
assert not build_owner(params, other(platform)).tesla_screen.set_speed.active()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('platform', [None, 'HYUNDAI_IONIQ_5', 'TOYOTA_RAV4_TSS2', 'TESLA_MODEL_X', 'TESLA_MODEL_S_HW1', 'TESLA_MODEL_S_PREAP'])
|
||||
@pytest.mark.parametrize('page', ['vehicle', 'wheel', 'slc'])
|
||||
def test_galaxy_gets_the_same_bytes_for_other_cars_and_for_no_car(tmp_path, platform, page):
|
||||
params = switch_on(Params(str(tmp_path)))
|
||||
now = galaxy_rows(params, other(platform), page)
|
||||
with patch.object(feature_settings_owner, 'TeslaVehicleRows', ScreenRowsBefore), \
|
||||
patch.object(feature_settings_owner, 'TeslaWheelRows', WheelBefore):
|
||||
before = galaxy_rows(params, other(platform), page)
|
||||
assert now == before
|
||||
assert all('status' not in row and 'links' not in row for row in json.loads(now)), 'no key the page did not have before'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('model', MODELS)
|
||||
@pytest.mark.parametrize('switch', [False, True])
|
||||
def test_a_tesla_gets_its_rows_above_the_screen_rows_and_below_the_wheel_buttons(tmp_path, model, switch):
|
||||
params = Params(str(tmp_path))
|
||||
params.put_bool('TeslaSpeedSync', switch, block=True)
|
||||
cp = tesla(model, selected=True)
|
||||
now, before = pages(build_owner(params, cp)), pages(build_owner(params, cp, before=True))
|
||||
for key, state in now.items():
|
||||
labels, old = [row.label for row in state.rows], [row.label for row in before[key].rows]
|
||||
if key[0] == FeaturePage.VEHICLE:
|
||||
at = labels.index(CABLE_LABEL)
|
||||
assert labels[at:at + 2] == [CABLE_LABEL, SYNC_LABEL] and labels[at + 2] == 'Disengage AOL on Brake'
|
||||
assert labels[:at] + labels[at + 2:] == old, 'two rows added, nothing else moved'
|
||||
elif key[0] == FeaturePage.WHEEL:
|
||||
added = labels[len(old):]
|
||||
assert labels[:len(old)] == old and len(added) == 14
|
||||
assert added[0] == 'Right scroll wheel / Scroll up' and added[-1] == 'Tesla screen / Three-finger tap'
|
||||
else:
|
||||
assert labels == old, 'the Speed Limit Controller page has the same rows'
|
||||
kept = [row for row in state.rows if row.label not in (CABLE_LABEL, SYNC_LABEL) and
|
||||
not row.label.startswith(('Right scroll wheel /', 'Right stalk /', 'Tesla screen /'))]
|
||||
assert kept == list(before[key].rows), 'the rows it had are the same rows, whatever the switch says'
|
||||
|
||||
|
||||
# Adopt limits early and After an accelerator override work with the switch on, so their rows are the stock ones.
|
||||
|
||||
@pytest.mark.parametrize('model', MODELS)
|
||||
def test_the_speed_limit_controller_page_is_the_stock_page_with_the_switch_on(tmp_path, model):
|
||||
params = Params(str(tmp_path))
|
||||
params.put_bool('SpeedLimitController', True, block=True)
|
||||
params.put(ADVANCE_KEYS[0], 3, block=True)
|
||||
cp = tesla(model, selected=True)
|
||||
|
||||
def page(owner):
|
||||
return owner.snapshot(FeaturePage.SLC, parked=True, system_long=True, lateral_context=False, metric=False).rows
|
||||
|
||||
off = page(build_owner(params, cp))
|
||||
switch_on(params)
|
||||
owner = build_owner(params, cp)
|
||||
assert owner.tesla_screen.set_speed.active()
|
||||
assert page(owner) == off == page(build_owner(params, cp, before=True))
|
||||
rows = {row.key: row for row in off if row.key in RULE_KEYS}
|
||||
assert list(rows) == list(RULE_KEYS) and all(row.available for row in rows.values())
|
||||
assert rows[ADVANCE_KEYS[0]].value == '3 s'
|
||||
|
||||
|
||||
STEP_ROWS = ['Short press', 'Hold']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('model', MODELS)
|
||||
@pytest.mark.parametrize('cable', [True, False])
|
||||
def test_galaxy_leaves_the_cruise_step_rows_out_for_a_model_3_or_y(tmp_path, model, cable):
|
||||
# Galaxy shows Short press and Hold above the wheel rows for every car. StarPilot never steps a Model 3/Y's set speed
|
||||
# from cruise buttons (the scroll wheel steps are fixed), so they are left out there, cable or not.
|
||||
rows = json.loads(galaxy_rows(Params(str(tmp_path)), tesla(model, cable=cable, selected=cable), 'wheel'))
|
||||
labels = [row['label'] for row in rows]
|
||||
assert not [label for label in labels if label in STEP_ROWS]
|
||||
assert labels[0] == 'Right scroll wheel / Scroll up' and labels[-1] == 'Tesla screen / Three-finger tap'
|
||||
with patch.object(feature_settings_owner, 'TeslaWheelRows', WheelBefore):
|
||||
before = [row['label'] for row in json.loads(galaxy_rows(Params(str(tmp_path)), tesla(model, cable=cable, selected=cable), 'wheel'))]
|
||||
assert before[:2] == STEP_ROWS, 'they were the first two rows'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('platform', ['HYUNDAI_IONIQ_5', 'TESLA_MODEL_X', 'TESLA_MODEL_S_HW1', 'TESLA_MODEL_S_PREAP'])
|
||||
def test_galaxy_keeps_the_cruise_step_rows_for_other_cars(tmp_path, platform):
|
||||
labels = [row['label'] for row in json.loads(galaxy_rows(Params(str(tmp_path)), other(platform), 'wheel'))]
|
||||
assert labels[:2] == STEP_ROWS
|
||||
|
||||
|
||||
def tesla_owner(tmp_path):
|
||||
params = Params(str(tmp_path))
|
||||
cp = tesla(selected=True)
|
||||
return params, cp, build_owner(params, cp)
|
||||
|
||||
|
||||
def page_row(owner, page, key):
|
||||
state = owner.snapshot(page, parked=True, system_long=True, lateral_context=False, metric=False)
|
||||
return next(row for row in state.rows if row.key == key)
|
||||
|
||||
|
||||
def request_for(row, value):
|
||||
return FeatureSettingsRequest(row.key, row.source, value, confirmation=True, vehicle_fingerprint=row.vehicle_fingerprint,
|
||||
capability=row.capability, dependencies=row.dependencies, display_unit=row.display_unit)
|
||||
|
||||
|
||||
ROUTES = [('TeslaSpeedSync', 'set_speed'), ('tesla_input:right_wheel_left', 'controls'), ('tesla_input:right_wheel_left_hold', 'controls'),
|
||||
('tesla_input:right_wheel_left:speed', 'controls'), ('tesla_input:right_stalk_down_tap_engaged', 'controls'),
|
||||
('tesla_input:screen_three_finger_tap', 'controls'), ('TeslaAOLDisengageOnBrake', 'screen')]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('key,target', ROUTES)
|
||||
def test_each_tesla_key_reaches_its_own_feature_through_the_owner(tmp_path, key, target):
|
||||
_, _, owner = tesla_owner(tmp_path)
|
||||
request = FeatureSettingsRequest(key, None, 'On', confirmation=True, vehicle_fingerprint='TESLA_MODEL_3')
|
||||
with patch.object(owner.tesla_screen.set_speed, 'apply', return_value=True) as set_speed, \
|
||||
patch.object(owner.tesla_screen.controls, 'apply', return_value=True) as controls, \
|
||||
patch.object(TeslaScreenFeature, 'apply', return_value=True) as screen, \
|
||||
patch.object(owner.wheel, 'apply', return_value=True) as wheel, \
|
||||
patch.object(owner.wheel.tesla, 'apply', return_value=True) as wheel_tesla, \
|
||||
patch.object(owner.tesla_coop, 'apply', return_value=True) as coop:
|
||||
assert owner.apply(request) is True
|
||||
calls = {'set_speed': set_speed.call_count, 'controls': controls.call_count, 'screen': screen.call_count}
|
||||
assert calls == {name: int(name == target) for name in calls}
|
||||
assert {'set_speed': set_speed, 'controls': controls, 'screen': screen}[target].call_args.args[-1] is request
|
||||
assert not wheel.called and not wheel_tesla.called and not coop.called
|
||||
|
||||
|
||||
@pytest.mark.parametrize('key', ['tesla_input:right_wheel_up', 'tesla_input:right_wheel_press', 'tesla_input:', 'tesla_input:unknown',
|
||||
'tesla_input:indicator_left_half', 'TeslaIndependentSetSpeed', 'TeslaOverrideSetSpeed',
|
||||
'TeslaGentleSlowing', 'TeslaAOLScreenTap'])
|
||||
def test_keys_that_are_not_settings_reach_no_tesla_feature(tmp_path, key):
|
||||
params, _, owner = tesla_owner(tmp_path)
|
||||
request = FeatureSettingsRequest(key, None, 'On', confirmation=True, vehicle_fingerprint='TESLA_MODEL_3')
|
||||
with patch.object(owner.tesla_screen.set_speed, 'apply', return_value=True) as set_speed, \
|
||||
patch.object(owner.tesla_screen.controls, 'apply', return_value=True) as controls, \
|
||||
patch.object(TeslaScreenFeature, 'apply', return_value=True) as screen:
|
||||
assert not owner.apply(request)
|
||||
assert not set_speed.called and not controls.called and not screen.called
|
||||
assert params.get(PARAM) is None
|
||||
|
||||
|
||||
def test_a_wheel_button_key_still_reaches_the_wheel_feature(tmp_path):
|
||||
_, _, owner = tesla_owner(tmp_path)
|
||||
request = FeatureSettingsRequest('wheel:anything', None, 'Off')
|
||||
with patch.object(WheelFeature, 'apply', return_value=True) as wheel, \
|
||||
patch.object(owner.tesla_screen.controls, 'apply', return_value=True) as controls:
|
||||
assert owner.apply(request) is True
|
||||
assert wheel.call_count == 1 and not controls.called
|
||||
|
||||
|
||||
def test_a_set_speed_request_is_saved_through_the_owner_and_turns_the_rule_on(tmp_path):
|
||||
params, cp, owner = tesla_owner(tmp_path)
|
||||
row = page_row(owner, FeaturePage.VEHICLE, 'TeslaSpeedSync')
|
||||
assert row.available and row.vehicle_fingerprint == 'TESLA_MODEL_3' and not owner.tesla_screen.set_speed.active()
|
||||
assert owner.apply(request_for(row, 'On')) and params.get_bool('TeslaSpeedSync')
|
||||
assert page_row(owner, FeaturePage.VEHICLE, 'TeslaSpeedSync').value == 'On'
|
||||
assert owner.tesla_screen.set_speed.active(), 'the same owner sees it at once'
|
||||
assert page_row(owner, FeaturePage.SLC, PEDAL_OVERRIDE_KEY).available, 'After an accelerator override stays in use'
|
||||
assert not owner.apply(request_for(row, 'On')), 'the row shown before the save is stale'
|
||||
assert cp.safetyConfigs[0].safetyParam == 4097, "the car's parameters do not change"
|
||||
|
||||
|
||||
def test_a_control_request_is_saved_through_the_owner(tmp_path):
|
||||
params, _, owner = tesla_owner(tmp_path)
|
||||
row = page_row(owner, FeaturePage.WHEEL, 'tesla_input:right_wheel_left')
|
||||
assert owner.apply(request_for(row, 'Bookmark'))
|
||||
assert params.get(PARAM) == {'version': 1, 'vehicle': 'TESLA_MODEL_3', 'bindings': {
|
||||
'right_wheel_left': {'key': BOOKMARK, 'value': None, 'label': 'Bookmark'}}}
|
||||
assert page_row(owner, FeaturePage.WHEEL, 'tesla_input:right_wheel_left').value == 'Bookmark'
|
||||
assert not params.get_bool('TeslaSpeedSync')
|
||||
|
||||
|
||||
def test_the_tap_row_in_wheel_controls_is_the_only_place_its_always_on_lateral_switch_is_set(tmp_path):
|
||||
params, _, owner = tesla_owner(tmp_path)
|
||||
for parked in (True, False):
|
||||
state = owner.snapshot(FeaturePage.VEHICLE, parked=parked, system_long=True, lateral_context=False, metric=False)
|
||||
assert 'TeslaAOLScreenTap' not in [row.key for row in state.rows]
|
||||
assert 'Three-Finger AOL Tap' not in [row.label for row in state.rows]
|
||||
tap = page_row(owner, FeaturePage.WHEEL, 'tesla_input:screen_three_finger_tap')
|
||||
assert owner.apply(request_for(tap, 'Always On Lateral on/off')) and params.get_bool('TeslaAOLScreenTap')
|
||||
tap = page_row(owner, FeaturePage.WHEEL, 'tesla_input:screen_three_finger_tap')
|
||||
assert tap.value == 'Always On Lateral on/off'
|
||||
assert owner.apply(request_for(tap, 'Unassigned')) and params.get('TeslaAOLScreenTap') is False
|
||||
assert page_row(owner, FeaturePage.WHEEL, 'tesla_input:screen_three_finger_tap').value == 'Unassigned'
|
||||
switch = FeatureSettingsRequest('TeslaAOLScreenTap', None, 'On', confirmation=True, vehicle_fingerprint='TESLA_MODEL_3',
|
||||
capability=owner.tesla_screen.capability())
|
||||
assert not owner.apply(switch) and params.get('TeslaAOLScreenTap') is False, 'the old Vehicle Settings switch is gone'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('platform', [None, 'HYUNDAI_IONIQ_5', 'TESLA_MODEL_X'])
|
||||
def test_tesla_requests_through_the_owner_save_nothing_for_another_car(tmp_path, platform):
|
||||
params = Params(str(tmp_path))
|
||||
cp = other(platform)
|
||||
owner = build_owner(params, cp)
|
||||
(tmp_path / 'tesla').mkdir()
|
||||
tesla_rows = tesla_owner(tmp_path / 'tesla')[2]
|
||||
sync = replace(request_for(page_row(tesla_rows, FeaturePage.VEHICLE, 'TeslaSpeedSync'), 'On'),
|
||||
vehicle_fingerprint=getattr(cp, 'carFingerprint', None))
|
||||
control = replace(request_for(page_row(tesla_rows, FeaturePage.WHEEL, 'tesla_input:right_wheel_left'), 'Bookmark'),
|
||||
vehicle_fingerprint=getattr(cp, 'carFingerprint', None))
|
||||
assert not owner.apply(sync) and not owner.apply(control)
|
||||
assert not params.get_bool('TeslaSpeedSync') and params.get(PARAM) is None
|
||||
@@ -0,0 +1,202 @@
|
||||
"""The comma-speed actions the Tesla's own controls run: the right scroll wheel's steps and Resume Speed Limit + Offset.
|
||||
|
||||
They are looked up apart from the favorites catalog, and every step still passes the publisher's own checks, so nothing
|
||||
is sent for a car that does not own its set speed."""
|
||||
import atexit
|
||||
import tempfile
|
||||
from types import SimpleNamespace as NS
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from opendbc.car.structs import car
|
||||
from openpilot.cereal import messaging
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.starpilot.common.car_control_config import SPEED_DOWN, SPEED_RESUME, SPEED_UP
|
||||
from openpilot.starpilot.controllers.cruise_action import CruiseActionPublisher
|
||||
from openpilot.starpilot.controllers.tests.test_cruise_action import State, cp as mock_cp
|
||||
from openpilot.starpilot.tests.tesla_set_speed_fixture import tesla
|
||||
from openpilot.starpilot.ui.tesla_speed_actions import TeslaSpeedActions
|
||||
|
||||
_param_dir = tempfile.TemporaryDirectory(prefix="starpilot-speed-actions-test-")
|
||||
atexit.register(_param_dir.cleanup)
|
||||
_original_params_init = Params.__init__
|
||||
with patch.object(Params, "__init__", lambda self, d="": _original_params_init(self, _param_dir.name)):
|
||||
from openpilot.starpilot.ui import runtime_app
|
||||
|
||||
NOW = 5_000_000_000
|
||||
|
||||
|
||||
class SavedParams:
|
||||
def __init__(self):
|
||||
self.safe = False
|
||||
|
||||
def get_bool(self, key):
|
||||
return self.safe if key == 'SafeMode' else False
|
||||
|
||||
|
||||
class Publisher:
|
||||
def __init__(self):
|
||||
self.sent = []
|
||||
|
||||
def send(self, topic, message):
|
||||
self.sent.append(messaging.log_from_bytes(message.to_bytes()))
|
||||
|
||||
|
||||
class Shell(TeslaSpeedActions):
|
||||
def __init__(self):
|
||||
self.cruise_actions = CruiseActionPublisher()
|
||||
self.slc_car_actions = None
|
||||
|
||||
def _live_slc_message(self, now_ns, *, car_input=False):
|
||||
return None
|
||||
|
||||
def _favorite_authority(self):
|
||||
return False # a car button never needs the screen's own authority
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def rig():
|
||||
ui = NS(params=SavedParams(), replay_clock=None, started_frame=123, CP=tesla(selected=True), sm=State(NOW))
|
||||
publisher = Publisher()
|
||||
with patch.object(runtime_app, 'ui_state', ui), patch.object(runtime_app, '_slc_action_publisher', lambda: publisher), \
|
||||
patch('openpilot.starpilot.ui.tesla_speed_actions.time.monotonic_ns', return_value=NOW):
|
||||
yield NS(ui=ui, publisher=publisher, shell=Shell())
|
||||
|
||||
|
||||
def steps(rig):
|
||||
return [(message.slcAction.kind, message.slcAction.controllerCruise.stepUnits) for message in rig.publisher.sent]
|
||||
|
||||
|
||||
def test_the_lookup_is_the_two_steps_and_resume(rig):
|
||||
actions = rig.shell._comma_speed_actions()
|
||||
assert set(actions) == {SPEED_UP, SPEED_DOWN, SPEED_RESUME}
|
||||
assert (actions[SPEED_UP].label, actions[SPEED_DOWN].label) == ('Increase Comma Set Speed', 'Decrease Comma Set Speed')
|
||||
assert actions[SPEED_UP].available and actions[SPEED_DOWN].available
|
||||
assert actions[SPEED_RESUME].label == 'Resume Speed Limit + Offset' and not actions[SPEED_RESUME].available
|
||||
assert not rig.publisher.sent, 'looking up sends nothing'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('key,sign', [(SPEED_UP, 1), (SPEED_DOWN, -1)])
|
||||
def test_a_scroll_is_one_unit_and_a_fast_scroll_one_fast_step(rig, key, sign):
|
||||
action = rig.shell._comma_speed_actions()[key]
|
||||
assert action.invoke_value(0) is True
|
||||
assert action.invoke_value(1) is True
|
||||
assert action.invoke() is True
|
||||
assert steps(rig) == [('cruiseStep', sign), ('cruiseStep', sign * 5), ('cruiseStep', sign)]
|
||||
assert all(message.slcAction.controllerCruise.carFingerprint == 'TESLA_MODEL_3' for message in rig.publisher.sent)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('value', [2, -1, 5, .5, None, '1', float('nan')])
|
||||
def test_any_other_value_sends_nothing(rig, value):
|
||||
for key in (SPEED_UP, SPEED_DOWN):
|
||||
assert rig.shell._comma_speed_actions()[key].invoke_value(value) is False
|
||||
assert not rig.publisher.sent
|
||||
|
||||
|
||||
def test_safe_mode_and_replay_block_the_lookup_and_an_earlier_lookup(rig):
|
||||
actions = rig.shell._comma_speed_actions()
|
||||
rig.ui.params.safe = True
|
||||
assert not rig.shell._comma_speed_actions()[SPEED_UP].available
|
||||
assert actions[SPEED_UP].invoke_value(0) is False and actions[SPEED_DOWN].invoke_value(1) is False
|
||||
rig.ui.params.safe = False
|
||||
rig.ui.replay_clock = object()
|
||||
assert not rig.shell._comma_speed_actions()[SPEED_DOWN].available
|
||||
assert actions[SPEED_UP].invoke_value(0) is False, 'a callback found earlier is refused during playback too'
|
||||
assert not rig.publisher.sent
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault', ['not engaged', 'can invalid', 'stale car state', 'offroad'])
|
||||
def test_the_steps_need_fresh_engaged_driving(rig, fault):
|
||||
actions = rig.shell._comma_speed_actions()
|
||||
if fault == 'not engaged':
|
||||
rig.ui.sm['carControl'].enabled = False
|
||||
if fault == 'can invalid':
|
||||
rig.ui.sm['carState'].canValid = False
|
||||
if fault == 'stale car state':
|
||||
rig.ui.sm.logMonoTime['carState'] = NOW - 1_000_000_000
|
||||
if fault == 'offroad':
|
||||
rig.ui.sm['deviceState'].started = False
|
||||
assert not rig.shell._comma_speed_actions()[SPEED_UP].available
|
||||
assert actions[SPEED_UP].invoke_value(0) is False and not rig.publisher.sent
|
||||
|
||||
|
||||
@pytest.mark.parametrize('make', [tesla, lambda: tesla('TESLA_MODEL_Y'), lambda: tesla(cable=False, selected=True),
|
||||
lambda: tesla(long=False, selected=True), lambda: tesla('TESLA_MODEL_S_HW1', selected=True),
|
||||
mock_cp, lambda: mock_cp(True), lambda: None])
|
||||
def test_no_step_is_ever_sent_for_a_car_that_does_not_own_its_set_speed(rig, make):
|
||||
rig.ui.CP = make()
|
||||
actions = rig.shell._comma_speed_actions()
|
||||
for key in (SPEED_UP, SPEED_DOWN):
|
||||
for fast in (0, 1):
|
||||
assert actions[key].invoke_value(fast) is False
|
||||
assert actions[key].invoke() is False
|
||||
assert not rig.publisher.sent
|
||||
|
||||
|
||||
def test_the_token_follows_the_drive_the_car_and_availability(rig):
|
||||
first = rig.shell._comma_speed_actions()[SPEED_UP].token
|
||||
assert rig.shell._comma_speed_actions()[SPEED_UP].token == first
|
||||
rig.ui.started_frame = 124
|
||||
second = rig.shell._comma_speed_actions()[SPEED_UP].token
|
||||
rig.ui.params.safe = True
|
||||
third = rig.shell._comma_speed_actions()[SPEED_UP].token
|
||||
assert len({first, second, third}) == 3
|
||||
|
||||
|
||||
@pytest.mark.parametrize('model', ['TESLA_MODEL_3', 'TESLA_MODEL_Y'])
|
||||
@pytest.mark.parametrize('selected', [False, True])
|
||||
def test_resume_joins_the_favorites_catalog_on_a_model_3_or_y_with_the_cable(rig, model, selected):
|
||||
rig.ui.CP = tesla(model, selected=selected)
|
||||
catalog = {'existing': object()}
|
||||
result = rig.shell._tesla_favorite_actions(catalog, 'drive')
|
||||
assert result is catalog and set(catalog) == {'existing', SPEED_RESUME}
|
||||
assert catalog[SPEED_RESUME].label == 'Resume Speed Limit + Offset' and not catalog[SPEED_RESUME].available
|
||||
assert SPEED_UP not in catalog and SPEED_DOWN not in catalog, 'the scroll steps are never favorites'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('make', [lambda: None, lambda: tesla('TESLA_MODEL_X'), lambda: tesla('TESLA_MODEL_S_HW1'),
|
||||
lambda: tesla(cable=False), lambda: tesla('TESLA_MODEL_Y', cable=False, selected=True),
|
||||
lambda: car.CarParams.new_message(brand='hyundai', carFingerprint='HYUNDAI_IONIQ_5', flags=8),
|
||||
lambda: car.CarParams.new_message(brand='mock', carFingerprint='TESLA_MODEL_3', flags=8)])
|
||||
def test_other_cars_and_a_tesla_without_the_cable_keep_the_favorites_catalog_as_built(rig, make):
|
||||
rig.ui.CP = make()
|
||||
catalog = {'existing': object()}
|
||||
before = dict(catalog)
|
||||
assert rig.shell._tesla_favorite_actions(catalog, 'drive') is catalog and catalog == before
|
||||
|
||||
|
||||
def test_the_favorites_condition_reads_the_switch_at_most_once_a_second(rig, tmp_path):
|
||||
# The catalog is built many times a second; the saved switch behind its speed actions is not read each time.
|
||||
params = Params(str(tmp_path))
|
||||
opened = []
|
||||
rig.ui.params = NS(get_param_path=lambda key='': opened.append(key) or params.get_param_path(key))
|
||||
now = [100.]
|
||||
cp = tesla(selected=True)
|
||||
assert rig.shell._tesla_set_speed(None) is False and opened == [], 'made on first use; nothing read without a car'
|
||||
polled = rig.shell._tesla_set_speed_polled
|
||||
assert polled.params is rig.ui.params
|
||||
polled.clock = lambda: now[0]
|
||||
assert rig.shell._tesla_set_speed(cp) is False
|
||||
params.put_bool('TeslaSpeedSync', True, block=True)
|
||||
for _ in range(50):
|
||||
now[0] += .01
|
||||
assert rig.shell._tesla_set_speed(cp) is False
|
||||
assert opened == ['TeslaSpeedSync'], 'one read for all of those'
|
||||
now[0] = 101.
|
||||
assert rig.shell._tesla_set_speed(cp) is True and rig.shell._tesla_set_speed_polled is polled
|
||||
assert rig.shell._tesla_set_speed(tesla()) is False, 'started without the scroll frame'
|
||||
assert rig.shell._tesla_set_speed(None) is False and rig.shell._tesla_set_speed(mock_cp(True)) is False
|
||||
assert opened == ['TeslaSpeedSync', 'TeslaSpeedSync', 'SafeMode']
|
||||
|
||||
|
||||
def test_nothing_is_read_for_the_favorites_condition_of_another_car(rig):
|
||||
def forbidden(key=''):
|
||||
raise AssertionError('the switch was read for another car')
|
||||
rig.ui.params = NS(get_param_path=forbidden)
|
||||
for cp in (None, mock_cp(), mock_cp(True), tesla(), tesla(cable=False, selected=True), tesla('TESLA_MODEL_S_HW1', selected=True)):
|
||||
assert rig.shell._tesla_set_speed(cp) is False
|
||||
|
||||
|
||||
def test_the_session_mixes_the_actions_in():
|
||||
assert issubclass(runtime_app.StarShellSession, TeslaSpeedActions)
|
||||
assert runtime_app.StarShellSession._comma_speed_actions is TeslaSpeedActions._comma_speed_actions
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
VEHICLE_BOOL_KEYS = frozenset(("AlphaLongitudinalEnabled", "SubaruAvhStartup", "SubaruStopStartOff", "SubaruSNG", "SubaruRedneckCruise", "RedneckCruise",
|
||||
"GMPedalLongitudinal", "DisableOpenpilotLongitudinal", "LongPitch", "VoltSNG", "SNGHack", "GMAutoHold", "VoltOnePedalMode",
|
||||
"TeslaCoopSteering", "TeslaAOLScreenTap", "TeslaAOLDisengageOnBrake",
|
||||
"TeslaCoopSteering", "TeslaAOLDisengageOnBrake", "TeslaSpeedSync",
|
||||
"RemoteStartBootsComma", "HKGRemoteStartBootsComma", "IgnoreIgnitionLine", "TeslaWakeOnCAN"))
|
||||
|
||||
|
||||
@@ -46,8 +46,9 @@ def confirmation_question(request):
|
||||
return f"{verb} compensation for road grade? This refreshes during the drive."
|
||||
if request.key == "TeslaCoopSteering":
|
||||
return f"{verb} Tesla cooperative steering after the next startup? Light steering input adjusts the assisted steering angle within its limits."
|
||||
if request.key == "TeslaAOLScreenTap":
|
||||
return f"{verb} three-finger screen taps for Always On Lateral after the next startup? Cruise control stays independent."
|
||||
if request.key == "TeslaAOLDisengageOnBrake":
|
||||
return f"{verb} disarming Always On Lateral with the brake after the next startup? This applies with either Tesla harness."
|
||||
if request.key == "TeslaSpeedSync":
|
||||
return (f"{verb} Comma can set speed on Tesla dashboard? While it is on, StarPilot keeps its own set speed and scrolls the " +
|
||||
"Tesla's set speed to match it.")
|
||||
raise ValueError("Unsupported vehicle preference")
|
||||
|
||||
@@ -40,6 +40,7 @@ class VehicleStartupPreferences:
|
||||
gm_auto_hold: bool = False
|
||||
volt_one_pedal: bool = False
|
||||
tesla_cooperative: bool = field(default=False, kw_only=True)
|
||||
tesla_speed_sync: bool = field(default=False, kw_only=True)
|
||||
tesla_aol: bool = field(default=False, kw_only=True)
|
||||
tesla_screen: bool = False
|
||||
tesla_screen_brake: bool = False
|
||||
@@ -112,6 +113,10 @@ class VehicleStartupPreferences:
|
||||
cooperative = bool(enabled and readable and safe in (None, b"0") and
|
||||
read_saved(params, "TeslaCoopSteering", 8) == (b"1", True))
|
||||
screen_brake = read_saved(params, 'TeslaAOLDisengageOnBrake', 8) == (b'1', True)
|
||||
# Comma can set speed on Tesla dashboard: admit its scroll frame, so the switch works without a restart
|
||||
# (experimental, so not on release branches).
|
||||
speed_sync = bool(enabled and readable and safe in (None, b"0") and
|
||||
read_saved(params, "IsReleaseBranch", 8) in ((None, True), (b"0", True)))
|
||||
return cls(controller_selection=controller_selection, vw_stock_long=vw_stock_long,
|
||||
subaru_smoothing=smoothing, subaru_avh_startup=bool(enabled and readable and safe in (None, b"0") and
|
||||
read_saved(params, "IsReleaseBranch", 8) in ((None, True), (b"0", True)) and
|
||||
@@ -124,7 +129,7 @@ class VehicleStartupPreferences:
|
||||
subaru_software_cruise=bool(enabled and readable and safe in (None, b"0") and
|
||||
read_saved(params, "SubaruRedneckCruise", 8) == (b"1", True)),
|
||||
ford_bluepilot=tuple(ford_bluepilot(params, enabled=enabled).items()), tesla_aol=tesla_aol, tesla_screen=screen,
|
||||
tesla_screen_brake=screen_brake, tesla_cooperative=cooperative, toyota_auto_hold=toyota,
|
||||
tesla_screen_brake=screen_brake, tesla_cooperative=cooperative, tesla_speed_sync=speed_sync, toyota_auto_hold=toyota,
|
||||
toyota_sng=bool(enabled and readable and safe in (None, b"0") and
|
||||
read_saved(params, "SNGHack", 8) == (b"1", True)), jeep_brake_hold=jeep_hold,
|
||||
gm_longitudinal_tune=selected_tune(params, enabled=enabled),
|
||||
@@ -207,6 +212,8 @@ class VehicleStartupPreferences:
|
||||
apply_modern_aol(cp, self.tesla_aol, self.tesla_screen, self.tesla_screen_brake)
|
||||
from openpilot.starpilot.car.tesla.coop_preferences import prepare
|
||||
prepare(cp, self.tesla_cooperative)
|
||||
from opendbc.car.tesla.speed_sync import prepare as prepare_speed_sync
|
||||
prepare_speed_sync(cp, self.tesla_speed_sync)
|
||||
self._prepare_honda_radar(cp)
|
||||
from opendbc.car.chrysler.brake_hold import apply_brake_hold
|
||||
apply_brake_hold(cp, self.jeep_brake_hold)
|
||||
@@ -253,6 +260,8 @@ class VehicleStartupPreferences:
|
||||
apply_modern_aol(cp, self.tesla_aol, self.tesla_screen, self.tesla_screen_brake)
|
||||
from openpilot.starpilot.car.tesla.coop_preferences import prepare
|
||||
prepare(cp, self.tesla_cooperative)
|
||||
from opendbc.car.tesla.speed_sync import prepare as prepare_speed_sync
|
||||
prepare_speed_sync(cp, self.tesla_speed_sync)
|
||||
self._prepare_honda_radar(cp)
|
||||
from opendbc.car.chrysler.brake_hold import apply_brake_hold
|
||||
apply_brake_hold(cp, self.jeep_brake_hold)
|
||||
|
||||
Reference in New Issue
Block a user