Compare commits

...

91 Commits

Author SHA1 Message Date
whoisdomi 68429f5451 Engine Sound Pack 2026-11-24 10:01:02 -06:00
firestar5683 c707dd4938 Repair GM, Palisade and Galaxy CI fixtures 2026-11-24 01:18:20 -06:00
firestar5683 698a203cbc Test preference reset with the real navigation owner 2026-11-23 23:48:12 -06:00
firestar5683 db79a4620d Align Subaru and Toyota CI with current vehicle contracts 2026-11-23 23:43:42 -06:00
firestar5683 48fb24ee48 Repair alert and Galaxy test fixtures 2026-11-23 23:37:59 -06:00
firestar5683 22f010c1ac Requalify FLM source provenance after navigation changes 2026-11-23 23:27:58 -06:00
firestar5683 d89f221d06 Repair static analysis and settings CI regressions 2026-11-23 23:26:32 -06:00
firestar5683 07331b33e8 Keep Kona handoff compliant with native safety lint 2026-11-23 23:19:22 -06:00
natehuby76 951beb26be Merge pull request #347 from natehuby76/smooth-nav-braking 2026-11-24 00:15:40 -05:00
firestar5683 683435ac68 Cover Kona handoff and Subaru sibling alerts in safety CI 2026-11-23 23:11:17 -06:00
firestar5683 241e0a43d4 Fix Galaxy local pairing with a new password 2026-11-23 22:59:05 -06:00
natehuby76 fad5a9faaf keep nav turns from canceling lane changes 2026-11-23 23:58:46 -05:00
firestar5683 19b7edf344 Keep stock MQB AOL armed through the first Panda acknowledgment 2026-11-23 22:54:38 -06:00
natehuby76 ab02d5a44c smooth navigation braking between gps fixes 2026-11-23 23:46:51 -05:00
firestar5683 8a9f7a084c Revert second-Panda Hyundai HDA2 stock cruise fallback 2026-11-23 22:46:29 -06:00
firestar5683 e59fa4930a Keep second-Panda Hyundai HDA2 on stock cruise at startup 2026-11-23 22:42:06 -06:00
firestar5683 855dfb3a17 Smooth tight-curve steering on Ioniq 5 HDA II 2026-11-23 22:33:32 -06:00
firestar5683 026ce00b72 Add device restart to Galaxy 2026-11-23 22:30:31 -06:00
firestar5683 3728cea591 Fix switching software branches in Galaxy 2026-11-23 22:14:35 -06:00
firestar5683 bc1edc500d Restore Save Me cleanup in Galaxy 2026-11-23 21:48:54 -06:00
firestar5683 330a302aa1 Keep stock Prius CAN healthy when the gap button signal is absent 2026-11-23 21:46:54 -06:00
firestar5683 6e879b55da Remove Galaxy reset that erases Wi-Fi settings 2026-11-23 21:39:06 -06:00
firestar5683 059612c13a Retain Subaru AOL when Panda sees the paddle shift first 2026-11-23 21:37:53 -06:00
firestar5683 bbe680c127 Allow remote Galaxy factory reset requests 2026-11-23 21:34:06 -06:00
firestar5683 ceb0bea247 Add the native factory reset to Galaxy 2026-11-23 20:22:45 -06:00
AngusBell97 35c80054d3 Add Tesla Model 3/Y wheel controls and comma-set dashboard speed 2026-11-23 20:15:03 -06:00
firestar5683 6cfa8b9f25 Restore Honda Fit steering after extended EPS pauses 2026-11-23 20:10:22 -06:00
firestar5683 919363f4fa Keep classic Ford discovery on the normal CAN harness 2026-11-23 20:09:55 -06:00
firestar5683 131ad10d63 Allow on-road startup without cloud registration 2026-11-23 19:54:30 -06:00
firestarsdog 47346ad98b Jetlink +tici support in controller 2026-11-23 20:11:19 -05:00
firestar5683 9c5a5e5b86 Preserve Mazda AOL intent at a complete stop 2026-11-23 18:16:19 -06:00
firestar5683 ce47ff1da3 Set a minimum width for automatic lane changes 2026-11-23 18:15:00 -06:00
firestar5683 55269d0856 Port Frogger900’s 2025 Subaru HUD and AVH features 2026-11-23 17:04:41 -06:00
firestar5683 0da55d93ae Ramp Honda Fit steering torque after EPS pauses 2026-11-23 17:01:30 -06:00
firestar5683 6f73fad098 Port Frogger900’s 2025 Subaru HUD and AVH features 2026-11-23 16:58:09 -06:00
firestar5683 9da91c24af Apply Coast Downhills changes during the drive 2026-11-23 16:56:49 -06:00
firestar5683 bd2e523bfe Default second-generation Niro EV to StarPilot steering 2026-11-23 16:37:53 -06:00
firestar5683 70de2df8f2 Refine Palisade HDA2 camera timing and highway response 2026-11-23 16:32:15 -06:00
firestar5683 d461cad223 Soften Sonata low-speed center corrections 2026-11-23 16:25:26 -06:00
firestar5683 a8d1dd1d91 Confirm manual MQB startup steering within its deadline 2026-11-23 16:18:57 -06:00
firestar5683 2151b3c77b Fix model selection on the large device UI 2026-11-23 16:13:32 -06:00
dirwin31 e555faacc1 Merge pull request #345 from dirwin31/StarPortAdapterCarLogging
StarPort: Add Logging
2026-11-23 14:09:50 -08:00
Danny e7f5d5fd4e StarPort: Log why an adapter has no car and name the car that tried to connect 2026-11-23 14:08:52 -08:00
Claude 9a32c18941 Regenerate cereal's C++ files for the Tesla schema additions
custom.capnp gained stepUnits, sourceTeslaGesture, the TeslaGesture struct
and the cruiseStep action, but the generated files kept beside it were not
updated. The build rewrote them, so the complete custom pytest catalog job
saw built trees that differed from the commit and rejected all 32 passing
shards. These are the files the build's own capnpc command writes
(Cap'n Proto 1.0.1, the version that reproduces stable's copies exactly).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 22:07:39 +00:00
firestar5683 aafa97df61 Stabilize Palisade HDA2 steering and camera status 2026-11-23 15:51:25 -06:00
firestar5683 4f07a1ea4a Dampen longitudinal oscillation on four-byte filter Sienna 2026-11-23 15:49:30 -06:00
firestar5683 cf26c720f0 Restore the proven Kona steering handoff 2026-11-23 15:48:36 -06:00
firestar5683 ef38e75164 Preserve armed AOL through the speed ceiling 2026-11-23 15:48:29 -06:00
firestar5683 0ecbad2a41 Time out Connect registration during startup 2026-11-23 15:26:59 -06:00
firestar5683 ff9f0f0b33 Restore Kona factory steering while StarPilot is idle 2026-11-23 15:20:16 -06:00
firestar5683 d24bfcd0f3 Match Camry SE radar filter idle cruise messages 2026-11-23 15:18:23 -06:00
firestar5683 17ea1c3c3e Add independent TEMP gauge units to Galaxy 2026-11-23 15:11:39 -06:00
firestar5683 4ef3b1c2b4 Auto-detect the 2018 SASCM Volt CAN layout 2026-11-23 15:09:27 -06:00
firestar5683 f9bc75a3fd Clear stale Honda Fit steering integral after driver override 2026-11-23 15:05:38 -06:00
Claude f67edb6529 Tesla Model 3/Y: controls work with nothing saved, and three recovery fixes
- The input worker never parsed its settings on an install where CarControlAssignments had never been saved, so no
  scroll, stalk press or nudge reached the comma until a Wheel Controls row was changed. It now starts from the
  defaults.
- Saved assignments are used on either model: a Model 3 and a Model Y have the same controls. Before, a document
  saved on the other model gave no controls and locked every Wheel Controls row.
- Speed sync no longer waits for the Tesla's own speed to change after unanswered requests once the comma's speed is
  on the other side of the Tesla's (the Tesla had been at its own lowest or highest set speed).
- The UI restarts a stopped input worker after a wait that grows from 2 s to 30 s, instead of at most three times a
  drive. A first start that fails is retried on the same wait, not every frame.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 20:12:29 +00:00
firestar5683 fa66e9baac Show StarPilot release versions in update prompts 2026-11-23 12:57:37 -06:00
firestar5683 6dea0ec66c Allow downhill coasting from 1 percent grade 2026-11-23 12:37:02 -06:00
firestar5683 3fa425f769 Add Coast Downhills to Long Planner 2026-11-23 12:33:37 -06:00
Claude 7dbbb43c3b 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>
2026-11-23 18:32:41 +00:00
firestar5683 777df8f6d8 Keep MQB AOL through a held-brake source handoff 2026-11-23 12:32:41 -06:00
firestar5683 f29ab3c676 Preserve Mazda lateral authority through Cancel deadline overlap 2026-11-23 12:31:11 -06:00
firestar5683 d197e09d3b Preserve Honda Fit AOL intent through EPS feedback reordering 2026-11-23 12:22:39 -06:00
firestar5683 24f65c6feb Recognize official StarPilot startup channels 2026-11-23 12:12:06 -06:00
firestar5683 cf2ddc0734 Complete verified FLM curve quieting trials 2026-11-23 11:55:09 -06:00
firestar5683 3693294b10 Show live thermal readings in Galaxy 2026-11-23 11:30:12 -06:00
firestar5683 0ea99a0128 Add Toggle Screen Off to Wheel Controls 2026-11-23 11:21:05 -06:00
firestar5683 981455ecc6 Keep parked FLM reads waiting for fresh status 2026-11-23 11:18:20 -06:00
firestar5683 2c53700269 Add a navigation turn slowdown distance slider 2026-11-23 11:14:41 -06:00
firestar5683 3393b7d698 Smooth Model Y manual cruise speed changes 2026-11-23 11:12:13 -06:00
firestar5683 ec4c158e20 Record Safe Mode in the route settings snapshot 2026-11-23 11:06:35 -06:00
firestar5683 1c087154ae Show detected stoplights while armed AOL is stationary 2026-11-23 11:01:37 -06:00
firestar5683 a46f9941e7 Keep Honda Fit AOL armed through delayed EPS feedback 2026-11-23 11:01:37 -06:00
firestar5683 47bbc2e1bf Show manual and learned FLM settings together 2026-11-23 10:51:54 -06:00
dirwin31 c0d7eeb09c Merge pull request #341 from dirwin31/HondaStarportToggles
Add Honda Starport Toggles
2026-11-23 07:44:03 -08:00
Danny 16786b6517 Build 2026-11-23 07:23:21 -08:00
Danny 00be4586e2 StarPort: Add wired hands-free toggle for cars that need it, and remove the Fit fix 2026-11-23 07:22:32 -08:00
firestar5683 0b0f216dff Rebalance lifecycle CI using current hosted timings 2026-11-23 02:15:32 -06:00
firestar5683 b119731ad2 Recognize factory Camry radar and mirrored startup traffic for AOL 2026-11-22 23:58:51 -06:00
Sam Yau e71059b2d1 Subaru AOL: manual-mode ratio gears pause output, not intent 2026-11-22 23:54:37 -06:00
firestar5683 288027a08d Clarify Toyota factory ACC setting 2026-11-22 23:20:57 -06:00
firestar5683 0b5e75d9c5 Set StarPilot testing version to 7.0.2 2026-11-22 22:47:02 -06:00
firestar5683 9b25c7c0cc Share early Subaru steering and Cruise MAIN AOL 2026-11-22 22:33:21 -06:00
firestar5683 6ccf23ddb6 Share early Subaru steering and Cruise MAIN AOL 2026-11-22 22:31:35 -06:00
firestar5683 bb4840ab89 Restore early Crosstrek steering and Cruise MAIN AOL 2026-11-22 22:23:25 -06:00
firestar5683 7848780457 Restore early Crosstrek steering and Cruise MAIN AOL 2026-11-22 22:21:42 -06:00
firestar5683 b5931c365d Restore Toyota factory cruise selection in Vehicle Settings 2026-11-22 22:14:27 -06:00
firestar5683 6c2f6fc048 Show early Subaru Crosstrek in vehicle selection 2026-11-22 22:10:44 -06:00
firestar5683 3f5068a19b Retain Honda Fit AOL through brief EPS torque refusals 2026-11-22 22:04:12 -06:00
firestar5683 f7ef9b117c Capture parked status when an FLM read is interrupted 2026-11-22 22:03:37 -06:00
firestar5683 0972ef0d44 Keep Ford AOL armed through the Cancel safety echo 2026-11-22 22:02:26 -06:00
Sam Yau 459d2e6b94 Subaru AOL: manual-mode ratio gears pause output, not intent
In paddle/manual mode the Subaru transmission reports the simulated
ratio instead of D, which parses as GearShifter.unknown. The generic
disarming_fault() treated the resulting soft wrongGear event as a
disarming fault and cleared the AOL latch; with no fresh MAIN edge on
the return to Drive, AOL never resumed (pre-7.0 it resumed
automatically).

Add a Subaru-scoped intent_disarming_fault() that filters the soft
wrongGear event for qualified cars at unknown gear, dispatched like
the existing Volkswagen/Chrysler overrides. Output stays paused in
manual mode through the normal runtime and panda gates; only the
intent revocation is removed. Generic classification is unchanged.

