Compare commits

..

4 Commits

Author SHA1 Message Date
Danny 007935f816 Build 2026-11-23 14:36:46 -08:00
Danny 9d44060e03 MDNS: Add to Comma Menu and Galaxy 2026-11-23 14:34:00 -08:00
Danny 33eaa9d781 Galaxy: Open by galaxy.local on Every Network, Including the Hotspot 2026-11-23 14:34:00 -08:00
Danny 6a33facb4c Galaxy: Hold Connection Slots Only While a Request Runs 2026-11-23 14:34:00 -08:00
343 changed files with 2071 additions and 44878 deletions
-4
View File
@@ -49,7 +49,3 @@ The explicit StarPilot [jacobw Subaru adapter](opendbc_repo/opendbc/car/subaru/J
The previous optional StarPilot Controller, formerly in `openpilot/starpilot/car/ford/starpilot_tuning.py`, restored demand tuning from StarPilot `8da0c9d916^`, descended from BluePilot bp-7.0 `e1d051d7ba270261b4455068bd68f1a58db15a4a` through StarPilot `2efe6017bfe14cee4807833e05f9a7f6ba255cdb`. Contributors to that lineage include Alan Polk, John Christman, Jacob Neulight, tonesto7 and Haibin Wen. The current protocol adapter is maintained by StarPilot separately from the pinned BluePilot library; this attribution does not imply BluePilot maintains or endorses the adapted tune.
The current StarPilot Controller replaces that historical curvature-primary tune with a separately maintained adaptation of BluePilot v0.2.1's angle strategy (`2b9dc6cc784faac47a1885d0bda0561f7b76f74d`, `core/lateral_angle_ext.py`). Alan Polk is the principal controller author; John Christman contributed angle-mode anti-stall work, Jacob Neulight the pinion/shadow measurement, Nathan Ingraham and Praeuner high-speed damping, and other contributors are retained in the pinned library's `CREDITS.md`. StarPilot adds bounded small-signal conditioning ahead of the unchanged angle limit chain. This adaptation is not maintained or endorsed by BluePilot; the pinned library and its imported hooks are unchanged.
## Uniden radar detector link
The Uniden detector link builds on **inauner's** earlier Uniden R4/R8/R9 work in [inauner/StarPilot, uniden](https://github.com/inauner/StarPilot/tree/c4b694b2ac8742ddec44123d53f1f84d2990b47e) (`uniden_protocol.py`, `uniden_r4.py`, `uniden_radar_d.py`, the Galaxy Uniden panel and the radar alert banner), which established the detector's BLE alert flow and the Galaxy/UI integration approach. This branch's monitor, transport, widgets and tests are a separate implementation on the current StarPilot Bluetooth owner; the experimental settings and speed-limit slowdown logic are not included. The alert parser and command framing are based on AegisX86/UnidenR8wlink (see THIRD_PARTY_NOTICES.md).
-4
View File
@@ -154,7 +154,3 @@ The Subaru angle implementation includes work from Jacob Waller's `jul-angle-bas
The historical tuning formerly in `openpilot/starpilot/car/ford/starpilot_tuning.py` included the BluePilot bp-7.0-derived work identified in [CREDITS.md](CREDITS.md#starpilot-ford-demand-tuning). The published upstream license notices retained above and in the pinned BluePilot library remain applicable to the adapted source. StarPilot's separate protocol adapter does not modify those notices or resolve their scope.
The angle-primary adaptation in `openpilot/starpilot/car/ford/starpilot_controller.py` is derived from BluePilot v0.2.1. It retains the complete MIT copyright and permission notice in `opendbc_repo/opendbc/bluepilot_lateral/LICENSE`, including Comma.ai, BluePilot and StarPilot contributors. See the contributor attribution in `CREDITS.md`.
## Uniden detector protocol
The detector alert parser and command framing in `openpilot/starpilot/uniden/` are based on [AegisX86/UnidenR8wlink](https://github.com/AegisX86/UnidenR8wlink)'s MIT-licensed protocol documentation, copyright (c) 2026 Aegis "P.R Aigis". The complete notice is retained in [UPSTREAM-LICENSE](openpilot/starpilot/uniden/UPSTREAM-LICENSE).
+6 -11
View File
@@ -1,4 +1,4 @@
"""Normal-bus discovery for Ford vehicles."""
"""Normal-bus discovery for explicitly selected Ford CAN-FD vehicles."""
import time
from opendbc.car.ford.values import CAR, FordFlags
@@ -42,8 +42,7 @@ 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}
CAMERA_STEERING_LAYOUT = {(2, 0x3D3): 8, (2, 0x3D6): 8}
(0, 0x217): 8, (2, 0x3CA): 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):
@@ -56,10 +55,6 @@ 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
@@ -72,9 +67,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 (expected := NORMAL_BUS0_LAYOUT.get(key) or CAMERA_STEERING_LAYOUT.get(key)) is not None:
if key in NORMAL_BUS0_LAYOUT:
length = len(frame.dat)
malformed |= length != expected
malformed |= length != NORMAL_BUS0_LAYOUT[key]
received[key] = length
return packets
@@ -82,11 +77,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 complete() and reads < 24 and clock() < deadline:
while not (not malformed and received == NORMAL_BUS0_LAYOUT) 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 complete() and normal_bus0_queries():
if not malformed and received == NORMAL_BUS0_LAYOUT and normal_bus0_queries():
return 'ford'
if gm_probe is not None and not gm_malformed and gm_probe(gm_received):
return 'gm'
@@ -358,8 +358,7 @@ class CarController(CarControllerBase):
fcw_opt_usm=2 if apply_steer_req or icon == 3 else 1))
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)):
if self.frame - self.blended_camera_sent_frame >= 5 and camera_counter != self.blended_camera_sent_counter:
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
@@ -150,7 +150,6 @@ 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
@@ -348,7 +347,6 @@ 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"])
@@ -67,10 +67,7 @@ class TestBlendedSender(unittest.TestCase):
command.actuators.longControlState = structs.CarControl.Actuators.LongControlState.pid
command.hudControl.setSpeed = 25.0
for frame in range(32):
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)
actuators, messages = ci.apply(command.as_reader(), 2_000_000_000 + frame * 10_000_000)
wanted = []
if frame % 100 == 0:
wanted.append((0x730 if hdaii else 0x7D0, int(hdaii)))
@@ -93,8 +90,6 @@ 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))
@@ -111,7 +111,7 @@ class TestPalisade2023(unittest.TestCase):
addresses = {a for a, _, _ in messages}
self.assertFalse(addresses & {0x420, 0x421, 0x389, 0x7D0, 0x730})
if topology == 'hdaii':
self.assertEqual(addresses, {0x50, 0x2A4} if tick in (0, 7, 12, 17) else {0x50})
self.assertEqual(addresses, {0x50, 0x2A4} if tick in (0, 5, 10, 15) else {0x50})
self.assertTrue(all(bus == 0 for _, _, bus in messages))
else:
self.assertEqual(addresses, {0x340, 0x364})
@@ -128,7 +128,7 @@ 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):
def test_hda2_camera_copy_follows_new_input_instead_of_free_running(self):
ci = CarInterface(params('hdaii'))
for tick in range(12):
feed(ci, tick)
@@ -136,10 +136,10 @@ class TestPalisade2023(unittest.TestCase):
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))
feed(ci, tick, camera={0: 12, 6: 13, 11: 14, 16: 15}.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)])
self.assertEqual(copied, [(0, 12), (6, 13), (11, 14), (16, 15)])
def test_hda2_alpha_long_keeps_primary_steering_payload(self):
from opendbc.car.hyundai.blended_longitudinal import candidate_from_stock
+4 -5
View File
@@ -1,4 +1,4 @@
"""One bounded Subaru AVH ON request; 0x32B is status, never a TX command."""
"""One bounded Legacy AVH ON request; 0x32B is status, never a TX command."""
AVH_REQUEST = 0x6BB
AVH_STATUS = 0x32B
@@ -132,14 +132,13 @@ class AvhStartup:
def eligible(cp):
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})
from opendbc.car.subaru.startup import supported
return bool(supported(cp) and cp.carFingerprint == '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 (1041, 1169, 1425, 3089))
return bool(eligible(cp) and cp.flags & SubaruFlags.AVH_STARTUP and cp.safetyConfigs[0].safetyParam in (1169, 1425))
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, FROGGER_ANGLE_SIBLINGS, DBC, GLOBAL_ES_ADDR, CanBus, CarControllerParams, SubaruFlags
from opendbc.car.subaru.values import CAR, 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,15 +128,14 @@ class CarController(CarControllerBase):
return self.aol_dash_green_last
def _ascent_lkas_alert(self, CC, CS):
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):
if self.CP.carFingerprint not in (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
frogger_hud = self.CP.carFingerprint != CAR.SUBARU_ASCENT_2023
is_legacy_2025 = self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025
lateral_active = self.angle_was_active and CC.latActive and (
CC.enabled or subaru_aol_qualified(self.CP, marked_only=True)
)
if frogger_hud:
if is_legacy_2025:
armed = CS.out.cruiseState.available
if self.CP.openpilotLongitudinalControl:
acc_lead_visible = bool(CC.longActive and not CS.out.gasPressed and CC.hudControl.leadVisible)
@@ -214,7 +213,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 in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_LEGACY_2025}:
if self.CP.carFingerprint == 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:
@@ -307,8 +306,7 @@ class CarController(CarControllerBase):
can_sends.extend(send_sng(self, CC, CS, now_nanos))
# *** alerts and pcm cancel ***
frogger_hud = self.CP.carFingerprint in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_LEGACY_2025}
enabled_for_dash_2025 = self.angle_was_active
enabled_for_dash_2025 = False
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025:
enabled_for_dash_2025 = self._legacy_2025_aol_dash_green(
hud_control,
@@ -343,17 +341,13 @@ 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 frogger_hud:
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025:
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)
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:
if not (in_drive and cruise_available) or lateral_off or not hud_control.lanesVisible:
left_line = 0
right_line = 0
left_depart = False
@@ -382,7 +376,7 @@ class CarController(CarControllerBase):
hud_control.leftLaneDepart, hud_control.rightLaneDepart))
if self.CP.flags & SubaruFlags.SEND_INFOTAINMENT:
if frogger_hud:
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025:
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,
+2 -4
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, FROGGER_ANGLE_SIBLINGS, EARLY_GLOBAL_TORQUE_CARS, GLOBAL_ES_ADDR, CanBus, SubaruFlags, SubaruSafetyFlags
from opendbc.car.subaru.values import CAR, 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 FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025} and fingerprint[CanBus.camera].get(0x3C4) == 8:
if candidate in (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,8 +76,6 @@ 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:
+1 -7
View File
@@ -1,6 +1,6 @@
"""Exact stock-cruise Subaru independent-lateral configuration contract."""
from opendbc.car import structs
from opendbc.car.subaru.values import CAR, FROGGER_ANGLE_SIBLINGS, EARLY_GLOBAL_TORQUE_CARS, SubaruFlags, SubaruSafetyFlags
from opendbc.car.subaru.values import CAR, EARLY_GLOBAL_TORQUE_CARS, SubaruFlags, SubaruSafetyFlags
AOL_EXPERIENCE = 32
IMPREZA_MAIN_AOL = 4096
@@ -37,12 +37,6 @@ 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)
@@ -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, FROGGER_ANGLE_SIBLINGS, SubaruFlags, SubaruSafetyFlags
from opendbc.car.subaru.values import CAR, DBC, 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 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})
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)
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,10 +145,9 @@ 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 == state.out.steeringAngleDeg
assert controller.angle_filter.x == command.actuators.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, FROGGER_ANGLE_SIBLINGS, SubaruSafetyFlags
from opendbc.car.subaru.values import CAR, DBC, SubaruSafetyFlags
from opendbc.safety.tests import test_subaru_gen2_angle_pair as pair
from opendbc.safety.tests.libsafety import libsafety_py
@@ -74,9 +74,6 @@ 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,19 +69,6 @@ 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():
@@ -280,9 +280,6 @@ SUBARU_ALT_VERSION_RESPONSE = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER +
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,4 +1,3 @@
import time
import numpy as np
from opendbc.car import ACCEL_MAX_TAKEOFF
from opendbc.can import CANPacker
@@ -11,7 +10,6 @@ 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():
@@ -24,7 +22,6 @@ 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
@@ -94,10 +91,6 @@ 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,6 +1,4 @@
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
@@ -34,7 +32,6 @@ 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])
@@ -163,9 +160,6 @@ 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,11 +13,6 @@ 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,20 +1,10 @@
"""Exact modern Tesla screen harness capability and frozen safety selection."""
from opendbc.car.tesla.values import CAR, TeslaFlags, TeslaSafetyFlags
from opendbc.car.tesla.values import CAR, TeslaFlags
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):
@@ -22,13 +12,9 @@ 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 & ~KNOWN_FLAGS):
cp.flags & ~int(TeslaFlags.MISSING_DAS_SETTINGS | TeslaFlags.HAS_VEHICLE_BUS | TeslaFlags.AOL_SCREEN_BUTTON)):
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
@@ -45,12 +31,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) & ~SPEED_SYNC) in SCREEN_WORDS and
return bool(screen_tap_supported(cp) and int(cp.safetyConfigs[0].safetyParam) 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) & ~SPEED_SYNC) in AOL_WORDS and
return bool(modern_aol_supported(cp) and int(cp.safetyConfigs[0].safetyParam) in AOL_WORDS and
cp.alternativeExperience in ((32,) if marked_only else (0, 32)))
@@ -58,7 +44,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 | SPEED_SYNC) # scroll speed sync rides on top of any AOL word
base = int(cp.safetyConfigs[0].safetyParam) & 257
cp.flags &= ~int(TeslaFlags.AOL_SCREEN_BUTTON)
cp.safetyConfigs[0].safetyParam = base
if requested:
@@ -70,7 +56,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 | SPEED_SYNC)
base = int(cp.safetyConfigs[0].safetyParam) & 257
cp.flags &= ~int(TeslaFlags.AOL_SCREEN_BUTTON)
cp.safetyConfigs[0].safetyParam = base
if requested:
@@ -1,22 +0,0 @@
"""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)
@@ -1,730 +0,0 @@
"""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]
@@ -1,210 +0,0 @@
"""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
@@ -1,138 +0,0 @@
"""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
@@ -1,331 +0,0 @@
"""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'
@@ -1,341 +0,0 @@
"""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() == ()
@@ -1,161 +0,0 @@
"""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,7 +132,6 @@ 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,7 +22,6 @@ 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,7 +4,6 @@ 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
@@ -21,7 +20,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,
SUBARU.SUBARU_CROSSTREK_2018, VOLVO.VOLVO_XC40_RECHARGE, VOLVO.VOLVO_S60_RECHARGE, VOLVO.POLESTAR_2, VOLVO.VOLVO_V60,
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))
@@ -31,11 +31,6 @@ 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)
@@ -271,10 +266,6 @@ 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"])
@@ -370,10 +361,6 @@ 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
@@ -1,40 +0,0 @@
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)
@@ -1288,7 +1288,18 @@ static bool hyundai_kona_camera_fwd(const CANPacket_t *msg) {
}
#endif
static bool hyundai_canfd_tx_hook_checked(const CANPacket_t *msg) {
static bool hyundai_canfd_tx_hook(const CANPacket_t *msg) {
#ifdef ALLOW_DEBUG
if (hyundai_kona_idle_handoff && (msg->addr == 0x12AU)) {
const uint32_t now = microsecond_timer_get();
if (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])) {
return false;
}
}
#endif
bool tx = false;
const bool ordinary_angle_frame = hyundai_ordinary_angle_stock && ((msg->addr == 0x110U) || (msg->addr == 0x362U));
bool ordinary_angle_valid = true;
@@ -1356,24 +1367,6 @@ static bool hyundai_canfd_tx_hook_checked(const CANPacket_t *msg) {
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;
@@ -2321,32 +2314,37 @@ static safety_config hyundai_canfd_init_validated(uint16_t supplied_param) {
return ret;
}
static safety_config hyundai_canfd_init(uint16_t raw_param) {
static safety_config hyundai_canfd_init(uint16_t 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_idle_handoff = (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;
if ((param == 0x1C0CU) && !hyundai_kona_idle_handoff) {
return (safety_config){.disable_forwarding = true};
}
if (hyundai_kona_idle_handoff) {
param = 0x0C0CU;
}
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;
if (param == 0x1C0CU) {
return (safety_config){.disable_forwarding = true};
}
const bool valid = !GET_FLAG(param, 32768U);
#endif
safety_config ret = {.disable_forwarding = !kona_profile_valid};
safety_config ret = {0};
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 (kona_profile_valid && valid && marker_valid) {
if (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);
@@ -2357,7 +2355,7 @@ static safety_config hyundai_canfd_init(uint16_t raw_param) {
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) {
if (kona_tx[i].addr == 0x12AU) {
kona_tx[i].disable_static_blocking = true;
}
}
+7 -13
View File
@@ -300,15 +300,14 @@ static safety_config subaru_init(uint16_t raw_param) {
param &= ~4096U;
}
#ifdef ALLOW_DEBUG
const bool avh = ((param == 1169U) || (param == 1425U) || (param == 1041U) || (param == 3089U)) &&
const bool avh = ((param == 1169U) || (param == 1425U)) &&
(((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 ? (param & ~1024U) : param);
const bool sibling_hud = (base_param == 2065U);
const uint16_t base_param = stop_start ? ((param == 465U) ? 209U : 145U) : (avh ? 145U : param);
static const CanMsg SUBARU_TX_MSGS[] = {
SUBARU_BASE_TX_MSGS(SUBARU_MAIN_BUS, MSG_SUBARU_ES_LKAS)
SUBARU_COMMON_TX_MSGS(SUBARU_MAIN_BUS)
@@ -362,10 +361,6 @@ 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},
@@ -406,7 +401,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 && !sibling_hud && !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 && !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
@@ -424,8 +419,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 || 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);
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 || subaru_early_global_torque);
if (subaru_aol_enabled) {
static const AolSafetyPolicy policy = {
.reset = subaru_aol_reset,
@@ -459,11 +454,10 @@ 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 || sibling_hud) ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_ASCENT_ALERT_TX_MSGS) :
ascent_alert ? 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);
@@ -499,7 +493,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)) || (early_global_bit && !subaru_early_global_torque) || (((param == 1041U) || (param == 3089U)) && !avh)) {
(impreza_main && ((unsigned int)alternative_experience != 32U)) || (early_global_bit && !subaru_early_global_torque)) {
ret.tx_msgs = NULL;
ret.tx_msgs_len = 0;
}
+2 -16
View File
@@ -2,7 +2,6 @@
#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;
@@ -168,7 +167,6 @@ 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
@@ -197,11 +195,6 @@ 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
@@ -297,11 +290,6 @@ 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;
}
@@ -338,7 +326,6 @@ 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
@@ -349,8 +336,7 @@ static safety_config tesla_init(uint16_t param) {
#ifdef ALLOW_DEBUG
tesla_longitudinal = GET_FLAG(param, 1U);
#endif
tesla_screen_configure(tesla_sync_base_param(param));
tesla_sync_configure(param, tesla_longitudinal);
tesla_screen_configure(param);
tesla_stock_aeb = false;
tesla_stock_lkas = false;
tesla_stock_lkas_prev = false;
@@ -383,7 +369,7 @@ static safety_config tesla_init(uint16_t param) {
const safety_hooks tesla_hooks = {
.init = tesla_init,
.rx = tesla_rx_hook,
.optional_rx = tesla_optional_rx,
.optional_rx = tesla_screen_optional_rx,
.tx = tesla_tx_hook,
.fwd = tesla_fwd_hook,
.get_counter = tesla_get_counter,
@@ -1,215 +0,0 @@
#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_extended_param_valid(param)) {
if ((mode == SAFETY_TESLA) && (((param & ~(TESLA_HW1_FLAG | 257U)) != 0U) || ((param & TESLA_HW1_FLAG) && (param & 256U))) && !tesla_screen_param_valid(param)) {
current_hooks = &nooutput_hooks;
current_safety_mode = SAFETY_NOOUTPUT;
current_safety_param = 0;
@@ -443,15 +443,6 @@ 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,7 +20,6 @@ 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)
@@ -1,78 +0,0 @@
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, 0x810, 0x815, 0x891, 0x8B3, 0x9B1):
for flags in (0, 1, 0x11, 0xB1, 0x800, 0x811, 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 (0x811, 0x8B1, 0x91, 401) + ((1169, 1425) if debug else ()):
for flags in (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,8 +139,7 @@ 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
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):
for flags in (SubaruSafetyFlags.LONG, 0x800, invalid_option):
with self.subTest(car=car, flags=flags):
self.mode(cp, extra_flags=flags)
for frame in required:
@@ -36,26 +36,6 @@ 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()
@@ -67,6 +47,3 @@ 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,10 +38,7 @@ class TestModelSHW1Safety(unittest.TestCase):
def test_all_16bit_profile_words_are_isolated(self):
debug = lib.set_safety_hooks(CarParams.SafetyModel.allOutput, 0) == 0
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())
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())
for param in range(65536):
result = lib.set_safety_hooks(10, param)
expected = 0 if param in supported else -1
@@ -1,974 +0,0 @@
"""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()
-16
View File
@@ -480,21 +480,6 @@ 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 {
@@ -527,7 +512,6 @@ struct SlcAction @0x9ccdc8676701b412 {
forceCoastToggle @10;
pulseGlideToggle @11;
disengageRequest @12;
cruiseStep @13;
}
}
+75 -322
View File
@@ -6385,7 +6385,7 @@ const ::capnp::_::RawSchema s_9a4b2a0189fe1224 = {
};
#endif // !CAPNP_LITE
CAPNP_DEFINE_ENUM(Choice_9a4b2a0189fe1224, 9a4b2a0189fe1224);
static const ::capnp::_::AlignedData<180> b_9ccdc8676701b412 = {
static const ::capnp::_::AlignedData<176> 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,28 +6393,24 @@ static const ::capnp::_::AlignedData<180> 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, 71, 0, 0, 0,
29, 0, 0, 0, 55, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
93, 0, 0, 0, 255, 1, 0, 0,
77, 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,
16, 0, 0, 0, 1, 0, 1, 0,
12, 0, 0, 0, 1, 0, 1, 0,
105, 30, 140, 170, 192, 231, 57, 181,
25, 0, 0, 0, 186, 0, 0, 0,
172, 250, 175, 77, 32, 114, 213, 254,
29, 0, 0, 0, 106, 0, 0, 0,
17, 0, 0, 0, 186, 0, 0, 0,
169, 174, 255, 224, 77, 245, 161, 139,
29, 0, 0, 0, 194, 0, 0, 0,
21, 0, 0, 0, 194, 0, 0, 0,
149, 27, 24, 102, 230, 217, 203, 184,
33, 0, 0, 0, 42, 0, 0, 0,
25, 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,
@@ -6577,21 +6573,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, 180, d_9ccdc8676701b412, m_9ccdc8676701b412,
0x9ccdc8676701b412, b_9ccdc8676701b412.words, 176, 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<267> b_b539e7c0aa8c1e69 = {
static const ::capnp::_::AlignedData<234> 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,
5, 0, 7, 0, 0, 0, 0, 0,
4, 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, 79, 3, 0, 0,
37, 0, 0, 0, 223, 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,
@@ -6601,112 +6597,98 @@ static const ::capnp::_::AlignedData<267> 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,
60, 0, 0, 0, 3, 0, 4, 0,
52, 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,
149, 1, 0, 0, 66, 0, 0, 0,
93, 1, 0, 0, 66, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
144, 1, 0, 0, 3, 0, 1, 0,
156, 1, 0, 0, 2, 0, 1, 0,
88, 1, 0, 0, 3, 0, 1, 0,
100, 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,
153, 1, 0, 0, 82, 0, 0, 0,
97, 1, 0, 0, 82, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
152, 1, 0, 0, 3, 0, 1, 0,
164, 1, 0, 0, 2, 0, 1, 0,
96, 1, 0, 0, 3, 0, 1, 0,
108, 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,
161, 1, 0, 0, 74, 0, 0, 0,
105, 1, 0, 0, 74, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
160, 1, 0, 0, 3, 0, 1, 0,
172, 1, 0, 0, 2, 0, 1, 0,
104, 1, 0, 0, 3, 0, 1, 0,
116, 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,
169, 1, 0, 0, 138, 0, 0, 0,
113, 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,
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,
181, 1, 0, 0, 154, 0, 0, 0,
125, 1, 0, 0, 154, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
184, 1, 0, 0, 3, 0, 1, 0,
196, 1, 0, 0, 2, 0, 1, 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,
193, 1, 0, 0, 154, 0, 0, 0,
137, 1, 0, 0, 154, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
196, 1, 0, 0, 3, 0, 1, 0,
208, 1, 0, 0, 2, 0, 1, 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,
205, 1, 0, 0, 122, 0, 0, 0,
149, 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,
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,
213, 1, 0, 0, 202, 0, 0, 0,
157, 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,
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,
229, 1, 0, 0, 90, 0, 0, 0,
173, 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,
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,
0, 0, 0, 0, 0, 0, 0, 0,
237, 1, 0, 0, 82, 0, 0, 0,
181, 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,
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,
0, 0, 0, 0, 0, 0, 0, 0,
245, 1, 0, 0, 186, 0, 0, 0,
189, 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,
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,
0, 0, 0, 0, 0, 0, 0, 0,
1, 2, 0, 0, 170, 0, 0, 0,
201, 1, 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,
204, 1, 0, 0, 3, 0, 1, 0,
216, 1, 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,
13, 2, 0, 0, 122, 0, 0, 0,
213, 1, 0, 0, 122, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 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,
212, 1, 0, 0, 3, 0, 1, 0,
224, 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,
@@ -6828,228 +6810,16 @@ static const ::capnp::_::AlignedData<267> 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 ::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};
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};
const ::capnp::_::RawSchema s_b539e7c0aa8c1e69 = {
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
0xb539e7c0aa8c1e69, b_b539e7c0aa8c1e69.words, 234, nullptr, m_b539e7c0aa8c1e69,
0, 13, i_b539e7c0aa8c1e69, nullptr, nullptr, { &s_b539e7c0aa8c1e69, nullptr, nullptr, 0, 0, nullptr }, false
};
#endif // !CAPNP_LITE
static const ::capnp::_::AlignedData<236> b_8ba1f54de0ffaea9 = {
@@ -7302,7 +7072,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<90> b_b8cbd9e666181b95 = {
static const ::capnp::_::AlignedData<85> 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,
@@ -7312,7 +7082,7 @@ static const ::capnp::_::AlignedData<90> 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, 87, 1, 0, 0,
29, 0, 0, 0, 63, 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,
@@ -7320,48 +7090,45 @@ static const ::capnp::_::AlignedData<90> 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,
56, 0, 0, 0, 1, 0, 2, 0,
52, 0, 0, 0, 1, 0, 2, 0,
0, 0, 0, 0, 0, 0, 0, 0,
161, 0, 0, 0, 66, 0, 0, 0,
149, 0, 0, 0, 66, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0,
153, 0, 0, 0, 58, 0, 0, 0,
141, 0, 0, 0, 58, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
2, 0, 0, 0, 0, 0, 0, 0,
145, 0, 0, 0, 58, 0, 0, 0,
133, 0, 0, 0, 58, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
3, 0, 0, 0, 0, 0, 0, 0,
137, 0, 0, 0, 50, 0, 0, 0,
125, 0, 0, 0, 50, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
4, 0, 0, 0, 0, 0, 0, 0,
129, 0, 0, 0, 170, 0, 0, 0,
117, 0, 0, 0, 170, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
5, 0, 0, 0, 0, 0, 0, 0,
129, 0, 0, 0, 122, 0, 0, 0,
117, 0, 0, 0, 122, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
6, 0, 0, 0, 0, 0, 0, 0,
125, 0, 0, 0, 122, 0, 0, 0,
113, 0, 0, 0, 122, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
7, 0, 0, 0, 0, 0, 0, 0,
121, 0, 0, 0, 146, 0, 0, 0,
109, 0, 0, 0, 146, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
8, 0, 0, 0, 0, 0, 0, 0,
121, 0, 0, 0, 170, 0, 0, 0,
109, 0, 0, 0, 170, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
9, 0, 0, 0, 0, 0, 0, 0,
121, 0, 0, 0, 82, 0, 0, 0,
109, 0, 0, 0, 82, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
10, 0, 0, 0, 0, 0, 0, 0,
117, 0, 0, 0, 138, 0, 0, 0,
105, 0, 0, 0, 138, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
11, 0, 0, 0, 0, 0, 0, 0,
117, 0, 0, 0, 138, 0, 0, 0,
105, 0, 0, 0, 138, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
12, 0, 0, 0, 0, 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,
105, 0, 0, 0, 138, 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,
@@ -7390,16 +7157,14 @@ static const ::capnp::_::AlignedData<90> 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,
99, 114, 117, 105, 115, 101, 83, 116,
101, 112, 0, 0, 0, 0, 0, 0, }
0, 0, 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, 13, 12, 10, 11, 2, 8, 7, 0};
static const uint16_t m_b8cbd9e666181b95[] = {1, 3, 4, 6, 5, 9, 12, 10, 11, 2, 8, 7, 0};
const ::capnp::_::RawSchema s_b8cbd9e666181b95 = {
0xb8cbd9e666181b95, b_b8cbd9e666181b95.words, 90, nullptr, m_b8cbd9e666181b95,
0, 14, nullptr, nullptr, nullptr, { &s_b8cbd9e666181b95, nullptr, nullptr, 0, 0, nullptr }, false
0xb8cbd9e666181b95, b_b8cbd9e666181b95.words, 85, nullptr, m_b8cbd9e666181b95,
0, 13, nullptr, nullptr, nullptr, { &s_b8cbd9e666181b95, nullptr, nullptr, 0, 0, nullptr }, false
};
#endif // !CAPNP_LITE
CAPNP_DEFINE_ENUM(Kind_b8cbd9e666181b95, b8cbd9e666181b95);
@@ -23270,18 +23035,6 @@ 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;
+1 -449
View File
@@ -95,7 +95,6 @@ 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 {
@@ -112,7 +111,6 @@ 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);
@@ -843,7 +841,6 @@ struct SlcAction {
class Builder;
class Pipeline;
struct ControllerCruiseAction;
struct TeslaGesture;
struct ConditionalManualAction;
typedef ::capnp::schemas::Kind_b8cbd9e666181b95 Kind;
@@ -864,22 +861,7 @@ struct SlcAction::ControllerCruiseAction {
class Pipeline;
struct _capnpPrivate {
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)
CAPNP_DECLARE_STRUCT_HEADER(b539e7c0aa8c1e69, 7, 4)
#if !CAPNP_LITE
static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; }
#endif // !CAPNP_LITE
@@ -5903,11 +5885,6 @@ 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>
@@ -5991,16 +5968,6 @@ 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>
@@ -6019,148 +5986,6 @@ 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;
@@ -22501,279 +22326,6 @@ 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.
+1 -4
View File
@@ -85,10 +85,8 @@ 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, "1"}},
{"TeslaAOLScreenTap", {PERSISTENT, BOOL, "0"}},
{"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"}},
@@ -136,7 +134,6 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"LaneCenterOffset", {PERSISTENT, FLOAT, "0.0"}},
{"LaneCenteringE2EAuthority", {PERSISTENT, FLOAT, "0.5"}},
{"LaneCenteringStrength", {PERSISTENT, FLOAT, "1.5"}},
{"UnidenConfig", {PERSISTENT | DONT_LOG, JSON}},
{"StarPortEnabled", {PERSISTENT | DONT_LOG, BOOL, "0"}},
{"AdvancedLateralTune", {PERSISTENT, BOOL}},
{"LateralControllerSelection", {PERSISTENT | DONT_LOG, JSON}},
@@ -1,8 +1,6 @@
Japanese, Korean and Simplified Chinese subsets expanded for the shared StarPilot
UI catalogs. Generated with fontTools.subset (default options), retaining the
union of each original font cmap and all characters in app_ja.po/app_ko.po/
app_zh-CHS.po. Original subset: Dom 1f1b1d5db9. Regenerate the Simplified Chinese
subset whenever app_zh-CHS.po gains characters.
Japanese and Korean subsets expanded for the shared StarPilot UI catalogs.
Generated with fontTools.subset, retaining the union of each original font cmap
and all characters in app_ja.po/app_ko.po. Original subset: Dom 1f1b1d5db9.
The official upstream source fonts are licensed under Noto-OFL.txt.
NotoSansCJKjp-Regular.otf
@@ -14,8 +12,3 @@ NotoSansCJKkr-Regular.otf
Source: https://raw.githubusercontent.com/notofonts/noto-cjk/main/Sans/OTF/Korean/NotoSansCJKkr-Regular.otf
Source SHA-256: 6bcb2a0703aa137e874fc2dffa85f6c21ba9a67fa329e81b8c801663af7e992a
Subset SHA-256: 846e22c2bf1afffc11718ee95e4acc258538cc528b20aab3aa122476e64533b8
NotoSansCJKsc-Regular.otf
Source: https://raw.githubusercontent.com/notofonts/noto-cjk/main/Sans/OTF/SimplifiedChinese/NotoSansCJKsc-Regular.otf
Source SHA-256: 2c76254f6fc379fddfce0a7e84fb5385bb135d3e399294f6eeb6680d0365b74b
Subset SHA-256: 159db5944e2e2d2fbeaea3dd6db56b95f57eff80036f93fb7ac612ef25f03e84
+10 -17
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, tesla_set_speed_card
from openpilot.starpilot.speed_limits import physical_actions as slc_physical
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,7 +242,9 @@ class Car:
def pre_create_hook(cp, candidate, fingerprints, car_fw):
initialize_aol_preference(cp)
if candidate == HYUNDAI_CAR.HYUNDAI_IONIQ_6:
# Verify the opt-in before constructing the interface and publishing CarParams.
# 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.
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)
@@ -259,7 +261,8 @@ 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:
# READY or unknown keeps stock CarParams.
# Reboot in READY retains original stock CP before CI/parsers and
# publication. Unknown evidence cannot be treated as Ready=False.
long_cp = None
if long_cp is not None:
initialize_aol_preference(long_cp)
@@ -450,7 +453,6 @@ 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")
@@ -590,8 +592,7 @@ 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 or cruise_helper.tesla_set_speed and host_enabled) and
can_rcv_valid and not self.params.get_bool("SafeMode")))
enabled=bool(host_control_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
@@ -810,7 +811,6 @@ 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]))
@@ -853,9 +853,8 @@ 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()
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
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
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
@@ -869,7 +868,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), current_only=rule)
now_ns, after_ns=getattr(self, 'slc_source_floor_ns', 0))
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)
@@ -1238,8 +1237,6 @@ 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:
@@ -1896,9 +1893,6 @@ 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
@@ -1997,7 +1991,6 @@ 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:
+5 -12
View File
@@ -63,11 +63,6 @@ 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
@@ -93,9 +88,8 @@ 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 or self.tesla_set_speed
stock_software = subaru_software_selected(self.CP) or self.hyundai_software_cruise
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
@@ -248,7 +242,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 or self.tesla_set_speed
stock_software = subaru_software_selected(self.CP) or self.hyundai_software_cruise
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)):
@@ -304,9 +298,8 @@ 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. 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):
# Native cruise owns PCM SET, including when SLC supplies a planner cap.
if self.CP.pcmCruise:
return False
# A car-owned acknowledgment can outlive the physical button event.
if resume is None:
@@ -314,7 +307,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 and not (self.slc_pcm and slc_target_mps is not None):
if resume and self.v_cruise_initialized:
self.v_cruise_kph = self.v_cruise_kph_last
self.v_cruise_cluster_kph = self.v_cruise_kph
return False
@@ -21,18 +21,8 @@ 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 recorded_frames():
return [CanData(address, bytes.fromhex(data), bus) for bus, address, data in RECORDED]
def brand(frames):
@@ -43,19 +33,17 @@ 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(layout, missing):
frames = recorded_frames(layout)
def test_partial_layout_does_not_choose_ford(missing):
frames = recorded_frames()
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(layout, bad):
def test_wrong_bus_dlc_and_returned_frames_do_not_choose_ford(bad):
for bus_delta, size in ((1, 8), (128, 8), (0, 7), (0, 12)):
frames = recorded_frames(layout)
frames = recorded_frames()
original = frames[bad]
frames[bad] = CanData(original.address, bytes(size), original.src + bus_delta)
assert brand(frames) is None
@@ -89,21 +77,14 @@ def test_shared_probe_uses_existing_read_bound():
@pytest.mark.parametrize('firmware_known', [False, True])
@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):
def test_cold_automatic_uses_real_vin_isotp_fw_and_identity_matching(firmware_known):
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(layout))
transport = FordEcus(firmware=firmware, background=recorded_frames())
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):
@@ -112,12 +93,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 == candidate
assert ci.CP.carFingerprint == CAR.FORD_MUSTANG_MACH_E_MK1
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 != candidate
assert ci.CP.carFingerprint != CAR.FORD_MUSTANG_MACH_E_MK1
assert not ci.CP.safetyConfigs or ci.CP.safetyConfigs[-1].safetyModel != structs.CarParams.SafetyModel.ford
+7 -9
View File
@@ -633,13 +633,6 @@ class Controls:
new_desired_curvature = limit_curvature_to_plan(model_v2, new_desired_curvature, CS.vEgo, min_reach=4.0)
else:
self.subaru_twitch_guard_armed = update_twitch_guard(False, CS.vEgo, CS.standstill)
kona_tau = getattr(self, "kona_smoothing", 0.)
from openpilot.starpilot.car.subaru.smoothing import seconds as subaru_smooth_seconds, control_maximum
lat_delay = self.sm["lateralDelay"].lateralDelay + LAT_SMOOTH_SECONDS + subaru_smooth_seconds(CS.vEgo, control_maximum(self)) + kona_tau
if getattr(self, "volkswagen_smoothing", None) is not None:
lat_delay += self.volkswagen_smoothing.seconds(int(self.sm.logMonoTime["modelV2"]), time.monotonic_ns())
if self.highway_smoothing_supported:
preferences = getattr(self, "live_steering_preferences", None)
if preferences is not None:
@@ -663,13 +656,12 @@ class Controls:
or self.sm.valid['lateralManeuverPlan']
),
predicted=predicted,
steering_limited=self.steer_limited_by_safety,
actuator_delay_s=lat_delay,
)
lane_base_curvature = new_desired_curvature
self.lane_centering_applied = 0.0
self.lane_centering_inactive_reason = 'inactive'
self.last_lane_centering_result = None
kona_tau = getattr(self, "kona_smoothing", 0.)
lane_delay = None
if lane_centering is None and self.lane_centering_host is not None:
now_ns = int(self.sm.logMonoTime['carState']) if os.getenv('REPLAY') == '1' else time.monotonic_ns()
@@ -731,6 +723,12 @@ class Controls:
self.desired_curvature = guarded
curvature_limited = True
self.lane_centering_applied = self.desired_curvature - baseline_curvature
from openpilot.starpilot.car.subaru.smoothing import seconds as subaru_smooth_seconds, control_maximum
lat_delay = self.sm["lateralDelay"].lateralDelay + LAT_SMOOTH_SECONDS + subaru_smooth_seconds(CS.vEgo, control_maximum(self)) + kona_tau
if getattr(self, "volkswagen_smoothing", None) is not None:
lat_delay += self.volkswagen_smoothing.seconds(int(self.sm.logMonoTime["modelV2"]), time.monotonic_ns())
actuators.curvature = self.desired_curvature
if cycle_timing is not None:
cycle_timing.mark()
@@ -28,17 +28,7 @@ class DesireHelper:
def get_lane_change_direction(CS):
return LaneChangeDirection.left if CS.leftBlinker else LaneChangeDirection.right
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):
def update(self, carstate, lateral_active, lane_change_prob, *, auto_evidence=False, engaged=False, navigation_turn=False):
v_ego = carstate.vEgo
one_blinker = carstate.leftBlinker != carstate.rightBlinker
if not carstate.leftBlinker and not carstate.rightBlinker:
@@ -51,7 +41,8 @@ class DesireHelper:
self.auto_signal_blocked = True
self.last_signal_direction = signal_direction
self.auto_status = "manualRequired"
below_lane_change_speed = v_ego < self.lane_change_speed()
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)
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
@@ -59,12 +50,12 @@ class DesireHelper:
self.lane_change_timer = 0.0
self.pre_lane_change_timer = 0.0
else:
if navigation_turn and not route_turn and self.lane_change_state == LaneChangeState.preLaneChange:
if navigation_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 (route_turn or not navigation_turn) and not (self.policy.one_per_signal and self.lane_change_performed)):
not below_lane_change_speed and 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
@@ -110,7 +101,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 route_turn and not (self.policy.one_per_signal and self.lane_change_performed):
if one_blinker 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:
@@ -25,7 +25,6 @@ TIGHT_CURVE_OFF = 2.0 # m/s^2
ENVELOPE_HOLD = 2.0 # s
ENVELOPE_RELEASE_RATE = 0.3 # m/s^2 per second
BYPASS_FADE_RATE = 2.0 # per second
LIMIT_RECOVERY_RAMP = 0.4 # s
MIN_SETTING = 1.0
MAX_SETTING = 10.0
KEY = "HighwaySmoothingLevel"
@@ -84,11 +83,9 @@ class HighwayCorrectionGain:
self.prediction_envelope = _Envelope()
self.bypass_weight = 0.0
self.weight = 0.0
self.time_clear_of_limit: float | None = None
self.limit_recovery = 1.0
def update(self, curvature: float, v_ego: float, lat_active: bool, gain: float, bypass: bool,
predicted: tuple[float, ...] | None = None, *, steering_limited: bool = False, actuator_delay_s: float = 0.0) -> float:
predicted: tuple[float, ...] | None = None) -> float:
if not lat_active:
self.reset(curvature)
return curvature
@@ -120,19 +117,8 @@ class HighwayCorrectionGain:
step = BYPASS_FADE_RATE * DT_CTRL
self.bypass_weight += min(max((0.0 if bypass else 1.0) - self.bypass_weight, -step), step)
# Leave the original request intact while limited and let the delayed commands clear before blending back in.
if steering_limited:
self.time_clear_of_limit = self.limit_recovery = 0.0
elif self.time_clear_of_limit is not None:
if math.isfinite(actuator_delay_s) and actuator_delay_s >= 0.0:
target = max((self.time_clear_of_limit - actuator_delay_s) / LIMIT_RECOVERY_RAMP, 0.0)
self.limit_recovery = min(target, self.limit_recovery + DT_CTRL / LIMIT_RECOVERY_RAMP, 1.0)
self.time_clear_of_limit = None if self.limit_recovery == 1.0 else self.time_clear_of_limit + DT_CTRL
else:
self.time_clear_of_limit = self.limit_recovery = 0.0
gain = min(max(gain, MIN_SETTING / MAX_SETTING), 1.0)
self.weight = self.bypass_weight * _smoothstep(v_ego, SPEED_OFF, SPEED_ON) * gate * self.limit_recovery
self.weight = self.bypass_weight * _smoothstep(v_ego, SPEED_OFF, SPEED_ON) * gate
k = 1.0 - self.weight * (1.0 - gain)
if k >= 1.0:
return curvature
+4 -11
View File
@@ -334,12 +334,9 @@ def starpilot_main():
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)
navigation_slowdown_percent=navigation_slowdown_percent,
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.
@@ -403,7 +400,7 @@ 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:
if longitudinal_planner.downhill_surplus_mps > 0.:
subscribed_services.append('deviceMotion')
optional_conditional.append('deviceMotion')
sm = messaging.SubMaster(subscribed_services, poll='modelV2',
@@ -418,11 +415,7 @@ 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.
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)
slc_lifecycle.refresh(time.monotonic_ns(), pending_actions=pending_slc_actions, pending_cruise=pending_slc_cruise)
sm.update()
if sm.updated['modelV2']:
# Only explicit replay uses the recorded model timeline. In a live host,
@@ -119,28 +119,6 @@ def test_bypass_fades_without_steps():
assert np.max(np.abs(np.diff(out))) < 1.5 * max_raw_step
def test_limit_pauses_smoothing_until_the_actuator_delay_clears():
hcg = HighwayCorrectionGain()
_run(hcg, _weave(seconds=5.0), gain=0.5)
assert hcg.weight == 1.0
raw = 0.04 / _V_HWY ** 2
delay = 0.3
assert hcg.update(raw, _V_HWY, True, 0.5, False, steering_limited=True, actuator_delay_s=delay) == raw
for _ in range(round(delay / DT_CTRL)):
assert hcg.update(raw, _V_HWY, True, 0.5, False, actuator_delay_s=delay) == raw
weights = []
for _ in range(41):
hcg.update(raw, _V_HWY, True, 0.5, False, actuator_delay_s=delay)
weights.append(hcg.weight)
assert 0.4 < weights[20] < 0.6
assert weights[-1] == 1.0
assert np.max(np.diff(weights)) < 0.026
assert hcg.update(raw, _V_HWY, True, 0.5, False, steering_limited=True, actuator_delay_s=delay) == raw
for _ in range(100):
assert hcg.update(raw, _V_HWY, True, 0.5, False, actuator_delay_s=math.nan) == raw
def test_active_from_40_mph():
v = 40.0 * 0.44704
raw = _weave(v_ego=v)
+2 -3
View File
@@ -560,8 +560,7 @@ 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),
waiting_for_lane=DH.waiting_for_lane(sm["carState"]))
supported=turn_supported, model_stop=bool(prev_action.shouldStop))
is_rhd = sm["driverMonitoringState"].isRHD
frame_id = sm["narrowRoadCameraState"].frameId
v_ego = max(sm["carState"].vEgo, 0.)
@@ -692,7 +691,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, route_turn=matching_turn_signal(sm, mono_now_ns, supported=navigation_turn.automatic_turn_enabled))
navigation_turn=signal_turn or 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.
Binary file not shown.
@@ -129,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 == 8192U) || (word == 8200U) || (word == 1041U) || (word == 2065U) || (word == 3089U);
(word == 4096U) || (word == 4104U) || (word == 4608U) || (word == 4616U) || (word == 8192U) || (word == 8200U);
assert(aol_capable(subaru, 11U, VEHICLE_REGISTRY) == expected);
subaru.capability_flags = 0U;
assert(!aol_capable(subaru, 11U, VEHICLE_REGISTRY));
@@ -295,46 +295,30 @@ 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;
expected |= ((exact & 1U) != 0U) && (word == (exact | tesla_speed_sync));
}
assert(tesla_screen_aol_param(static_cast<uint16_t>(word)) == expected);
for (const auto exact : tesla_screen_words) expected |= word == exact;
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;
}
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);
}
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);
}
AolAxisNegotiator ford_pause(VEHICLE_REGISTRY);
FakeTransport ford_transport;
+3 -6
View File
@@ -6,7 +6,6 @@ import threading
import uuid
from copy import copy
from dataclasses import replace
from typing import cast
import openpilot.cereal.messaging as messaging
@@ -1307,7 +1306,7 @@ class SelfdriveD:
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 = copy(self.events.event_rules[EventName.speedTooHigh][ET.WARNING])
speed_alert.alert_type = 'speedTooHigh/warning'
speed_alert.event_type = 'aolSpeedPause'
alerts.append(speed_alert)
@@ -2299,11 +2298,9 @@ 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) or
mazda_stopped_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))
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
@@ -8,7 +8,6 @@ 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
@@ -43,7 +42,6 @@ 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,7 +7,6 @@ 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
@@ -35,7 +34,6 @@ 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
File diff suppressed because it is too large Load Diff
+1 -5
View File
@@ -29,7 +29,6 @@ def update_frame(preview=None, controllers=None, star=None, game_mode=None, arab
star._poll_projection_bookmark(time.monotonic_ns())
star._poll_projection_slc(time.monotonic_ns())
poll_screen_off_wheel(star, device.awake, time.monotonic_ns())
star._poll_detector()
if game_mode is not None:
game_mode()
if controllers is not None:
@@ -73,10 +72,7 @@ def main():
borrowed_messages=True, evidence_wait_ms=0)
controllers = None if ui_state.replay_clock is not None else ControllerRuntime(ui_state.params, actions=layout.star._favorite_actions,
favorites=layout.star.favorites_owner.snapshot,
invoke_favorite=layout.star.favorites_owner.invoke, authority=controller_authority, input_capture=game_input,
vehicle=lambda: ui_state.CP, messages=lambda: ui_state.sm,
speed_actions=getattr(layout.star, '_comma_speed_actions', None),
keyed_actions=getattr(layout.star, '_favorite_render_actions', None))
invoke_favorite=layout.star.favorites_owner.invoke, authority=controller_authority, input_capture=game_input)
preview = None if ui_state.replay_clock is not None else LayoutPreviewRuntime(ui_state.params, (Profile.LARGE if BIG_UI else Profile.COMPACT).value,
offroad_hint=ui_state.is_offroad, authority=preview_authority)
else:
@@ -265,12 +265,9 @@ def retain_fit_eps_intent(feedback, sm, cp, cs, axis, now_ns, *, latched, produc
if (not cs.steerFaultTemporary or grant is None or grant[:2] != (producer, epoch) or
inventory != grant[3] or not 0 < grant[2] <= now_ns <= grant[2] + SAFETY_MAX_AGE_NS):
return False
source_ns = now_ns
else:
if inventory != known[3]:
return False
source_ns = now_ns if cs.steerFaultTemporary else known[2]
feedback.fit_eps_intent = (producer, epoch, source_ns, inventory)
elif inventory != known[3]:
return False
feedback.fit_eps_intent = (producer, epoch, now_ns if cs.steerFaultTemporary else known[2], inventory)
if native.requestedLateral and not native.lateralAllowed:
feedback.honda_eps_retained_native_ns = native.observedMonoTime
return True
@@ -120,7 +120,7 @@ class TestActualFreshCardStartup(TestCase):
patch.object(manager, 'save_bootlog'), \
patch.object(manager.HARDWARE, 'get_serial', return_value='fixture'), \
patch.object(manager.HARDWARE, 'get_device_type', return_value='pc'), \
patch.object(manager, 'register_at_startup', return_value='fixture'), \
patch.object(manager, 'register', return_value='fixture'), \
patch.object(manager.cloudlog, 'bind_global'):
manager.manager_init()
target = Path(params.get_param_path('AlwaysOnLateral'))
@@ -1,59 +0,0 @@
from contextlib import ExitStack
import pytest
from opendbc.car import gen_empty_fingerprint
from opendbc.car.mazda.interface import CarInterface
from opendbc.car.mazda.values import CAR
from openpilot.cereal import log
from openpilot.common.params import Params
from openpilot.common.prefix import OpenpilotPrefix
from openpilot.starpilot.aol.intent import read_settings
from openpilot.starpilot.aol.tests import test_ioniq_availability as fixture
@pytest.mark.parametrize('identity', [CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021])
@pytest.mark.parametrize('case_name', ['launch', 'moving_denial', 'panda_fault'])
def test_mazda_intersection_aol(identity, case_name):
with OpenpilotPrefix(), ExitStack() as cleanup:
case = fixture.IoniqAvailabilityTests(methodName='runTest')
cleanup.callback(case.doCleanups)
params = Params()
params.put('AolBrakePauseSpeedMps', 0.0, block=True)
params.put('PauseLateralSpeed', 0.0, block=True)
params.put_bool('PauseLateralOnSignal', False, block=True)
cp = CarInterface.get_params(identity, gen_empty_fingerprint(), [], False, False, False)
sd, _, step = case._authority_callers(False, cp=cp, genuine_events=True)
sd.aol_settings = read_settings(params)
assert sd.aol_settings.pause_brake_mps == 0.0
state = fixture.car_state()
state.leftBlinker = True
state.cruiseState.enabled = True
state.vEgo = state.vEgoRaw = 20.0
axis, _, command = step(2, observed_state=state, native_request_long=False)
assert axis.lateralActive and command.latActive and not command.longActive
state.standstill = case_name != 'moving_denial'
if state.standstill:
state.vEgo = state.vEgoRaw = 0.0
axis, _, command = step(3, observed_state=state, allowed=False, native_request_long=False,
panda_fault=case_name == 'panda_fault')
assert not axis.lateralActive and not command.latActive and not command.longActive
if case_name != 'launch':
assert log.OnroadEvent.EventName.controlsMismatch in sd.events.names
return
assert log.OnroadEvent.EventName.controlsMismatch not in sd.events.names
assert not sd.aol_authority_lost
state.cruiseState.enabled = False
for tick in range(4, 30):
state.brakePressed = tick < 27
axis, _, command = step(tick, observed_state=state, gas=tick >= 28, allowed=False, native_request_long=False)
assert not command.latActive and not command.longActive and not sd.aol_authority_lost
assert sd.aol_last_intent.allowedLatch
state.standstill = state.brakePressed = False
state.vEgo = state.vEgoRaw = 20.0
axis, _, command = step(30, observed_state=state, gas=True, native_request_long=False)
assert axis.lateralActive and command.latActive and not command.longActive
assert sd.aol_last_intent.allowedLatch and not sd.aol_authority_lost
state.brakePressed = True
axis, _, command = step(31, observed_state=state, native_request_long=False)
assert axis.lateralActive and command.latActive and not command.longActive
@@ -40,8 +40,7 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha,
startup_delivery_delay=0, startup_delivery_services=(), receipt_sink=None,
route2c_start=False, startup_block_until=0, startup_expect_expiry=False,
startup_probe_denials=False, startup_stall=None, startup_stall_mode='frozen',
startup_floor_dip=False, cancel_delivery_delay=0, brake_delivery_delay=0, rushed_start=False,
heartbeat_after_can=False):
startup_floor_dip=False, cancel_delivery_delay=0, brake_delivery_delay=0, rushed_start=False):
pq = candidate == CAR.VOLKSWAGEN_SHARAN_MK2
with ExitStack() as cleanup:
cleanup.enter_context(OpenpilotPrefix())
@@ -173,8 +172,7 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha,
for tick in range(120):
now = 10_000_000_000 + tick * 10_000_000
native.set_timer(1_000_000 + tick * 10_000)
update_heartbeat = (parked_boot or main_cycle or creep_start and tick >= 12) and (not delayed_heartbeat or tick % 10 == 1)
if update_heartbeat and not heartbeat_after_can:
if (parked_boot or main_cycle or creep_start and tick >= 12) and (not delayed_heartbeat or tick % 10 == 1):
native.set_aol_test_heartbeat(bool((card.aol_card_intent.allowed_latch or request) and tick >= startup_block_until))
if quiet is not None:
quiet.set_timer(1_000_000 + tick * 10_000)
@@ -238,8 +236,6 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha,
for addr, data, bus in incoming:
native.safety_rx_hook(make_msg(bus - offset, addr, dat=data))
native.safety_tick()
if update_heartbeat and heartbeat_after_can:
native.set_aol_test_heartbeat(bool((card.aol_card_intent.allowed_latch or request) and tick >= startup_block_until))
native.aol_set_host_request(request)
permission = native.aol_get_permission_mask()
if early_brake and tick == 60:
@@ -758,18 +754,6 @@ def test_mqb_cancel_with_accelerator_and_driver_steering(gearbox, alpha, phase):
gearbox, alpha, 0, False, True, cruise_cancel=True, cancel_override=True, native_phase=phase)
def test_mqb_atlas_stock_cruise_off_waits_for_initial_native_lateral():
receipt = []
test_mqb_full_engagement_brake_reverse_drive_actual_callers(
'automatic', False, 0, False, False, candidate=CAR.VOLKSWAGEN_ATLAS_MK1,
parked_boot=True, delayed_heartbeat=True, native_phase=1, receipt_sink=receipt, heartbeat_after_can=True)
first_active = next(row for row in receipt if row['control'].get('latActive'))
assert not first_active['control'].get('enabled') and first_active['permission_mask'] == 1
assert any(row['host_request'] == 1 and row['permission_mask'] == 0
for row in receipt[:first_active['tick']])
assert all(not row['control'].get('longActive') for row in receipt)
@pytest.mark.parametrize('gearbox', ('automatic', 'manual', 'direct'))
@pytest.mark.parametrize('alpha', (False, True))
def test_mqb_reverse_braked_start_waits_before_consuming_default_main(gearbox, alpha):
+8 -17
View File
@@ -2,7 +2,7 @@ import unittest
from opendbc.car import Bus, gen_empty_fingerprint, structs
from opendbc.can import CANPacker
from opendbc.car.toyota.interface import CarInterface, prepare_camera_stock_acc
from opendbc.car.toyota.interface import CarInterface
from opendbc.car.toyota.values import CAR, DBC, ToyotaFlags
from openpilot.starpilot.aol.intent import AolSettings
from openpilot.starpilot.aol.vehicle import policy_for
@@ -81,21 +81,9 @@ class TestHighlanderAol(unittest.TestCase):
preferences.finalize(cp)
self.assertEqual(cp.alternativeExperience, 160 if hold else 32)
self.assertTrue(qualified(cp, marked_only=True))
self._assert_camera_stock_handoff(cp, hold)
def _assert_camera_stock_handoff(self, cp, hold):
stock = cp.as_reader().as_builder()
if hold:
stock.safetyConfigs[0].safetyParam = 585
stock.openpilotLongitudinalControl = False
self.assertFalse(qualified(stock))
else:
prepare_camera_stock_acc(stock, requested=True)
self.assertEqual(stock.safetyConfigs[0].safetyParam, 585)
self.assertFalse(stock.openpilotLongitudinalControl)
self.assertTrue(qualified(stock, marked_only=True))
stock.pcmCruise = False
self.assertFalse(qualified(stock))
cp.safetyConfigs[0].safetyParam = 585
cp.openpilotLongitudinalControl = False
self.assertFalse(qualified(cp))
def test_prius_filter_exact_profile_and_startup_transport(self):
from opendbc.car.toyota.prius_longitudinal import prepare_stock
@@ -213,7 +201,10 @@ class TestHighlanderAol(unittest.TestCase):
bad = cp.as_reader().as_builder()
bad.flags |= int(flag)
self.assertFalse(qualified(bad, marked_only=True))
self._assert_camera_stock_handoff(cp, hold)
bad = cp.as_reader().as_builder()
bad.safetyConfigs[0].safetyParam = 585
bad.openpilotLongitudinalControl = False
self.assertFalse(qualified(bad))
# The separately paired DSU port supports legacy IS with stock LONG.
cp = CarInterface.get_params(CAR.LEXUS_IS, gen_empty_fingerprint(), [], True, False, False)
self.assertTrue(qualified(cp))
+8 -5
View File
@@ -32,6 +32,7 @@ def _configured_transport_native(sm, cp, session, now_ns, native=None, *, requir
(require_longitudinal and native.requestedLongitudinal and str(config.safetyModel) not in ('silent', 'noOutput') and not p.controlsAllowed)
for p, config in zip(native.pandaInventory, cp.safetyConfigs, strict=True))):
return None
# v2: producer-read 200ms lease; separate BOOTTIME veto.
stamp = int(sm.logMonoTime['pandaStates'])
if not (sm.seen['pandaStates'] and sm.valid['pandaStates'] and sm.alive['pandaStates'] and
stamp > 0 and (coherent or stamp <= now_ns and now_ns - stamp <= SAFETY_MAX_AGE_NS)):
@@ -100,7 +101,6 @@ class TransportPauseFeedback:
self.cp = cp_identity(cp)
self.session = ''
self.sequence = 0
self.subaru_paddle_denial = None
self.signature = None
self.paused = False
self.qualified = False
@@ -216,6 +216,7 @@ class TransportPauseFeedback:
not axis.desiredLongitudinal and not axis.longitudinalActive) and not cs.regenBraking and
cs.cruiseState.available and not cs.doorOpen and not cs.seatbeltUnlatched and
not cs.vehicleSensorsInvalid and cs.gearShifter == structs.CarState.GearShifter.drive)
# Require fresh LAT and all health/fault checks.
ford_long = bool(ford_qualified(cp, marked_only=True) and cp.openpilotLongitudinalControl)
from opendbc.car.volkswagen.long_aol import qualified as volkswagen_long_qualified
cancel_event_ns = int(sm.logMonoTime['onroadEvents'])
@@ -270,6 +271,8 @@ class TransportPauseFeedback:
log.OnroadEvent.EventName.buttonCancel)) for event in sm['onroadEvents'])):
return None
native = independent_lateral_health(sm, cp, cs, self.session, now_ns)
# Brake health may precede axis status.
# Cancel needs acknowledged LAT, original deadlines and a fresh withdrawal event.
ford_cancel_health = bool(ford_withdrawal and not cs.cruiseState.enabled and
not axis.desiredLongitudinal and not axis.longitudinalActive and
0 < event_ns <= now_ns and (now_ns - event_ns <= AXIS_MAX_AGE_NS or
@@ -803,6 +806,7 @@ class TransportPauseFeedback:
native.observedMonoTime < self.lateral_native_ns or
(native.pandaSerial, tuple(p.hardwareSerial for p in native.pandaInventory)) != self.lateral_inventory):
return False
# Stock USER: LONG-off; source-zero requires LAT-only/native proof.
previous = self.signature
from openpilot.starpilot.car.toyota.aol import qualified as toyota_qualified
toyota_pedal = bool(toyota_qualified(cp, marked_only=True) and cs.brakePressed != cs.gasPressed and
@@ -825,6 +829,7 @@ class TransportPauseFeedback:
(previous[9] and previous[5] == 'none' or (self.retention_verified or self.retention_started_ns) and
previous[5] == 'availabilityPause' and previous[8] == 0 and not previous[9] and
previous[6] == axis.faultEventMonoTime) or
# Critical: matched lag only; otherwise keep pending_event.
self.lateral_only_baseline and not self.failed and not self.pending_event and
(previous[5] == 'critical' or previous[5] == 'availabilityPause' and self.ordinary_warning_retained) and
previous[1] == self.sequence and not any(previous[9:14]) and
@@ -1240,7 +1245,6 @@ class TransportPauseFeedback:
self.cold_park_waiting = False
self.cold_main_sparse_waiting = False
self.subaru_braked_main = None
self.subaru_paddle_denial = None
self.subaru_eps_brake_event_ns = 0
stamp = int(sm.logMonoTime['aolAxisState'])
reason = str(axis.faultReason)
@@ -1423,9 +1427,8 @@ class TransportPauseFeedback:
if retain_physical_pause_intent(self, sm, cp, cs, axis, now_ns, latched=latched, producer=intent_producer_session):
return False
if cp.brand == 'subaru' and current and continuity:
from openpilot.starpilot.car.subaru.paused_intent import retain_paddle_denial, retain_paused_restriction
if (retain_paddle_denial(self, sm, cp, cs, axis, stamp, now_ns, latched=latched, producer=intent_producer_session) or
retain_paused_restriction(self, sm, cp, cs, axis, stamp, now_ns, latched=latched, producer=intent_producer_session)):
from openpilot.starpilot.car.subaru.paused_intent import retain_paused_restriction
if retain_paused_restriction(self, sm, cp, cs, axis, stamp, now_ns, latched=latched, producer=intent_producer_session):
self.sequence, self.signature = int(axis.sequence), signature
return False
fit_eps_retained = False
+2 -17
View File
@@ -45,9 +45,6 @@ def set_device_class(major: int, minor: int) -> bool:
BLUEZ = 'org.bluez'
ADAPTER = 'org.bluez.Adapter1'
DEVICE = 'org.bluez.Device1'
# BlueZ Connect failures that mean the device never answered.
UNREACHABLE_ERRORS = ('org.bluez.Error.Failed', 'org.bluez.Error.NotAvailable', 'org.bluez.Error.NotReady',
'org.bluez.Error.ConnectionAttemptFailed', 'org.bluez.Error.BREDR.ProfileUnavailable')
AGENT = 'org.bluez.Agent1'
AGENT_PATH = '/org/starpilot/bluetooth/pairing'
ADMISSION_LOCK = Path('/data/starpilot/bluetooth-owner.lock')
@@ -297,18 +294,8 @@ class BlueZ:
path = self._device_path(address)
if operation == 'forget':
self._call(adapter_path, ADAPTER, 'RemoveDevice', 'o', (path,))
elif operation == 'connect':
try:
self._call(path, DEVICE, 'Connect')
except TimeoutError:
raise BluetoothRejected('Device did not respond', code='unreachable') from None
except BluetoothRejected as error:
# Off, out of range or held by another phone/app; not a changed device.
if str(error) in UNREACHABLE_ERRORS:
raise BluetoothRejected(f'Device did not respond ({error})', code='unreachable') from None
raise
elif operation == 'disconnect':
self._call(path, DEVICE, 'Disconnect')
elif operation in ('connect', 'disconnect'):
self._call(path, DEVICE, operation.capitalize())
else:
raise ValueError('Unsupported Bluetooth operation')
@@ -596,7 +583,6 @@ class BluetoothOwner:
self.admission_lock = admission_lock
self.admission_file = None
self.power_change_active = False
self.uniden: Any = None
def _admission_enter(self) -> None:
if self.admission_file is not None:
@@ -965,7 +951,6 @@ class BluetoothOwner:
self._client().operation(operation, address)
if operation == 'forget':
assert address is not None
self.uniden = None
self._forget_starport_car(address)
if operation == 'power' and not enabled:
self.systemctl(['sudo', '-n', 'systemctl', 'stop', RADIO_UNIT], check=True, timeout=15)
@@ -838,32 +838,6 @@ class BluetoothOwnerTest(unittest.TestCase):
bluez.snapshot()
self.assertIn('Set', calls)
def test_connect_to_silent_device_reports_unreachable_not_changed(self):
bluez = BlueZ.__new__(BlueZ)
objects = {
'/org/bluez/hci0': {'org.bluez.Adapter1': {'Powered': ('b', True)}},
'/org/bluez/hci0/dev_AA_BB_CC_DD_EE_FF': {'org.bluez.Device1': {'Address': ('s', 'AA:BB:CC:DD:EE:FF'), 'Paired': ('b', True)}},
}
failure = []
def call(path, interface, member, signature=None, body=()):
if member == 'GetManagedObjects':
return (objects,)
raise failure[0]
self.enterContext(patch.object(bluez, '_call', call))
for error, code in [(BluetoothRejected('org.bluez.Error.Failed'), 'unreachable'), (TimeoutError(), 'unreachable'),
(BluetoothRejected('org.bluez.Error.NotAuthorized'), 'changed')]:
failure[:] = [error]
with self.assertRaises(BluetoothRejected) as raised:
bluez.operation('connect', 'AA:BB:CC:DD:EE:FF')
self.assertEqual(raised.exception.code, code)
failure[:] = [BluetoothRejected('org.bluez.Error.Failed')]
with self.assertRaises(BluetoothRejected) as raised:
bluez.operation('disconnect', 'AA:BB:CC:DD:EE:FF')
self.assertEqual(raised.exception.code, 'changed')
def test_each_bluez_close_releases_router_and_underlying_connection(self):
closed = []
@@ -244,9 +244,7 @@ def test_actual_selfdrived_alert_path_works_disengaged_and_resets_offroad(monkey
from openpilot.selfdrive.selfdrived.state import StateMachine
from openpilot.starpilot.controllers.mode_actions import SwitchbackCooldown
from openpilot.starpilot.longitudinal.force_stop_alert import HoldAlertState
from openpilot.starpilot.aol.runtime import AxisDecision
daemon = SelfdriveD.__new__(SelfdriveD)
daemon.aol_axis_decision = AxisDecision()
daemon.CP, daemon.AM = vehicle(), AlertManager()
daemon.sm = messaging.SubMaster(['deviceState', 'radarTracks'])
daemon.events, daemon.enabled, daemon.personality, daemon.is_metric = Events(), False, 1, True
-11
View File
@@ -61,14 +61,3 @@ def physical_cancel_lateral_allowed(cp, cs, intent, native, *, settings, previou
native.validUntilMonoTime - native.observedMonoTime <= SAFETY_MAX_AGE_NS)
except (AttributeError, KeyError, IndexError, TypeError, ValueError, OverflowError):
return False
def expected_stopped_lateral_denial(cp, state, native, *, sm, axis_session_id, now_ns):
from openpilot.starpilot.aol.transport_pause import _configured_transport_native
return bool(qualified(cp, marked_only=True) and state.canValid and not state.canTimeout and
state.standstill and state.gearShifter == structs.CarState.GearShifter.drive and
state.cruiseState.available and not state.steerFaultPermanent and not state.accFaulted and
native is not None and native.pandaInventory and native.requestedLateral and not native.lateralAllowed and
not native.requestedLongitudinal and not native.longitudinalAllowed and
_configured_transport_native(sm, cp, axis_session_id, now_ns, native, allow_restricted_lateral=True) == native)
+3 -3
View File
@@ -1,7 +1,7 @@
"""Subaru physical cruise intent with independent lateral authority."""
from opendbc.car import structs
from opendbc.car.subaru.stock_aol import IMPREZA_MAIN_AOL, qualified, temporary_restriction
from opendbc.car.subaru.values import CAR, EARLY_GLOBAL_TORQUE_CARS, FROGGER_ANGLE_SIBLINGS, SubaruSafetyFlags
from opendbc.car.subaru.values import CAR, EARLY_GLOBAL_TORQUE_CARS, SubaruSafetyFlags
from openpilot.starpilot.aol.intent import AolCardIntent
from openpilot.starpilot.aol.policy import AolVehiclePolicy
@@ -115,7 +115,7 @@ def policy_for(cp):
def native_profile_supported(model, param):
return model == int(structs.CarParams.SafetyModel.subaru) and param in (
0, 1, 8, 16, 17, 145, 177, 209, 401, 465, 512, 520, 1169, 1425, 2225, 4096, 4104, 4608, 4616,
SubaruSafetyFlags.EARLY_GLOBAL_TORQUE, SubaruSafetyFlags.EARLY_GLOBAL_TORQUE | 8, 1041, 2065, 3089)
SubaruSafetyFlags.EARLY_GLOBAL_TORQUE, SubaruSafetyFlags.EARLY_GLOBAL_TORQUE | 8)
def native_accepts_cp(cp, model, param):
@@ -248,7 +248,7 @@ def sync_legacy_card_lateral(card, cs, cc) -> None:
def sync_legacy_card_aol(card) -> None:
cs = getattr(getattr(card, "CI", None), "CS", None)
if cs is not None and getattr(getattr(cs, "CP", None), "carFingerprint", None) in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_LEGACY_2025}:
if cs is not None and getattr(getattr(cs, "CP", None), "carFingerprint", None) == CAR.SUBARU_LEGACY_2025:
intent = getattr(card, "aol_card_intent", None)
settings = getattr(intent, "settings", None)
cs.aol_enabled = bool(settings.enabled) if settings is not None else bool(card.params.get_bool("AlwaysOnLateral"))
+1 -1
View File
@@ -5,7 +5,7 @@
inline bool subaru_aol_param(uint16_t param) {
return (param == 16U) || (param == 0U) || (param == 1U) || (param == 17U) || (param == 209U) || (param == 465U) || (param == 145U) ||
(param == 1169U) || (param == 1425U) || (param == 401U) || (param == 177U) || (param == 8U) || (param == 520U) || (param == 512U) || (param == 2225U) ||
(param == 4096U) || (param == 4104U) || (param == 4608U) || (param == 4616U) || (param == 8192U) || (param == 8200U) || (param == 1041U) || (param == 2065U) || (param == 3089U);
(param == 4096U) || (param == 4104U) || (param == 4608U) || (param == 4616U) || (param == 8192U) || (param == 8200U);
}
inline constexpr AolSafetyProfile SUBARU_AOL_PROFILE{11U, subaru_aol_param, true};
@@ -1,4 +1,4 @@
"""Parked software-cruise preference for the Subaru AVH startup request."""
"""Parked software-cruise preference for Dom's Legacy AVH startup request."""
from opendbc.car.subaru.avh import eligible
from openpilot.starpilot.saved_document import commit_exact
@@ -134,57 +134,6 @@ def retain_stopped_source_feedback(feedback, sm, cp, state, axis, stamp, now_ns,
feedback.healthy_inventory == (native.pandaSerial, tuple(slot.hardwareSerial for slot in native.pandaInventory)))
def retain_paddle_denial(feedback, sm, cp, state, axis, stamp, now_ns, *, latched, producer):
"""Join the gear pause with an early Panda denial of the outgoing LAT request."""
from openpilot.starpilot.aol.transport_pause import _configured_transport_native
from openpilot.starpilot.car.subaru.aol import known_paddle_pause
if cp.carFingerprint != CAR.SUBARU_IMPREZA_2020:
return False
pending = feedback.subaru_paddle_denial
feedback.subaru_paddle_denial = None
previous = feedback.signature
paddle = known_paddle_pause(cp, state)
drive = state.gearShifter == structs.CarState.GearShifter.drive
epoch = int(axis.intentIntegrityEpoch)
if (not (paddle or pending is not None and drive) or not latched or feedback.failed or feedback.paused or
feedback.pending_event or feedback.retention_started_ns or feedback.source_retention_started_ns or
not feedback.ever_lateral_active or previous is None or not feedback.session or not producer or
previous[0] != feedback.session or previous[7] != feedback.session or previous[5] != 'none' or
previous[10] or previous[12] or previous[14:16] != (producer, epoch) or
axis.intentProducerSessionId != producer or str(axis.sessionId) != feedback.session or
str(axis.faultReason) != 'none' or axis.desiredLongitudinal or axis.longitudinalActive or
not 0 < previous[8] <= axis.sourceCarStateMonoTime <= stamp <= now_ns or
now_ns - axis.sourceCarStateMonoTime > AXIS_MAX_AGE_NS or
not state.canValid or state.canTimeout or state.steerFaultTemporary or state.steerFaultPermanent or
state.accFaulted or state.vehicleSensorsInvalid or state.doorOpen or state.seatbeltUnlatched or
state.steeringDisengage or state.buttonEvents or not state.cruiseState.available or state.cruiseState.enabled):
return False
names = log.OnroadEvent.EventName
event_ns = int(sm.logMonoTime['onroadEvents'])
if (not sm.seen['onroadEvents'] or not sm.valid['onroadEvents'] or not sm.alive['onroadEvents'] or
not 0 < event_ns <= now_ns or now_ns - event_ns > 1_500_000_000 or
any(e.immediateDisable or e.softDisable and e.name != names.wrongGear or
e.userDisable and e.name != names.pcmDisable and not (e.name == names.pedalPressed and state.brakePressed)
for e in sm['onroadEvents'])):
return False
native = _configured_transport_native(sm, cp, feedback.session, now_ns, allow_restricted_lateral=True)
if (native is None or not native.pandaInventory or not native.requestedLateral or native.lateralAllowed or
native.requestedLongitudinal or native.longitudinalAllowed or
feedback.healthy_inventory != (native.pandaSerial, tuple(slot.hardwareSerial for slot in native.pandaInventory))):
return False
denied_ns = int(native.observedMonoTime)
if pending is None:
if (not paddle or not previous[9] or not previous[11] or not previous[13] or
not 0 < previous[8] <= previous[2] <= now_ns <= previous[4] or
not 0 < feedback.healthy_native_ns < denied_ns <= now_ns):
return False
elif pending != (denied_ns, producer, epoch):
return False
feedback.subaru_paddle_denial = denied_ns, producer, epoch
return True
def retain_paused_restriction(feedback, sm, cp, state, axis, stamp, now_ns, *, latched, producer):
"""Accepted intent survives coherent OFF, waiting, and active LAT phases."""
if retain_pending_restriction_recovery(feedback, sm, cp, state, axis, stamp, now_ns, latched=latched, producer=producer):
@@ -2,7 +2,7 @@ from dataclasses import replace
from pathlib import Path
from opendbc.car import gen_empty_fingerprint
from opendbc.car.subaru.interface import CarInterface
from opendbc.car.subaru.values import CAR, FROGGER_ANGLE_SIBLINGS
from opendbc.car.subaru.values import CAR
from openpilot.common.params import Params
from openpilot.starpilot.ui.feature_settings_owner import FeatureSettingsOwner
from openpilot.starpilot.ui.feature_settings_state import row_change
@@ -46,9 +46,9 @@ def test_only_supported_identity_and_exact_saved_boolean_startup(tmp_path):
cp = CarInterface.get_params(car, gen_empty_fingerprint(), [], True, False, False)
before = cp.to_dict()
choice.prepare(cp)
assert selected(cp) == (expected and car in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_LEGACY_2025})
assert selected(cp) == (expected and car == CAR.SUBARU_LEGACY_2025)
assert not cp.openpilotLongitudinalControl and not cp.alphaLongitudinalAvailable
if car not in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_LEGACY_2025} or not expected:
if car != CAR.SUBARU_LEGACY_2025 or not expected:
assert cp.to_dict() == before
@@ -6,7 +6,7 @@ from unittest.mock import patch
import pytest
from opendbc.can import CANParser
from opendbc.car import Bus, gen_empty_fingerprint, structs
from opendbc.car.subaru.values import CAR, DBC, FROGGER_ANGLE_SIBLINGS
from opendbc.car.subaru.values import CAR, DBC
from opendbc.car.subaru.fingerprints import FW_VERSIONS
from opendbc.safety.tests.libsafety import libsafety_py
from openpilot.cereal import messaging
@@ -24,25 +24,18 @@ from openpilot.starpilot.car.subaru.tests.native_fixture import subaru_native_pa
@pytest.mark.parametrize('enabled', [False, True])
@pytest.mark.parametrize('combined', [False, True])
@pytest.mark.parametrize('aol', [False, True])
def test_actual_startup_factory_card_controls_native(enabled, combined, aol, subaru_native_pair, tmp_path, configure_delay=0,
candidate=CAR.SUBARU_LEGACY_2025, camera_hud=False):
def test_actual_startup_factory_card_controls_native(enabled, combined, aol, subaru_native_pair, tmp_path, configure_delay=0):
candidate = CAR.SUBARU_LEGACY_2025
fw = firmware_records(candidate, FW_VERSIONS, 'subaru')
rows = []
fingerprint = gen_empty_fingerprint()
if camera_hud:
fingerprint[2][0x3C4] = 8
with actual_factory(candidate, fingerprint, fw, '0' * 17, manual=False, aol=aol,
with actual_factory(candidate, gen_empty_fingerprint(), fw, '0' * 17, manual=False, aol=aol,
preferences={"SubaruAvhStartup": enabled, "SubaruStopStartOff": combined}) as (card, params, matches):
cp = card.CP
ci = card.CI
safety = libsafety_py.libsafety
assert cp.pcmCruise and not cp.openpilotLongitudinalControl and not cp.alphaLongitudinalAvailable
assert cp.alternativeExperience == (32 if aol else 0) and not cp.dashcamOnly
sibling = candidate in FROGGER_ANGLE_SIBLINGS
expected = (2065 if camera_hud else 17) if sibling else 145
assert cp.safetyConfigs[0].safetyParam == expected + (1024 if enabled else 0) + (256 if combined and not sibling else 0)
if sibling:
assert ci.CC.stop_start is None
assert cp.safetyConfigs[0].safetyParam == (145 + (1024 if enabled else 0) + (256 if combined else 0))
sd, controls = SelfdriveD(CP=cp), Controls()
stream = CompleteCan(ci)
base = time.monotonic_ns() + 100_000_000
@@ -197,17 +190,14 @@ def test_actual_startup_factory_card_controls_native(enabled, combined, aol, sub
if any(address == 0x322 for address, _, _ in outgoing):
dash = dash_decoder.vl['ES_LKAS_State']
expected = ci.CC.angle_was_active if steering_name == 'ES_LKAS_ANGLE' else card.sm['carControl'].latActive
if sibling or candidate == CAR.SUBARU_LEGACY_2025:
if candidate == 'SUBARU_LEGACY_2025':
assert bool(dash['LKAS_ACTIVE']), (candidate, tick, expected, dash)
dash_green = ci.CC.aol_dash_green_last if candidate == CAR.SUBARU_LEGACY_2025 else expected
if not cs.cruiseState.available or cs.steerFaultTemporary or cs.steerFaultPermanent:
assert not ci.CC.aol_dash_green_last, (candidate, tick, dash)
if expected:
assert dash_green, (candidate, tick, dash)
assert ci.CC.aol_dash_green_last, (candidate, tick, dash)
ready_wheel = cs.cruiseState.available and bool(getattr(ci.CS, 'aol_enabled', True))
if candidate in FROGGER_ANGLE_SIBLINGS:
ready_wheel = ready_wheel and aol
expected_dash = 2 if dash_green else (1 if ready_wheel else 0)
expected_dash = 2 if ci.CC.aol_dash_green_last else (1 if ready_wheel else 0)
assert dash['LKAS_Dash_State'] == expected_dash, (candidate, tick, expected, expected_dash, dash)
else:
assert bool(dash['LKAS_ACTIVE']) == expected, (candidate, tick, expected, dash)
@@ -253,7 +243,7 @@ def test_actual_startup_factory_card_controls_native(enabled, combined, aol, sub
assert not command.enabled and not command.latActive and not command.longActive, row
assert not safety.get_controls_allowed() and safety.aol_get_permission_mask() == 0, row
if configure_delay == 0:
assert bool(stop_start_emissions) == (combined and not sibling)
assert bool(stop_start_emissions) == combined
assert dash_emissions >= 20
assert bool(startup_emissions) == enabled
assert len(startup_emissions) == (4 if enabled else 0)
@@ -3,7 +3,6 @@ from types import SimpleNamespace
from opendbc.car import structs
from openpilot.starpilot.aol.intent import AolSettings
from openpilot.starpilot.aol.runtime import AxisDecision
from openpilot.starpilot.car.subaru.aol import SubaruStockCardIntent
@@ -255,7 +254,7 @@ def test_legacy_2025_line_visibility_and_passive_dashcam_chimes():
drive.switchback_setting_ns = now
drive.switchback_cooldown_ns = 0
drive.switchback_cooldown = SwitchbackCooldown()
drive.aol_axis_decision = AxisDecision()
drive.aol_axis_decision = None
drive.aol_fault_reason = 'none'
drive.radar_recovery_enabled = False
drive.legacy_2025_green_wheel_active = True
@@ -13,11 +13,8 @@ from openpilot.starpilot.car.subaru.tests.caller_helpers import actual_factory,
@pytest.mark.parametrize('manual', [False, True])
@pytest.mark.parametrize('aol', [False, True])
def test_actual_factory_frozen_default(candidate, manual, aol):
shared_early_fw = candidate == CAR.SUBARU_CROSSTREK_2018
fw_candidate = CAR.SUBARU_IMPREZA if shared_early_fw else candidate
vin = 'JF2GTAAC0JH000001' if shared_early_fw else '0' * 17
fw = firmware_records(fw_candidate, FW_VERSIONS, 'subaru')
with actual_factory(candidate, gen_empty_fingerprint(), fw, vin, manual=manual, aol=aol, firmware_candidate=fw_candidate) as (card, params, _):
fw = firmware_records(candidate, FW_VERSIONS, 'subaru')
with actual_factory(candidate, gen_empty_fingerprint(), fw, '0' * 17, manual=manual, aol=aol) as (card, params, _):
assert card.CP.flags & MARKER
expected = .4 if candidate == CAR.SUBARU_OUTBACK_2023 else 0.
assert read_frozen(card.CP, params) == expected
@@ -6,7 +6,7 @@ from unittest.mock import patch
import pytest
from opendbc.can import CANParser
from opendbc.car import Bus, gen_empty_fingerprint, structs
from opendbc.car.subaru.values import CAR, DBC, FROGGER_ANGLE_SIBLINGS
from opendbc.car.subaru.values import CAR, DBC
from opendbc.car.subaru.fingerprints import FW_VERSIONS
from opendbc.safety.tests.libsafety import libsafety_py
from openpilot.cereal import log, messaging
@@ -25,7 +25,7 @@ from openpilot.starpilot.car.subaru.tests.native_fixture import subaru_native_pa
CAR.SUBARU_FORESTER, CAR.SUBARU_OUTBACK])
def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate, subaru_native_pair, tmp_path, aol=True, manual=False, stop_resume=False,
hard_stop_native_first=False, main_only=False, preferences=None, firmware=None,
manual_ratio=None, camera_hud=False, manual_phase=0,
manual_ratio=None,
deadline_gap=False, fixed_angle_handoff=False, host_first_stop=False,
source_outage=False, vm_angle_handoff=0, crawl=False, eps_brake_join=False,
high_angle_guard=False, main_on_brake=False, guard_brake_release=False,
@@ -38,10 +38,7 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
if candidate == CAR.SUBARU_IMPREZA_2025 and firmware is None:
from opendbc.car.subaru.tests.test_supported_firmware import recorded_impreza_firmware
fw = recorded_impreza_firmware()
fingerprint = gen_empty_fingerprint()
if camera_hud:
fingerprint[2][0x3C4] = 8
with actual_factory(candidate, fingerprint, fw, '0' * 17, manual=manual, aol=aol, preferences=preferences) as (card, params, matches):
with actual_factory(candidate, gen_empty_fingerprint(), fw, '0' * 17, manual=manual, aol=aol, preferences=preferences) as (card, params, matches):
cp = card.CP
ci = card.CI
safety = libsafety_py.libsafety
@@ -82,9 +79,8 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
ticks = (list(range(30)) + list(range(30, 50)) * 16 + list(range(50, 460))
if main_during_eps else list(range(125)) + list(range(125, 135)) * 30 + list(range(135, 460))
if hard_stop_native_first or stop_creep_eps else list(range(70)) + list(range(70, 90)) * 16 + list(range(90, 460))
if angle_continuation else list(range(151)) + list(range(151, 185)) * 54 + list(range(185, 460))
if manual_phase == 1 else list(range(150)) + list(range(150, 185)) * 16 + list(range(185, 460))
if manual_ratio == 137 and not manual_phase else range(460))
if angle_continuation else list(range(150)) + list(range(150, 185)) * 16 + list(range(185, 460))
if manual_ratio == 137 else range(460))
gap_tick = 75 if main_only else 210
last_card_published = {}
pending_host_can = []
@@ -104,7 +100,7 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
brake = bool(brake or angle_continuation and 70 <= tick < 90)
if eps_clear_join and 90 <= tick < 145:
brake = eps_clear_join in (5, 6) and 95 <= tick < 102
reverse = 150 + manual_phase <= tick < 185
reverse = 150 <= tick < 185
gear = manual_ratio if reverse and manual_ratio is not None else 3 if reverse else 121
temporary = not guard_brake_release and 225 <= tick < 260
main = not 310 <= tick < 350 and (tick >= 30 or not main_only)
@@ -164,13 +160,8 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
if 225 <= tick < 260:
values['Steering_Torque'].update(Steering_Angle=100, Steer_Torque_Sensor=94)
values['Wheel_Speeds'] = dict.fromkeys(('FL', 'FR', 'RL', 'RR'), 8)
if vm_angle_handoff and tick >= 90:
values['Steering_2']['Steering_Angle'] = ci.CC.apply_angle_last
if angle_continuation:
angle = ci.CC.apply_angle_last
if reverse:
angle -= min(abs(angle), 3.) * (1 if angle > 0 else -1)
values['Steering_2']['Steering_Angle'] = angle
values['Steering_2']['Steering_Angle'] = ci.CC.apply_angle_last if tick < 90 else 0
values['Wheel_Speeds'] = dict.fromkeys(('FL', 'FR', 'RL', 'RR'), 17.28)
if paused_eps:
values['Dashlights'] = {'LEFT_BLINKER': int(90 <= tick < 115)}
@@ -202,8 +193,6 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
values['Brake_Pressure_L_R'] = {'Steering_Angle': 101 if 125 <= tick < 148 else 0}
else:
values['Steering_Torque']['Steer_Warning'] = int(137 <= tick < 148 or temporary)
if camera_hud and candidate in FROGGER_ANGLE_SIBLINGS:
values['ES_LKAS_Alert'] = {'LKAS_Alert': 25, 'LKAS_HUD_Lights': 0}
incoming = stream.frames(values, tick=tick)
if source_outage:
pending_host_can.append((now, incoming))
@@ -212,8 +201,7 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
safety.safety_rx_hook(libsafety_py.make_CANPacket(addr, bus, data))
safety.safety_tick()
hard_stop_receipt = (hard_stop_native_first or host_first_stop) and elapsed == 125
paddle_native_receipt = bool(manual_phase and elapsed == 150 + manual_phase)
if hard_stop_receipt or paddle_native_receipt:
if hard_stop_receipt:
# Native zero wheels and its USB poll precede the host's stopped CarState.
receipt, hard_order = pandad.step(driven, published, now)
assert hard_order['before'][:2] == (1, 0), hard_order
@@ -250,8 +238,7 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
pending_eps_event = driven_new[service]
else:
peers.append(driven_new[service])
if receipt is not None and (tick % 10 == 1 or paddle_native_receipt or
hard_stop_receipt and not host_first_stop or host_first_stop and elapsed == 127):
if receipt is not None and (tick % 10 == 1 or hard_stop_receipt and not host_first_stop or host_first_stop and elapsed == 127):
peers.append(receipt.as_reader())
if paused_eps in (5, 6):
# SubMaster delivers the latest publication per service after conflation.
@@ -297,7 +284,7 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
if hard_stop_receipt and not host_first_stop:
_assert_hard_stop_fault_guards(card, cs, now + 2000)
# Deliver each genuine10Hz native receipt once; do not refresh receive time/frequency from a cached snapshot.
new_native = receipt if receipt is not None and (tick % 10 == 1 or hard_stop_receipt or paddle_native_receipt) else None
new_native = receipt if receipt is not None and (tick % 10 == 1 or hard_stop_receipt) else None
if deadline_gap and elapsed == gap_tick:
prior = driven['aolAxisState'].aolAxisState
assert prior.lateralActive and now + 2000 > prior.validUntilMonoTime
@@ -348,33 +335,19 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
outgoing = can_capnp_to_list([published['sendcan'].as_builder().to_bytes()], msgtype='sendcan')[0][1] if 'sendcan' in published else []
tx = [(a, d.hex(), b, bool(safety.safety_tx_hook(libsafety_py.make_CANPacket(a, b, d)))) for a, d, b in outgoing]
decoder.update([(now, outgoing)])
if camera_hud and candidate in FROGGER_ANGLE_SIBLINGS:
for address, data, bus, accepted in tx:
if address == 0x3C4:
assert bus == 0 and accepted, (candidate, tick, tx)
stock_chime = bytes((25, 0, 0))
suppress = ci.CS.out.cruiseState.available and ci.CC.angle_was_active and card.sm['carControl'].latActive
expected_alert = bytes(3) if suppress else stock_chime
assert bytes.fromhex(data)[2:5] == expected_alert, (candidate, tick, data)
assert not (candidate in FROGGER_ANGLE_SIBLINGS and any(frame[0] == 0x390 for frame in tx))
dash_decoder.update([(now, outgoing)])
if any(address == 0x322 for address, _, _ in outgoing):
dash = dash_decoder.vl['ES_LKAS_State']
expected = ci.CC.angle_was_active if steering_name == 'ES_LKAS_ANGLE' else card.sm['carControl'].latActive
if candidate in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_LEGACY_2025}:
if candidate == 'SUBARU_LEGACY_2025':
assert bool(dash['LKAS_ACTIVE']), (candidate, tick, expected, dash)
dash_green = ci.CC.aol_dash_green_last if candidate == CAR.SUBARU_LEGACY_2025 else expected
if not cs.cruiseState.available or cs.steerFaultTemporary or cs.steerFaultPermanent:
assert not ci.CC.aol_dash_green_last, (candidate, tick, dash)
if expected:
assert dash_green, (candidate, tick, dash)
assert ci.CC.aol_dash_green_last, (candidate, tick, dash)
ready_wheel = cs.cruiseState.available and bool(getattr(ci.CS, 'aol_enabled', True))
if candidate in FROGGER_ANGLE_SIBLINGS:
ready_wheel = ready_wheel and aol
expected_dash = 2 if dash_green else (1 if ready_wheel else 0)
expected_dash = 2 if ci.CC.aol_dash_green_last else (1 if ready_wheel else 0)
assert dash['LKAS_Dash_State'] == expected_dash, (candidate, tick, expected, expected_dash, dash)
if camera_hud and expected and candidate in FROGGER_ANGLE_SIBLINGS:
assert dash['LKAS_Left_Line_Visible'] and dash['LKAS_Right_Line_Visible'], (candidate, tick, dash)
else:
assert bool(dash['LKAS_ACTIVE']) == expected, (candidate, tick, expected, dash)
assert dash['LKAS_Dash_State'] == (2 if expected else 0), (candidate, tick, expected, dash)
@@ -402,7 +375,7 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
if output != 0:
active_emissions.append(tick)
if 165 <= tick < 180 or 240 <= tick < 255 or not aol and (125 <= tick < 145 or 205 <= tick < 220 or 280 <= tick < 300):
if angle_handoff or angle_continuation:
if angle_handoff:
assert not request and abs(output - cs.steeringAngleDeg) <= 0.011, (tick, decoded_steering)
else:
assert not request and output == 0, (tick, decoded_steering)
@@ -482,10 +455,9 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
assert command.latActive and bool(intent and intent.allowedLatch) == aol and row['permission'] == int(aol), row
if not stopped and (first_resume or 205 <= tick < 220 or 280 <= tick < 300):
assert command.latActive == aol and bool(intent and intent.allowedLatch) == aol and row['permission'] == int(aol) and not row['controls'], row
if manual_ratio is not None and 150 + manual_phase <= tick < 185:
if manual_ratio is not None and 150 <= tick < 185:
assert not command.latActive and row['permission'] == 0 and row['cardLatch'] and row['armed'], row
assert all(not steering['request'] or tick == 150 + manual_phase and not steering['nativeAccepted']
for steering in row['steering']), row
assert all(not steering['request'] for steering in row['steering']), row
if 165 <= tick < 180:
assert (not command.latActive and not bool(intent and intent.allowedLatch) and
bool(intent and intent.lateralArmed) == aol and row['cardLatch'] == aol and row['permission'] == 0), row
@@ -821,10 +793,3 @@ def test_actual_stopped_brake_release_source_gap_keeps_armed_intent(subaru_nativ
def test_actual_crosstrek_manual_ratio_pauses_and_recovers(subaru_native_pair, tmp_path, ratio):
test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(
CAR.SUBARU_IMPREZA_2020, subaru_native_pair, tmp_path, main_only=True, manual_ratio=ratio)
@pytest.mark.parametrize("phase", (1, 4, 7))
def test_actual_crosstrek_native_first_paddle_pause(subaru_native_pair, tmp_path, phase):
test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(
CAR.SUBARU_IMPREZA_2020, subaru_native_pair, tmp_path, main_only=True, manual_ratio=145, manual_phase=phase,
preferences={'SubaruSNG': True})
+2 -4
View File
@@ -2,7 +2,7 @@ from opendbc.car import structs
from opendbc.car.tesla.preap.aol import qualified, temporary_restriction as preap_temporary_restriction
from openpilot.starpilot.aol.policy import AolVehiclePolicy
from openpilot.starpilot.car.tesla.stock_intent import TeslaPreapCardIntent
from opendbc.car.tesla.screen_button import modern_aol_supported, modern_aol_qualified, AOL_WORDS, SPEED_SYNC, SYNC_WORDS
from opendbc.car.tesla.screen_button import modern_aol_supported, modern_aol_qualified, AOL_WORDS
from openpilot.starpilot.car.tesla.screen_intent import TeslaScreenCardIntent
@@ -25,9 +25,7 @@ def policy_for(cp):
def native_profile_supported(model, param):
# Scroll speed sync rides on top of an Always On Lateral word; the panda reports the whole word.
screen = param & ~SPEED_SYNC if param in SYNC_WORDS else param
return (model == 39 and param in (0, 1, 2, 3, 6, 7)) or (model == 10 and screen in AOL_WORDS)
return (model == 39 and param in (0, 1, 2, 3, 6, 7)) or (model == 10 and param in AOL_WORDS)
def native_accepts_cp(cp, model, param):
@@ -10,11 +10,6 @@ inline constexpr AolSafetyProfile TESLA_PREAP_AOL_PROFILE{39U, tesla_preap_aol_p
inline bool tesla_screen_aol_param(uint16_t param) {
param &= ~256U;
// Scroll speed sync (4096) rides on a word with longitudinal control; Always On Lateral sees the word without it,
// as the panda's own screen policy does.
if (((param & 4096U) != 0U) && ((param & 1U) != 0U)) {
param &= ~4096U;
}
return param == 512U || param == 513U || param == 1536U || param == 1537U ||
param == 2048U || param == 2049U || param == 3072U || param == 3073U;
}
@@ -1,5 +1,4 @@
"""Frozen Model 3/Y cooperative steering selection."""
from opendbc.car.tesla.screen_button import SPEED_SYNC, speed_sync_allowed
from opendbc.car.tesla.values import CAR, TeslaSafetyFlags, TeslaFlags
@@ -10,11 +9,6 @@ def supported(cp):
cp.flags & ~int(TeslaFlags.MISSING_DAS_SETTINGS | TeslaFlags.HAS_VEHICLE_BUS | TeslaFlags.AOL_SCREEN_BUTTON)):
return False
word = int(cp.safetyConfigs[0].safetyParam)
# Scroll speed sync rides on top of the cooperative word (e.g. 4353 = 4096 | 256 | 1); it is stripped before the check.
if word & SPEED_SYNC:
if not speed_sync_allowed(cp, word):
return False
word &= ~SPEED_SYNC
return (word in (0, 1, 256, 257, 512, 513, 768, 769, 1536, 1537, 1792, 1793, 2048, 2049, 2304, 2305, 3072, 3073, 3328, 3329) and
bool(word & 1) == bool(cp.openpilotLongitudinalControl))
except (AttributeError, TypeError, ValueError, IndexError):

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