Tests: openpilot/starpilot/car/subaru/tests/test_aol_manual_gear.py
2026-11-22 19:45:56 -08:00
742 changed files with 25418 additions and 1064 deletions
+8 -1
View File
@@ -10,7 +10,8 @@ from opendbc.car.fw_versions import (ObdCallback, get_fw_versions, get_fw_versio
get_present_ecus, match_fw_to_car)
from opendbc.car.mock.values import CAR as MOCK
from opendbc.car.gm.pedal_capability import automatic_bolt_candidate
from opendbc.car.gm.discovery import automatic_trax_candidate, automatic_volt_candidate, normal_bus0_topology as gm_normal_bus0_topology
from opendbc.car.gm.discovery import (automatic_trax_candidate, automatic_volt_ascm_candidate, automatic_volt_candidate,
normal_bus0_topology as gm_normal_bus0_topology)
from opendbc.car.ford.discovery import (normal_bus0_selection as ford_normal_bus0_selection,
normal_bus0_queries as ford_normal_bus0_queries, normal_bus_query_brand)
from opendbc.car.volvo.discovery import normal_bus_topology as volvo_normal_bus_topology, v60_bus_topology as volvo_v60_bus_topology
@@ -96,6 +97,7 @@ def can_fingerprint(can_recv: CanRecvCallable, *, vin: str = VIN_UNKNOWN,
frame += 1
car_fingerprint = automatic_volt_candidate(car_fingerprint, finger, candidate_cars)
car_fingerprint = automatic_volt_ascm_candidate(car_fingerprint, finger, candidate_cars, vin)
car_fingerprint = automatic_trax_candidate(car_fingerprint, finger, candidate_cars, vin)
return automatic_bolt_candidate(car_fingerprint, finger, camera_cruise_messages, vin), finger
@@ -261,6 +263,11 @@ def fingerprint(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_mu
# Refine after both automatic sources, before the explicit override below.
if not fixed_fingerprint:
car_fingerprint = automatic_bolt_candidate(car_fingerprint, finger, camera_cruise_messages, vin)
if car_fingerprint == 'SUBARU_IMPREZA' and source == CarParams.FingerprintSource.fw and exact_match:
# Subaru's early GT Crosstrek and Impreza share a firmware bucket.
# NHTSA vPIC identifies JF2GT with model-year codes J and K as Crosstrek.
if is_valid_vin(vin) and vin.startswith('JF2GT') and vin[9] in ('J', 'K'):
car_fingerprint = 'SUBARU_CROSSTREK_2018'
if fixed_fingerprint:
car_fingerprint = fixed_fingerprint
+11 -6
View File
@@ -1,4 +1,4 @@
"""Normal-bus discovery for explicitly selected Ford CAN-FD vehicles."""
"""Normal-bus discovery for Ford vehicles."""
import time
from opendbc.car.ford.values import CAR, FordFlags
@@ -42,7 +42,8 @@ def normal_bus0_selection(candidate):
# diagnostic query family; live VIN, ECU responses and fingerprinting still
# determine the vehicle and its control configuration.
NORMAL_BUS0_LAYOUT = {(0, 0x82): 8, (0, 0x165): 8, (0, 0x204): 8,
(0, 0x217): 8, (2, 0x3CA): 8, (2, 0x3D6): 8}
(0, 0x217): 8, (2, 0x3CA): 8}
CAMERA_STEERING_LAYOUT = {(2, 0x3D3): 8, (2, 0x3D6): 8}
def normal_bus_query_brand(can_recv, hyundai_probe, *, gm_probe=None, volvo_probe=None, tesla_probe=None, clock=time.monotonic):
@@ -55,6 +56,10 @@ def normal_bus_query_brand(can_recv, hyundai_probe, *, gm_probe=None, volvo_prob
reads = 0
deadline = clock() + .12
def complete():
return (not malformed and NORMAL_BUS0_LAYOUT.items() <= received.items() and
any(key in received for key in CAMERA_STEERING_LAYOUT))
def observe(**kwargs):
nonlocal malformed, gm_malformed, reads
reads += 1
@@ -67,9 +72,9 @@ def normal_bus_query_brand(can_recv, hyundai_probe, *, gm_probe=None, volvo_prob
length = len(frame.dat)
gm_malformed |= frame.address in bus and bus[frame.address] != length
bus[frame.address] = length
if key in NORMAL_BUS0_LAYOUT:
if (expected := NORMAL_BUS0_LAYOUT.get(key) or CAMERA_STEERING_LAYOUT.get(key)) is not None:
length = len(frame.dat)
malformed |= length != NORMAL_BUS0_LAYOUT[key]
malformed |= length != expected
received[key] = length
return packets
@@ -77,11 +82,11 @@ def normal_bus_query_brand(can_recv, hyundai_probe, *, gm_probe=None, volvo_prob
return 'hyundai'
# Rejecting HKG or Ford does not reject GM. Finish the shared passive window
# within its original budget even when an early frame excludes Ford.
while not (not malformed and received == NORMAL_BUS0_LAYOUT) and reads < 24 and clock() < deadline:
while not complete() and reads < 24 and clock() < deadline:
if malformed and ((gm_probe is None and volvo_probe is None and tesla_probe is None) or gm_malformed):
break
observe(wait_for_one=True)
if not malformed and received == NORMAL_BUS0_LAYOUT and normal_bus0_queries():
if complete() and normal_bus0_queries():
return 'ford'
if gm_probe is not None and not gm_malformed and gm_probe(gm_received):
return 'gm'
+1 -1
View File
@@ -50,7 +50,7 @@ def migrate_assignments(params, cp):
('LongDistanceButtonControl', 'LongCancelButtonControl', 5),
('VeryLongDistanceButtonControl', 'VeryLongCancelButtonControl', 6))
pending = []
valid = tuple(str(value).encode() for value in range(15))
valid = tuple(str(value).encode() for value in range(16))
for source, target, default in pairs:
raw, readable = read_saved(params, target, 8)
previous, source_readable = read_saved(params, source, 8)
+19
View File
@@ -46,6 +46,25 @@ def automatic_volt_candidate(candidate, fingerprint, candidates):
return CAR.CHEVROLET_VOLT_CC
def automatic_volt_ascm_candidate(candidate, fingerprint, candidates, vin):
# The recorded 2018 SASCM Volt falls out of both legacy CAN candidate lists.
if (candidate is not None or any(candidates.values()) or not isinstance(vin, str) or not is_valid_vin(vin) or
not vin.startswith('1G1RD6S5') or vin[9] != 'J'):
return candidate
pt = fingerprint.get(CanBus.POWERTRAIN, {})
camera = fingerprint.get(CanBus.CAMERA, {})
radar = fingerprint.get(CanBus.OBSTACLE, {})
required = {0xC9: 8, 0x180: 4, 0x184: 8, 0x1C4: 8, 0x1E1: 7,
0x2FF: 4, 0x348: 5, 0x34A: 5, 0x370: 6}
if (pt != camera or any(pt.get(address) != size for address, size in required.items()) or
radar.get(0x460) != 8 or radar.get(0x474) != 8 or
any(address in pt for address in (0xBE, 0x201)) or pt.get(0x320) not in (None, 3) or
any(messages for bus, messages in fingerprint.items() if bus not in (CanBus.POWERTRAIN, CanBus.OBSTACLE, CanBus.CAMERA))):
return candidate
return CAR.CHEVROLET_VOLT_ASCM
# Frequent normal-bus frames observed on mirrored pedal installations. This is
# only diagnostic query-family evidence, never a vehicle/control fingerprint.
PEDAL_NORMAL_BUS_LAYOUT = {0xD3: 2, 0xBE: 6, 0xC9: 8, 0x1C4: 8,
@@ -0,0 +1,58 @@
import json
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
import pytest
from opendbc.car import car_helpers, structs
from opendbc.car.can_definitions import CanData
from opendbc.car.gm.values import CAR
VIN = '1G1RD6S50JU000001'
RECORDED = Path(__file__).parent / 'testdata/volt_2018_ascm_fingerprint.json'
@pytest.fixture
def fingerprint():
return {int(bus): {int(address): size for address, size in messages.items()}
for bus, messages in json.loads(RECORDED.read_text()).items()}
def receive(fingerprint):
packets = [CanData(address, bytes(size), bus)
for bus, messages in fingerprint.items() for address, size in messages.items()]
return lambda **kwargs: [packets]
def test_recorded_startup_selects_ascm_and_preserves_manual_override(fingerprint):
fw = structs.CarParams.CarFw.new_message(brand='gm', logging=True)
cache = SimpleNamespace(carFingerprint='MOCK', carVin=VIN, carFw=[fw], brand='mock')
with patch.dict(car_helpers.os.environ, {'FINGERPRINT': '', 'SKIP_FW_QUERY': '', 'DISABLE_FW_CACHE': ''}), \
patch.object(car_helpers, 'get_vin', return_value=(0x64B, 0, VIN)), \
patch.object(car_helpers, 'get_fw_versions', return_value=[fw]):
args = (receive(fingerprint), lambda _: None, lambda _: None, False, True)
auto = car_helpers.get_car(*args, cached_params=cache).CP
manual = car_helpers.get_car(*args, forced_candidate=CAR.CHEVROLET_VOLT).CP
assert auto.carFingerprint == CAR.CHEVROLET_VOLT_ASCM
assert auto.fingerprintSource == structs.CarParams.FingerprintSource.can
assert auto.pcmCruise and not auto.openpilotLongitudinalControl and not auto.dashcamOnly
assert auto.safetyConfigs[0].safetyParam == 0xE05
assert manual.carFingerprint == CAR.CHEVROLET_VOLT
assert manual.fingerprintSource == structs.CarParams.FingerprintSource.fixed
@pytest.mark.parametrize('vin', ['0' * 17, '1G1RD6S50KU000001', '1G1FX6S50JU000001'])
def test_layout_alone_does_not_match(fingerprint, vin):
assert car_helpers.can_fingerprint(receive(fingerprint), vin=vin)[0] is None
@pytest.mark.parametrize('bus,address,size', [(0, 0x2FF, 8), (0, 0x201, 6), (0, 0x320, 6),
(2, 0x180, None), (1, 0x474, None)])
def test_other_harness_or_control_sources_do_not_match(fingerprint, bus, address, size):
for target in (0, 2) if bus == 0 else (bus,):
if size is None:
fingerprint[target].pop(address)
else:
fingerprint[target][address] = size
assert car_helpers.can_fingerprint(receive(fingerprint), vin=VIN)[0] != CAR.CHEVROLET_VOLT_ASCM
@@ -0,0 +1,5 @@
{
"0": {"189": 7, "193": 8, "197": 8, "201": 8, "209": 7, "211": 2, "241": 6, "298": 8, "304": 1, "308": 4, "309": 8, "311": 8, "313": 8, "320": 3, "328": 1, "352": 5, "381": 6, "384": 4, "386": 8, "388": 8, "451": 8, "452": 8, "453": 6, "479": 3, "481": 7, "485": 8, "489": 8, "493": 8, "497": 8, "500": 6, "501": 8, "528": 4, "532": 6, "560": 8, "562": 8, "563": 5, "565": 5, "566": 5, "608": 8, "609": 6, "610": 6, "611": 6, "612": 8, "613": 8, "707": 8, "715": 8, "717": 5, "761": 7, "767": 4, "810": 8, "840": 5, "842": 5, "844": 8, "869": 4, "880": 6, "977": 8, "1001": 8, "1017": 8, "1020": 8, "1033": 7, "1034": 7, "1217": 8, "1221": 5, "1233": 8, "1249": 8, "1265": 8, "1267": 1, "1280": 4, "1296": 4, "1300": 8, "1922": 7, "1930": 7},
"1": {"161": 7, "262": 5, "309": 1, "768": 8, "771": 2, "774": 8, "776": 7, "784": 6, "848": 8, "849": 8, "850": 8, "851": 8, "852": 8, "853": 8, "854": 3, "1033": 7, "1034": 7, "1056": 6, "1057": 8, "1058": 8, "1059": 8, "1060": 8, "1061": 8, "1062": 8, "1063": 8, "1064": 8, "1065": 8, "1066": 8, "1067": 8, "1068": 8, "1088": 8, "1089": 8, "1090": 8, "1091": 8, "1092": 8, "1093": 8, "1094": 8, "1095": 8, "1096": 8, "1097": 8, "1098": 8, "1099": 8, "1100": 8, "1120": 8, "1121": 8, "1122": 8, "1123": 8, "1124": 8, "1125": 8, "1126": 8, "1127": 8, "1128": 8, "1129": 8, "1130": 8, "1131": 8, "1132": 8, "1133": 8, "1134": 8, "1135": 8, "1136": 8, "1137": 8, "1138": 8, "1139": 8, "1140": 8, "1141": 8, "1142": 8, "1143": 8, "1146": 8, "1147": 8, "1148": 8, "1149": 8, "1150": 8, "1151": 8, "1362": 8, "1857": 8, "1859": 8, "1920": 7},
"2": {"189": 7, "193": 8, "197": 8, "201": 8, "209": 7, "211": 2, "241": 6, "298": 8, "304": 1, "308": 4, "309": 8, "311": 8, "313": 8, "320": 3, "328": 1, "352": 5, "381": 6, "384": 4, "386": 8, "388": 8, "451": 8, "452": 8, "453": 6, "479": 3, "481": 7, "485": 8, "489": 8, "493": 8, "497": 8, "500": 6, "501": 8, "528": 4, "532": 6, "560": 8, "562": 8, "563": 5, "565": 5, "566": 5, "608": 8, "609": 6, "610": 6, "611": 6, "612": 8, "613": 8, "707": 8, "715": 8, "717": 5, "761": 7, "767": 4, "810": 8, "840": 5, "842": 5, "844": 8, "869": 4, "880": 6, "977": 8, "1001": 8, "1017": 8, "1020": 8, "1033": 7, "1034": 7, "1217": 8, "1221": 5, "1233": 8, "1249": 8, "1265": 8, "1267": 1, "1280": 4, "1296": 4, "1300": 8, "1922": 7, "1930": 7}
}
@@ -117,7 +117,8 @@ CARNIVAL_LONG_AOL_WORD = 0x28B4
LONG_AOL_WORDS = frozenset((CARNIVAL_LONG_AOL_WORD, 0x080D, 0x0815, 0x0895, 0x2815, 0x2895)) | SPORTAGE_LONG_AOL_WORDS
CCNC_LONG_AOL_WORDS = frozenset((0x0C0C, 0x0C0E, 0x0C2C, 0x0C2E))
LONG_EV_CARS = frozenset((CAR.HYUNDAI_IONIQ_5, CAR.HYUNDAI_KONA_EV_2ND_GEN))
LONG_AOL_WORDS |= CCNC_LONG_AOL_WORDS
KONA_IDLE_AOL_WORD = 0x1C0C
LONG_AOL_WORDS |= CCNC_LONG_AOL_WORDS | {KONA_IDLE_AOL_WORD}
GENERIC_HDA2_CARS = frozenset((
CAR.GENESIS_G80_2ND_GEN_FL,
CAR.HYUNDAI_IONIQ_5_N,
@@ -149,6 +150,12 @@ INDEPENDENT_LONG_BUTTON_CARS = LONG_EV_CARS | GENERIC_HDA2_CARS | {
}
def kona_idle_handoff_profile(cp):
return (cp.carFingerprint == CAR.HYUNDAI_KONA_2ND_GEN and len(cp.safetyConfigs) == 1 and
cp.alphaLongitudinalAvailable and cp.openpilotLongitudinalControl and not cp.pcmCruise and
_base_word(cp, experiences=(0, 32)) == 0x408)
def qualified_long(cp, *, marked_only=False):
if cp.carFingerprint == CAR.KIA_EV6 and int(cp.flags) & _FLAG_CANFD_LKA_STEER_MSG:
from opendbc.car.hyundai.ev6_aol import qualified as ev6_qualified
@@ -189,6 +196,8 @@ def qualified_long(cp, *, marked_only=False):
if not raw & 0x2000:
return False
raw &= ~0x2000
if raw == KONA_IDLE_AOL_WORD:
return cp.alternativeExperience == 32 and kona_idle_handoff_profile(cp)
return (raw == (word | 0x804) and cp.alternativeExperience == 32) or (
not marked_only and raw == (word | 4) and cp.alternativeExperience == 0
)
@@ -31,6 +31,7 @@ from opendbc.car.hyundai.canfd_lfa_status import preserves_stock_lfa
from opendbc.car.hyundai.classic_scc_aol import qualified as qualified_classic_stock_aol
from opendbc.car.hyundai.classic_long_aol import AOL_EXPERIENCE, qualified as qualified_classic_long_aol
from opendbc.car.hyundai.canfd_stock_aol import qualified as qualified_canfd_stock_aol, qualified_long as qualified_canfd_long_aol
from opendbc.car.hyundai.canfd_stock_aol import KONA_IDLE_AOL_WORD
from opendbc.car.hyundai.g90_longitudinal import G90LongitudinalPolicy
from opendbc.car.hyundai.gv70_longitudinal import is_gv70, scc_request, suppress_stock_cancel
from opendbc.car.hyundai.g90_lead import G90LeadState, eligible as g90_lead_eligible
@@ -140,6 +141,8 @@ class CarController(CarControllerBase):
self.blended_longitudinal = None
self.blended_previous_lateral = False
self.blended_disengage_frame = None
self.blended_camera_sent_frame = -5
self.blended_camera_sent_counter = None
self.last_ccnc_161_ts_ns = 0
self.last_ccnc_162_ts_ns = 0
self.last_ccnc_now_ns = 0
@@ -174,6 +177,7 @@ class CarController(CarControllerBase):
int(CP.safetyConfigs[-1].safetyParam) in (0x0811, 0x0891))
self.canfd_torque_aol_status = (qualified_canfd_stock_aol(CP) or qualified_canfd_long_aol(CP))
self.ccnc_fault_ownership_required = preserves_stock_lfa(CP)
self.kona_last_lfa_counter = None
self.canfd_dash_icons = CanFDDashIcons() if ioniq6_status or self.canfd_torque_aol_status else None
self.classic_dash_icons = CanFDDashIcons() if classic_aol_dash_enabled(CP) else None
self.classic_lfa_icon = None
@@ -352,9 +356,15 @@ class CarController(CarControllerBase):
sys_warning, sys_state, CC.enabled, hud_control.leftLaneVisible, hud_control.rightLaneVisible,
left_lane_warning, right_lane_warning, {}, include_alerts=False, counter_mod=0xF,
fcw_opt_usm=2 if apply_steer_req or icon == 3 else 1))
if (self.frame % 5 == 0 and CS.out.canValid and not CS.out.canTimeout and
CS.blended_camera_current):
can_sends.append(hyundaicanfd.create_suppress_lfa(self.packer, self.CAN, CS.lfa_block_msg, False))
if CS.out.canValid and not CS.out.canTimeout and CS.blended_camera_current:
camera_counter = CS.lfa_block_msg["COUNTER"]
if (self.frame - self.blended_camera_sent_frame >= 5 and camera_counter != self.blended_camera_sent_counter and
(not CC.latActive or CS.blended_camera_updated)):
can_sends.append(hyundaicanfd.create_suppress_lfa(self.packer, self.CAN, CS.lfa_block_msg, False))
self.blended_camera_sent_frame = self.frame
self.blended_camera_sent_counter = camera_counter
else:
self.blended_camera_sent_counter = None
else:
_projection_packet_index = len(can_sends) if _projection is not None else 0
can_sends.extend(hyundaican.create_lkas11_can_canfd_blended(
@@ -569,14 +579,26 @@ class CarController(CarControllerBase):
stock_ccnc_owned = stock_source.owns_ccnc_fault_status(clock_boot_ns(), display_sample_ns=CS.ccnc_162_ts_ns,
healthy=display_healthy, qualified_warning=stock_owned_status)
damping_source = getattr(CS, "stock_lkas_damping", None)
can_sends.extend(hyundaicanfd.create_steering_messages(self.packer, self.CP, self.CAN,
steering_status_active, apply_steer_req, apply_torque,
stock_lfa=stock_lfa, stock_lfa_faults=stock_faults,
stock_lfa_owned_status=stock_owned_status,
stock_lkas_damping=(damping_source.current_damping(clock_boot_ns())
if damping_source is not None else None)))
if _projection is not None:
_projection.emit('hyundai.CANFD_TORQUE', apply_torque, apply_steer_req, can_sends[-1])
kona_handoff = (self.CP.carFingerprint == CAR.HYUNDAI_KONA_2ND_GEN and
self.CP.safetyConfigs[-1].safetyParam == KONA_IDLE_AOL_WORD)
lfa_counter = None
if kona_handoff:
if (CC.enabled or CC.latActive) and stock_lfa is not None:
if stock_lfa[2] != self.kona_last_lfa_counter:
lfa_counter = stock_lfa[2]
self.kona_last_lfa_counter = lfa_counter
else:
self.kona_last_lfa_counter = None
if not kona_handoff or lfa_counter is not None:
can_sends.extend(hyundaicanfd.create_steering_messages(self.packer, self.CP, self.CAN,
steering_status_active, apply_steer_req, apply_torque,
stock_lfa=stock_lfa, stock_lfa_faults=stock_faults,
stock_lfa_owned_status=stock_owned_status,
stock_lkas_damping=(damping_source.current_damping(clock_boot_ns())
if damping_source is not None else None),
lfa_counter=lfa_counter))
if _projection is not None:
_projection.emit('hyundai.CANFD_TORQUE', apply_torque, apply_steer_req, can_sends[-1])
# prevent LFA from activating on LKA steering cars by sending "no lane lines detected" to ADAS ECU
if (
+7 -1
View File
@@ -140,6 +140,7 @@ class CarState(CarStateBase):
self.dashboard_limit = LimitTracker()
self.dashboard_stop_sign = None
self.drive_mode = None
self.accelerator_pedal = None
self.ioniq6_bsm_sources = (Ioniq6BlindspotSources()
if CP.carFingerprint == CAR.HYUNDAI_IONIQ_6 and CP.openpilotLongitudinalControl else None)
self.ioniq6_bsm_now_ns = 0
@@ -150,6 +151,7 @@ class CarState(CarStateBase):
self.params = CarControllerParams(CP)
self.blended_camera_current = False
self.blended_camera_updated = False
self.ray_pedal_valid = False
self.ray_pedal_state = 5
@@ -347,6 +349,7 @@ class CarState(CarStateBase):
self.lfa_block_msg = copy.copy(cp_cam.vl["CAM_0x2a4"])
from opendbc.car.hyundai.blended_stock_aol import camera_current
self.blended_camera_current = camera_current(cp_cam)
self.blended_camera_updated = bool(cp_cam.vl_all["CAM_0x2a4"]["COUNTER"])
self.lkas11 = {}
else:
self.msg_364 = copy.copy(cp_cam.vl["ALERTS_364"])
@@ -433,7 +436,10 @@ class CarState(CarStateBase):
speed_factor = CV.KPH_TO_MS if self.is_metric else CV.MPH_TO_MS
if self.CP.flags & (HyundaiFlags.EV.value | HyundaiFlags.HYBRID.value):
ret.gasPressed = cp.vl[self.accelerator_msg_canfd]["ACCELERATOR_PEDAL"] > 1e-5
pedal = cp.vl[self.accelerator_msg_canfd]["ACCELERATOR_PEDAL"]
ret.gasPressed = pedal > 1e-5
stamp = cp.ts_nanos[self.accelerator_msg_canfd]["ACCELERATOR_PEDAL"]
self.accelerator_pedal = (float(pedal), stamp) if stamp > 0 else None
else:
ret.gasPressed = bool(cp.vl[self.accelerator_msg_canfd]["ACCELERATOR_PEDAL_PRESSED"])
@@ -45,7 +45,7 @@ LFA_FAULT_MASK = bytes.fromhex("00000000c001c0f00000000000000000")
def create_steering_messages(packer, CP, CAN, enabled, lat_active, apply_torque, *, stock_lfa=None, stock_lfa_faults=None,
stock_lkas_damping=None, stock_lfa_owned_status=False):
stock_lkas_damping=None, stock_lfa_owned_status=False, lfa_counter=None):
values = {
"LKA_OptUsmSta": 2,
"LKA_SysIndReq": 2 if enabled else 1,
@@ -73,6 +73,8 @@ def create_steering_messages(packer, CP, CAN, enabled, lat_active, apply_torque,
lkas_values = {**values, "Damping_Gain": damping}
ret.append(packer.make_can_msg(lkas_msg, CAN.ACAN, lkas_values))
else:
if lfa_counter is not None:
values["COUNTER"] = lfa_counter
message = packer.make_can_msg("LFA", CAN.ECAN, values)
source = stock_lfa if stock_lfa is not None else stock_lfa_faults
if source is not None:
@@ -67,7 +67,10 @@ class TestBlendedSender(unittest.TestCase):
command.actuators.longControlState = structs.CarControl.Actuators.LongControlState.pid
command.hudControl.setSpeed = 25.0
for frame in range(32):
actuators, messages = ci.apply(command.as_reader(), 2_000_000_000 + frame * 10_000_000)
tick = 16 + frame
camera = 16 + frame // 5 if frame % 5 == 0 else False
feed(ci, tick, camera=camera)
actuators, messages = ci.apply(command.as_reader(), 1_000_000_000 + tick * 10_000_000)
wanted = []
if frame % 100 == 0:
wanted.append((0x730 if hdaii else 0x7D0, int(hdaii)))
@@ -90,6 +93,8 @@ class TestBlendedSender(unittest.TestCase):
wanted.append((0x485, 1))
self.assertEqual([(address, bus) for address, _, bus in messages], wanted)
packets = {address: data for address, data, _ in messages}
if hdaii and frame % 5 == 0:
self.assertEqual(decode(ci, 0x2A4, packets[0x2A4], 'COUNTER'), camera)
for address, data, _ in messages:
if address not in (0x730, 0x7D0, 0x50, 0x51, 0x2A4):
self.assertEqual(data[0], hyundai_checksum(data[1:8]), hex(address))
@@ -37,9 +37,10 @@ def test_factory_ccnc_alpha_admits_only_matching_owner(car, alternate, offset):
assert qualified_long(cp) and independent_cruise_buttons_supported(cp)
policy = policy_for(cp)
assert policy.intent_supported and policy.runtime_supported and policy.explicit_latch
assert policy.safety_param_addition == 0x800 and policy.alternative_experience_addition == 32
expected = 0x800
assert policy.safety_param_addition == expected and policy.alternative_experience_addition == 32
assert cp.to_dict() == original
word = int(cp.safetyConfigs[-1].safetyParam) | 0x800
word = int(cp.safetyConfigs[-1].safetyParam) | expected
cp.safetyConfigs[-1].safetyParam = word
cp.alternativeExperience = 32
assert qualified_long(cp, marked_only=True)
@@ -199,3 +200,29 @@ def test_wheel_choices_keep_aol_with_either_longitudinal_owner(car, alternate, a
feature = WheelFeature(Owner())
assert 'Toggle AOL' in feature.choices('LKASButtonControl')
assert 'Toggle AOL' in feature.choices('MainCruiseButtonControl')
def test_idle_handoff_omits_only_kona_steering_packet():
reference_cp = kona_params(CARS[0])
handoff_cp = kona_params(CARS[0])
for cp, word in ((reference_cp, 0x0C0C), (handoff_cp, 0x1C0C)):
cp.safetyConfigs[0].safetyParam = word
cp.alternativeExperience = 32
reference, candidate = CarInterface(reference_cp), CarInterface(handoff_cp)
source = Mock()
source.owns_display_status.return_value = False
candidate.CS.stock_lfa_status = source
states = ((False, False, 10), (True, True, 11), (False, True, 11), (True, False, 12),
(True, True, None), (False, False, 13), (True, True, 14))
expected_counters = (None, 11, None, 12, None, None, 14)
for (enabled, lateral, camera_counter), expected in zip(states, expected_counters, strict=True):
if camera_counter is None:
source.current.return_value = None
else:
source.current.return_value = bytes([0, 0, camera_counter] + [0] * 13)
ctrl = structs.CarControl(enabled=enabled, latActive=lateral).as_reader()
_, before = reference.apply(ctrl, 1_000_000_000)
_, after = candidate.apply(ctrl, 1_000_000_000)
assert [frame for frame in after if frame[0] != 0x12A] == [frame for frame in before if frame[0] != 0x12A]
assert any(frame[0] == 0x12A for frame in before)
assert [data[2] for addr, data, _ in after if addr == 0x12A] == ([] if expected is None else [expected])
@@ -23,13 +23,17 @@ def params(topology='hdai', *, adas=False, alpha=False, release=False):
return CarInterface.get_params(CAR.HYUNDAI_PALISADE_2023, fp, fw, alpha, release, False)
def feed(ci, tick, *, main=True, cruise=1, display=0, gas=False, brake=False, torque=0):
def feed(ci, tick, *, main=True, cruise=1, display=0, gas=False, brake=False, torque=0, camera=True):
packer = CANPacker(DBC[ci.CP.carFingerprint][Bus.pt])
messages = []
for parser in ci.can_parsers.values():
for address in parser.addresses:
if address == 0x2A4 and camera is False:
continue
message = parser.dbc.addr_to_msg[address]
values = {'COUNTER': tick % 16} if 'COUNTER' in message.sigs else {}
if address == 0x2A4 and type(camera) is int:
values['COUNTER'] = camera
if message.name == 'SCC12':
values.update(MainMode_ACC=int(main), ACCMode=cruise, SCCInfoDisplay=display, VSetDis=90)
elif message.name == 'EMS16':
@@ -100,13 +104,14 @@ class TestPalisade2023(unittest.TestCase):
command.hudControl.setSpeed = 25.
previous = 0
for tick in range(20):
feed(ci, tick + 12, camera=12 + (tick + 3) // 5 if tick == 0 or tick % 5 == 2 else False)
actuators, messages = ci.apply(command.as_reader(), 1_200_000_000 + tick * 10_000_000)
self.assertEqual(actuators.torqueOutputCan - previous, 3 if topology == 'hdaii' else 2)
previous = actuators.torqueOutputCan
addresses = {a for a, _, _ in messages}
self.assertFalse(addresses & {0x420, 0x421, 0x389, 0x7D0, 0x730})
if topology == 'hdaii':
self.assertEqual(addresses, {0x50, 0x2A4} if tick % 5 == 0 else {0x50})
self.assertEqual(addresses, {0x50, 0x2A4} if tick in (0, 7, 12, 17) else {0x50})
self.assertTrue(all(bus == 0 for _, _, bus in messages))
else:
self.assertEqual(addresses, {0x340, 0x364})
@@ -123,6 +128,37 @@ class TestPalisade2023(unittest.TestCase):
actuators, _ = ci.apply(command.as_reader(), 1_500_000_000)
self.assertEqual(actuators.torqueOutputCan, 0)
def test_hda2_camera_copy_skips_samples_that_miss_the_send_slot(self):
ci = CarInterface(params('hdaii'))
for tick in range(12):
feed(ci, tick)
command = structs.CarControl(enabled=True, latActive=True)
copied = []
for frame in range(20):
tick = frame + 12
feed(ci, tick, camera={0: 12, 4: 13, 9: 14, 14: 15, 19: 16}.get(frame, False))
_, messages = ci.apply(command.as_reader(), 1_000_000_000 + tick * 10_000_000)
copied.extend((frame, data[2]) for address, data, _ in messages if address == 0x2A4)
self.assertEqual(copied, [(0, 12), (9, 14), (14, 15), (19, 16)])
def test_hda2_alpha_long_keeps_primary_steering_payload(self):
from opendbc.car.hyundai.blended_longitudinal import candidate_from_stock
stock = params('hdaii')
alpha = candidate_from_stock(stock, alpha_requested=True, native_qualified=True)
self.assertTrue(alpha.openpilotLongitudinalControl)
interfaces = [CarInterface(cp) for cp in (stock, alpha)]
command = structs.CarControl(enabled=True, latActive=True)
command.actuators.torque = .25
for tick in range(12):
steering = []
for ci in interfaces:
feed(ci, tick)
_, messages = ci.apply(command.as_reader(), 1_000_000_000 + tick * 10_000_000)
steering.append(next((data, bus) for address, data, bus in messages if address == 0x50))
self.assertEqual(steering[0], steering[1])
self.assertEqual(steering[0][0][8], 0)
def test_cancel_resume_route_to_exact_pt_bus_and_sibling_params_unchanged(self):
for topology in ('hdai', 'hdaii'):
ci = CarInterface(params(topology))
+5 -4
View File
@@ -1,4 +1,4 @@
"""One bounded Legacy AVH ON request; 0x32B is status, never a TX command."""
"""One bounded Subaru AVH ON request; 0x32B is status, never a TX command."""
AVH_REQUEST = 0x6BB
AVH_STATUS = 0x32B
@@ -132,13 +132,14 @@ class AvhStartup:
def eligible(cp):
from opendbc.car.subaru.startup import supported
return bool(supported(cp) and cp.carFingerprint == 'SUBARU_LEGACY_2025')
from opendbc.car.subaru.stock_aol import qualified
from opendbc.car.subaru.values import CAR, FROGGER_ANGLE_SIBLINGS
return bool(qualified(cp) and cp.carFingerprint in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_LEGACY_2025})
def selected(cp):
from opendbc.car.subaru.values import SubaruFlags
return bool(eligible(cp) and cp.flags & SubaruFlags.AVH_STARTUP and cp.safetyConfigs[0].safetyParam in (1169, 1425))
return bool(eligible(cp) and cp.flags & SubaruFlags.AVH_STARTUP and cp.safetyConfigs[0].safetyParam in (1041, 1169, 1425, 3089))
def prepare(cp, enabled):
@@ -8,7 +8,7 @@ from opendbc.car.interfaces import CarControllerBase
from opendbc.car.subaru import subarucan
from opendbc.car.subaru.jacobw_angle import MAX_ANGLE as JACOBW_MAX_ANGLE, filter_angle as jacobw_filter_angle, limit_angle as jacobw_limit_angle
from opendbc.car.subaru.stock_aol import qualified as subaru_aol_qualified
from opendbc.car.subaru.values import CAR, DBC, GLOBAL_ES_ADDR, CanBus, CarControllerParams, SubaruFlags
from opendbc.car.subaru.values import CAR, FROGGER_ANGLE_SIBLINGS, DBC, GLOBAL_ES_ADDR, CanBus, CarControllerParams, SubaruFlags
from opendbc.car.vehicle_model import VehicleModel
# FIXME: These limits aren't exact. The real limit is more than likely over a larger time period and
@@ -128,14 +128,15 @@ class CarController(CarControllerBase):
return self.aol_dash_green_last
def _ascent_lkas_alert(self, CC, CS):
if self.CP.carFingerprint not in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025) or not self.CP.flags & SubaruFlags.ASCENT_LKAS_ALERT:
if (self.CP.carFingerprint not in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025} or
not self.CP.flags & SubaruFlags.ASCENT_LKAS_ALERT):
return None
dat = CS.es_lkas_alert_dat
is_legacy_2025 = self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025
frogger_hud = self.CP.carFingerprint != CAR.SUBARU_ASCENT_2023
lateral_active = self.angle_was_active and CC.latActive and (
CC.enabled or subaru_aol_qualified(self.CP, marked_only=True)
)
if is_legacy_2025:
if frogger_hud:
armed = CS.out.cruiseState.available
if self.CP.openpilotLongitudinalControl:
acc_lead_visible = bool(CC.longActive and not CS.out.gasPressed and CC.hudControl.leadVisible)
@@ -213,7 +214,7 @@ class CarController(CarControllerBase):
not legacy_lateral_off and
not CS.out.standstill and not CS.out.steerFaultTemporary and not CS.out.steerFaultPermanent)
angle_active = self.angle_active(CS, angle_available)
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025:
if self.CP.carFingerprint in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_LEGACY_2025}:
if angle_active and self.angle_was_active and abs(self.apply_angle_last - CS.out.steeringAngleDeg) > 5.0:
self.eps_stall_count += 1
if self.eps_stall_count >= 8:
@@ -306,7 +307,8 @@ class CarController(CarControllerBase):
can_sends.extend(send_sng(self, CC, CS, now_nanos))
# *** alerts and pcm cancel ***
enabled_for_dash_2025 = False
frogger_hud = self.CP.carFingerprint in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_LEGACY_2025}
enabled_for_dash_2025 = self.angle_was_active
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025:
enabled_for_dash_2025 = self._legacy_2025_aol_dash_green(
hud_control,
@@ -341,13 +343,17 @@ class CarController(CarControllerBase):
can_sends.append(subarucan.create_es_dashstatus(self.packer, self.frame // 10, CS.es_dashstatus_msg, CC.enabled,
self.CP.openpilotLongitudinalControl, CC.longActive, hud_control.leadVisible))
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025:
if frogger_hud:
in_drive = CS.out.gearShifter in (structs.CarState.GearShifter.drive, structs.CarState.GearShifter.manumatic)
cruise_available = CS.out.cruiseState.available
lateral_off = self._legacy_2025_effective_lateral_off(CS, CC)
aol_enabled = bool(getattr(CS, "aol_enabled", True))
if self.CP.carFingerprint in FROGGER_ANGLE_SIBLINGS:
aol_enabled = aol_enabled and subaru_aol_qualified(self.CP, marked_only=True)
wheel_ready = bool(cruise_available and aol_enabled)
if not (in_drive and cruise_available) or lateral_off or not hud_control.lanesVisible:
lanes_visible = hud_control.lanesVisible or (
self.CP.carFingerprint in FROGGER_ANGLE_SIBLINGS and self.angle_was_active)
if not (in_drive and cruise_available) or lateral_off or not lanes_visible:
left_line = 0
right_line = 0
left_depart = False
@@ -376,7 +382,7 @@ class CarController(CarControllerBase):
hud_control.leftLaneDepart, hud_control.rightLaneDepart))
if self.CP.flags & SubaruFlags.SEND_INFOTAINMENT:
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025:
if frogger_hud:
can_sends.append(subarucan.create_es_infotainment(
self.packer, self.frame // 10, CS.es_infotainment_msg, hud_control.visualAlert,
audible_alert=hud_control.audibleAlert, legacy_2025=True,
@@ -110,6 +110,8 @@ class CarState(CarStateBase):
can_gear = int(cp_transmission.vl["Transmission"]["Gear"])
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025 and can_gear in SUBARU_CVT_MANUAL_GEARS:
ret.gearShifter = structs.CarState.GearShifter.manumatic
elif self.CP.carFingerprint == CAR.SUBARU_IMPREZA_2020 and self.shifter_values.get(can_gear) in ("1", "2", "3", "4", "5", "6"):
ret.gearShifter = structs.CarState.GearShifter.manumatic
elif self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025 and can_gear == 0:
ret.gearShifter = structs.CarState.GearShifter.neutral
else:
+6 -3
View File
@@ -5,7 +5,7 @@ from opendbc.car.disable_ecu import disable_ecu
from opendbc.car.interfaces import CarInterfaceBase
from opendbc.car.subaru.carcontroller import CarController
from opendbc.car.subaru.carstate import CarState
from opendbc.car.subaru.values import CAR, GLOBAL_ES_ADDR, CanBus, SubaruFlags, SubaruSafetyFlags
from opendbc.car.subaru.values import CAR, FROGGER_ANGLE_SIBLINGS, EARLY_GLOBAL_TORQUE_CARS, GLOBAL_ES_ADDR, CanBus, SubaruFlags, SubaruSafetyFlags
GEN2_ANGLE_PORTS = frozenset((CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_LEGACY_2025,
CAR.SUBARU_ASCENT_2023, CAR.SUBARU_FORESTER_2022, CAR.SUBARU_OUTBACK_2023))
@@ -59,7 +59,7 @@ class CarInterface(CarInterfaceBase):
if not (ret.flags & SubaruFlags.PREGLOBAL) and 0x323 in fingerprint[2]:
ret.flags |= SubaruFlags.SEND_INFOTAINMENT.value
if candidate in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025) and fingerprint[CanBus.camera].get(0x3C4) == 8:
if candidate in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025} and fingerprint[CanBus.camera].get(0x3C4) == 8:
ret.flags |= SubaruFlags.ASCENT_LKAS_ALERT.value
if ret.flags & SubaruFlags.PREGLOBAL:
@@ -76,6 +76,8 @@ class CarInterface(CarInterfaceBase):
ret.safetyConfigs[0].safetyParam |= SubaruSafetyFlags.LKAS_ANGLE.value
if candidate in (CAR.SUBARU_LEGACY_2025, CAR.SUBARU_ASCENT_2023, CAR.SUBARU_OUTBACK_2023):
ret.safetyConfigs[0].safetyParam |= SubaruSafetyFlags.FIXED_ANGLE_LIMITS.value
if candidate in FROGGER_ANGLE_SIBLINGS and ret.flags & SubaruFlags.ASCENT_LKAS_ALERT:
ret.safetyConfigs[0].safetyParam |= SubaruSafetyFlags.ASCENT_LKAS_ALERT.value
if candidate == CAR.SUBARU_OUTBACK_2023:
ret.safetyConfigs[0].safetyParam |= SubaruSafetyFlags.D_PLATFORM.value
if candidate == CAR.SUBARU_ASCENT_2023:
@@ -99,7 +101,8 @@ class CarInterface(CarInterfaceBase):
ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0., 20.], [0., 20.]]
ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.0025, 0.1], [0.00025, 0.01]]
elif candidate == CAR.SUBARU_IMPREZA:
elif candidate in EARLY_GLOBAL_TORQUE_CARS:
ret.safetyConfigs[0].safetyParam = SubaruSafetyFlags.EARLY_GLOBAL_TORQUE.value
ret.steerActuatorDelay = 0.4 # end-to-end angle controller
ret.lateralTuning.init('pid')
ret.lateralTuning.pid.kf = 0.00005
+4 -2
View File
@@ -2,10 +2,10 @@
from opendbc.car import structs
from opendbc.car.subaru.stock_aol import IMPREZA_MAIN_AOL
from opendbc.car.subaru.values import CAR, SubaruFlags
from opendbc.car.subaru.values import CAR, EARLY_GLOBAL_TORQUE_CARS, SubaruFlags, SubaruSafetyFlags
STOP_AND_GO = 8
SUPPORTED = frozenset((CAR.SUBARU_ASCENT, CAR.SUBARU_IMPREZA, CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_FORESTER))
SUPPORTED = EARLY_GLOBAL_TORQUE_CARS | {CAR.SUBARU_ASCENT, CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_FORESTER}
def eligible(cp):
@@ -16,6 +16,8 @@ def eligible(cp):
return False
word &= ~IMPREZA_MAIN_AOL
words = (0, 8, 512, 520) if cp.carFingerprint == CAR.SUBARU_IMPREZA_2020 else (0, 8)
if cp.carFingerprint in EARLY_GLOBAL_TORQUE_CARS:
words = (SubaruSafetyFlags.EARLY_GLOBAL_TORQUE, SubaruSafetyFlags.EARLY_GLOBAL_TORQUE | STOP_AND_GO)
return bool(
cp.brand == 'subaru'
and cp.carFingerprint in SUPPORTED
+11 -3
View File
@@ -1,11 +1,11 @@
"""Exact stock-cruise Subaru independent-lateral configuration contract."""
from opendbc.car import structs
from opendbc.car.subaru.values import CAR, SubaruFlags, SubaruSafetyFlags
from opendbc.car.subaru.values import CAR, FROGGER_ANGLE_SIBLINGS, EARLY_GLOBAL_TORQUE_CARS, SubaruFlags, SubaruSafetyFlags
AOL_EXPERIENCE = 32
IMPREZA_MAIN_AOL = 4096
TORQUE_CARS = frozenset((CAR.SUBARU_ASCENT, CAR.SUBARU_OUTBACK, CAR.SUBARU_LEGACY,
CAR.SUBARU_IMPREZA, CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_FORESTER))
CAR.SUBARU_IMPREZA, CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_FORESTER, CAR.SUBARU_CROSSTREK_2018))
ANGLE_CARS = frozenset((CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_LEGACY_2025,
CAR.SUBARU_ASCENT_2023, CAR.SUBARU_FORESTER_2022, CAR.SUBARU_OUTBACK_2023))
@@ -24,6 +24,8 @@ def qualified(cp, *, marked_only=False):
static = int(CAR[cp.carFingerprint].config.flags)
allowed = int(SubaruFlags.HAS_BSM | SubaruFlags.SEND_INFOTAINMENT | SubaruFlags.SMOOTHING_BOUND)
expected = int(SubaruSafetyFlags.GEN2) if static & SubaruFlags.GLOBAL_GEN2 else 0
if cp.carFingerprint in EARLY_GLOBAL_TORQUE_CARS:
expected |= int(SubaruSafetyFlags.EARLY_GLOBAL_TORQUE) | (word & 8)
if cp.carFingerprint == CAR.SUBARU_OUTBACK_2023:
expected |= int(SubaruSafetyFlags.D_PLATFORM)
allowed |= int(SubaruFlags.STOP_START_OFF)
@@ -35,6 +37,12 @@ def qualified(cp, *, marked_only=False):
expected |= int(SubaruSafetyFlags.AVH_STARTUP)
if cp.flags & SubaruFlags.STOP_START_OFF:
expected |= int(SubaruSafetyFlags.STOP_START_BUTTON)
if cp.carFingerprint in FROGGER_ANGLE_SIBLINGS:
allowed |= int(SubaruFlags.AVH_STARTUP | SubaruFlags.ASCENT_LKAS_ALERT)
if cp.flags & SubaruFlags.AVH_STARTUP:
expected |= int(SubaruSafetyFlags.AVH_STARTUP)
if cp.flags & SubaruFlags.ASCENT_LKAS_ALERT:
expected |= int(SubaruSafetyFlags.ASCENT_LKAS_ALERT)
angle = cp.carFingerprint in ANGLE_CARS
if angle:
expected |= int(SubaruSafetyFlags.LKAS_ANGLE)
@@ -50,7 +58,7 @@ def qualified(cp, *, marked_only=False):
return False
if cp.carFingerprint == CAR.SUBARU_IMPREZA_2020 and word == 512:
expected |= 512
if cp.carFingerprint in (CAR.SUBARU_ASCENT, CAR.SUBARU_IMPREZA, CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_FORESTER) and word in (8, 520):
if cp.carFingerprint in (CAR.SUBARU_ASCENT, CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_FORESTER) and word in (8, 520):
expected |= 8
if cp.carFingerprint == CAR.SUBARU_IMPREZA_2020:
expected |= word & 512
@@ -4,7 +4,7 @@ from opendbc.car import structs
from opendbc.car.subaru.carcontroller import CarController
from opendbc.car.subaru.carstate import CarState
from opendbc.car.subaru.interface import CarInterface
from opendbc.car.subaru.values import CAR, DBC, SubaruFlags, SubaruSafetyFlags
from opendbc.car.subaru.values import CAR, DBC, FROGGER_ANGLE_SIBLINGS, SubaruFlags, SubaruSafetyFlags
from opendbc.car.subaru import subarucan
from opendbc.safety.tests.test_subaru_gen2_angle_pair import TestSubaruGen2AnglePair
@@ -18,8 +18,8 @@ class TestAscentLkasAlert(unittest.TestCase):
def test_platform_bus_length_gate_preserves_native_identity(self):
for car in CAR:
cp = self.params(car)
self.assertEqual(bool(cp.flags & SubaruFlags.ASCENT_LKAS_ALERT), car in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025))
self.assertEqual(bool(cp.safetyConfigs[0].safetyParam & SubaruSafetyFlags.ASCENT_LKAS_ALERT), car == CAR.SUBARU_ASCENT_2023)
self.assertEqual(bool(cp.flags & SubaruFlags.ASCENT_LKAS_ALERT), car in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025})
self.assertEqual(bool(cp.safetyConfigs[0].safetyParam & SubaruSafetyFlags.ASCENT_LKAS_ALERT), car in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_ASCENT_2023})
for bus, length in ((0, 8), (1, 8), (2, 4), (2, 16)):
cp = self.params(bus=bus, length=length)
self.assertFalse(cp.flags & SubaruFlags.ASCENT_LKAS_ALERT)
@@ -145,9 +145,10 @@ def test_hackathon_filter_updates_at_control_rate(speed, tau):
assert not any(frame[0] == 0x124 for frame in odd_sends)
assert controller.angle_filter.x == pytest.approx(.1 * (1. - (1. - alpha) ** 2))
command.latActive = False
state.out.steeringAngleDeg = .3
command.actuators.steeringAngleDeg = -.2
controller.update(command.as_reader(), state, 1_020_000_000)
assert controller.angle_filter.x == command.actuators.steeringAngleDeg
assert controller.angle_filter.x == state.out.steeringAngleDeg
def test_hackathon_geometry_is_scoped_and_native_bound_remains_strict():
@@ -7,7 +7,7 @@ from opendbc.car import Bus, structs
from opendbc.car.subaru import subarucan
from opendbc.car.subaru.stock_aol import ANGLE_CARS, TORQUE_CARS
from opendbc.car.subaru.tests.test_ascent_angle import setup_controller, step
from opendbc.car.subaru.values import CAR, DBC, SubaruSafetyFlags
from opendbc.car.subaru.values import CAR, DBC, FROGGER_ANGLE_SIBLINGS, SubaruSafetyFlags
from opendbc.safety.tests import test_subaru_gen2_angle_pair as pair
from opendbc.safety.tests.libsafety import libsafety_py
@@ -74,6 +74,9 @@ def test_dash_uses_current_request_without_mutating_physical_template(car, enabl
if car == CAR.SUBARU_LEGACY_2025:
assert bool(dash['LKAS_ACTIVE'])
assert dash['LKAS_Dash_State'] == (2 if expected else (1 if state.out.cruiseState.available else 0))
elif car in FROGGER_ANGLE_SIBLINGS:
assert bool(dash['LKAS_ACTIVE'])
assert dash['LKAS_Dash_State'] == (2 if expected else (1 if marked and state.out.cruiseState.available else 0))
else:
if car in ANGLE_CARS or marked or enabled:
assert bool(dash['LKAS_ACTIVE']) == expected
@@ -69,6 +69,19 @@ class TestSupportedSubaruFirmware(unittest.TestCase):
self.assertTrue(cp.pcmCruise)
self.assertEqual(cp.safetyConfigs[0].safetyParam, word)
def test_early_crosstrek_shares_firmware_but_has_distinct_vehicle_params(self):
platform = CAR.SUBARU_CROSSTREK_2018
self.assertNotIn(platform, FW_VERSIONS)
shared = FW_VERSIONS[CAR.SUBARU_IMPREZA]
live = {(address, sub): {versions[0]} for (_, address, sub), versions in shared.items()}
self.assertEqual(match_fw_to_car_exact(live, match_brand='subaru', log=False), {CAR.SUBARU_IMPREZA})
for release in (False, True):
cp = CarInterface.get_params(platform, {0: {}, 1: {}, 2: {}}, [], False, release, False)
self.assertEqual(cp.carFingerprint, platform)
self.assertFalse(cp.dashcamOnly)
self.assertTrue(cp.pcmCruise)
self.assertFalse(cp.openpilotLongitudinalControl or cp.alphaLongitudinalAvailable)
def test_three_byte_diagnostic_response_is_not_a_camera_identity(self):
for platform in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025):
for versions in FW_VERSIONS[platform].values():
+14
View File
@@ -37,6 +37,8 @@ class CarControllerParams:
self.STEER_MAX = 1000
self.STEER_DELTA_UP = 40
self.STEER_DELTA_DOWN = 40
elif CP.carFingerprint in EARLY_GLOBAL_TORQUE_CARS:
self.STEER_MAX = 3071
elif CP.carFingerprint == CAR.SUBARU_IMPREZA_2020:
self.STEER_DELTA_UP = 35
self.STEER_MAX = 1439
@@ -71,6 +73,7 @@ class SubaruSafetyFlags(IntFlag):
GEN2 = 1
LONG = 2
PREGLOBAL_REVERSED_DRIVER_TORQUE = 4
EARLY_GLOBAL_TORQUE = 8192
PREGLOBAL_OUTBACK_STOCK_ACC = 8
LKAS_ANGLE = 16
D_PLATFORM = 64
@@ -168,6 +171,11 @@ class CAR(Platforms):
SUBARU_IMPREZA = SubaruPlatformConfig(
[
SubaruCarDocs("Subaru Impreza 2017-19"),
],
CarSpecs(mass=1568, wheelbase=2.67, steerRatio=15),
)
SUBARU_CROSSTREK_2018 = SubaruPlatformConfig(
[
SubaruCarDocs("Subaru Crosstrek 2018-19", video="https://youtu.be/Agww7oE1k-s?t=26"),
SubaruCarDocs("Subaru XV 2018-19", video="https://youtu.be/Agww7oE1k-s?t=26"),
],
@@ -269,6 +277,12 @@ SUBARU_ALT_VERSION_REQUEST = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER]) +
SUBARU_ALT_VERSION_RESPONSE = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER + 0x40]) + \
p16(0xf100)
EARLY_GLOBAL_TORQUE_CARS = frozenset((CAR.SUBARU_IMPREZA, CAR.SUBARU_CROSSTREK_2018))
FROGGER_ANGLE_SIBLINGS = frozenset((CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_CROSSTREK_2025))
FW_QUERY_CONFIG = FwQueryConfig(
validate_fw_match=validate_fw_match,
fw_version_regex=br"(?:[\x00-\xff]{4,5}|[\x00-\xff]{8}|[\x00-\xff]{10})",
@@ -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,730 @@
"""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
# The Tesla moved, or the comma now wants the other way (the Tesla was at its own limit in the old direction):
# the unanswered request says nothing about this one.
if (self.native_ns > u.sent_ns and self.native != u.before) or u.direction != (1 if target > native else -1):
self.unanswered = None
self.unanswered_count = 0
self.retry_refused = False
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,331 @@
"""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_an_unanswered_request_does_not_hold_back_the_other_direction():
# The Tesla ignores scrolls one way (it is at its own lowest or highest set speed). A comma speed still on that side
# keeps waiting; once it is on the other side of the Tesla's, sync carries on without the Tesla changing first.
r = Rig()
r.tick()
for _ in range(100):
r.tick(dt=100_000_000)
assert r.sync.status == 'waiting_for_native_change'
sent = len(r.sent)
r.target = 55 # further the same way (the Tesla shows 45)
for _ in range(20):
assert r.tick() is None
assert r.sync.status == 'waiting_for_native_change'
r.target = 40 # now below the Tesla's
assert any(r.tick() for _ in range(20))
assert len(r.sent) == sent + 1 and clicks(r.sent[-1][1]) == -1
r.speed -= 1 # the Tesla follows: nothing is left of the old wait
assert any(r.tick() for _ in range(20)) and r.sync.unanswered is None
def test_request_needs_a_new_physical_neutral_frame():
r = Rig()
r.tick()
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
+1
View File
@@ -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
+1
View File
@@ -22,6 +22,7 @@ from opendbc.car.mg.values import CAR as MG
# Configurations with source tests but no matching recorded route.
unrecorded_route_gaps = {
SUBARU.SUBARU_CROSSTREK_2018: "subaru/tests/test_supported_firmware.py",
GM.CHEVROLET_VOLT_CC: "gm/tests/test_volt_cc_gas.py",
GM.CHEVROLET_MALIBU_HYBRID_CC: "gm/tests/test_ordinary_cc.py",
TOYOTA.TOYOTA_PRIUS_RETROFIT: "toyota/tests/test_retrofit.py",
@@ -4,6 +4,7 @@ from pathlib import Path
from opendbc.car.values import PLATFORMS
from opendbc.car.tests.routes import non_tested_cars, routes, unrecorded_route_gaps
from opendbc.car.gm.values import CAR as GM
from opendbc.car.subaru.values import CAR as SUBARU
from opendbc.car.tesla.values import CAR as TESLA
from opendbc.car.toyota.values import CAR as TOYOTA
from opendbc.car.volvo.values import CAR as VOLVO
@@ -20,7 +21,7 @@ class TestRoutes(unittest.TestCase):
def test_explicit_unrecorded_configuration_gaps(self):
self.assertEqual(set(unrecorded_route_gaps), {
GM.CHEVROLET_VOLT_CC, GM.CHEVROLET_MALIBU_HYBRID_CC, TOYOTA.TOYOTA_PRIUS_RETROFIT, TESLA.TESLA_MODEL_S_HW1,
VOLVO.VOLVO_XC40_RECHARGE, VOLVO.VOLVO_S60_RECHARGE, VOLVO.POLESTAR_2, VOLVO.VOLVO_V60,
SUBARU.SUBARU_CROSSTREK_2018, VOLVO.VOLVO_XC40_RECHARGE, VOLVO.VOLVO_S60_RECHARGE, VOLVO.POLESTAR_2, VOLVO.VOLVO_V60,
})
self.assertFalse(set(unrecorded_route_gaps) & {route.car_model for route in routes})
self.assertTrue(set(unrecorded_route_gaps) <= set(non_tested_cars))
@@ -111,6 +111,7 @@ legend = ["LAT_ACCEL_FACTOR", "MAX_LAT_ACCEL_MEASURED", "FRICTION"]
"SEAT_ATECA_MK1" = "VOLKSWAGEN_GOLF_MK7"
"VOLKSWAGEN_JETTA_MK6" = "VOLKSWAGEN_PASSAT_NMS"
"SUBARU_CROSSTREK_2018" = "SUBARU_IMPREZA"
"SUBARU_CROSSTREK_HYBRID" = "SUBARU_IMPREZA_2020"
"SUBARU_FORESTER_HYBRID" = "SUBARU_IMPREZA_2020"
"SUBARU_LEGACY" = "SUBARU_OUTBACK"
@@ -11,7 +11,7 @@ from opendbc.car.interfaces import CarControllerBase
from opendbc.car.toyota import toyotacan
from opendbc.car.toyota import (dom_defaults, prius_longitudinal, rav4h_filter, pedal, eps8_sdsu, legacy_sdsu,
advert_filter, legacy_stop_timer, legacy_advert_filter)
from opendbc.car.toyota import pedal_composite, camera_2aa_filter, prius_sdsu, prius_advert_filter
from opendbc.car.toyota import pedal_composite, camera_2aa_filter, prius_sdsu, prius_advert_filter, radar_filter
from opendbc.car.toyota.door_locks import DoorLocks
from opendbc.car.toyota.values import CAR, CarControllerParams, ToyotaFlags, TOYOTA_AUTO_HOLD_CARS, uses_toyota_auto_hold_aeb
from opendbc.can import CANPacker
@@ -58,7 +58,10 @@ def supports_toyota_auto_hold(CP):
def get_long_tune(CP, params):
prius = prius_longitudinal.enabled(CP)
if prius or CP.flags & ToyotaFlags.TSS2 or dom_defaults.camry_hybrid(CP) or dom_defaults.rav4h_sdsu(CP):
# The generic integral gain amplifies small acceleration requests on the four-byte Sienna filter.
sienna_filter = (CP.carFingerprint == CAR.TOYOTA_SIENNA and not CP.flags & ToyotaFlags.GAS_INTERCEPTOR and
legacy_advert_filter.enabled(CP))
if prius or sienna_filter or CP.flags & ToyotaFlags.TSS2 or dom_defaults.camry_hybrid(CP) or dom_defaults.rav4h_sdsu(CP):
kiBP = [2., 5.]
kiV = [0.5, 0.25]
else:
@@ -93,6 +96,7 @@ class CarController(CarControllerBase):
self.legacy_stop_timer = legacy_stop_timer.enabled(CP)
self.legacy_advert_filter = legacy_advert_filter.configured(CP)
self.camera_twoaa_filter = camera_2aa_filter.configured(CP)
self.camry_se_idle_contract = radar_filter.camry_se_idle_contract(CP)
self.permit_braking = True
self.steer_rate_counter = 0
self.distance_button = 0
@@ -464,10 +468,21 @@ class CarController(CarControllerBase):
not (self.brake_hold_active and not uses_toyota_auto_hold_aeb(self.CP))):
pcm_accel_cmd = 0.
main_accel_cmd = 0. if self.CP.flags & ToyotaFlags.SECOC.value else pcm_accel_cmd
can_sends.append(toyotacan.create_accel_command(self.packer, main_accel_cmd, pcm_cancel_cmd, self.permit_braking, self.standstill_req, lead,
CS.acc_type, fcw_alert, self.distance_button,
reverse_cruise=bool(self.CP.pcmCruise and self.reverse_cruise_input is not None and
self.reverse_cruise_input.update())))
if (self.camry_se_idle_contract and CS.out.canValid and not CS.out.canTimeout and
not CS.out.accFaulted and not CS.out.stockAeb and CS.pcm_acc_status == 0 and not CS.out.cruiseState.enabled and
not CC.enabled and not CC.longActive and not pcm_cancel_cmd and not fcw_alert):
# Match the filter's observed neutral frame until the PCM accepts SET.
self.prev_accel = pcm_accel_cmd = 0.
can_sends.append(self.packer.make_can_msg("ACC_CONTROL", 0, {
"ACC_TYPE": 1,
"ALLOW_LONG_PRESS": 3,
"PERMIT_BRAKING": 1,
}))
else:
can_sends.append(toyotacan.create_accel_command(self.packer, main_accel_cmd, pcm_cancel_cmd, self.permit_braking, self.standstill_req, lead,
CS.acc_type, fcw_alert, self.distance_button,
reverse_cruise=bool(self.CP.pcmCruise and self.reverse_cruise_input is not None and
self.reverse_cruise_input.update())))
if self.CP.flags & ToyotaFlags.SECOC.value:
acc_cmd_2 = toyotacan.create_accel_command_2(self.packer, pcm_accel_cmd)
acc_cmd_2 = add_mac(self.secoc_key,
@@ -31,6 +31,11 @@ TEMP_STEER_FAULTS = (0, 9, 11, 21, 25)
PERM_STEER_FAULTS = (3, 17)
def has_optional_prius_gap_button(CP):
return (CP.carFingerprint == CAR.TOYOTA_PRIUS and not CP.openpilotLongitudinalControl and
not CP.flags & (ToyotaFlags.LONG_FILTER | ToyotaFlags.FILTER_BUTTONS))
class CarState(CarStateBase):
def __init__(self, CP):
super().__init__(CP)
@@ -266,6 +271,10 @@ class CarState(CarStateBase):
if self.CP.flags & ToyotaFlags.FILTER_BUTTONS or advert_filter.configured(self.CP) or prius_advert_filter.configured(self.CP):
fresh = cp.advert_button_ns > 0 and 0 <= cp._last_update_nanos - cp.advert_button_ns <= 200_000_000
self.distance_button = cp.advert_distance_button if fresh else 0
elif not bypass and has_optional_prius_gap_button(self.CP):
self.distance_button = cp_acc.vl["ACC_CONTROL"]["DISTANCE"]
# A live gesture needs its source until the physical release arrives.
cp_acc.message_states[0x343].ignore_alive = not self.distance_button
else:
self.distance_button = (cp.vl["SDSU"]["FD_BUTTON"] if self.CP.flags & ToyotaFlags.LONG_FILTER
else cp_acc.vl["ACC_CONTROL"]["DISTANCE"])
@@ -361,6 +370,10 @@ class CarState(CarStateBase):
("BLINKERS_STATE", float('nan')),
]
if has_optional_prius_gap_button(CP):
# Factory cruise state and AEB are received on separate messages.
pt_messages.append(("ACC_CONTROL", math.nan))
if CP.carFingerprint == CAR.TOYOTA_SIENNA_4TH_GEN:
pt_messages.append(("PCM_CRUISE_4", 1))
from opendbc.car.toyota import camera_2aa_filter
@@ -12,6 +12,36 @@ from opendbc.safety import ALTERNATIVE_EXPERIENCE
SteerControlType = structs.CarParams.SteerControlType
CAMERA_TORQUE_CARS = frozenset((
CAR.TOYOTA_ALPHARD_TSS2, CAR.TOYOTA_AVALON_TSS2, CAR.TOYOTA_CAMRY_TSS2, CAR.TOYOTA_COROLLA_TSS2,
CAR.TOYOTA_HIGHLANDER_TSS2, CAR.TOYOTA_PRIUS_TSS2, CAR.TOYOTA_RAV4_TSS2, CAR.TOYOTA_MIRAI,
CAR.LEXUS_ES_TSS2, CAR.LEXUS_NX_TSS2, CAR.LEXUS_LC_TSS2, CAR.LEXUS_RX_TSS2,
CAR.LEXUS_IS_TSS2, CAR.LEXUS_RC_TSS2,
))
def camera_stock_acc_supported(cp) -> bool:
required = ToyotaFlags.TSS2 | ToyotaFlags.NO_DSU | ToyotaFlags.RAISED_ACCEL_LIMIT
allowed = required | ToyotaFlags.HYBRID | ToyotaFlags.HAS_BSM
if (cp is None or cp.brand != "toyota" or cp.carFingerprint not in CAMERA_TORQUE_CARS or
cp.notCar or cp.passive or cp.dashcamOnly or cp.secOcRequired or cp.alphaLongitudinalAvailable or not cp.pcmCruise or
cp.steerControlType != SteerControlType.torque or len(cp.safetyConfigs) != 1 or
cp.flags & required != required or int(cp.flags) & ~int(allowed)):
return False
config = cp.safetyConfigs[0]
expected = EPS_SCALE[cp.carFingerprint]
if not cp.openpilotLongitudinalControl:
expected |= int(ToyotaSafetyFlags.STOCK_LONGITUDINAL)
return config.safetyModel == structs.CarParams.SafetyModel.toyota and config.safetyParam == expected
def prepare_camera_stock_acc(cp, requested: bool) -> None:
if requested and camera_stock_acc_supported(cp):
cp.openpilotLongitudinalControl = False
cp.autoResumeSng = False
cp.safetyConfigs[0].safetyParam |= int(ToyotaSafetyFlags.STOCK_LONGITUDINAL)
def toyota_auto_hold_supported(CP) -> bool:
from opendbc.car.toyota import pedal, pedal_composite
if not (CP.brand == "toyota" and CP.carFingerprint in TOYOTA_AUTO_HOLD_CARS and
@@ -49,6 +49,17 @@ def configured(cp):
cp.safetyConfigs[0].safetyParam == (profile[1] if cp.openpilotLongitudinalControl else profile[2]))
def camry_se_idle_contract(cp):
if (cp.carFingerprint != CAR.TOYOTA_CAMRY or not cp.openpilotLongitudinalControl or
not cp.pcmCruise or cp.passive or cp.dashcamOnly or cp.notCar or
not cp.flags & ToyotaFlags.FILTER_BUTTONS or cp.flags & (ToyotaFlags.HYBRID | ToyotaFlags.GAS_INTERCEPTOR) or
not configured(cp)):
return False
firmware = {(str(fw.ecu), fw.address, bytes(fw.fwVersion)) for fw in cp.carFw}
return {("engine", 0x700, b"\x018966333P4700\x00\x00\x00\x00"),
("dsu", 0x791, b"8821F0601300 ")} <= firmware
def prepare_stock(cp):
from opendbc.car.toyota import pedal_composite
if pedal_composite.marked(cp):
+20 -3
View File
@@ -20,9 +20,26 @@ WORDS = frozenset(PROFILES.values())
def hardware_supported(candidate, fingerprint):
return (candidate in PROFILES and
not any(address in frames for frames in fingerprint.values() for address in (0x201, 0x2FF, 0x2AA)) and
not any(address in fingerprint.get(2, {}) for address in (0x343, 0x4CB)))
if candidate not in PROFILES:
return False
from opendbc.car.toyota.radar_filter import _cluster_radar_bus
for bus, frames in fingerprint.items():
if 0x201 in frames or 0x2AA in frames:
return False
if 0x2FF in frames and not (candidate == CAR.TOYOTA_CAMRY and _cluster_radar_bus(candidate, bus, frames)):
return False
camera = fingerprint.get(2, {})
if 0x4CB in camera:
return False
if 0x343 not in camera:
return True
# The stock Camry can mirror its powertrain bus at startup, including ACC_CONTROL.
# An independent camera fingerprint is still treated as possible takeover hardware.
pt = fingerprint.get(0, {})
return (candidate == CAR.TOYOTA_CAMRY and pt == camera and
all(pt.get(address) == 8 for address in (0xAA, 0x262, 0x343)))
def apply(cp):
@@ -0,0 +1,40 @@
import pytest
from opendbc.can import CANPacker
from opendbc.car import Bus, gen_empty_fingerprint, structs
from opendbc.car.toyota.carstate import CarState
from opendbc.car.toyota.interface import CarInterface
from opendbc.car.toyota.values import CAR, DBC
@pytest.mark.parametrize('stock_aol', (True, False))
def test_prius_gap_button_requires_the_source_only_during_a_press(stock_aol):
fp = gen_empty_fingerprint()
if not stock_aol:
fp[2][0x343] = 8
cp = CarInterface.get_params(CAR.TOYOTA_PRIUS, fp, [], False, False, False)
assert not cp.openpilotLongitudinalControl
assert cp.safetyConfigs[0].safetyParam == (0x6242 if stock_aol else 0x242)
state = CarState(cp)
parsers = state.get_can_parsers(cp)
packer = CANPacker(DBC[CAR.TOYOTA_PRIUS][Bus.pt])
gap = structs.CarState.ButtonEvent.Type.gapAdjustCruise
def edges(stamp, value=None):
frames = [] if value is None else [packer.make_can_msg('ACC_CONTROL', 0, {'DISTANCE': value})]
for parser in parsers.values():
parser.update([(stamp, frames)])
return [event.pressed for event in state.update(parsers).buttonEvents if event.type == gap]
assert edges(1_000_000_000) == []
assert parsers[Bus.pt].message_states[0x343].ignore_alive
assert not parsers[Bus.pt].message_states[0x1D3].ignore_alive
assert not parsers[Bus.pt].message_states[0x262].ignore_alive
assert edges(1_030_000_000, 1) == [True]
gap_message = parsers[Bus.pt].message_states[0x343]
assert not gap_message.ignore_alive
assert edges(12_000_000_000) == []
assert not gap_message.valid(12_000_000_000, False)
assert edges(12_030_000_000, 0) == [False]
assert gap_message.ignore_alive
assert gap_message.valid(23_000_000_000, False)
@@ -0,0 +1,29 @@
import pytest
from opendbc.car import gen_empty_fingerprint, structs
from opendbc.car.toyota import legacy_advert_filter
from opendbc.car.toyota.carcontroller import get_long_tune
from opendbc.car.toyota.fingerprints import FW_VERSIONS
from opendbc.car.toyota.interface import CarInterface
from opendbc.car.toyota.values import CAR, CarControllerParams
@pytest.mark.parametrize('vehicle,dlc,factory_acc,expected', (
(CAR.TOYOTA_SIENNA, 4, False, ([2., 5.], [0.5, 0.25])),
(CAR.TOYOTA_SIENNA, 4, True, ([0., 5., 35.], [3.6, 2.4, 1.5])),
(CAR.TOYOTA_SIENNA, 8, False, ([0., 5., 35.], [3.6, 2.4, 1.5])),
(CAR.TOYOTA_HIGHLANDER, 4, False, ([0., 5., 35.], [3.6, 2.4, 1.5])),
))
def test_sienna_filter_integral_tune(vehicle, dlc, factory_acc, expected):
fp = gen_empty_fingerprint()
fp[0][0x2FF] = dlc
fw = [structs.CarParams.CarFw(ecu=ecu, address=addr, subAddress=sub or 0, fwVersion=versions[0], brand='toyota', bus=0)
for (ecu, addr, sub), versions in FW_VERSIONS[vehicle].items()]
cp = CarInterface.get_params(vehicle, fp, fw, True, False, False)
assert cp.openpilotLongitudinalControl
assert legacy_advert_filter.enabled(cp) == (dlc == 4)
if factory_acc:
assert legacy_advert_filter.prepare_stock(cp)
tune = get_long_tune(cp, CarControllerParams(cp))
assert tune._k_i == expected
assert tune.k_f == 1.
@@ -1228,7 +1228,67 @@ static bool hyundai_canfd_tx_hook_valid(const CANPacket_t *msg) {
return tx;
}
static bool hyundai_canfd_tx_hook(const CANPacket_t *msg) {
#ifdef ALLOW_DEBUG
static bool hyundai_kona_idle_handoff = false;
static bool hyundai_kona_camera_seen = false;
static bool hyundai_kona_output_seen = false;
static bool hyundai_kona_host_output = false;
static uint32_t hyundai_kona_camera_ts = 0U;
static uint32_t hyundai_kona_output_ts = 0U;
static uint8_t hyundai_kona_camera_counter = 0U;
static uint8_t hyundai_kona_output_counter = 0U;
static bool hyundai_kona_host_steering(void) {
return controls_allowed || ((aol_get_permission_mask() & 1U) != 0U);
}
static bool hyundai_kona_lfa_valid(const CANPacket_t *msg) {
return msg->fd && !msg->extended && (GET_LEN(msg) == 16U) &&
(hyundai_canfd_get_checksum(msg) == (hyundai_common_canfd_compute_checksum(msg) ^ 0x041DU));
}
static bool hyundai_kona_output_ready(uint32_t now, bool host, uint8_t counter) {
const uint32_t age = safety_get_ts_elapsed(now, hyundai_kona_output_ts);
const uint8_t delta = (uint8_t)(counter - hyundai_kona_output_counter);
return !hyundai_kona_output_seen ||
(((hyundai_kona_host_output == host) || (age >= 10000U)) &&
((age > 50000U) || ((delta > 0U) && (delta <= 127U))));
}
static void hyundai_kona_track_output(uint32_t now, bool host, uint8_t counter) {
hyundai_kona_output_seen = true;
hyundai_kona_host_output = host;
hyundai_kona_output_ts = now;
hyundai_kona_output_counter = counter;
}
static bool hyundai_kona_camera_fwd(const CANPacket_t *msg) {
bool blocked = false;
if (hyundai_kona_idle_handoff && (msg->bus == 2U) && (msg->addr == 0x12AU)) {
const uint32_t now = microsecond_timer_get();
const bool valid = hyundai_kona_lfa_valid(msg);
if (valid) {
const uint8_t delta = (uint8_t)(msg->data[2] - hyundai_kona_camera_counter);
if (!hyundai_kona_camera_seen ||
(safety_get_ts_elapsed(now, hyundai_kona_camera_ts) > 50000U) ||
((delta > 0U) && (delta <= 127U))) {
hyundai_kona_camera_seen = true;
hyundai_kona_camera_counter = msg->data[2];
hyundai_kona_camera_ts = now;
}
}
blocked = !valid || safety_rx_checks_invalid || !aol_rx_healthy() || hyundai_kona_host_steering() ||
(msg->data[2] != hyundai_kona_camera_counter) ||
!hyundai_kona_output_ready(now, false, msg->data[2]);
if (!blocked) {
hyundai_kona_track_output(now, false, msg->data[2]);
}
}
return blocked;
}
#endif
static bool hyundai_canfd_tx_hook_checked(const CANPacket_t *msg) {
bool tx = false;
const bool ordinary_angle_frame = hyundai_ordinary_angle_stock && ((msg->addr == 0x110U) || (msg->addr == 0x362U));
bool ordinary_angle_valid = true;
@@ -1288,9 +1348,32 @@ static bool hyundai_canfd_tx_hook(const CANPacket_t *msg) {
if (hyundai_angle_aol_enabled && independent_command && !tx) {
hyundai_ordinary_angle_release();
}
#ifdef ALLOW_DEBUG
if (hyundai_kona_idle_handoff && (msg->addr == 0x12AU) && tx && !relay_malfunction) {
hyundai_kona_track_output(microsecond_timer_get(), true, msg->data[2]);
}
#endif
return tx;
}
static bool hyundai_canfd_tx_hook(const CANPacket_t *msg) {
#ifdef ALLOW_DEBUG
bool allowed = true;
if (hyundai_kona_idle_handoff && (msg->addr == 0x12AU)) {
const uint32_t now = microsecond_timer_get();
allowed = !safety_rx_checks_invalid && aol_rx_healthy() && hyundai_kona_host_steering() &&
hyundai_kona_lfa_valid(msg) && hyundai_kona_camera_seen &&
(safety_get_ts_elapsed(now, hyundai_kona_camera_ts) <= 50000U) &&
(msg->data[2] == hyundai_kona_camera_counter) && hyundai_kona_output_ready(now, true, msg->data[2]);
}
#endif
return
#ifdef ALLOW_DEBUG
allowed &&
#endif
hyundai_canfd_tx_hook_checked(msg);
}
static void hyundai_canfd_reset_ioniq6_state(void) {
hyundai_canfd_ioniq6_long = false;
aol_ioniq6_long = false;
@@ -2238,29 +2321,50 @@ static safety_config hyundai_canfd_init_validated(uint16_t supplied_param) {
return ret;
}
static safety_config hyundai_canfd_init(uint16_t param) {
static safety_config hyundai_canfd_init(uint16_t raw_param) {
hyundai_daw_init(true, false);
hyundai_canfd_reset_ioniq6_state();
hyundai_ordinary_angle_reset();
#ifdef ALLOW_DEBUG
hyundai_kona_idle_handoff = (raw_param == 0x1C0CU) && (alternative_experience == 32);
hyundai_kona_camera_seen = false;
hyundai_kona_output_seen = false;
const bool kona_profile_valid = (raw_param != 0x1C0CU) || hyundai_kona_idle_handoff;
const uint16_t param = hyundai_kona_idle_handoff ? 0x0C0CU : raw_param;
const bool valid = !GET_FLAG(param, 32768U) || (param == 0x8015U) || (param == 0x8095U) ||
(param == 0x8815U) || (param == 0x8895U) ||
hyundai_canfd_gv60_long_param(param);
#else
const bool kona_profile_valid = raw_param != 0x1C0CU;
const uint16_t param = raw_param;
const bool valid = !GET_FLAG(param, 32768U);
#endif
safety_config ret = {0};
safety_config ret = {.disable_forwarding = !kona_profile_valid};
const bool marker_valid = GET_FLAG(param, 16384U) || !GET_FLAG(param, 2048U) ||
hyundai_canfd_stock_torque_aol_param(param) ||
#ifdef ALLOW_DEBUG
(hyundai_canfd_torque_long_aol_param(param) && ((unsigned int)alternative_experience == 32U)) ||
#endif
(param == 0x8815U) || (param == 0x8895U);
if (valid && marker_valid) {
if (kona_profile_valid && valid && marker_valid) {
ret = hyundai_canfd_init_validated(param);
const bool daw_profile = (param == 0x0011U) || (param == 0x0091U) || (param == 0x0811U) || (param == 0x0891U) ||
(param == 0x8015U) || (param == 0x8095U) || (param == 0x8815U) || (param == 0x8895U);
ret = hyundai_daw_configure(ret, true, daw_profile);
#ifdef ALLOW_DEBUG
if (hyundai_kona_idle_handoff) {
static CanMsg kona_tx[64];
if (hyundai_canfd_angle_aol_capacity(&ret)) {
for (int i = 0; i < ret.tx_msgs_len; i++) {
kona_tx[i] = ret.tx_msgs[i];
if (kona_tx[i].addr == 0x12A) {
kona_tx[i].disable_static_blocking = true;
}
}
ret.tx_msgs = kona_tx;
}
}
#endif
}
return ret;
}
@@ -2271,6 +2375,9 @@ const safety_hooks hyundai_canfd_hooks = {
.optional_rx = hyundai_canfd_optional_rx_hook,
.tx = hyundai_canfd_tx_hook,
.fwd = hyundai_canfd_fwd_hook,
#ifdef ALLOW_DEBUG
.fwd_packet = hyundai_kona_camera_fwd,
#endif
.get_counter = hyundai_canfd_get_counter,
.get_checksum = hyundai_canfd_get_checksum,
.compute_checksum = hyundai_common_canfd_compute_checksum,
@@ -25,7 +25,7 @@ static inline bool hyundai_canfd_torque_long_aol_param(uint16_t param) {
((base & 4U) != 0U) && ((fuel == 0U) || (fuel == 2U)) &&
((topology == 0U) || (topology == 8U) || (topology == 16U) ||
(topology == 144U) || (topology == 32U) || (topology == 40U));
return (param == 0x0C0CU) || (param == 0x0C0EU) || (param == 0x0C2CU) || (param == 0x0C2EU) ||
return (param == 0x1C0CU) || (param == 0x0C0CU) || (param == 0x0C0EU) || (param == 0x0C2CU) || (param == 0x0C2EU) ||
(param == 0x28B4U) || sportage || (param == 0x080DU) || (param == 0x0815U) || (param == 0x0895U) || (param == 0x2815U) || (param == 0x2895U);
}
#endif
+22 -9
View File
@@ -177,8 +177,11 @@ static void subaru_rx_hook(const CANPacket_t *msg) {
subaru_avh_rx(msg);
}
static bool subaru_early_global_torque = false;
static bool subaru_tx_hook(const CANPacket_t *msg) {
const TorqueSteeringLimits SUBARU_STEERING_LIMITS = SUBARU_STEERING_LIMITS_GENERATOR(2047, 50, 70);
const TorqueSteeringLimits SUBARU_EARLY_GLOBAL_STEERING_LIMITS = SUBARU_STEERING_LIMITS_GENERATOR(3071, 50, 70);
const TorqueSteeringLimits SUBARU_GEN2_STEERING_LIMITS = SUBARU_STEERING_LIMITS_GENERATOR(1000, 40, 40);
const AngleSteeringLimits SUBARU_ANGLE_STEERING_LIMITS = {
.max_angle = (subaru_forester_angle ? 650 : SUBARU_JACOBW_MAX_ANGLE) * 100,
@@ -236,7 +239,8 @@ static bool subaru_tx_hook(const CANPacket_t *msg) {
bool steer_req = (msg->data[3] >> 5) & 1U;
const TorqueSteeringLimits limits = subaru_gen2 ? SUBARU_GEN2_STEERING_LIMITS : SUBARU_STEERING_LIMITS;
const TorqueSteeringLimits limits = subaru_early_global_torque ? SUBARU_EARLY_GLOBAL_STEERING_LIMITS :
(subaru_gen2 ? SUBARU_GEN2_STEERING_LIMITS : SUBARU_STEERING_LIMITS);
violation |= steer_torque_cmd_checks(desired_torque, steer_req, limits);
}
if (msg->addr == MSG_SUBARU_ES_LKAS_ANGLE) {
@@ -287,20 +291,24 @@ static bool subaru_tx_hook(const CANPacket_t *msg) {
}
static safety_config subaru_init(uint16_t raw_param) {
uint16_t param = raw_param;
const bool early_global_bit = GET_FLAG(raw_param, 8192U);
subaru_early_global_torque = ((raw_param == 8192U) || (raw_param == 8200U)) &&
(((unsigned int)alternative_experience == 0U) || ((unsigned int)alternative_experience == 32U));
uint16_t param = subaru_early_global_torque ? (raw_param & ~8192U) : raw_param;
const bool impreza_main = (param == 4096U) || (param == 4104U) || (param == 4608U) || (param == 4616U);
if (impreza_main) {
param &= ~4096U;
}
#ifdef ALLOW_DEBUG
const bool avh = ((param == 1169U) || (param == 1425U)) &&
const bool avh = ((param == 1169U) || (param == 1425U) || (param == 1041U) || (param == 3089U)) &&
(((unsigned int)alternative_experience == 0U) || ((unsigned int)alternative_experience == 32U));
#else
const bool avh = false;
#endif
const bool stop_start = ((param == 401U) || (param == 465U) || (avh && (param == 1425U))) &&
(((unsigned int)alternative_experience == 0U) || ((unsigned int)alternative_experience == 32U));
const uint16_t base_param = stop_start ? ((param == 465U) ? 209U : 145U) : (avh ? 145U : param);
const uint16_t base_param = stop_start ? ((param == 465U) ? 209U : 145U) : (avh ? (param & ~1024U) : param);
const bool sibling_hud = (base_param == 2065U);
static const CanMsg SUBARU_TX_MSGS[] = {
SUBARU_BASE_TX_MSGS(SUBARU_MAIN_BUS, MSG_SUBARU_ES_LKAS)
SUBARU_COMMON_TX_MSGS(SUBARU_MAIN_BUS)
@@ -354,6 +362,10 @@ static safety_config subaru_init(uint16_t raw_param) {
{0x390U, SUBARU_ALT_BUS, 8, .check_relay = false},
};
static const CanMsg SUBARU_SIBLING_AVH_TX_MSGS[] = {
SUBARU_GEN2_ANGLE_TX_MSGS(SUBARU_MAIN_BUS)
{0x6BBU, SUBARU_ALT_BUS, 8, .check_relay = false},
};
static const CanMsg SUBARU_AVH_TX_MSGS[] = {
SUBARU_GEN2_ANGLE_TX_MSGS(SUBARU_MAIN_BUS)
{MSG_SUBARU_ES_LKAS_Alert, SUBARU_MAIN_BUS, 8, .check_relay = true},
@@ -394,7 +406,7 @@ static safety_config subaru_init(uint16_t raw_param) {
subaru_fixed_angle_limits = GET_FLAG(param, SUBARU_PARAM_FIXED_ANGLE);
subaru_angle_invalid = (subaru_lkas_angle && (base_param != (SUBARU_PARAM_GEN2 | SUBARU_PARAM_LKAS_ANGLE)) &&
(base_param != (SUBARU_PARAM_GEN2 | SUBARU_PARAM_LKAS_ANGLE | SUBARU_PARAM_FIXED_ANGLE)) &&
(base_param != (SUBARU_PARAM_GEN2 | SUBARU_PARAM_LKAS_ANGLE | SUBARU_PARAM_FIXED_ANGLE | SUBARU_PARAM_ANGLE_MAIN_BUS)) && !ascent_alert && !subaru_forester_angle && !subaru_d_platform) ||
(base_param != (SUBARU_PARAM_GEN2 | SUBARU_PARAM_LKAS_ANGLE | SUBARU_PARAM_FIXED_ANGLE | SUBARU_PARAM_ANGLE_MAIN_BUS)) && !ascent_alert && !sibling_hud && !subaru_forester_angle && !subaru_d_platform) ||
((subaru_fixed_angle_limits || subaru_angle_main_bus) && !subaru_lkas_angle);
// TODO: re-enable once more work is done on the limits
@@ -412,8 +424,8 @@ static safety_config subaru_init(uint16_t raw_param) {
subaru_aol_legacy_2025 = legacy_2025;
subaru_aol_enabled = ((unsigned int)alternative_experience == 32U) &&
((param == 209U) || (param == 465U) || (param == 16U) || (param == 0U) || (param == 1U) || (param == 17U) || (param == 145U) ||
avh || (param == 177U) || (param == 401U) || (param == 8U) || (param == 520U) || (param == 512U) || (param == 2225U));
subaru_aol_main_arm = subaru_aol_enabled && ((param == 17U) || impreza_main || subaru_d_platform || legacy_2025);
avh || sibling_hud || (param == 177U) || (param == 401U) || (param == 8U) || (param == 520U) || (param == 512U) || (param == 2225U));
subaru_aol_main_arm = subaru_aol_enabled && ((base_param == 17U) || sibling_hud || impreza_main || subaru_d_platform || legacy_2025 || subaru_early_global_torque);
if (subaru_aol_enabled) {
static const AolSafetyPolicy policy = {
.reset = subaru_aol_reset,
@@ -447,10 +459,11 @@ static safety_config subaru_init(uint16_t raw_param) {
ret = subaru_d_platform ? (stop_start ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_OUTBACK_STOP_START_TX_MSGS) :
BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_ASCENT_ANGLE_TX_MSGS_LIST)) :
subaru_forester_angle ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_FORESTER_ANGLE_TX_MSGS) :
avh && (base_param == 17U) ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_SIBLING_AVH_TX_MSGS) :
avh ? (stop_start ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_AVH_STOP_START_TX_MSGS) :
BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_AVH_TX_MSGS)) :
stop_start ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_STOP_START_TX_MSGS) :
ascent_alert ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_ASCENT_ALERT_TX_MSGS) :
(ascent_alert || sibling_hud) ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_ASCENT_ALERT_TX_MSGS) :
legacy_2025 ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_LEGACY_ANGLE_TX_MSGS) :
subaru_angle_main_bus ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_ASCENT_ANGLE_TX_MSGS_LIST) :
BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_GEN2_ANGLE_TX_MSGS_LIST);
@@ -486,7 +499,7 @@ static safety_config subaru_init(uint16_t raw_param) {
}
ret.rx_checks_len = rx_count;
if ((((unsigned int)alternative_experience == 32U) && !subaru_aol_enabled) ||
(impreza_main && ((unsigned int)alternative_experience != 32U))) {
(impreza_main && ((unsigned int)alternative_experience != 32U)) || (early_global_bit && !subaru_early_global_torque) || (((param == 1041U) || (param == 3089U)) && !avh)) {
ret.tx_msgs = NULL;
ret.tx_msgs_len = 0;
}
+16 -2
View File
@@ -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;
}
+1 -1
View File
@@ -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;
@@ -20,6 +20,7 @@ class TestGmSdgmStock(unittest.TestCase):
return libsafety_py.make_CANPacket(msg[0], msg[2], msg[1])
def mode(self, cp):
self.safety.set_alternative_experience(0)
self.assertEqual(self.safety.set_safety_hooks(CarParams.SafetyModel.gm, cp.safetyConfigs[0].safetyParam), 0)
self.safety.init_tests()
self.safety.set_timer(1_000_000)
@@ -0,0 +1,78 @@
import unittest
from opendbc.car import structs
from opendbc.safety.tests.libsafety import libsafety_py
class TestHyundaiKonaCcncHandoff(unittest.TestCase):
def setUp(self):
self.safety = libsafety_py.libsafety
self.addCleanup(self.safety.set_alternative_experience, 0)
self.addCleanup(self.safety.set_relay_malfunction, False)
def mode(self, word, alternative=32):
self.safety.init_tests()
self.safety.set_alternative_experience(alternative)
self.assertEqual(self.safety.set_safety_hooks(structs.CarParams.SafetyModel.hyundaiCanfd, word), 0)
def packet(self, bus, body):
packet = libsafety_py.make_CANPacket(0x12A, bus, bytes.fromhex(body))
packet[0].fd = 1
return packet
def test_handoff_is_debug_only_and_requires_exact_alternative_experience(self):
debug = self.safety.set_safety_hooks(structs.CarParams.SafetyModel.allOutput, 0) == 0
camera = self.packet(2, 'a6770a1880001800000a000000900000')
for experience in ((0,) if debug else (0, 32)):
self.mode(0x1C0C, experience)
self.assertEqual(self.safety.safety_fwd_packet_hook(camera), -1)
self.assertFalse(self.safety.safety_tx_hook(self.packet(0, 'a6770a1880001800000a000000900000')))
self.assertEqual(self.safety.safety_fwd_hook(2, 0x123), -1)
def test_handoff_requires_current_camera_and_one_output_owner(self):
if self.safety.set_safety_hooks(structs.CarParams.SafetyModel.allOutput, 0) != 0:
self.skipTest('Kona factory handoff is DEBUG only')
camera = self.packet(2, 'a6770a1880001800000a000000900000')
self.mode(0x0C0C)
self.assertEqual(self.safety.safety_fwd_packet_hook(camera), -1)
self.mode(0x1C0C)
self.safety.set_timer(1_000_000)
self.assertEqual(self.safety.safety_fwd_packet_hook(camera), -1)
for status in self.safety.rx_status:
status.msg_seen = True
status.valid_checksum = True
status.valid_quality_flag = True
status.last_timestamp = 1_000_000
self.assertEqual(self.safety.safety_fwd_packet_hook(camera), 0)
self.assertEqual(self.safety.safety_fwd_packet_hook(camera), -1)
corrupt = self.packet(2, 'a6770a1881001800000a000000900000')
self.assertEqual(self.safety.safety_fwd_packet_hook(corrupt), -1)
self.assertFalse(self.safety.safety_tx_hook(self.packet(0, 'a6770a1880001800000a000000900000')))
warning = self.packet(2, '784d1400000108f0000a000000640000')
self.assertEqual(self.safety.safety_fwd_packet_hook(warning), 0)
self.safety.set_controls_allowed(True)
self.safety.set_aol_test_heartbeat(True)
self.safety.aol_set_host_request(3)
following = self.packet(2, '110d1600000108f0000a000000640000')
host = self.packet(0, 'a009150280001800000a000000900000')
self.safety.set_timer(1_009_999)
self.assertFalse(self.safety.safety_tx_hook(host)) # Require the matching camera counter first.
camera_match = self.packet(2, '5ce51500000108f0000a000000640000')
self.assertEqual(self.safety.safety_fwd_packet_hook(camera_match), -1)
self.assertFalse(self.safety.safety_tx_hook(host))
self.safety.set_timer(1_010_000)
self.assertTrue(self.safety.safety_tx_hook(host))
self.assertFalse(self.safety.safety_tx_hook(host))
self.safety.set_controls_allowed(False)
self.safety.aol_set_host_request(0)
self.safety.set_timer(1_019_999)
self.assertEqual(self.safety.safety_fwd_packet_hook(following), -1)
self.safety.set_timer(1_020_000)
self.assertEqual(self.safety.safety_fwd_packet_hook(following), 0)
self.assertEqual(self.safety.safety_fwd_packet_hook(following), -1)
self.safety.set_relay_malfunction(True)
self.assertEqual(self.safety.safety_fwd_packet_hook(following), -1)
self.assertFalse(self.safety.safety_tx_hook(host))
@@ -18,7 +18,7 @@ class TestSubaruAscentAlert(unittest.TestCase):
return libsafety_py.make_CANPacket(0x3C4, bus, data)
def test_exact_parameter_bus_checksum_length_and_forwarding(self):
for flags in (0, 1, 0x11, 0xB1, 0x800, 0x811, 0x891, 0x8B3, 0x9B1):
for flags in (0, 1, 0x11, 0xB1, 0x800, 0x810, 0x815, 0x891, 0x8B3, 0x9B1):
self.mode(flags)
self.assertFalse(self.safety.safety_tx_hook(self.packet()), hex(flags))
self.assertEqual(self.safety.safety_fwd_hook(2, 0x3C4), 0)
@@ -28,7 +28,7 @@ class TestSubaruAscentAlert(unittest.TestCase):
self.mode(flags)
self.assertFalse(self.safety.safety_tx_hook(self.packet()), hex(flags))
self.assertEqual(self.safety.safety_fwd_hook(2, 0x3C4), 0)
for flags in (0x8B1, 0x91, 401) + ((1169, 1425) if debug else ()):
for flags in (0x811, 0x8B1, 0x91, 401) + ((1169, 1425) if debug else ()):
self.mode(flags)
self.assertTrue(self.safety.safety_tx_hook(self.packet()), hex(flags))
self.assertEqual(self.safety.safety_fwd_hook(2, 0x3C4), -1)
@@ -139,7 +139,8 @@ class TestSubaruGen2AnglePair(unittest.TestCase):
self.arm(cp, frames)
_, steer, _ = self.controller(car, cp, frames)
invalid_option = 0x200 if car == CAR.SUBARU_LEGACY_2025 else 0x100
for flags in (SubaruSafetyFlags.LONG, 0x800, invalid_option):
invalid_alert = 0x4000 if car in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025) else 0x800
for flags in (SubaruSafetyFlags.LONG, invalid_alert, invalid_option):
with self.subTest(car=car, flags=flags):
self.mode(cp, extra_flags=flags)
for frame in required:
@@ -5,7 +5,7 @@ from opendbc.safety.tests.libsafety import libsafety_py
from opendbc.safety.tests import test_subaru_stock_aol as stock_module
@pytest.fixture(params=(17, 145, 209, 401, 465, 4096, 4104, 4608, 4616))
@pytest.fixture(params=(17, 145, 209, 401, 465, 4096, 4104, 4608, 4616, 8192, 8200))
def owner(request):
item = stock_module.TestSubaruStockAol(methodName='runTest')
item.setUp()
@@ -142,3 +142,40 @@ def test_legacy_2025_cvt_manual_gears():
assert item.feed(gear=137) == 0
finally:
item.tearDown()
@pytest.mark.parametrize('param, experience, max_torque', [(0, 0, 2047), (8192, 0, 3071), (8192, 32, 3071), (8200, 0, 3071), (8200, 32, 3071)])
def test_early_crosstrek_steering_limit(param, experience, max_torque):
item = stock_module.TestSubaruStockAol(methodName='runTest')
item.setUp()
try:
item.configure(param, experience)
neutral(item)
assert item.feed(cruise=experience == 0) == int(experience == 32)
assert item.safety.get_controls_allowed() == (experience == 0)
def tx(torque):
item.safety.set_desired_torque_last(torque)
item.safety.set_rt_torque_last(torque)
return item.safety.safety_tx_hook(item.frame('ES_LKAS', {'LKAS_Output': torque, 'LKAS_Request': 1}))
for direction in (-1, 1):
assert tx(direction * max_torque)
assert not tx(direction * (max_torque + 1))
assert item.feed(main=False) == 0
assert not tx(50)
finally:
item.tearDown()
@pytest.mark.parametrize('param, experience', [(8193, 32), (8194, 0), (8192, 33), (8200, 33), (8201, 32)])
def test_early_crosstrek_rejects_mixed_safety_settings(param, experience):
item = stock_module.TestSubaruStockAol(methodName='runTest')
item.setUp()
try:
item.configure(param, experience)
neutral(item)
assert item.feed() == 0
assert not item.safety.safety_tx_hook(item.frame('ES_LKAS', {}))
finally:
item.tearDown()
@@ -47,7 +47,7 @@ class TestSubaruStockAol(unittest.TestCase):
('ES_Status', {'Cruise_Activated': int(cruise)}, 2 if self.param == 16 else 1),
('ES_DashStatus', {'Cruise_On': int(main)}, 2),
]
if not omit_distance and self.param in (17, 145, 209, 401, 465, 1169, 1425, 4096, 4104, 4608, 4616):
if not omit_distance and self.param in (17, 145, 209, 401, 465, 1169, 1425, 4096, 4104, 4608, 4616, 8192, 8200):
frames.append(('ES_Distance', {'Cruise_Fault': int(acc_fault)},
1 if self.param in (17, 145, 209, 401, 465, 1169, 1425) else 2))
if not omit_gear:
@@ -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()
+17
View File
@@ -223,6 +223,7 @@ struct StarPilotCarState @0xf35cc4560bbf6ec2 {
steeringLimitInfo @39 :StarPilotCarControl.SteeringLimitInfo;
toyotaCruise @38 :ToyotaCruise;
gmRegenGear @40 :Bool;
acceleratorPedal @41 :Float32; # driver pedal travel, 0..1; 0 when the platform doesn't publish it
struct ToyotaCruise {
version @0 :UInt16;
@@ -480,6 +481,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 +528,7 @@ struct SlcAction @0x9ccdc8676701b412 {
forceCoastToggle @10;
pulseGlideToggle @11;
disengageRequest @12;
cruiseStep @13;
}
}
+344 -97
View File
@@ -6385,7 +6385,7 @@ const ::capnp::_::RawSchema s_9a4b2a0189fe1224 = {
};
#endif // !CAPNP_LITE
CAPNP_DEFINE_ENUM(Choice_9a4b2a0189fe1224, 9a4b2a0189fe1224);
static const ::capnp::_::AlignedData<176> b_9ccdc8676701b412 = {
static const ::capnp::_::AlignedData<180> b_9ccdc8676701b412 = {
{ 0, 0, 0, 0, 5, 0, 6, 0,
18, 180, 1, 103, 103, 200, 205, 156,
13, 0, 0, 0, 1, 0, 5, 0,
@@ -6393,24 +6393,28 @@ static const ::capnp::_::AlignedData<176> b_9ccdc8676701b412 = {
4, 0, 7, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
21, 0, 0, 0, 186, 0, 0, 0,
29, 0, 0, 0, 55, 0, 0, 0,
29, 0, 0, 0, 71, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
77, 0, 0, 0, 255, 1, 0, 0,
93, 0, 0, 0, 255, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
99, 117, 115, 116, 111, 109, 46, 99,
97, 112, 110, 112, 58, 83, 108, 99,
65, 99, 116, 105, 111, 110, 0, 0,
12, 0, 0, 0, 1, 0, 1, 0,
16, 0, 0, 0, 1, 0, 1, 0,
105, 30, 140, 170, 192, 231, 57, 181,
17, 0, 0, 0, 186, 0, 0, 0,
25, 0, 0, 0, 186, 0, 0, 0,
172, 250, 175, 77, 32, 114, 213, 254,
29, 0, 0, 0, 106, 0, 0, 0,
169, 174, 255, 224, 77, 245, 161, 139,
21, 0, 0, 0, 194, 0, 0, 0,
29, 0, 0, 0, 194, 0, 0, 0,
149, 27, 24, 102, 230, 217, 203, 184,
25, 0, 0, 0, 42, 0, 0, 0,
33, 0, 0, 0, 42, 0, 0, 0,
67, 111, 110, 116, 114, 111, 108, 108,
101, 114, 67, 114, 117, 105, 115, 101,
65, 99, 116, 105, 111, 110, 0, 0,
84, 101, 115, 108, 97, 71, 101, 115,
116, 117, 114, 101, 0, 0, 0, 0,
67, 111, 110, 100, 105, 116, 105, 111,
110, 97, 108, 77, 97, 110, 117, 97,
108, 65, 99, 116, 105, 111, 110, 0,
@@ -6573,21 +6577,21 @@ static const ::capnp::_::RawSchema* const d_9ccdc8676701b412[] = {
static const uint16_t m_9ccdc8676701b412[] = {5, 6, 7, 2, 4, 3, 1, 0, 8};
static const uint16_t i_9ccdc8676701b412[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
const ::capnp::_::RawSchema s_9ccdc8676701b412 = {
0x9ccdc8676701b412, b_9ccdc8676701b412.words, 176, d_9ccdc8676701b412, m_9ccdc8676701b412,
0x9ccdc8676701b412, b_9ccdc8676701b412.words, 180, d_9ccdc8676701b412, m_9ccdc8676701b412,
3, 9, i_9ccdc8676701b412, nullptr, nullptr, { &s_9ccdc8676701b412, nullptr, nullptr, 0, 0, nullptr }, false
};
#endif // !CAPNP_LITE
static const ::capnp::_::AlignedData<234> b_b539e7c0aa8c1e69 = {
static const ::capnp::_::AlignedData<267> b_b539e7c0aa8c1e69 = {
{ 0, 0, 0, 0, 5, 0, 6, 0,
105, 30, 140, 170, 192, 231, 57, 181,
23, 0, 0, 0, 1, 0, 7, 0,
18, 180, 1, 103, 103, 200, 205, 156,
4, 0, 7, 0, 0, 0, 0, 0,
5, 0, 7, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
21, 0, 0, 0, 114, 1, 0, 0,
41, 0, 0, 0, 7, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
37, 0, 0, 0, 223, 2, 0, 0,
37, 0, 0, 0, 79, 3, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
99, 117, 115, 116, 111, 109, 46, 99,
@@ -6597,98 +6601,112 @@ static const ::capnp::_::AlignedData<234> b_b539e7c0aa8c1e69 = {
114, 67, 114, 117, 105, 115, 101, 65,
99, 116, 105, 111, 110, 0, 0, 0,
0, 0, 0, 0, 1, 0, 1, 0,
52, 0, 0, 0, 3, 0, 4, 0,
60, 0, 0, 0, 3, 0, 4, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
93, 1, 0, 0, 66, 0, 0, 0,
149, 1, 0, 0, 66, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
88, 1, 0, 0, 3, 0, 1, 0,
100, 1, 0, 0, 2, 0, 1, 0,
144, 1, 0, 0, 3, 0, 1, 0,
156, 1, 0, 0, 2, 0, 1, 0,
1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
97, 1, 0, 0, 82, 0, 0, 0,
153, 1, 0, 0, 82, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
96, 1, 0, 0, 3, 0, 1, 0,
108, 1, 0, 0, 2, 0, 1, 0,
152, 1, 0, 0, 3, 0, 1, 0,
164, 1, 0, 0, 2, 0, 1, 0,
2, 0, 0, 0, 1, 0, 0, 0,
0, 0, 1, 0, 2, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
105, 1, 0, 0, 74, 0, 0, 0,
161, 1, 0, 0, 74, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
104, 1, 0, 0, 3, 0, 1, 0,
116, 1, 0, 0, 2, 0, 1, 0,
160, 1, 0, 0, 3, 0, 1, 0,
172, 1, 0, 0, 2, 0, 1, 0,
3, 0, 0, 0, 2, 0, 0, 0,
0, 0, 1, 0, 3, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
113, 1, 0, 0, 138, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
116, 1, 0, 0, 3, 0, 1, 0,
128, 1, 0, 0, 2, 0, 1, 0,
4, 0, 0, 0, 3, 0, 0, 0,
0, 0, 1, 0, 4, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
125, 1, 0, 0, 154, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
128, 1, 0, 0, 3, 0, 1, 0,
140, 1, 0, 0, 2, 0, 1, 0,
5, 0, 0, 0, 4, 0, 0, 0,
0, 0, 1, 0, 5, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
137, 1, 0, 0, 154, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
140, 1, 0, 0, 3, 0, 1, 0,
152, 1, 0, 0, 2, 0, 1, 0,
6, 0, 0, 0, 1, 0, 0, 0,
0, 0, 1, 0, 6, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
149, 1, 0, 0, 122, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
148, 1, 0, 0, 3, 0, 1, 0,
160, 1, 0, 0, 2, 0, 1, 0,
7, 0, 0, 0, 5, 0, 0, 0,
0, 0, 1, 0, 7, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
157, 1, 0, 0, 202, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
164, 1, 0, 0, 3, 0, 1, 0,
176, 1, 0, 0, 2, 0, 1, 0,
8, 0, 0, 0, 2, 0, 0, 0,
0, 0, 1, 0, 8, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
173, 1, 0, 0, 90, 0, 0, 0,
169, 1, 0, 0, 138, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
172, 1, 0, 0, 3, 0, 1, 0,
184, 1, 0, 0, 2, 0, 1, 0,
9, 0, 0, 0, 2, 0, 0, 0,
0, 0, 1, 0, 9, 0, 0, 0,
4, 0, 0, 0, 3, 0, 0, 0,
0, 0, 1, 0, 4, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
181, 1, 0, 0, 82, 0, 0, 0,
181, 1, 0, 0, 154, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
180, 1, 0, 0, 3, 0, 1, 0,
192, 1, 0, 0, 2, 0, 1, 0,
10, 0, 0, 0, 6, 0, 0, 0,
0, 0, 1, 0, 10, 0, 0, 0,
184, 1, 0, 0, 3, 0, 1, 0,
196, 1, 0, 0, 2, 0, 1, 0,
5, 0, 0, 0, 4, 0, 0, 0,
0, 0, 1, 0, 5, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
189, 1, 0, 0, 186, 0, 0, 0,
193, 1, 0, 0, 154, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
192, 1, 0, 0, 3, 0, 1, 0,
204, 1, 0, 0, 2, 0, 1, 0,
11, 0, 0, 0, 3, 0, 0, 0,
0, 0, 1, 0, 11, 0, 0, 0,
196, 1, 0, 0, 3, 0, 1, 0,
208, 1, 0, 0, 2, 0, 1, 0,
6, 0, 0, 0, 1, 0, 0, 0,
0, 0, 1, 0, 6, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
201, 1, 0, 0, 170, 0, 0, 0,
205, 1, 0, 0, 122, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
204, 1, 0, 0, 3, 0, 1, 0,
216, 1, 0, 0, 2, 0, 1, 0,
7, 0, 0, 0, 5, 0, 0, 0,
0, 0, 1, 0, 7, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
213, 1, 0, 0, 202, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
220, 1, 0, 0, 3, 0, 1, 0,
232, 1, 0, 0, 2, 0, 1, 0,
8, 0, 0, 0, 2, 0, 0, 0,
0, 0, 1, 0, 8, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
229, 1, 0, 0, 90, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
228, 1, 0, 0, 3, 0, 1, 0,
240, 1, 0, 0, 2, 0, 1, 0,
9, 0, 0, 0, 2, 0, 0, 0,
0, 0, 1, 0, 9, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
237, 1, 0, 0, 82, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
236, 1, 0, 0, 3, 0, 1, 0,
248, 1, 0, 0, 2, 0, 1, 0,
10, 0, 0, 0, 6, 0, 0, 0,
0, 0, 1, 0, 10, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
245, 1, 0, 0, 186, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
248, 1, 0, 0, 3, 0, 1, 0,
4, 2, 0, 0, 2, 0, 1, 0,
11, 0, 0, 0, 3, 0, 0, 0,
0, 0, 1, 0, 11, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
1, 2, 0, 0, 170, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
4, 2, 0, 0, 3, 0, 1, 0,
16, 2, 0, 0, 2, 0, 1, 0,
12, 0, 0, 0, 1, 0, 0, 0,
0, 0, 1, 0, 12, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
213, 1, 0, 0, 122, 0, 0, 0,
13, 2, 0, 0, 122, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
212, 1, 0, 0, 3, 0, 1, 0,
224, 1, 0, 0, 2, 0, 1, 0,
12, 2, 0, 0, 3, 0, 1, 0,
24, 2, 0, 0, 2, 0, 1, 0,
13, 0, 0, 0, 3, 0, 0, 0,
0, 0, 1, 0, 13, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
21, 2, 0, 0, 82, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
20, 2, 0, 0, 3, 0, 1, 0,
32, 2, 0, 0, 2, 0, 1, 0,
14, 0, 0, 0, 4, 0, 0, 0,
0, 0, 1, 0, 14, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
29, 2, 0, 0, 154, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
32, 2, 0, 0, 3, 0, 1, 0,
44, 2, 0, 0, 2, 0, 1, 0,
118, 101, 114, 115, 105, 111, 110, 0,
7, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
@@ -6810,16 +6828,228 @@ static const ::capnp::_::AlignedData<234> b_b539e7c0aa8c1e69 = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
10, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
115, 116, 101, 112, 85, 110, 105, 116,
115, 0, 0, 0, 0, 0, 0, 0,
2, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
2, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
115, 111, 117, 114, 99, 101, 84, 101,
115, 108, 97, 71, 101, 115, 116, 117,
114, 101, 0, 0, 0, 0, 0, 0,
16, 0, 0, 0, 0, 0, 0, 0,
172, 250, 175, 77, 32, 114, 213, 254,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
16, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, }
};
::capnp::word const* const bp_b539e7c0aa8c1e69 = b_b539e7c0aa8c1e69.words;
#if !CAPNP_LITE
static const uint16_t m_b539e7c0aa8c1e69[] = {8, 9, 6, 11, 5, 3, 2, 1, 7, 10, 12, 4, 0};
static const uint16_t i_b539e7c0aa8c1e69[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
static const ::capnp::_::RawSchema* const d_b539e7c0aa8c1e69[] = {
&s_fed572204daffaac,
};
static const uint16_t m_b539e7c0aa8c1e69[] = {8, 9, 6, 11, 5, 3, 2, 1, 7, 10, 14, 13, 12, 4, 0};
static const uint16_t i_b539e7c0aa8c1e69[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
const ::capnp::_::RawSchema s_b539e7c0aa8c1e69 = {
0xb539e7c0aa8c1e69, b_b539e7c0aa8c1e69.words, 234, nullptr, m_b539e7c0aa8c1e69,
0, 13, i_b539e7c0aa8c1e69, nullptr, nullptr, { &s_b539e7c0aa8c1e69, nullptr, nullptr, 0, 0, nullptr }, false
0xb539e7c0aa8c1e69, b_b539e7c0aa8c1e69.words, 267, d_b539e7c0aa8c1e69, m_b539e7c0aa8c1e69,
1, 15, i_b539e7c0aa8c1e69, nullptr, nullptr, { &s_b539e7c0aa8c1e69, nullptr, nullptr, 0, 0, nullptr }, false
};
#endif // !CAPNP_LITE
static const ::capnp::_::AlignedData<179> b_fed572204daffaac = {
{ 0, 0, 0, 0, 5, 0, 6, 0,
172, 250, 175, 77, 32, 114, 213, 254,
23, 0, 0, 0, 1, 0, 4, 0,
18, 180, 1, 103, 103, 200, 205, 156,
4, 0, 7, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
21, 0, 0, 0, 34, 1, 0, 0,
37, 0, 0, 0, 7, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
33, 0, 0, 0, 55, 2, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
99, 117, 115, 116, 111, 109, 46, 99,
97, 112, 110, 112, 58, 83, 108, 99,
65, 99, 116, 105, 111, 110, 46, 84,
101, 115, 108, 97, 71, 101, 115, 116,
117, 114, 101, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0, 1, 0,
40, 0, 0, 0, 3, 0, 4, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
9, 1, 0, 0, 66, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
4, 1, 0, 0, 3, 0, 1, 0,
16, 1, 0, 0, 2, 0, 1, 0,
1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
13, 1, 0, 0, 114, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
12, 1, 0, 0, 3, 0, 1, 0,
24, 1, 0, 0, 2, 0, 1, 0,
2, 0, 0, 0, 1, 0, 0, 0,
0, 0, 1, 0, 2, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
21, 1, 0, 0, 74, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
20, 1, 0, 0, 3, 0, 1, 0,
32, 1, 0, 0, 2, 0, 1, 0,
3, 0, 0, 0, 2, 0, 0, 0,
0, 0, 1, 0, 3, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
29, 1, 0, 0, 146, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
32, 1, 0, 0, 3, 0, 1, 0,
44, 1, 0, 0, 2, 0, 1, 0,
4, 0, 0, 0, 1, 0, 0, 0,
0, 0, 1, 0, 4, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
41, 1, 0, 0, 162, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
44, 1, 0, 0, 3, 0, 1, 0,
56, 1, 0, 0, 2, 0, 1, 0,
5, 0, 0, 0, 1, 0, 0, 0,
0, 0, 1, 0, 5, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
53, 1, 0, 0, 42, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
48, 1, 0, 0, 3, 0, 1, 0,
60, 1, 0, 0, 2, 0, 1, 0,
6, 0, 0, 0, 32, 0, 0, 0,
0, 0, 1, 0, 6, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
57, 1, 0, 0, 42, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
52, 1, 0, 0, 3, 0, 1, 0,
64, 1, 0, 0, 2, 0, 1, 0,
7, 0, 0, 0, 2, 0, 0, 0,
0, 0, 1, 0, 7, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
61, 1, 0, 0, 130, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
60, 1, 0, 0, 3, 0, 1, 0,
72, 1, 0, 0, 2, 0, 1, 0,
8, 0, 0, 0, 3, 0, 0, 0,
0, 0, 1, 0, 8, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
69, 1, 0, 0, 98, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
68, 1, 0, 0, 3, 0, 1, 0,
80, 1, 0, 0, 2, 0, 1, 0,
9, 0, 0, 0, 3, 0, 0, 0,
0, 0, 1, 0, 9, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
77, 1, 0, 0, 154, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
80, 1, 0, 0, 3, 0, 1, 0,
92, 1, 0, 0, 2, 0, 1, 0,
118, 101, 114, 115, 105, 111, 110, 0,
7, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
7, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
119, 111, 114, 107, 101, 114, 83, 101,
115, 115, 105, 111, 110, 0, 0, 0,
12, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
12, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
115, 101, 113, 117, 101, 110, 99, 101,
0, 0, 0, 0, 0, 0, 0, 0,
9, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
9, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
115, 111, 117, 114, 99, 101, 67, 97,
110, 66, 111, 111, 116, 84, 105, 109,
101, 0, 0, 0, 0, 0, 0, 0,
9, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
9, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
115, 111, 117, 114, 99, 101, 67, 97,
110, 70, 114, 97, 109, 101, 73, 110,
100, 101, 120, 0, 0, 0, 0, 0,
7, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
7, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
110, 97, 109, 101, 0, 0, 0, 0,
12, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
12, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
102, 97, 115, 116, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
97, 115, 115, 105, 103, 110, 109, 101,
110, 116, 115, 72, 97, 115, 104, 0,
12, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
12, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
118, 101, 104, 105, 99, 108, 101, 72,
97, 115, 104, 0, 0, 0, 0, 0,
12, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
12, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
100, 114, 105, 118, 101, 83, 116, 97,
114, 116, 77, 111, 110, 111, 84, 105,
109, 101, 0, 0, 0, 0, 0, 0,
9, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
9, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, }
};
::capnp::word const* const bp_fed572204daffaac = b_fed572204daffaac.words;
#if !CAPNP_LITE
static const uint16_t m_fed572204daffaac[] = {7, 9, 6, 5, 2, 3, 4, 8, 0, 1};
static const uint16_t i_fed572204daffaac[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
const ::capnp::_::RawSchema s_fed572204daffaac = {
0xfed572204daffaac, b_fed572204daffaac.words, 179, nullptr, m_fed572204daffaac,
0, 10, i_fed572204daffaac, nullptr, nullptr, { &s_fed572204daffaac, nullptr, nullptr, 0, 0, nullptr }, false
};
#endif // !CAPNP_LITE
static const ::capnp::_::AlignedData<236> b_8ba1f54de0ffaea9 = {
@@ -7072,7 +7302,7 @@ const ::capnp::_::RawSchema s_8ba1f54de0ffaea9 = {
1, 13, i_8ba1f54de0ffaea9, nullptr, nullptr, { &s_8ba1f54de0ffaea9, nullptr, nullptr, 0, 0, nullptr }, false
};
#endif // !CAPNP_LITE
static const ::capnp::_::AlignedData<85> b_b8cbd9e666181b95 = {
static const ::capnp::_::AlignedData<90> b_b8cbd9e666181b95 = {
{ 0, 0, 0, 0, 5, 0, 6, 0,
149, 27, 24, 102, 230, 217, 203, 184,
23, 0, 0, 0, 2, 0, 0, 0,
@@ -7082,7 +7312,7 @@ static const ::capnp::_::AlignedData<85> b_b8cbd9e666181b95 = {
21, 0, 0, 0, 226, 0, 0, 0,
33, 0, 0, 0, 7, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
29, 0, 0, 0, 63, 1, 0, 0,
29, 0, 0, 0, 87, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
99, 117, 115, 116, 111, 109, 46, 99,
@@ -7090,45 +7320,48 @@ static const ::capnp::_::AlignedData<85> b_b8cbd9e666181b95 = {
65, 99, 116, 105, 111, 110, 46, 75,
105, 110, 100, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0, 1, 0,
52, 0, 0, 0, 1, 0, 2, 0,
56, 0, 0, 0, 1, 0, 2, 0,
0, 0, 0, 0, 0, 0, 0, 0,
149, 0, 0, 0, 66, 0, 0, 0,
161, 0, 0, 0, 66, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0,
141, 0, 0, 0, 58, 0, 0, 0,
153, 0, 0, 0, 58, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
2, 0, 0, 0, 0, 0, 0, 0,
133, 0, 0, 0, 58, 0, 0, 0,
145, 0, 0, 0, 58, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
3, 0, 0, 0, 0, 0, 0, 0,
125, 0, 0, 0, 50, 0, 0, 0,
137, 0, 0, 0, 50, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
4, 0, 0, 0, 0, 0, 0, 0,
117, 0, 0, 0, 170, 0, 0, 0,
129, 0, 0, 0, 170, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
5, 0, 0, 0, 0, 0, 0, 0,
117, 0, 0, 0, 122, 0, 0, 0,
129, 0, 0, 0, 122, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
6, 0, 0, 0, 0, 0, 0, 0,
113, 0, 0, 0, 122, 0, 0, 0,
125, 0, 0, 0, 122, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
7, 0, 0, 0, 0, 0, 0, 0,
109, 0, 0, 0, 146, 0, 0, 0,
121, 0, 0, 0, 146, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
8, 0, 0, 0, 0, 0, 0, 0,
109, 0, 0, 0, 170, 0, 0, 0,
121, 0, 0, 0, 170, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
9, 0, 0, 0, 0, 0, 0, 0,
109, 0, 0, 0, 82, 0, 0, 0,
121, 0, 0, 0, 82, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
10, 0, 0, 0, 0, 0, 0, 0,
105, 0, 0, 0, 138, 0, 0, 0,
117, 0, 0, 0, 138, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
11, 0, 0, 0, 0, 0, 0, 0,
105, 0, 0, 0, 138, 0, 0, 0,
117, 0, 0, 0, 138, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
12, 0, 0, 0, 0, 0, 0, 0,
105, 0, 0, 0, 138, 0, 0, 0,
117, 0, 0, 0, 138, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
13, 0, 0, 0, 0, 0, 0, 0,
117, 0, 0, 0, 90, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
117, 110, 107, 110, 111, 119, 110, 0,
97, 99, 99, 101, 112, 116, 0, 0,
@@ -7157,14 +7390,16 @@ static const ::capnp::_::AlignedData<85> b_b8cbd9e666181b95 = {
0, 0, 0, 0, 0, 0, 0, 0,
100, 105, 115, 101, 110, 103, 97, 103,
101, 82, 101, 113, 117, 101, 115, 116,
0, 0, 0, 0, 0, 0, 0, 0, }
0, 0, 0, 0, 0, 0, 0, 0,
99, 114, 117, 105, 115, 101, 83, 116,
101, 112, 0, 0, 0, 0, 0, 0, }
};
::capnp::word const* const bp_b8cbd9e666181b95 = b_b8cbd9e666181b95.words;
#if !CAPNP_LITE
static const uint16_t m_b8cbd9e666181b95[] = {1, 3, 4, 6, 5, 9, 12, 10, 11, 2, 8, 7, 0};
static const uint16_t m_b8cbd9e666181b95[] = {1, 3, 4, 6, 5, 9, 13, 12, 10, 11, 2, 8, 7, 0};
const ::capnp::_::RawSchema s_b8cbd9e666181b95 = {
0xb8cbd9e666181b95, b_b8cbd9e666181b95.words, 85, nullptr, m_b8cbd9e666181b95,
0, 13, nullptr, nullptr, nullptr, { &s_b8cbd9e666181b95, nullptr, nullptr, 0, 0, nullptr }, false
0xb8cbd9e666181b95, b_b8cbd9e666181b95.words, 90, nullptr, m_b8cbd9e666181b95,
0, 14, nullptr, nullptr, nullptr, { &s_b8cbd9e666181b95, nullptr, nullptr, 0, 0, nullptr }, false
};
#endif // !CAPNP_LITE
CAPNP_DEFINE_ENUM(Kind_b8cbd9e666181b95, b8cbd9e666181b95);
@@ -23035,6 +23270,18 @@ constexpr ::capnp::_::RawSchema const* SlcAction::ControllerCruiseAction::_capnp
#endif // !CAPNP_NEED_REDUNDANT_CONSTEXPR_DECL
#endif // !CAPNP_LITE
// SlcAction::TeslaGesture
#if CAPNP_NEED_REDUNDANT_CONSTEXPR_DECL
constexpr uint16_t SlcAction::TeslaGesture::_capnpPrivate::dataWordSize;
constexpr uint16_t SlcAction::TeslaGesture::_capnpPrivate::pointerCount;
#endif // !CAPNP_NEED_REDUNDANT_CONSTEXPR_DECL
#if !CAPNP_LITE
#if CAPNP_NEED_REDUNDANT_CONSTEXPR_DECL
constexpr ::capnp::Kind SlcAction::TeslaGesture::_capnpPrivate::kind;
constexpr ::capnp::_::RawSchema const* SlcAction::TeslaGesture::_capnpPrivate::schema;
#endif // !CAPNP_NEED_REDUNDANT_CONSTEXPR_DECL
#endif // !CAPNP_LITE
// SlcAction::ConditionalManualAction
#if CAPNP_NEED_REDUNDANT_CONSTEXPR_DECL
constexpr uint16_t SlcAction::ConditionalManualAction::_capnpPrivate::dataWordSize;
+449 -1
View File
@@ -95,6 +95,7 @@ enum class Choice_9a4b2a0189fe1224: uint16_t {
CAPNP_DECLARE_ENUM(Choice, 9a4b2a0189fe1224);
CAPNP_DECLARE_SCHEMA(9ccdc8676701b412);
CAPNP_DECLARE_SCHEMA(b539e7c0aa8c1e69);
CAPNP_DECLARE_SCHEMA(fed572204daffaac);
CAPNP_DECLARE_SCHEMA(8ba1f54de0ffaea9);
CAPNP_DECLARE_SCHEMA(b8cbd9e666181b95);
enum class Kind_b8cbd9e666181b95: uint16_t {
@@ -111,6 +112,7 @@ enum class Kind_b8cbd9e666181b95: uint16_t {
FORCE_COAST_TOGGLE,
PULSE_GLIDE_TOGGLE,
DISENGAGE_REQUEST,
CRUISE_STEP,
};
CAPNP_DECLARE_ENUM(Kind, b8cbd9e666181b95);
CAPNP_DECLARE_SCHEMA(cd96dafb67a082d0);
@@ -841,6 +843,7 @@ struct SlcAction {
class Builder;
class Pipeline;
struct ControllerCruiseAction;
struct TeslaGesture;
struct ConditionalManualAction;
typedef ::capnp::schemas::Kind_b8cbd9e666181b95 Kind;
@@ -861,7 +864,22 @@ struct SlcAction::ControllerCruiseAction {
class Pipeline;
struct _capnpPrivate {
CAPNP_DECLARE_STRUCT_HEADER(b539e7c0aa8c1e69, 7, 4)
CAPNP_DECLARE_STRUCT_HEADER(b539e7c0aa8c1e69, 7, 5)
#if !CAPNP_LITE
static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; }
#endif // !CAPNP_LITE
};
};
struct SlcAction::TeslaGesture {
TeslaGesture() = delete;
class Reader;
class Builder;
class Pipeline;
struct _capnpPrivate {
CAPNP_DECLARE_STRUCT_HEADER(fed572204daffaac, 4, 4)
#if !CAPNP_LITE
static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; }
#endif // !CAPNP_LITE
@@ -5885,6 +5903,11 @@ public:
inline float getTargetSpeedMps() const;
inline ::int8_t getStepUnits() const;
inline bool hasSourceTeslaGesture() const;
inline ::cereal::SlcAction::TeslaGesture::Reader getSourceTeslaGesture() const;
private:
::capnp::_::StructReader _reader;
template <typename, ::capnp::Kind>
@@ -5968,6 +5991,16 @@ public:
inline float getTargetSpeedMps();
inline void setTargetSpeedMps(float value);
inline ::int8_t getStepUnits();
inline void setStepUnits( ::int8_t value);
inline bool hasSourceTeslaGesture();
inline ::cereal::SlcAction::TeslaGesture::Builder getSourceTeslaGesture();
inline void setSourceTeslaGesture( ::cereal::SlcAction::TeslaGesture::Reader value);
inline ::cereal::SlcAction::TeslaGesture::Builder initSourceTeslaGesture();
inline void adoptSourceTeslaGesture(::capnp::Orphan< ::cereal::SlcAction::TeslaGesture>&& value);
inline ::capnp::Orphan< ::cereal::SlcAction::TeslaGesture> disownSourceTeslaGesture();
private:
::capnp::_::StructBuilder _builder;
template <typename, ::capnp::Kind>
@@ -5986,6 +6019,148 @@ public:
inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless)
: _typeless(kj::mv(typeless)) {}
inline ::cereal::SlcAction::TeslaGesture::Pipeline getSourceTeslaGesture();
private:
::capnp::AnyPointer::Pipeline _typeless;
friend class ::capnp::PipelineHook;
template <typename, ::capnp::Kind>
friend struct ::capnp::ToDynamic_;
};
#endif // !CAPNP_LITE
class SlcAction::TeslaGesture::Reader {
public:
typedef TeslaGesture Reads;
Reader() = default;
inline explicit Reader(::capnp::_::StructReader base): _reader(base) {}
inline ::capnp::MessageSize totalSize() const {
return _reader.totalSize().asPublic();
}
#if !CAPNP_LITE
inline ::kj::StringTree toString() const {
return ::capnp::_::structString(_reader, *_capnpPrivate::brand());
}
#endif // !CAPNP_LITE
inline ::uint16_t getVersion() const;
inline bool hasWorkerSession() const;
inline ::capnp::Text::Reader getWorkerSession() const;
inline ::uint64_t getSequence() const;
inline ::uint64_t getSourceCanBootTime() const;
inline ::uint16_t getSourceCanFrameIndex() const;
inline bool hasName() const;
inline ::capnp::Text::Reader getName() const;
inline bool getFast() const;
inline bool hasAssignmentsHash() const;
inline ::capnp::Text::Reader getAssignmentsHash() const;
inline bool hasVehicleHash() const;
inline ::capnp::Text::Reader getVehicleHash() const;
inline ::uint64_t getDriveStartMonoTime() const;
private:
::capnp::_::StructReader _reader;
template <typename, ::capnp::Kind>
friend struct ::capnp::ToDynamic_;
template <typename, ::capnp::Kind>
friend struct ::capnp::_::PointerHelpers;
template <typename, ::capnp::Kind>
friend struct ::capnp::List;
friend class ::capnp::MessageBuilder;
friend class ::capnp::Orphanage;
};
class SlcAction::TeslaGesture::Builder {
public:
typedef TeslaGesture Builds;
Builder() = delete; // Deleted to discourage incorrect usage.
// You can explicitly initialize to nullptr instead.
inline Builder(decltype(nullptr)) {}
inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {}
inline operator Reader() const { return Reader(_builder.asReader()); }
inline Reader asReader() const { return *this; }
inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); }
#if !CAPNP_LITE
inline ::kj::StringTree toString() const { return asReader().toString(); }
#endif // !CAPNP_LITE
inline ::uint16_t getVersion();
inline void setVersion( ::uint16_t value);
inline bool hasWorkerSession();
inline ::capnp::Text::Builder getWorkerSession();
inline void setWorkerSession( ::capnp::Text::Reader value);
inline ::capnp::Text::Builder initWorkerSession(unsigned int size);
inline void adoptWorkerSession(::capnp::Orphan< ::capnp::Text>&& value);
inline ::capnp::Orphan< ::capnp::Text> disownWorkerSession();
inline ::uint64_t getSequence();
inline void setSequence( ::uint64_t value);
inline ::uint64_t getSourceCanBootTime();
inline void setSourceCanBootTime( ::uint64_t value);
inline ::uint16_t getSourceCanFrameIndex();
inline void setSourceCanFrameIndex( ::uint16_t value);
inline bool hasName();
inline ::capnp::Text::Builder getName();
inline void setName( ::capnp::Text::Reader value);
inline ::capnp::Text::Builder initName(unsigned int size);
inline void adoptName(::capnp::Orphan< ::capnp::Text>&& value);
inline ::capnp::Orphan< ::capnp::Text> disownName();
inline bool getFast();
inline void setFast(bool value);
inline bool hasAssignmentsHash();
inline ::capnp::Text::Builder getAssignmentsHash();
inline void setAssignmentsHash( ::capnp::Text::Reader value);
inline ::capnp::Text::Builder initAssignmentsHash(unsigned int size);
inline void adoptAssignmentsHash(::capnp::Orphan< ::capnp::Text>&& value);
inline ::capnp::Orphan< ::capnp::Text> disownAssignmentsHash();
inline bool hasVehicleHash();
inline ::capnp::Text::Builder getVehicleHash();
inline void setVehicleHash( ::capnp::Text::Reader value);
inline ::capnp::Text::Builder initVehicleHash(unsigned int size);
inline void adoptVehicleHash(::capnp::Orphan< ::capnp::Text>&& value);
inline ::capnp::Orphan< ::capnp::Text> disownVehicleHash();
inline ::uint64_t getDriveStartMonoTime();
inline void setDriveStartMonoTime( ::uint64_t value);
private:
::capnp::_::StructBuilder _builder;
template <typename, ::capnp::Kind>
friend struct ::capnp::ToDynamic_;
friend class ::capnp::Orphanage;
template <typename, ::capnp::Kind>
friend struct ::capnp::_::PointerHelpers;
};
#if !CAPNP_LITE
class SlcAction::TeslaGesture::Pipeline {
public:
typedef TeslaGesture Pipelines;
inline Pipeline(decltype(nullptr)): _typeless(nullptr) {}
inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless)
: _typeless(kj::mv(typeless)) {}
private:
::capnp::AnyPointer::Pipeline _typeless;
friend class ::capnp::PipelineHook;
@@ -22326,6 +22501,279 @@ inline void SlcAction::ControllerCruiseAction::Builder::setTargetSpeedMps(float
::capnp::bounded<1>() * ::capnp::ELEMENTS, value);
}
inline ::int8_t SlcAction::ControllerCruiseAction::Reader::getStepUnits() const {
return _reader.getDataField< ::int8_t>(
::capnp::bounded<3>() * ::capnp::ELEMENTS);
}
inline ::int8_t SlcAction::ControllerCruiseAction::Builder::getStepUnits() {
return _builder.getDataField< ::int8_t>(
::capnp::bounded<3>() * ::capnp::ELEMENTS);
}
inline void SlcAction::ControllerCruiseAction::Builder::setStepUnits( ::int8_t value) {
_builder.setDataField< ::int8_t>(
::capnp::bounded<3>() * ::capnp::ELEMENTS, value);
}
inline bool SlcAction::ControllerCruiseAction::Reader::hasSourceTeslaGesture() const {
return !_reader.getPointerField(
::capnp::bounded<4>() * ::capnp::POINTERS).isNull();
}
inline bool SlcAction::ControllerCruiseAction::Builder::hasSourceTeslaGesture() {
return !_builder.getPointerField(
::capnp::bounded<4>() * ::capnp::POINTERS).isNull();
}
inline ::cereal::SlcAction::TeslaGesture::Reader SlcAction::ControllerCruiseAction::Reader::getSourceTeslaGesture() const {
return ::capnp::_::PointerHelpers< ::cereal::SlcAction::TeslaGesture>::get(_reader.getPointerField(
::capnp::bounded<4>() * ::capnp::POINTERS));
}
inline ::cereal::SlcAction::TeslaGesture::Builder SlcAction::ControllerCruiseAction::Builder::getSourceTeslaGesture() {
return ::capnp::_::PointerHelpers< ::cereal::SlcAction::TeslaGesture>::get(_builder.getPointerField(
::capnp::bounded<4>() * ::capnp::POINTERS));
}
#if !CAPNP_LITE
inline ::cereal::SlcAction::TeslaGesture::Pipeline SlcAction::ControllerCruiseAction::Pipeline::getSourceTeslaGesture() {
return ::cereal::SlcAction::TeslaGesture::Pipeline(_typeless.getPointerField(4));
}
#endif // !CAPNP_LITE
inline void SlcAction::ControllerCruiseAction::Builder::setSourceTeslaGesture( ::cereal::SlcAction::TeslaGesture::Reader value) {
::capnp::_::PointerHelpers< ::cereal::SlcAction::TeslaGesture>::set(_builder.getPointerField(
::capnp::bounded<4>() * ::capnp::POINTERS), value);
}
inline ::cereal::SlcAction::TeslaGesture::Builder SlcAction::ControllerCruiseAction::Builder::initSourceTeslaGesture() {
return ::capnp::_::PointerHelpers< ::cereal::SlcAction::TeslaGesture>::init(_builder.getPointerField(
::capnp::bounded<4>() * ::capnp::POINTERS));
}
inline void SlcAction::ControllerCruiseAction::Builder::adoptSourceTeslaGesture(
::capnp::Orphan< ::cereal::SlcAction::TeslaGesture>&& value) {
::capnp::_::PointerHelpers< ::cereal::SlcAction::TeslaGesture>::adopt(_builder.getPointerField(
::capnp::bounded<4>() * ::capnp::POINTERS), kj::mv(value));
}
inline ::capnp::Orphan< ::cereal::SlcAction::TeslaGesture> SlcAction::ControllerCruiseAction::Builder::disownSourceTeslaGesture() {
return ::capnp::_::PointerHelpers< ::cereal::SlcAction::TeslaGesture>::disown(_builder.getPointerField(
::capnp::bounded<4>() * ::capnp::POINTERS));
}
inline ::uint16_t SlcAction::TeslaGesture::Reader::getVersion() const {
return _reader.getDataField< ::uint16_t>(
::capnp::bounded<0>() * ::capnp::ELEMENTS);
}
inline ::uint16_t SlcAction::TeslaGesture::Builder::getVersion() {
return _builder.getDataField< ::uint16_t>(
::capnp::bounded<0>() * ::capnp::ELEMENTS);
}
inline void SlcAction::TeslaGesture::Builder::setVersion( ::uint16_t value) {
_builder.setDataField< ::uint16_t>(
::capnp::bounded<0>() * ::capnp::ELEMENTS, value);
}
inline bool SlcAction::TeslaGesture::Reader::hasWorkerSession() const {
return !_reader.getPointerField(
::capnp::bounded<0>() * ::capnp::POINTERS).isNull();
}
inline bool SlcAction::TeslaGesture::Builder::hasWorkerSession() {
return !_builder.getPointerField(
::capnp::bounded<0>() * ::capnp::POINTERS).isNull();
}
inline ::capnp::Text::Reader SlcAction::TeslaGesture::Reader::getWorkerSession() const {
return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_reader.getPointerField(
::capnp::bounded<0>() * ::capnp::POINTERS));
}
inline ::capnp::Text::Builder SlcAction::TeslaGesture::Builder::getWorkerSession() {
return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_builder.getPointerField(
::capnp::bounded<0>() * ::capnp::POINTERS));
}
inline void SlcAction::TeslaGesture::Builder::setWorkerSession( ::capnp::Text::Reader value) {
::capnp::_::PointerHelpers< ::capnp::Text>::set(_builder.getPointerField(
::capnp::bounded<0>() * ::capnp::POINTERS), value);
}
inline ::capnp::Text::Builder SlcAction::TeslaGesture::Builder::initWorkerSession(unsigned int size) {
return ::capnp::_::PointerHelpers< ::capnp::Text>::init(_builder.getPointerField(
::capnp::bounded<0>() * ::capnp::POINTERS), size);
}
inline void SlcAction::TeslaGesture::Builder::adoptWorkerSession(
::capnp::Orphan< ::capnp::Text>&& value) {
::capnp::_::PointerHelpers< ::capnp::Text>::adopt(_builder.getPointerField(
::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value));
}
inline ::capnp::Orphan< ::capnp::Text> SlcAction::TeslaGesture::Builder::disownWorkerSession() {
return ::capnp::_::PointerHelpers< ::capnp::Text>::disown(_builder.getPointerField(
::capnp::bounded<0>() * ::capnp::POINTERS));
}
inline ::uint64_t SlcAction::TeslaGesture::Reader::getSequence() const {
return _reader.getDataField< ::uint64_t>(
::capnp::bounded<1>() * ::capnp::ELEMENTS);
}
inline ::uint64_t SlcAction::TeslaGesture::Builder::getSequence() {
return _builder.getDataField< ::uint64_t>(
::capnp::bounded<1>() * ::capnp::ELEMENTS);
}
inline void SlcAction::TeslaGesture::Builder::setSequence( ::uint64_t value) {
_builder.setDataField< ::uint64_t>(
::capnp::bounded<1>() * ::capnp::ELEMENTS, value);
}
inline ::uint64_t SlcAction::TeslaGesture::Reader::getSourceCanBootTime() const {
return _reader.getDataField< ::uint64_t>(
::capnp::bounded<2>() * ::capnp::ELEMENTS);
}
inline ::uint64_t SlcAction::TeslaGesture::Builder::getSourceCanBootTime() {
return _builder.getDataField< ::uint64_t>(
::capnp::bounded<2>() * ::capnp::ELEMENTS);
}
inline void SlcAction::TeslaGesture::Builder::setSourceCanBootTime( ::uint64_t value) {
_builder.setDataField< ::uint64_t>(
::capnp::bounded<2>() * ::capnp::ELEMENTS, value);
}
inline ::uint16_t SlcAction::TeslaGesture::Reader::getSourceCanFrameIndex() const {
return _reader.getDataField< ::uint16_t>(
::capnp::bounded<1>() * ::capnp::ELEMENTS);
}
inline ::uint16_t SlcAction::TeslaGesture::Builder::getSourceCanFrameIndex() {
return _builder.getDataField< ::uint16_t>(
::capnp::bounded<1>() * ::capnp::ELEMENTS);
}
inline void SlcAction::TeslaGesture::Builder::setSourceCanFrameIndex( ::uint16_t value) {
_builder.setDataField< ::uint16_t>(
::capnp::bounded<1>() * ::capnp::ELEMENTS, value);
}
inline bool SlcAction::TeslaGesture::Reader::hasName() const {
return !_reader.getPointerField(
::capnp::bounded<1>() * ::capnp::POINTERS).isNull();
}
inline bool SlcAction::TeslaGesture::Builder::hasName() {
return !_builder.getPointerField(
::capnp::bounded<1>() * ::capnp::POINTERS).isNull();
}
inline ::capnp::Text::Reader SlcAction::TeslaGesture::Reader::getName() const {
return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_reader.getPointerField(
::capnp::bounded<1>() * ::capnp::POINTERS));
}
inline ::capnp::Text::Builder SlcAction::TeslaGesture::Builder::getName() {
return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_builder.getPointerField(
::capnp::bounded<1>() * ::capnp::POINTERS));
}
inline void SlcAction::TeslaGesture::Builder::setName( ::capnp::Text::Reader value) {
::capnp::_::PointerHelpers< ::capnp::Text>::set(_builder.getPointerField(
::capnp::bounded<1>() * ::capnp::POINTERS), value);
}
inline ::capnp::Text::Builder SlcAction::TeslaGesture::Builder::initName(unsigned int size) {
return ::capnp::_::PointerHelpers< ::capnp::Text>::init(_builder.getPointerField(
::capnp::bounded<1>() * ::capnp::POINTERS), size);
}
inline void SlcAction::TeslaGesture::Builder::adoptName(
::capnp::Orphan< ::capnp::Text>&& value) {
::capnp::_::PointerHelpers< ::capnp::Text>::adopt(_builder.getPointerField(
::capnp::bounded<1>() * ::capnp::POINTERS), kj::mv(value));
}
inline ::capnp::Orphan< ::capnp::Text> SlcAction::TeslaGesture::Builder::disownName() {
return ::capnp::_::PointerHelpers< ::capnp::Text>::disown(_builder.getPointerField(
::capnp::bounded<1>() * ::capnp::POINTERS));
}
inline bool SlcAction::TeslaGesture::Reader::getFast() const {
return _reader.getDataField<bool>(
::capnp::bounded<32>() * ::capnp::ELEMENTS);
}
inline bool SlcAction::TeslaGesture::Builder::getFast() {
return _builder.getDataField<bool>(
::capnp::bounded<32>() * ::capnp::ELEMENTS);
}
inline void SlcAction::TeslaGesture::Builder::setFast(bool value) {
_builder.setDataField<bool>(
::capnp::bounded<32>() * ::capnp::ELEMENTS, value);
}
inline bool SlcAction::TeslaGesture::Reader::hasAssignmentsHash() const {
return !_reader.getPointerField(
::capnp::bounded<2>() * ::capnp::POINTERS).isNull();
}
inline bool SlcAction::TeslaGesture::Builder::hasAssignmentsHash() {
return !_builder.getPointerField(
::capnp::bounded<2>() * ::capnp::POINTERS).isNull();
}
inline ::capnp::Text::Reader SlcAction::TeslaGesture::Reader::getAssignmentsHash() const {
return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_reader.getPointerField(
::capnp::bounded<2>() * ::capnp::POINTERS));
}
inline ::capnp::Text::Builder SlcAction::TeslaGesture::Builder::getAssignmentsHash() {
return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_builder.getPointerField(
::capnp::bounded<2>() * ::capnp::POINTERS));
}
inline void SlcAction::TeslaGesture::Builder::setAssignmentsHash( ::capnp::Text::Reader value) {
::capnp::_::PointerHelpers< ::capnp::Text>::set(_builder.getPointerField(
::capnp::bounded<2>() * ::capnp::POINTERS), value);
}
inline ::capnp::Text::Builder SlcAction::TeslaGesture::Builder::initAssignmentsHash(unsigned int size) {
return ::capnp::_::PointerHelpers< ::capnp::Text>::init(_builder.getPointerField(
::capnp::bounded<2>() * ::capnp::POINTERS), size);
}
inline void SlcAction::TeslaGesture::Builder::adoptAssignmentsHash(
::capnp::Orphan< ::capnp::Text>&& value) {
::capnp::_::PointerHelpers< ::capnp::Text>::adopt(_builder.getPointerField(
::capnp::bounded<2>() * ::capnp::POINTERS), kj::mv(value));
}
inline ::capnp::Orphan< ::capnp::Text> SlcAction::TeslaGesture::Builder::disownAssignmentsHash() {
return ::capnp::_::PointerHelpers< ::capnp::Text>::disown(_builder.getPointerField(
::capnp::bounded<2>() * ::capnp::POINTERS));
}
inline bool SlcAction::TeslaGesture::Reader::hasVehicleHash() const {
return !_reader.getPointerField(
::capnp::bounded<3>() * ::capnp::POINTERS).isNull();
}
inline bool SlcAction::TeslaGesture::Builder::hasVehicleHash() {
return !_builder.getPointerField(
::capnp::bounded<3>() * ::capnp::POINTERS).isNull();
}
inline ::capnp::Text::Reader SlcAction::TeslaGesture::Reader::getVehicleHash() const {
return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_reader.getPointerField(
::capnp::bounded<3>() * ::capnp::POINTERS));
}
inline ::capnp::Text::Builder SlcAction::TeslaGesture::Builder::getVehicleHash() {
return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_builder.getPointerField(
::capnp::bounded<3>() * ::capnp::POINTERS));
}
inline void SlcAction::TeslaGesture::Builder::setVehicleHash( ::capnp::Text::Reader value) {
::capnp::_::PointerHelpers< ::capnp::Text>::set(_builder.getPointerField(
::capnp::bounded<3>() * ::capnp::POINTERS), value);
}
inline ::capnp::Text::Builder SlcAction::TeslaGesture::Builder::initVehicleHash(unsigned int size) {
return ::capnp::_::PointerHelpers< ::capnp::Text>::init(_builder.getPointerField(
::capnp::bounded<3>() * ::capnp::POINTERS), size);
}
inline void SlcAction::TeslaGesture::Builder::adoptVehicleHash(
::capnp::Orphan< ::capnp::Text>&& value) {
::capnp::_::PointerHelpers< ::capnp::Text>::adopt(_builder.getPointerField(
::capnp::bounded<3>() * ::capnp::POINTERS), kj::mv(value));
}
inline ::capnp::Orphan< ::capnp::Text> SlcAction::TeslaGesture::Builder::disownVehicleHash() {
return ::capnp::_::PointerHelpers< ::capnp::Text>::disown(_builder.getPointerField(
::capnp::bounded<3>() * ::capnp::POINTERS));
}
inline ::uint64_t SlcAction::TeslaGesture::Reader::getDriveStartMonoTime() const {
return _reader.getDataField< ::uint64_t>(
::capnp::bounded<3>() * ::capnp::ELEMENTS);
}
inline ::uint64_t SlcAction::TeslaGesture::Builder::getDriveStartMonoTime() {
return _builder.getDataField< ::uint64_t>(
::capnp::bounded<3>() * ::capnp::ELEMENTS);
}
inline void SlcAction::TeslaGesture::Builder::setDriveStartMonoTime( ::uint64_t value) {
_builder.setDataField< ::uint64_t>(
::capnp::bounded<3>() * ::capnp::ELEMENTS, value);
}
inline ::uint16_t SlcAction::ConditionalManualAction::Reader::getVersion() const {
return _reader.getDataField< ::uint16_t>(
::capnp::bounded<0>() * ::capnp::ELEMENTS);
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+10 -2
View File
@@ -85,11 +85,15 @@ 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"}},
{"CoastDownhills", {PERSISTENT, BOOL, "0"}},
{"DownhillSpeedSurplus", {PERSISTENT, FLOAT, "0.0"}},
{"SwitchbackModeCooldown", {PERSISTENT, FLOAT, "5.0"}},
{"CustomCruise", {PERSISTENT, FLOAT, "1.0"}},
{"CustomCruiseLong", {PERSISTENT, FLOAT, "5.0"}},
@@ -159,6 +163,9 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"BlindSpotMetrics", {PERSISTENT, BOOL, "1"}},
{"GreenLightAlert", {PERSISTENT, BOOL, "0"}},
{"LeadDepartingAlert", {PERSISTENT, BOOL, "0"}},
{"EngineSound", {PERSISTENT, BOOL, "0"}},
{"EngineSoundProfile", {PERSISTENT, STRING, "lfa"}},
{"EngineSoundVolume", {PERSISTENT, INT, "60"}},
{"LoudBlindspotAlert", {PERSISTENT, BOOL, "0"}},
{"LoudBlindspotAlertWhenDisengaged", {PERSISTENT, BOOL, "0"}},
{"LoudBlindspotAlertMuteAtStandstill", {PERSISTENT, BOOL, "0"}},
@@ -268,6 +275,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"IsLdwEnabled", {PERSISTENT, BOOL}},
{"IsLiveStreaming", {CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON, BOOL}},
{"IsMetric", {PERSISTENT, BOOL}},
{"TemperatureGaugeUnit", {PERSISTENT, STRING, "auto"}},
{"IsOffroad", {CLEAR_ON_MANAGER_START, BOOL}},
{"IsRhdDetected", {PERSISTENT, BOOL}},
{"IsReleaseBranch", {CLEAR_ON_MANAGER_START, BOOL}},
@@ -365,7 +373,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"TeslaPreAPPedalStartup", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION | DONT_LOG, BYTES}},
{"NAPRadarEnabled", {PERSISTENT, BOOL, "0"}},
{"NAPRadarBehindNosecone", {PERSISTENT, BOOL, "0"}},
{"SafeMode", {PERSISTENT | DONT_LOG, BOOL, "0"}},
{"SafeMode", {PERSISTENT, BOOL, "0"}},
{"CurveSpeedController", {PERSISTENT | DONT_LOG, BOOL, "0"}},
{"CurveSpeedControllerNoLead", {PERSISTENT | DONT_LOG, BOOL, "0"}},
{"ShowCSCStatus", {PERSISTENT | DONT_LOG, BOOL, "0"}},
@@ -0,0 +1,25 @@
import pytest
from openpilot.common.version import build_metadata_from_dict
@pytest.mark.parametrize("origin, channel, expected", [
("https://github.com/StarPilotHQ/StarPilot.git", "stable", True),
("https://github.com/StarPilotHQ/StarPilot.git", "testing", True),
("https://github.com/firestar5683/StarPilot.git", "stable", True),
("git@github.com:firestar5683/StarPilot.git", "testing", True),
("https://github.com/StarPilotHQ/StarPilot.git", "StarPilot", True),
("https://github.com/StarPilotHQ/StarPilot.git", "Dom", True),
("https://github.com/firestar5683/StarPilot.git", "StarPilot", True),
("https://github.com/firestar5683/StarPilot.git", "Dom", True),
("https://github.com/StarPilotHQ/StarPilot.git", "feature", False),
("https://github.com/StarPilotHQ/StarPilot.git", "HEAD", False),
("https://github.com/other/StarPilot.git", "stable", False),
("https://github.com/other/StarPilot.git", "testing", False),
("https://github.com/commaai/openpilot.git", "release-tizi", True),
("https://github.com/commaai/openpilot.git", "master", False),
("https://github.com/StarPilotHQ/StarPilot.git", "replay", False),
])
def test_standard_startup(origin, channel, expected):
metadata = build_metadata_from_dict({"channel": channel, "openpilot": {"git_origin": origin}})
assert metadata.standard_startup is expected
+7
View File
@@ -99,6 +99,13 @@ class BuildMetadata:
def tested_channel(self) -> bool:
return self.channel in TESTED_BRANCHES
@property
def standard_startup(self) -> bool:
starpilot_origins = ('github.com/starpilothq/starpilot', 'github.com/firestar5683/starpilot')
if self.openpilot.git_normalized_origin.lower() in starpilot_origins:
return self.channel in ('stable', 'StarPilot', 'Dom', 'testing')
return self.openpilot.comma_remote and self.tested_channel
@property
def release_channel(self) -> bool:
return self.channel in RELEASE_BRANCHES
+21 -12
View File
@@ -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
@@ -242,9 +242,7 @@ class Car:
def pre_create_hook(cp, candidate, fingerprints, car_fw):
initialize_aol_preference(cp)
if candidate == HYUNDAI_CAR.HYUNDAI_IONIQ_6:
# This decision must precede CarInterface parser/controller construction
# and the first CarParams publication below. The exact opt-in is
# still subject to current source and restore verification.
# Verify the opt-in before constructing the interface and publishing CarParams.
eligible = alpha_long_allowed and IONIQ6_LONG_PREARM_ENABLED and not is_release and openpilot_enabled_toggle and not self.params.get_bool("IsOffroad")
if eligible:
self.sm.update(0)
@@ -261,8 +259,7 @@ class Car:
preflight = inspect_ioniq6_long_sources(self.can_callbacks[0], ecan_bus=HyundaiCanBus(cp).ECAN)
cloudlog.event('ioniq6_long_preflight', reason=preflight.reason)
if preflight.source_period is None or preflight.vehicle_ready is not False:
# Reboot in READY retains original stock CP before CI/parsers and
# publication. Unknown evidence cannot be treated as Ready=False.
# READY or unknown keeps stock CarParams.
long_cp = None
if long_cp is not None:
initialize_aol_preference(long_cp)
@@ -453,6 +450,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 +590,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
@@ -676,6 +675,8 @@ class Car:
if self.aol_card_intent.explicit_latch and (permission_owner or self.sm.updated['aolSafetyWire'])
else None
)
honda_eps_pending = bool(honda_aol and not transport_reset and native is not None and
getattr(self.aol_transport_feedback, 'honda_eps_retained_native_ns', 0) == int(native.observedMonoTime))
native_reset = False
if permission_owner:
observe, restrict = native_handlers(
@@ -693,7 +694,7 @@ class Car:
native,
latched=self.aol_card_intent.allowed_latch,
panda_ready=angle_panda_ready,
restricted=(getattr(self.aol_transport_feedback, 'ordinary_warning_qualified', False) or
restricted=(honda_eps_pending or getattr(self.aol_transport_feedback, 'ordinary_warning_qualified', False) or
ford_initial_wait and not self.sm['aolAxisState'].desiredLateral or
restrict(self.CP, CS) or
((angle_aol or ford_aol or mazda_aol or preap_aol or rivian_aol) and self.aol_card_intent.pause_lateral) or
@@ -719,7 +720,7 @@ class Car:
volkswagen_reverse_pending = bool(volkswagen_aol and not transport_reset and native is not None and
getattr(self.aol_transport_feedback, 'volkswagen_reverse_retained_native_ns', 0) == int(native.observedMonoTime))
rejected = native_reset or (not angle_arm_pending and not subaru_braked_main_pending and
not volkswagen_initial_wait and not volkswagen_reverse_pending and
not volkswagen_initial_wait and not volkswagen_reverse_pending and not honda_eps_pending and
native_latch_rejected(self.CP, native, state=CS if angle_panda_ready else None))
rejection_ns = now_ns if native_reset else int(native.observedMonoTime) if rejected else 0
observe_physical = getattr(self.aol_card_intent, 'observe_physical_samples', None)
@@ -809,6 +810,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 +853,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 +869,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 +1238,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 +1896,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 +1997,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:
+12 -5
View File
@@ -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
@@ -21,8 +21,18 @@ RECORDED = (
)
def recorded_frames():
return [CanData(address, bytes.fromhex(data), bus) for bus, address, data in RECORDED]
MAVERICK_RECORDED = (
(0, 130, '69081400b2004000'),
(0, 357, '50c0000000000000'),
(0, 516, 'f8727d00007c0000'),
(0, 535, '052004a6050c048d'),
(2, 970, '1e80080000000000'),
(2, 979, '7d10007ce0801000'),
)
def recorded_frames(layout=RECORDED):
return [CanData(address, bytes.fromhex(data), bus) for bus, address, data in layout]
def brand(frames):
@@ -33,17 +43,19 @@ def test_recorded_normal_harness_selects_ford_queries_only():
assert brand(recorded_frames()) == 'ford'
@pytest.mark.parametrize('layout', [RECORDED, MAVERICK_RECORDED])
@pytest.mark.parametrize('missing', range(6))
def test_partial_layout_does_not_choose_ford(missing):
frames = recorded_frames()
def test_partial_layout_does_not_choose_ford(layout, missing):
frames = recorded_frames(layout)
del frames[missing]
assert brand(frames) is None
@pytest.mark.parametrize('layout', [RECORDED, MAVERICK_RECORDED])
@pytest.mark.parametrize('bad', range(6))
def test_wrong_bus_dlc_and_returned_frames_do_not_choose_ford(bad):
def test_wrong_bus_dlc_and_returned_frames_do_not_choose_ford(layout, bad):
for bus_delta, size in ((1, 8), (128, 8), (0, 7), (0, 12)):
frames = recorded_frames()
frames = recorded_frames(layout)
original = frames[bad]
frames[bad] = CanData(original.address, bytes(size), original.src + bus_delta)
assert brand(frames) is None
@@ -77,14 +89,21 @@ def test_shared_probe_uses_existing_read_bound():
@pytest.mark.parametrize('firmware_known', [False, True])
def test_cold_automatic_uses_real_vin_isotp_fw_and_identity_matching(firmware_known):
@pytest.mark.parametrize('candidate', [CAR.FORD_MUSTANG_MACH_E_MK1, CAR.FORD_MAVERICK_MK1])
def test_cold_automatic_uses_real_vin_isotp_fw_and_identity_matching(firmware_known, candidate):
firmware = {(0x706, b'\x22\xf1\x88'): b'RJ6T-14H102-BAE'.ljust(24, b'\0'),
(0x730, b'\x22\xf1\x88'): b'LJ9C-14D003-FA'.ljust(24, b'\0'),
(0x760, b'\x22\xf1\x88'): b'LK9C-2D053-CN'.ljust(24, b'\0'),
(0x764, b'\x22\xf1\x88'): b'ML3T-14D049-AL'.ljust(24, b'\0')}
layout = RECORDED
if candidate == CAR.FORD_MAVERICK_MK1:
firmware = {(address, b'\x22\xf1\x88'): version.ljust(24, b'\0') for address, version in (
(0x706, b'NZ6T-14F397-AC'), (0x730, b'NZ6C-14D003-AL'),
(0x760, b'PZ6C-2D053-EF'), (0x764, b'NZ6T-14D049-AA'))}
layout = MAVERICK_RECORDED
if not firmware_known:
firmware = dict.fromkeys(firmware, b'unknown')
transport = FordEcus(firmware=firmware, background=recorded_frames())
transport = FordEcus(firmware=firmware, background=recorded_frames(layout))
with mock.patch.dict(car_helpers.os.environ, {'FINGERPRINT': '', 'SKIP_FW_QUERY': '', 'DISABLE_FW_CACHE': ''}), \
mock.patch.object(car_helpers.time, 'monotonic', side_effect=lambda: transport.clock), \
mock.patch.object(car_helpers.time, 'sleep', side_effect=transport.sleep):
@@ -93,12 +112,12 @@ def test_cold_automatic_uses_real_vin_isotp_fw_and_identity_matching(firmware_kn
assert transport.sent and all(frame.src in (0, 4) for frame in transport.sent)
assert any(frame.dat[0] >> 4 == 3 for frame in transport.sent)
if firmware_known:
assert ci.CP.carFingerprint == CAR.FORD_MUSTANG_MACH_E_MK1
assert ci.CP.carFingerprint == candidate
assert ci.CP.fingerprintSource == structs.CarParams.FingerprintSource.fw
assert ci.CP.carVin == VIN
assert {(fw.address, fw.fwVersion) for fw in ci.CP.carFw} == {(address, data) for (address, _), data in firmware.items()}
else:
assert ci.CP.carFingerprint != CAR.FORD_MUSTANG_MACH_E_MK1
assert ci.CP.carFingerprint != candidate
assert not ci.CP.safetyConfigs or ci.CP.safetyConfigs[-1].safetyModel != structs.CarParams.SafetyModel.ford
@@ -28,7 +28,17 @@ class DesireHelper:
def get_lane_change_direction(CS):
return LaneChangeDirection.left if CS.leftBlinker else LaneChangeDirection.right
def update(self, carstate, lateral_active, lane_change_prob, *, auto_evidence=False, engaged=False, navigation_turn=False):
def lane_change_speed(self):
return max(MINIMUM_SPEED_MPS, self.policy.minimum_speed_mps,
20 * CV.MPH_TO_MS if self.policy.turn_signal_guidance else 0.0)
def waiting_for_lane(self, carstate):
return (self.policy.enabled and carstate.vEgo >= self.lane_change_speed() and
carstate.leftBlinker != carstate.rightBlinker and
(self.lane_change_state == LaneChangeState.preLaneChange or
(self.lane_change_state == LaneChangeState.off and not self.prev_one_blinker)))
def update(self, carstate, lateral_active, lane_change_prob, *, auto_evidence=False, engaged=False, navigation_turn=False, route_turn=False):
v_ego = carstate.vEgo
one_blinker = carstate.leftBlinker != carstate.rightBlinker
if not carstate.leftBlinker and not carstate.rightBlinker:
@@ -41,8 +51,7 @@ class DesireHelper:
self.auto_signal_blocked = True
self.last_signal_direction = signal_direction
self.auto_status = "manualRequired"
below_lane_change_speed = v_ego < max(MINIMUM_SPEED_MPS, self.policy.minimum_speed_mps,
20 * CV.MPH_TO_MS if self.policy.turn_signal_guidance else 0.0)
below_lane_change_speed = v_ego < self.lane_change_speed()
if not self.policy.enabled or not lateral_active or below_lane_change_speed or self.lane_change_timer > LANE_CHANGE_TIME_MAX:
self.lane_change_state = LaneChangeState.off
@@ -50,12 +59,12 @@ class DesireHelper:
self.lane_change_timer = 0.0
self.pre_lane_change_timer = 0.0
else:
if navigation_turn and self.lane_change_state == LaneChangeState.preLaneChange:
if navigation_turn and not route_turn and self.lane_change_state == LaneChangeState.preLaneChange:
self.lane_change_state = LaneChangeState.off
self.lane_change_direction = LaneChangeDirection.none
self.pre_lane_change_timer = 0.0
if (self.lane_change_state == LaneChangeState.off and one_blinker and not self.prev_one_blinker and
not below_lane_change_speed and not navigation_turn and not (self.policy.one_per_signal and self.lane_change_performed)):
not below_lane_change_speed and (route_turn or not navigation_turn) and not (self.policy.one_per_signal and self.lane_change_performed)):
self.lane_change_state = LaneChangeState.preLaneChange
self.lane_change_timer = 0.0
self.pre_lane_change_timer = 0.0
@@ -101,7 +110,7 @@ class DesireHelper:
if lane_change_prob < 0.02 and self.lane_change_timer >= LANE_CHANGE_START_TIME:
self.lane_change_timer = 0.0
if one_blinker and not (self.policy.one_per_signal and self.lane_change_performed):
if one_blinker and not route_turn and not (self.policy.one_per_signal and self.lane_change_performed):
self.lane_change_state = LaneChangeState.preLaneChange
self.lane_change_direction = self.get_lane_change_direction(carstate)
else:
@@ -14,10 +14,16 @@ class LatControlPID(LatControl):
pos_limit=self.steer_max,
neg_limit=-self.steer_max,
)
self.fit_pid_reset = CP.carFingerprint == "HONDA_FIT"
self.ff_factor = CP.lateralTuning.pid.kf
self.get_steer_feedforward = CI.get_steer_feedforward_function()
self.automatic_pid_previous_setpoint = None
def reset(self):
super().reset()
if self.fit_pid_reset:
self.pid.reset()
def update(self, active, CS, VM, params, steer_limited_by_safety, desired_curvature, curvature_limited, lat_delay):
if getattr(self, 'route_flm_effects', None) is not None:
self.route_flm_effects.begin_frame(self)
@@ -56,6 +62,9 @@ class LatControlPID(LatControl):
error = error_for_frame(self, CS, error, active=active, limited=steer_limited_by_safety or curvature_limited)
freeze_integrator = steer_limited_by_safety or CS.steeringPressed or CS.vEgo < 5
if self.fit_pid_reset and CS.steeringPressed:
self.pid.reset()
output_torque = self.pid.update(error, feedforward=ff, speed=CS.vEgo, freeze_integrator=freeze_integrator)
from openpilot.starpilot.flm.pid_stages import finish_frame
@@ -22,12 +22,15 @@ from openpilot.selfdrive.controls.lib.drive_helpers import CONTROL_N, get_accel_
from openpilot.selfdrive.car.cruise import V_CRUISE_MAX, V_CRUISE_UNSET
from openpilot.common.swaglog import cloudlog
from openpilot.starpilot.navigation.intent import NAVIGATION_BRAKE_MAGNITUDE, cruise_ceiling as navigation_ceiling
from openpilot.starpilot.navigation.slowdown import DEFAULT_SLOWDOWN_PERCENT
from openpilot.starpilot.car.tesla.preap_adaptive import startup_owner as preap_adaptive_owner
from openpilot.starpilot.longitudinal.vehicle_policy import forecast_should_stop, planner_cost_owner, far_follow_owner
from openpilot.starpilot.longitudinal.cruise_ceiling import CruiseCeiling, CurveCeiling, select_cruise_ceiling, select_curve_ceiling
from openpilot.starpilot.longitudinal.profile_runtime import (AppliedProfile, ProfileSmoother, ProfileTuning, SelectedProfileTuning,
TRAFFIC_CRUISE_BRAKE_MAGNITUDE)
from openpilot.starpilot.longitudinal.slc_coast import braking_lead_relevant
from openpilot.starpilot.longitudinal.downhill_coast import speed_error as downhill_speed_error
from openpilot.starpilot.conditional_mode.ui_action import current_authority, fresh_service
from openpilot.starpilot.longitudinal.throttle_gate import ModelThrottleGate
from openpilot.starpilot.longitudinal.ioniq6_start import eligible as ioniq6_long_eligible
from openpilot.starpilot.longitudinal.lane_change_gap import LaneChangeGap, project as project_lane_gap
@@ -50,6 +53,8 @@ A_CRUISE_MAX_BP = [0., 10.0, 25., 40.]
J_CRUISE_VALS = [1.6, 1.2, 0.8, 0.6]
A_CRUISE_MIN = -0.5
CRUISE_ACCEL_RESPONSE_TIME = 2.0
MODEL_Y_SPEED_STEP_JERK = 0.45
MODEL_Y_SPEED_STEP_DURATION_NS = 2_000_000_000
SLC_BRAKE_ONSET_JERK = 0.15 # m/s^3: how fast braking may build after an SLC overshoot
SLC_BRAKE_ONSET_ACCEL = -0.3 # m/s^2: past this the brakes are engaged and normal jerk resumes
CONTROL_N_T_IDX = ModelConstants.T_IDXS[:CONTROL_N]
@@ -74,7 +79,8 @@ def get_coast_accel(pitch):
def get_cruise_accel(e2e, v_cruise, v_ego, a_cruise_prev, angle_steers, CP, dt, accel_coast, allow_throttle,
profile: AppliedProfile | None = None,
base_brake_floor: float = A_CRUISE_MIN, selected_acceleration_max: float | None = None, faster_takeoffs: bool = False,
*, a_target_prev: float | None = None, ease_slc_braking: bool = False):
*, a_target_prev: float | None = None, ease_slc_braking: bool = False,
speed_step: bool = False, downhill_error: float | None = None):
ceiling = TAKEOFF_ACCEL_MAX if faster_takeoffs else ACCEL_MAX
max_accel = ceiling if e2e else get_max_accel(v_ego, faster_takeoffs)
if selected_acceleration_max is not None and not e2e:
@@ -97,12 +103,17 @@ def get_cruise_accel(e2e, v_cruise, v_ego, a_cruise_prev, angle_steers, CP, dt,
cruise_min = max(ACCEL_MIN, -profile.cruise_brake_magnitude) if profile is not None else max(ACCEL_MIN, base_brake_floor)
speed_error = v_cruise - v_ego
if downhill_error is not None:
speed_error = downhill_error
max_accel = min(max_accel, 0.)
if not e2e and not faster_takeoffs and v_ego >= MIN_ALLOW_THROTTLE_SPEED and speed_error > 0.:
speed_error /= CRUISE_ACCEL_RESPONSE_TIME
elif ease_slc_braking and speed_error < 0.:
speed_error /= CRUISE_ACCEL_RESPONSE_TIME # correct an SLC overshoot as gradually as an approach
target_accel = np.clip(speed_error, cruise_min, max_accel)
j_cruise = np.interp(v_ego, A_CRUISE_MAX_BP, J_CRUISE_VALS)
if speed_step and (v_cruise > v_ego or a_cruise_prev <= 0.0):
j_cruise = min(j_cruise, MODEL_Y_SPEED_STEP_JERK)
decel_start = a_cruise_prev if a_target_prev is None else min(a_cruise_prev, a_target_prev)
lower = decel_start - j_cruise * dt
if ease_slc_braking and decel_start > SLC_BRAKE_ONSET_ACCEL:
@@ -110,14 +121,16 @@ def get_cruise_accel(e2e, v_cruise, v_ego, a_cruise_prev, angle_steers, CP, dt,
lower = max(lower, min(decel_start, 0.) - SLC_BRAKE_ONSET_JERK * dt)
target_accel = float(np.clip(target_accel, lower, a_cruise_prev + j_cruise * dt))
return target_accel
return float(min(target_accel, max_accel)) if speed_step or downhill_error is not None else target_accel
class LongitudinalPlanner:
def __init__(self, CP, init_v=0.0, init_a=0.0, dt=DT_MDL, clock_ns: Callable[[], int] = time.monotonic_ns, *,
developer_tuning=None):
developer_tuning=None, navigation_slowdown_percent: int = DEFAULT_SLOWDOWN_PERCENT, downhill_surplus_mps: float = 0.):
self.CP = CP
tuning = developer_tuning or {}
self.navigation_slowdown_percent = navigation_slowdown_percent
self.downhill_surplus_mps = downhill_surplus_mps
self.action_delay_override = tuning.get("delay")
self.stop_speed = tuning.get("stop_speed", .3)
self.max_accel_override = tuning.get("max_accel")
@@ -139,6 +152,8 @@ class LongitudinalPlanner:
self.v_desired_filter = FirstOrderFilter(init_v, 2.0, self.dt)
self.a_cruise = init_a
self.previous_manual_cruise_kph: float | None = None
self.manual_cruise_step_until_ns = 0
self.output_a_target = init_a
self.output_should_stop = False
@@ -175,6 +190,8 @@ class LongitudinalPlanner:
if curve_ceiling is not None and curve_provider is not None:
raise ValueError('choose explicit Curve ceiling or same-cycle provider')
if self.plan_drive_id != drive_id:
self.previous_manual_cruise_kph = None
self.manual_cruise_step_until_ns = 0
self.model_lead_history.clear()
self.plan_drive_id = drive_id
faster_takeoffs = bool(faster_lead_takeoff)
@@ -327,7 +344,8 @@ class LongitudinalPlanner:
self.last_curve_ceiling_applied = False
if curve.effective_mps is not None:
v_cruise = curve.effective_mps
navigation_target = navigation_ceiling(sm, self.CP, sample_now_ns, v_cruise) if profile_eligible else None
navigation_target = (navigation_ceiling(sm, self.CP, sample_now_ns, v_cruise, slowdown_percent=self.navigation_slowdown_percent)
if profile_eligible else None)
if navigation_target is not None:
v_cruise = min(v_cruise, navigation_target)
coast_plan = None
@@ -425,12 +443,56 @@ class LongitudinalPlanner:
if preap_acceleration_cap is not None:
selected_acceleration = (preap_acceleration_cap if selected_acceleration is None else
min(selected_acceleration, preap_acceleration_cap))
downhill_error = None
if (self.downhill_surplus_mps > 0. and profile_eligible and not reset_state and self.allow_throttle and
v_cruise == v_cruise_kph * CV.KPH_TO_MS and v_ego >= v_cruise >= 5. and traffic_mode is False and
cruise_ceiling is None and curve_ceiling is None and navigation_target is None and
(coast_plan is None or not (coast_plan.force_decel or coast_plan.pulse_coasting)) and
(wheel_coast is None or not wheel_coast[0].conditional_stop) and
not self.fcw and not self.force_stop_plan.forcing and not self.force_stop_plan.should_stop and
self.force_stop_plan.approach_distance_m == 0. and not output_should_stop_mpc and not output_should_stop_e2e and
self.mpc.solution_status == 0 and not any(lead.present for lead in (sm['radarState'].leadOne, sm['radarState'].leadTwo))):
cs, orientation = sm['carState'], sm['carControl'].orientationNED
if (len(orientation) == 3 and not (cs.standstill or cs.gasPressed or cs.brakePressed) and
current_authority(sm, self.CP, drive_id, sample_now_ns) and
all(fresh_service(sm, name, drive_id, sample_now_ns) for name in ('radarState', 'modelV2', 'controlsState', 'deviceMotion'))):
limit = min(v_cruise + self.downhill_surplus_mps, V_CRUISE_MAX * CV.KPH_TO_MS)
downhill_error = downhill_speed_error(v_cruise, v_ego, cs.aEgo, orientation[1], limit=limit, delay=action_t)
if downhill_error is not None and navigation_ceiling(
sm, self.CP, sample_now_ns, limit + .25, slowdown_percent=self.navigation_slowdown_percent) is not None:
downhill_error = None
speed_step = False
if self.CP.carFingerprint == 'TESLA_MODEL_Y':
cs = sm['carState']
manual_cruise = (
profile_eligible and not reset_state and v_ego > MIN_ALLOW_THROTTLE_SPEED and
cs.canValid and not cs.canTimeout and not cs.gasPressed and not cs.brakePressed and not cs.standstill and
not sm['controlsState'].forceDecel and self.allow_throttle and not self.fcw and
not self.force_stop_plan.forcing and not self.force_stop_plan.should_stop and
not output_should_stop_mpc and not sm['modelV2'].action.shouldStop and
not any(lead.present for lead in (sm['radarState'].leadOne, sm['radarState'].leadTwo)) and
ceiling.effective_mps is None and curve.effective_mps is None and navigation_target is None and
(coast_plan is None or not (coast_plan.force_decel or coast_plan.pulse_coasting or
coast_plan.brake_floor is not None)) and self.mpc.solution_status == 0 and
math.isfinite(v_cruise_kph) and 0 < v_cruise_kph < V_CRUISE_UNSET and
v_cruise == v_cruise_kph * CV.KPH_TO_MS
)
if manual_cruise:
previous = self.previous_manual_cruise_kph
if previous is not None and abs(v_cruise_kph - previous) >= 0.5:
self.manual_cruise_step_until_ns = sample_now_ns + MODEL_Y_SPEED_STEP_DURATION_NS
self.previous_manual_cruise_kph = v_cruise_kph
speed_step = sample_now_ns < self.manual_cruise_step_until_ns
else:
self.previous_manual_cruise_kph = None
self.manual_cruise_step_until_ns = 0
self.a_cruise = get_cruise_accel(sm['selfdriveState'].experimentalMode, v_cruise, v_ego,
self.a_cruise, steer_angle_without_offset, self.CP, self.dt,
accel_coast, self.allow_throttle, cruise_profile,
base_brake_floor=global_floor, selected_acceleration_max=selected_acceleration, faster_takeoffs=faster_takeoffs,
a_target_prev=self.output_a_target,
ease_slc_braking=v_cruise == ceiling.effective_mps and not relevant_lead)
ease_slc_braking=v_cruise == ceiling.effective_mps and not relevant_lead, speed_step=speed_step,
downhill_error=downhill_error)
if self.button_cruise is not None:
button_target = self.button_cruise.sample(
sm, now_ns=sample_now_ns, drive_id=drive_id, target_speed=v_cruise,
@@ -438,7 +500,7 @@ class LongitudinalPlanner:
speed=self.v_desired_filter.x, previous_accel=self.output_a_target, reference=self.mpc,
blocked=bool(reset_state or not profile_eligible or not self.allow_throttle or traffic_mode is not False or self.fcw or
self.force_stop_plan.forcing or self.force_stop_plan.should_stop or output_should_stop_mpc or
sm['modelV2'].action.shouldStop or wheel_coast is not None or
sm['modelV2'].action.shouldStop or wheel_coast is not None or downhill_error is not None or
any(lead.present for lead in (sm['radarState'].leadOne, sm['radarState'].leadTwo))))
if button_target is not None:
self.a_cruise = button_target
@@ -524,7 +586,7 @@ class LongitudinalPlanner:
output_a_target, self.output_should_stop = self.ford_stop_approach.sample(
sm, now_ns=sample_now_ns, drive_id=drive_id, target=float(output_a_target),
stopping=self.output_should_stop, accel_min=ACCEL_MIN, active=profile_eligible and not reset_state)
self.output_a_target = np.clip(output_a_target, ACCEL_MIN, accel_ceiling)
self.output_a_target = np.clip(output_a_target, ACCEL_MIN, 0. if downhill_error is not None else accel_ceiling)
self.v_desired_filter.x = self.v_desired_filter.x + self.dt * (self.output_a_target + a_prev) / 2.0
+23 -2
View File
@@ -325,7 +325,21 @@ def starpilot_main():
ldw = LaneDepartureWarning()
from openpilot.starpilot.longitudinal.developer_tuning import read_tuning
longitudinal_planner = LongitudinalPlanner(CP, developer_tuning=read_tuning(params, CP))
from openpilot.starpilot.longitudinal.downhill_coast import read_surplus
from openpilot.starpilot.navigation.slowdown import DEFAULT_SLOWDOWN_PERCENT
navigation_slowdown_percent = DEFAULT_SLOWDOWN_PERCENT
if CP.openpilotLongitudinalControl and not CP.passive and not CP.dashcamOnly:
from openpilot.starpilot.navigation.owner import NavigationOwner
try:
navigation_slowdown_percent = NavigationOwner().read()['turnSlowdownPercent']
except (OSError, ValueError):
pass
downhill_available = CP.openpilotLongitudinalControl and not (CP.passive or CP.dashcamOnly or CP.notCar)
longitudinal_planner = LongitudinalPlanner(CP, developer_tuning=read_tuning(params, CP),
navigation_slowdown_percent=navigation_slowdown_percent)
downhill_request_ns = -1_000_000_000
if downhill_available and 'REPLAY' in os.environ:
longitudinal_planner.downhill_surplus_mps = read_surplus(params)
nudge_preferences = NudgePreferences(params)
# Saved-on features start only for a finalized, supported driving owner. Their
# current-source and longitudinal authority checks still run every frame.
@@ -389,6 +403,9 @@ def starpilot_main():
subscribed_services.extend(optional_slc)
subscribed_services.append('starpilotNavigation')
optional_conditional = ['starpilotNavigation'] + (['starpilotRadarState'] if conditional_host is not None else []) + optional_slc
if downhill_available:
subscribed_services.append('deviceMotion')
optional_conditional.append('deviceMotion')
sm = messaging.SubMaster(subscribed_services, poll='modelV2',
ignore_alive=optional_conditional, ignore_valid=optional_conditional,
ignore_avg_freq=optional_conditional)
@@ -401,7 +418,11 @@ def starpilot_main():
# Due saved-setting verification can block on Params. Complete it
# before acquiring the model and fast-source batch, not after that
# batch has already begun aging toward the CEM freshness deadline.
slc_lifecycle.refresh(time.monotonic_ns(), pending_actions=pending_slc_actions, pending_cruise=pending_slc_cruise)
settings_now_ns = time.monotonic_ns()
slc_lifecycle.refresh(settings_now_ns, pending_actions=pending_slc_actions, pending_cruise=pending_slc_cruise)
if downhill_available and not 0 <= settings_now_ns - downhill_request_ns < 1_000_000_000:
downhill_request_ns = settings_now_ns
longitudinal_planner.downhill_surplus_mps = read_surplus(params)
sm.update()
if sm.updated['modelV2']:
# Only explicit replay uses the recorded model timeline. In a live host,
+3 -2
View File
@@ -560,7 +560,8 @@ def main(demo=False):
turn_models = (model.lateral, model.longitudinal) if isinstance(model, LaboratoryPair) else (model,)
turn_supported = all(state.npy.get('desire') is not None and state.npy['desire'].shape[-1] == 8 for state in turn_models)
desire = navigation_turn.select(sm, time.monotonic_ns(), DH.desire,
supported=turn_supported, model_stop=bool(prev_action.shouldStop))
supported=turn_supported, model_stop=bool(prev_action.shouldStop),
waiting_for_lane=DH.waiting_for_lane(sm["carState"]))
is_rhd = sm["driverMonitoringState"].isRHD
frame_id = sm["narrowRoadCameraState"].frameId
v_ego = max(sm["carState"].vEgo, 0.)
@@ -691,7 +692,7 @@ def main(demo=False):
DH.update(car_state, sm['carControl'].latActive, lane_change_prob,
auto_evidence=auto_ready, engaged=auto_trigger_engaged(sm, runtime_lane_policy,
openpilot_longitudinal=bool(CP.openpilotLongitudinalControl), now_mono_ns=mono_now_ns),
navigation_turn=signal_turn or matching_turn_signal(sm, mono_now_ns, supported=navigation_turn.automatic_turn_enabled))
navigation_turn=signal_turn, route_turn=matching_turn_signal(sm, mono_now_ns, supported=navigation_turn.automatic_turn_enabled))
modelv2_send.modelV2.meta.laneChangeState = DH.lane_change_state
modelv2_send.modelV2.meta.laneChangeDirection = DH.lane_change_direction
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+10 -3
View File
@@ -473,6 +473,7 @@ void pandad_run(std::vector<Panda *> &pandas) {
constexpr AolSafetyProfile aol_profiles[] = {HONDA_AOL_PROFILE, HONDA_STOCK_AOL_PROFILE, HONDA_NIDEC_AOL_PROFILE, HYUNDAI_AOL_PROFILE, HYUNDAI_CLASSIC_AOL_PROFILE, HYUNDAI_LEGACY_AOL_PROFILE, GM_AOL_PROFILE, FORD_AOL_PROFILE, MAZDA_AOL_PROFILE, RIVIAN_AOL_PROFILE, CHRYSLER_AOL_PROFILE, TESLA_PREAP_AOL_PROFILE, TESLA_SCREEN_AOL_PROFILE, TOYOTA_AOL_PROFILE, NISSAN_AOL_PROFILE, VOLKSWAGEN_STOCK_AOL_PROFILE, VOLKSWAGEN_LONG_AOL_PROFILE, VOLKSWAGEN_MEB_AOL_PROFILE, VOLKSWAGEN_PQ_AOL_PROFILE, SUBARU_AOL_PROFILE, VOLVO_AOL_PROFILE};
const AolProfileRegistry aol_registry{aol_profiles, std::size(aol_profiles)};
AolAxisNegotiator aol_negotiator(aol_registry);
VolkswagenManualAolStartupPoll vw_startup_poll;
// Main loop: receive CAN first, then process lower priority panda and peripheral state.
while (!do_exit) {
if (!check_all_connected(pandas)) { break; }
@@ -483,10 +484,11 @@ void pandad_run(std::vector<Panda *> &pandas) {
{ process_peripheral_state(peripheral_panda, &pm, no_fan_control, is_onroad); }
}
// Process panda state at 10 Hz
if (rk.frame() % 10 == 0) {
// Process Panda state at 10 Hz, with one midpoint confirmation for pending manual MQB startup.
if (rk.frame() % 10 == 0 || vw_startup_poll.due(rk.frame())) {
sm.update(0);
engaged = sm.allAliveAndValid({"selfdriveState"}) && sm["selfdriveState"].getSelfdriveState().getEnabled();
const bool ordinary_engaged = sm.allAliveAndValid({"selfdriveState"}) && sm["selfdriveState"].getSelfdriveState().getEnabled();
engaged = ordinary_engaged;
// AOL axis and intent timestamps come from Python CLOCK_MONOTONIC.
// Keep the ordinary pandad/CAN BOOTTIME clock unchanged.
uint64_t now_ns = aol_monotonic_ns();
@@ -534,6 +536,11 @@ void pandad_run(std::vector<Panda *> &pandas) {
{ aol_after = (aol_write_ok && panda_safety.aolOwner() == panda) ? panda->get_aol_safety_state() : std::nullopt; }
if (aol_after && !panda_safety.aolStatusMatches(panda, *aol_after)) aol_after.reset();
auto outcome = aol_negotiator.complete(plan, aol_write_ok, aol_after);
const bool healthy_inventory = inventory.source_mono_time != 0U && inventory.slots.size() == pandas.size() &&
std::all_of(inventory.slots.begin(), inventory.slots.end(), [](const AolPandaSlot &slot) {
return !slot.safety_rx_checks_invalid && !slot.heartbeat_lost && slot.faults == 0U;
});
vw_startup_poll.observe(is_onroad, ordinary_engaged, healthy_inventory, plan, outcome);
if (aol_runtime) {
MessageBuilder axis_status_msg;
auto axis_status_event = axis_status_msg.initEvent();
Binary file not shown.
@@ -89,7 +89,39 @@ void queue(FakeTransport &transport, const aol_safety_health_t &before,
}
} // namespace
static void test_manual_mqb_startup_poll() {
const AolWritePlan lat{true, 1U, true};
const aol_safety_health_t pending{AOL_SAFETY_PROTOCOL_MAGIC, AOL_SAFETY_PROTOCOL_VERSION,
1U, 0U, VOLKSWAGEN_LONG_AOL_PROFILE.mode, 25U, 1U};
const AolOutcome ready{true, pending, "cold"};
for (unsigned refusal = 0; refusal < 11U; ++refusal) {
VolkswagenManualAolStartupPoll poll;
auto plan = lat;
auto outcome = ready;
if (refusal == 1U) outcome.status->safety_param = 9U;
if (refusal == 2U) outcome.status->safety_mode = 34U;
if (refusal == 3U) outcome.status->permission_mask = 1U;
if (refusal == 4U) plan.request_mask = 3U;
if (refusal == 5U) plan.retain_lateral_arm = false;
if (refusal == 6U) outcome.compatible = false;
if (refusal == 7U) outcome.session.clear();
poll.observe(refusal != 8U, refusal == 9U, refusal != 10U, plan, outcome);
for (uint64_t frame = 1U; frame < 10U; ++frame) {
assert(poll.due(frame) == (refusal == 0U && frame == 5U));
}
assert(!poll.due(15U));
if (refusal == 0U) {
poll.observe(true, false, true, lat, ready);
assert(!poll.due(15U));
}
poll.observe(false, false, true, lat, ready);
poll.observe(true, false, true, lat, ready);
assert(poll.due(25U));
}
}
int main() {
test_manual_mqb_startup_poll();
for (uint32_t word = 0U; word <= 65535U; word++) {
auto subaru = status();
subaru.safety_mode = 11U;
@@ -97,7 +129,7 @@ int main() {
subaru.capability_flags = 1U;
const bool expected = (word == 16U) || (word == 0U) || (word == 1U) || (word == 17U) ||
(word == 209U) || (word == 465U) || (word == 145U) || (word == 1169U) || (word == 1425U) || (word == 401U) || (word == 177U) || (word == 8U) || (word == 520U) || (word == 512U) || (word == 2225U) ||
(word == 4096U) || (word == 4104U) || (word == 4608U) || (word == 4616U);
(word == 4096U) || (word == 4104U) || (word == 4608U) || (word == 4616U) || (word == 8192U) || (word == 8200U) || (word == 1041U) || (word == 2065U) || (word == 3089U);
assert(aol_capable(subaru, 11U, VEHICLE_REGISTRY) == expected);
subaru.capability_flags = 0U;
assert(!aol_capable(subaru, 11U, VEHICLE_REGISTRY));
@@ -263,30 +295,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;
@@ -511,7 +559,7 @@ int main() {
constexpr uint16_t sportage_long_words[] = {0x0804U, 0x0806U, 0x080CU, 0x080EU, 0x0814U, 0x0816U,
0x0894U, 0x0896U, 0x0824U, 0x0826U, 0x082CU, 0x082EU};
for (uint32_t word = 0U; word <= 0xFFFFU; ++word) {
bool expected = word == 0x0C0CU || word == 0x0C0EU || word == 0x0C2CU || word == 0x0C2EU || word == 0x28B4U || word == 0x080DU || word == 0x2815U || word == 0x2895U || word == 0x0815U || word == 0x0895U || word == 0x8815U || word == 0x8895U || word == 0x5491U || word == 0x5C91U || word == 0x5C95U || word == 0x5495U;
bool expected = word == 0x1C0CU || word == 0x0C0CU || word == 0x0C0EU || word == 0x0C2CU || word == 0x0C2EU || word == 0x28B4U || word == 0x080DU || word == 0x2815U || word == 0x2895U || word == 0x0815U || word == 0x0895U || word == 0x8815U || word == 0x8895U || word == 0x5491U || word == 0x5C91U || word == 0x5C95U || word == 0x5495U;
for (uint16_t stock_word : stock_canfd_words) {
expected = expected || word == stock_word;
}
+57 -17
View File
@@ -6,6 +6,7 @@ import threading
import uuid
from copy import copy
from dataclasses import replace
from typing import cast
import openpilot.cereal.messaging as messaging
@@ -261,10 +262,7 @@ class SelfdriveD:
# Observational only. Do not cache this qualification for authority decisions.
# Determine startup event
official_starpilot = (build_metadata.openpilot.git_normalized_origin.lower() == 'github.com/starpilothq/starpilot' and
build_metadata.channel in ('stable', 'testing'))
standard_startup = official_starpilot or (build_metadata.openpilot.comma_remote and build_metadata.tested_channel)
self.startup_event = EventName.startup if standard_startup else EventName.startupMaster
self.startup_event = EventName.startup if build_metadata.standard_startup else EventName.startupMaster
if HARDWARE.get_device_type() == 'mici':
self.startup_event = None
if not car_recognized:
@@ -896,9 +894,9 @@ class SelfdriveD:
qualified_toyota(self.CP, marked_only=True) or qualified_mazda(self.CP, marked_only=True) or
self.ford_source_deadline_supported())
def held_axis_override_wait(self, CS, proof, now_ns, *, fresh_successor=False):
def held_axis_override_wait(self, CS, proof, now_ns, *, fresh_successor=False, fresh_mqb_brake=False):
"""Recognize an already applied override; never admit a new physical edge."""
if (proof is None or not (qualified_ioniq6(self.CP) or qualified_gm(self.CP) or
if (proof is None or not (fresh_mqb_brake or qualified_ioniq6(self.CP) or qualified_gm(self.CP) or
(self.CP.brand == 'hyundai' and self.source_deadline_deferral_supported()) or
self.ford_source_deadline_supported()) or not self.sm.seen['carControl'] or
not self.sm.valid['carControl'] or self.sm['carControl'].longActive or
@@ -915,7 +913,9 @@ class SelfdriveD:
held_brake = bool(proof[8] and not proof[9] and not self.enabled and not self.active and
(previous.brakePressed or previous.regenBraking) and
all(valid and sample.brakePressed == previous.brakePressed and sample.regenBraking == previous.regenBraking
and not sample.gasPressed and not sample.buttonEvents for sample, valid in samples))
and not sample.gasPressed and not sample.buttonEvents
and (not fresh_mqb_brake or sample.canValid and not sample.canTimeout and
not sample.steerFaultTemporary and not sample.steerFaultPermanent) for sample, valid in samples))
ford_lateral_gas = bool(self.ford_source_deadline_supported() and proof[8] and not proof[9] and
(not self.enabled and not self.active and not CS.cruiseState.enabled or
self.enabled and self.active and CS.cruiseState.enabled and proof[7]))
@@ -1305,6 +1305,12 @@ class SelfdriveD:
else:
# Retire only this presentation; retain every original safety alert.
self.AM.alerts.pop('aolAvailability/warning', None)
if self.aol_axis_decision.aol_speed_paused and ET.WARNING not in self.state_machine.current_alert_types:
# Preserve the existing speed warning duration even when only AOL was on.
speed_alert = copy(cast(Alert, self.events.event_rules[EventName.speedTooHigh][ET.WARNING]))
speed_alert.alert_type = 'speedTooHigh/warning'
speed_alert.event_type = 'aolSpeedPause'
alerts.append(speed_alert)
if getattr(self, 'jetlink_link_lost', False):
alerts.append(jetlink_lost_alert())
if (self.CP.brand == 'ford' or getattr(self, 'hkg_angle_steering', False)) and CS.steeringPressed:
@@ -1605,6 +1611,12 @@ class SelfdriveD:
previous=decision, source_ns=source_ns, now_ns=now_ns, axis_session_id=self.aol_session_id,
cancel_samples=getattr(self, 'car_state_envelopes', ())):
user_disable = any(event.userDisable and event.name != EventName.buttonCancel for event in self.events.to_msg())
if user_disable and fresh_successor and decision.lateral_active and not decision.longitudinal_active and self.CP.brand == 'mazda':
from openpilot.starpilot.car.mazda.aol import physical_cancel_lateral_allowed
native = current_native(self.sm, self.CP, now_ns=now_ns, axis_session_id=self.aol_session_id)
if physical_cancel_lateral_allowed(self.CP, CS, intent, native, settings=self.aol_settings,
previous=decision, source_ns=source_ns, now_ns=now_ns, axis_session_id=self.aol_session_id):
user_disable = any(event.userDisable and event.name != EventName.buttonCancel for event in self.events.to_msg())
if user_disable and fresh_successor and self.ford_source_deadline_supported():
from openpilot.starpilot.car.ford.aol import physical_cancel_lateral_allowed
native = current_native(self.sm, self.CP, now_ns=now_ns, axis_session_id=self.aol_session_id)
@@ -1612,8 +1624,16 @@ class SelfdriveD:
previous=decision, source_ns=source_ns, now_ns=now_ns, axis_session_id=self.aol_session_id, allow_brake=True):
user_disable = any(event.userDisable and event.name not in
(EventName.buttonCancel, EventName.pcmDisable, EventName.pedalPressed) for event in self.events.to_msg())
fresh_mqb_brake = False
if (user_disable and fresh_successor and self.CP.brand == 'volkswagen' and
decision.desired_lateral and not decision.desired_longitudinal and not decision.longitudinal_active and
intent.allowedLatch and intent.lateralArmed and not intent.pauseLateral and CS.brakePressed):
from opendbc.car.volkswagen.long_aol import qualified as mqb_long_qualified
from opendbc.car.volkswagen.stock_aol import qualified as mqb_stock_qualified
fresh_mqb_brake = mqb_long_qualified(self.CP, marked_only=True) or mqb_stock_qualified(self.CP, marked_only=True)
held_brake, held_gas = self.held_axis_override_wait(CS, proof, now_ns,
fresh_successor=fresh_successor and (qualified_gm(self.CP) or self.ford_source_deadline_supported()))
fresh_successor=fresh_successor and (qualified_gm(self.CP) or self.ford_source_deadline_supported()),
fresh_mqb_brake=fresh_mqb_brake)
if user_disable and (held_brake or self.ford_source_deadline_supported() and held_gas):
# A fresh same-owner source can establish its own LAT permission after
# an old output expires. Held-brake continuity does not renew that output;
@@ -1910,7 +1930,7 @@ class SelfdriveD:
from openpilot.starpilot.car.honda.aol import (below_engage_lateral_allowed as honda_below_engage_lateral_allowed,
physical_cancel_lateral_allowed as honda_cancel_lateral_allowed)
from openpilot.starpilot.car.ford.aol import physical_cancel_lateral_allowed as ford_cancel_lateral_allowed
from openpilot.starpilot.car.subaru.aol import sng_standstill_lateral_inhibit
from openpilot.starpilot.car.subaru.aol import known_paddle_pause, sng_standstill_lateral_inhibit
from openpilot.starpilot.car.volkswagen.aol import (lateral_output_inhibited as volkswagen_lateral_output_inhibited,
below_engage_lateral_allowed as volkswagen_below_engage_lateral_allowed,
physical_cancel_lateral_allowed as volkswagen_cancel_lateral_allowed)
@@ -1920,9 +1940,13 @@ class SelfdriveD:
from openpilot.starpilot.car.volkswagen.aol import lateral_immediate_disable
retained_dm_lateral, lateral_events = lateral_event_context(self, CS, intent, native, now_ns, ordinary_lag)
reverse_pause = known_reverse_pause(CS, getattr(self, 'car_state_samples', ()))
gear_pause = reverse_pause or known_paddle_pause(self.CP, CS, getattr(self, 'car_state_samples', ()))
pause_brake_mps = self.aol_settings.pause_brake_mps if self.aol_settings is not None else 0.0
if reverse_pause:
if gear_pause:
lateral_events = [event for event in lateral_events if event not in (EventName.wrongGear, EventName.reverseGear)]
speed_limited = EventName.speedTooHigh in lateral_events
if speed_limited:
lateral_events.remove(EventName.speedTooHigh)
below_entry_speed = EventName.belowEngageSpeed in lateral_events
honda_below_entry_speed = below_entry_speed and honda_below_engage_lateral_allowed(
self.CP, CS, intent, previously_active=getattr(self, 'aol_ever_active', False))
@@ -1935,7 +1959,7 @@ class SelfdriveD:
is_ordinary_ascm_profile(self.CP, longitudinal=True) or
is_ordinary_sdgm_profile(self.CP, longitudinal=True) or
(self.CP.carFingerprint in (GM_CAR.BUICK_LACROSSE, GM_CAR.CHEVROLET_SUBURBAN) and qualified_gm(self.CP))))
return decide_axes(
decision = decide_axes(
standard_lateral=self.active, standard_longitudinal=bool(self.enabled and self.CP.openpilotLongitudinalControl and
not honda_below_entry_speed and
not raw_longitudinal_withdrawal(self.CP, CS, self.sm, native, session=self.aol_session_id, now_ns=now_ns) and
@@ -1986,13 +2010,24 @@ class SelfdriveD:
self.sm['driverMonitoringState'].alwaysOnLockout or
self.sm['driverMonitoringState'].alertLevel == AlertLevel.three)),
pause_brake_mps=pause_brake_mps,
gear_pause=reverse_pause,
gear_pause=gear_pause,
lateral_inhibit=self.aol_dm_lateral_inhibit or sng_standstill_lateral_inhibit(
self.CP, CS, initial_wait=bool(native is None or not native.lateralAllowed)) or
volkswagen_lateral_output_inhibited(self.CP, CS) or any(
sample.steerFaultTemporary or pause_brake_mps > 0 and sample.brakePressed and not sample.standstill and
sample.vEgo < pause_brake_mps
for sample, _ in getattr(self, 'car_state_samples', ())))
if not speed_limited:
return decision
# Withdraw both requests at the existing ceiling. Keep only the already
# established driver's latch while the normal health and entry gates pass.
previous = self.aol_axis_decision
if (decision.native_acknowledged and decision.desired_lateral and
(previous.lateral_active or previous.aol_speed_paused) and
intent.allowedLatch and intent.lateralArmed and not self.events.contains(ET.USER_DISABLE) and
healthy_transport(self.sm, self.CP, CS, self.aol_session_id, now_ns, native)):
return AxisDecision(native_acknowledged=True, aol_speed_paused=True)
return AxisDecision()
def cold_volkswagen_main_readiness(self, CS, intent, now_ns):
from opendbc.car.volkswagen.long_aol import qualified as volkswagen_long_qualified
@@ -2264,9 +2299,11 @@ class SelfdriveD:
self.ordinary_native_long_withdrawal(
CS, native, previous, requested, intent, source_current=source_current, now_ns=now_ns))
from openpilot.starpilot.car.hyundai.aol import expected_stopped_lateral_denial
from openpilot.starpilot.car.mazda.aol import expected_stopped_lateral_denial as mazda_stopped_denial
stopped_lateral_withdrawal = bool(source_current and requested.desired_lateral and
expected_stopped_lateral_denial(self.CP, CS, native, sm=self.sm,
axis_session_id=self.aol_session_id, now_ns=now_ns))
(expected_stopped_lateral_denial(self.CP, CS, native, sm=self.sm,
axis_session_id=self.aol_session_id, now_ns=now_ns) or
mazda_stopped_denial(self.CP, CS, native, sm=self.sm, axis_session_id=self.aol_session_id, now_ns=now_ns)))
lost_permission = bool(lost_honda_lateral_grant or native is not None and not driver_override and (
previous.lateral_active and requested.desired_lateral and native.requestedLateral and
not native.lateralAllowed and not stopped_lateral_withdrawal and
@@ -2352,15 +2389,17 @@ class SelfdriveD:
# Temporary EPS withdraws steering commands without revoking the armed
# latch. Keep the event and ordinary soft-disable behavior unchanged.
from openpilot.starpilot.aol.seatbelt import seatbelt_lateral_soft_event_allowed
from openpilot.starpilot.car.subaru.aol import known_paddle_pause
reverse_pause = known_reverse_pause(CS, getattr(self, 'car_state_samples', ()))
gear_pause = reverse_pause or known_paddle_pause(self.CP, CS, getattr(self, 'car_state_samples', ()))
aol_hard_soft_fault = any(event.softDisable and not (
event.name == EventName.doorOpen or event.name in LONGITUDINAL_ONLY_EVENTS or
event.name == EventName.wrongGear and reverse_pause or
event.name == EventName.wrongGear and gear_pause or
event.name == EventName.steerTempUnavailable and CS.steerFaultTemporary and not CS.steerFaultPermanent or
seatbelt_lateral_soft_event_allowed(self.CP, CS, intent, native, event,
source_ns=self.aol_car_state_log_ns, now_ns=now_ns, axis_session_id=self.aol_session_id,
pending_lateral_request=not previous.lateral_active and not self.aol_authority_lost,
gear_pause=reverse_pause))
gear_pause=gear_pause))
for event in self.events.to_msg())
cold_main_wait = self.cold_gm_main_readiness(CS, intent, now_ns)
cold_park_wait = (self.cold_gm_park_readiness(CS, intent, now_ns) or
@@ -2419,7 +2458,8 @@ class SelfdriveD:
elif getattr(self, 'aol_availability_long_inhibit', False):
decision = self.aol_axis_decision
self.aol_axis_decision = AxisDecision(desired_lateral=decision.desired_lateral,
lateral_active=decision.lateral_active, native_acknowledged=decision.native_acknowledged)
lateral_active=decision.lateral_active, native_acknowledged=decision.native_acknowledged,
aol_speed_paused=decision.aol_speed_paused)
if pause:
# Negotiate the fresh lateral request while output and ordinary LONG
# remain off; requiring an active ack before requesting would deadlock.
@@ -8,6 +8,7 @@ from openpilot.common.params import Params
from opendbc.car import structs
from openpilot.selfdrive.selfdrived.alertmanager import AlertManager
from openpilot.selfdrive.selfdrived.events import Events, ET, Alert, Priority
from openpilot.starpilot.aol.runtime import AxisDecision
from openpilot.starpilot.controllers.mode_actions import SwitchbackCooldown
from openpilot.selfdrive.selfdrived.selfdrived import SelfdriveD
from openpilot.starpilot.longitudinal.force_stop_alert import HoldAlertState
@@ -42,6 +43,7 @@ class Sources:
def fixture():
drive = SelfdriveD.__new__(SelfdriveD)
drive.aol_axis_decision = AxisDecision()
drive.CP = structs.CarParams(openpilotLongitudinalControl=True)
drive.enabled, drive.personality, drive.is_metric = True, log.LongitudinalPersonality.standard, False
vars(drive)['state_machine'] = NS(current_alert_types=[ET.WARNING], soft_disable_timer=0)
@@ -7,6 +7,7 @@ import unittest
from opendbc.car.structs import car
from openpilot.cereal import log
from openpilot.starpilot.aol.runtime import AxisDecision
from openpilot.starpilot.controllers.mode_actions import SwitchbackCooldown
from openpilot.selfdrive.selfdrived.alertmanager import AlertManager
from openpilot.selfdrive.selfdrived.events import Alert, ET, EVENTS, Events, Priority
@@ -34,6 +35,7 @@ class TestLaneChangeAlert(unittest.TestCase):
model = SimpleNamespace(frameId=frame_id, timestampEof=10_000_000_000,
meta=SimpleNamespace(laneChangeDirection="left"))
drive = SelfdriveD.__new__(SelfdriveD)
drive.aol_axis_decision = AxisDecision()
drive.events = Events()
drive.events.add(EventName.preLaneChangeLeft)
self.enterContext(patch.object(drive, "state_machine", SimpleNamespace(current_alert_types=[ET.WARNING], soft_disable_timer=0), create=True))
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+3 -3
View File
@@ -1,4 +1,5 @@
import time
from openpilot.starpilot.ui.brand import home_description
from openpilot.starpilot.ui.raylib import rl
from collections.abc import Callable
from enum import IntEnum
@@ -232,6 +233,5 @@ class HomeLayout(Widget):
self._prev_alerts_present = alerts_present
def _get_version_text(self) -> str:
brand = "openpilot"
description = self.params.get("UpdaterCurrentDescription")
return f"{brand} {description}" if description else brand
description = home_description(self.params.get("UpdaterCurrentDescription") or "")
return f"StarPilot {description}"
+2 -2
View File
@@ -4,6 +4,7 @@ from dataclasses import dataclass
from collections.abc import Callable
from openpilot.cereal import log
from openpilot.selfdrive.ui.ui_state import ui_state
from openpilot.starpilot.ui.temperature import format_temperature
from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos, FONT_SCALE
from openpilot.system.ui.lib.multilang import tr, tr_noop
from openpilot.system.ui.lib.text_measure import measure_text_cached
@@ -119,8 +120,7 @@ class Sidebar(Widget):
self._net_strength = max(0, min(5, strength.raw + 1)) if strength.raw > 0 else 0
def _update_temperature_status(self, device_state):
temperature = device_state.maxTempC
value = f"{temperature:.0f}°C" if ui_state.is_metric else f"{temperature * 1.8 + 32:.0f}°F"
value = format_temperature(device_state.maxTempC, ui_state.temperature_metric)
color = Colors.GOOD if device_state.thermalStatus == ThermalStatus.ok else Colors.DANGER
self._temp_status.update(tr_noop("TEMP"), value, color)
@@ -303,9 +303,10 @@ class MiciOffroadAlerts(Scroller):
parts = new_desc.split(" / ")
if len(parts) > 3:
version, date = parts[0], parts[3]
version_string = f"\nopenpilot {version}, {date}\n"
if version:
version_string = f"\nStarPilot {version}, {date}"
update_alert_data.text = f"Update available {version_string}. Click to update. Read the release notes at blog.comma.ai."
update_alert_data.text = f"Update available{version_string}\nClick to update."
update_alert_data.visible = True
active_count += 1
else:
@@ -23505,4 +23505,82 @@ msgstr ""
#: openpilot/starpilot/galaxy/web/js/spotify.js
msgid "Storage & Account"
#: openpilot/starpilot/ui/sounds_owner.py
msgid "Plays a simulated engine on the car speakers that follows the accelerator pedal."
msgstr ""
#: openpilot/starpilot/ui/sounds_owner.py
msgid "Engine Type"
msgstr ""
#: openpilot/starpilot/ui/sounds_owner.py
msgid "Chooses which engine is simulated."
msgstr ""
#: openpilot/starpilot/ui/sounds_owner.py
msgid "Engine Sound Volume"
msgstr ""
#: openpilot/starpilot/ui/sounds_owner.py
msgid "Sets how loud the engine is before the car's own volume control."
msgstr ""
#: openpilot/starpilot/galaxy/setting_descriptions.py
msgid "Plays a simulated engine on the car speakers that follows the accelerator pedal, including revving in Park or Neutral. Uses the audio output chosen under Spotify and Phone Audio, and goes quiet while an alert sounds."
msgstr ""
#: openpilot/starpilot/engine_sound/profiles.py
msgid "BMW M3"
msgstr ""
#: openpilot/starpilot/engine_sound/profiles.py
msgid "BMW M3 Deep"
msgstr ""
#: openpilot/starpilot/engine_sound/profiles.py
msgid "F1 Car"
msgstr ""
#: openpilot/starpilot/engine_sound/profiles.py
msgid "Ferrari F136"
msgstr ""
#: openpilot/starpilot/engine_sound/profiles.py
msgid "Hellcat"
msgstr ""
#: openpilot/starpilot/engine_sound/profiles.py
msgid "Ioniq 5N Ignition"
msgstr ""
#: openpilot/starpilot/engine_sound/profiles.py
msgid "Jaguar F-Type"
msgstr ""
#: openpilot/starpilot/engine_sound/profiles.py
msgid "Nissan Super GT1"
msgstr ""
#: openpilot/starpilot/engine_sound/profiles.py
msgid "Nissan Super GT2"
msgstr ""
#: openpilot/starpilot/engine_sound/profiles.py
msgid "Supra Turbo"
msgstr ""
#: openpilot/starpilot/engine_sound/profiles.py
msgid "LFA"
msgstr ""
#: openpilot/starpilot/ui/sounds_owner.py
msgid "Engine Sounds"
msgstr ""
#: openpilot/starpilot/ui/sounds_owner.py
msgid "Plays on the car speakers through the Spotify and Phone Audio output."
msgstr ""
#: openpilot/starpilot/ui/sounds_owner.py
msgid "Choose an engine; it revs once so you can hear it."
msgstr ""
@@ -23517,3 +23517,82 @@ msgstr "Lenkung und Tasten"
msgid "Storage & Account"
msgstr "Speicher und Konto"
#: openpilot/starpilot/ui/sounds_owner.py
msgid "Plays a simulated engine on the car speakers that follows the accelerator pedal."
msgstr "Spielt über die Fahrzeuglautsprecher einen simulierten Motor ab, der dem Gaspedal folgt."
#: openpilot/starpilot/ui/sounds_owner.py
msgid "Engine Type"
msgstr "Motortyp"
#: openpilot/starpilot/ui/sounds_owner.py
msgid "Chooses which engine is simulated."
msgstr "Wählt den simulierten Motor."
#: openpilot/starpilot/ui/sounds_owner.py
msgid "Engine Sound Volume"
msgstr "Lautstärke des Motorsounds"
#: openpilot/starpilot/ui/sounds_owner.py
msgid "Sets how loud the engine is before the car's own volume control."
msgstr "Legt die Lautstärke des Motors vor der Lautstärkeregelung des Fahrzeugs fest."
#: openpilot/starpilot/galaxy/setting_descriptions.py
msgid "Plays a simulated engine on the car speakers that follows the accelerator pedal, including revving in Park or Neutral. Uses the audio output chosen under Spotify and Phone Audio, and goes quiet while an alert sounds."
msgstr "Spielt über die Fahrzeuglautsprecher einen simulierten Motor ab, der dem Gaspedal folgt, auch beim Hochdrehen in Parkstellung oder Neutral. Nutzt die unter Spotify und Telefon-Audio gewählte Audioausgabe und verstummt, solange ein Warnton ertönt."
#: openpilot/starpilot/engine_sound/profiles.py
msgid "BMW M3"
msgstr "BMW M3"
#: openpilot/starpilot/engine_sound/profiles.py
msgid "BMW M3 Deep"
msgstr "BMW M3 Deep"
#: openpilot/starpilot/engine_sound/profiles.py
msgid "F1 Car"
msgstr "F1 Car"
#: openpilot/starpilot/engine_sound/profiles.py
msgid "Ferrari F136"
msgstr "Ferrari F136"
#: openpilot/starpilot/engine_sound/profiles.py
msgid "Hellcat"
msgstr "Hellcat"
#: openpilot/starpilot/engine_sound/profiles.py
msgid "Ioniq 5N Ignition"
msgstr "Ioniq 5N Ignition"
#: openpilot/starpilot/engine_sound/profiles.py
msgid "Jaguar F-Type"
msgstr "Jaguar F-Type"
#: openpilot/starpilot/engine_sound/profiles.py
msgid "Nissan Super GT1"
msgstr "Nissan Super GT1"
#: openpilot/starpilot/engine_sound/profiles.py
msgid "Nissan Super GT2"
msgstr "Nissan Super GT2"
#: openpilot/starpilot/engine_sound/profiles.py
msgid "Supra Turbo"
msgstr "Supra Turbo"
#: openpilot/starpilot/engine_sound/profiles.py
msgid "LFA"
msgstr "LFA"
#: openpilot/starpilot/ui/sounds_owner.py
msgid "Engine Sounds"
msgstr "Motorsounds"
#: openpilot/starpilot/ui/sounds_owner.py
msgid "Plays on the car speakers through the Spotify and Phone Audio output."
msgstr "Spielt über die Fahrzeuglautsprecher mit der unter Spotify und Telefon-Audio gewählten Ausgabe."
#: openpilot/starpilot/ui/sounds_owner.py
msgid "Choose an engine; it revs once so you can hear it."
msgstr "Wähle einen Motor; er dreht einmal hoch, damit du ihn hörst."
@@ -23517,3 +23517,82 @@ msgstr "Dirección y botones"
msgid "Storage & Account"
msgstr "Almacenamiento y cuenta"
#: openpilot/starpilot/ui/sounds_owner.py
msgid "Plays a simulated engine on the car speakers that follows the accelerator pedal."
msgstr "Reproduce un motor simulado en los altavoces del coche que sigue el pedal del acelerador."
#: openpilot/starpilot/ui/sounds_owner.py
msgid "Engine Type"
msgstr "Tipo de motor"
#: openpilot/starpilot/ui/sounds_owner.py
msgid "Chooses which engine is simulated."
msgstr "Elige qué motor se simula."
#: openpilot/starpilot/ui/sounds_owner.py
msgid "Engine Sound Volume"
msgstr "Volumen del sonido del motor"
#: openpilot/starpilot/ui/sounds_owner.py
msgid "Sets how loud the engine is before the car's own volume control."
msgstr "Ajusta el volumen del motor antes del control de volumen del propio coche."
#: openpilot/starpilot/galaxy/setting_descriptions.py
msgid "Plays a simulated engine on the car speakers that follows the accelerator pedal, including revving in Park or Neutral. Uses the audio output chosen under Spotify and Phone Audio, and goes quiet while an alert sounds."
msgstr "Reproduce un motor simulado en los altavoces del coche que sigue el pedal del acelerador, incluso al acelerar en Estacionamiento o Punto muerto. Usa la salida de audio elegida en Spotify y audio del teléfono, y se silencia mientras suena una alerta."
#: openpilot/starpilot/engine_sound/profiles.py
msgid "BMW M3"
msgstr "BMW M3"
#: openpilot/starpilot/engine_sound/profiles.py
msgid "BMW M3 Deep"
msgstr "BMW M3 Deep"
#: openpilot/starpilot/engine_sound/profiles.py
msgid "F1 Car"
msgstr "F1 Car"
#: openpilot/starpilot/engine_sound/profiles.py
msgid "Ferrari F136"
msgstr "Ferrari F136"
#: openpilot/starpilot/engine_sound/profiles.py
msgid "Hellcat"
msgstr "Hellcat"
#: openpilot/starpilot/engine_sound/profiles.py
msgid "Ioniq 5N Ignition"
msgstr "Ioniq 5N Ignition"
#: openpilot/starpilot/engine_sound/profiles.py
msgid "Jaguar F-Type"
msgstr "Jaguar F-Type"
#: openpilot/starpilot/engine_sound/profiles.py
msgid "Nissan Super GT1"
msgstr "Nissan Super GT1"
#: openpilot/starpilot/engine_sound/profiles.py
msgid "Nissan Super GT2"
msgstr "Nissan Super GT2"
#: openpilot/starpilot/engine_sound/profiles.py
msgid "Supra Turbo"
msgstr "Supra Turbo"
#: openpilot/starpilot/engine_sound/profiles.py
msgid "LFA"
msgstr "LFA"
#: openpilot/starpilot/ui/sounds_owner.py
msgid "Engine Sounds"
msgstr "Sonidos del motor"
#: openpilot/starpilot/ui/sounds_owner.py
msgid "Plays on the car speakers through the Spotify and Phone Audio output."
msgstr "Suena en los altavoces del coche a través de la salida de Spotify y audio del teléfono."
#: openpilot/starpilot/ui/sounds_owner.py
msgid "Choose an engine; it revs once so you can hear it."
msgstr "Elige un motor; acelera una vez para que puedas oírlo."

Some files were not shown because too many files have changed in this diff Show More