mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-11-26 06:43:43 +08:00
Compare commits
118 Commits
Galaxy-mDNS
...
testing
| Author | SHA1 | Date | |
|---|---|---|---|
| 139d8cbe03 | |||
| b022663e6e | |||
| 4b70f5be81 | |||
| d1baceb3ef | |||
| dfa5c3490f | |||
| 4d6e2a3780 | |||
| 2f508d507c | |||
| aec40a8288 | |||
| ab0b4ccf54 | |||
| 6cd506c47a | |||
| 6ef1123e86 | |||
| 9ade0195e9 | |||
| b9f349c72d | |||
| bb2cd1407e | |||
| 83ebdc716b | |||
| e495c527ca | |||
| 7547aeeb5c | |||
| b4c2dfd8b2 | |||
| 1437f6b8f5 | |||
| 0d8918edf8 | |||
| 670e65d35a | |||
| 0c52893246 | |||
| caa3b2a0f3 | |||
| 944e513e9f | |||
| 13ab471cc5 | |||
| 72aa8b89e1 | |||
| 14babc867a | |||
| 69acfbb085 | |||
| d4ddf420a5 | |||
| 73eb7961d7 | |||
| 273f8b12e8 | |||
| cc36b77b65 | |||
| 3ab9f67c83 | |||
| df47158568 | |||
| bc68e381ae | |||
| f15af75c3a | |||
| 1868dd0b90 | |||
| 5b21a4ba70 | |||
| 6d5466a32f | |||
| 5dbc1d51b6 | |||
| 48971bc6f9 | |||
| 6a958352e2 | |||
| bf8efea392 | |||
| 8f40396736 | |||
| b51d18fd56 | |||
| ac77f9a20c | |||
| 25323cef46 | |||
| b094bcb4f7 | |||
| ca16979a38 | |||
| fa0914406f | |||
| f86381d823 | |||
| 206a8554db | |||
| b32fc5ec98 | |||
| 22d4d34405 | |||
| 0b18c93532 | |||
| 0f8f2a5ace | |||
| a1084ad630 | |||
| 6509fa1a00 | |||
| f06a781387 | |||
| 5c20480f13 | |||
| 13b4344a06 | |||
| be196c0baa | |||
| bf0344ffd7 | |||
| 24b5235ed5 | |||
| 725a530d8e | |||
| 1a53844575 | |||
| eaeb680b0a | |||
| 7e9e2b43b3 | |||
| d0a212be98 | |||
| c9fea63596 | |||
| 8852c7bce6 | |||
| 71a9228954 | |||
| 63fe5bb3e1 | |||
| 697dcf29e0 | |||
| 591c5fcf53 | |||
| 78303dda84 | |||
| fb4468b347 | |||
| c707dd4938 | |||
| 698a203cbc | |||
| db79a4620d | |||
| 48fb24ee48 | |||
| 22f010c1ac | |||
| d89f221d06 | |||
| 07331b33e8 | |||
| 951beb26be | |||
| 683435ac68 | |||
| 241e0a43d4 | |||
| fad5a9faaf | |||
| 19b7edf344 | |||
| ab02d5a44c | |||
| 8a9f7a084c | |||
| e59fa4930a | |||
| 855dfb3a17 | |||
| 026ce00b72 | |||
| 3728cea591 | |||
| bc1edc500d | |||
| 330a302aa1 | |||
| 6e879b55da | |||
| 059612c13a | |||
| bbe680c127 | |||
| ceb0bea247 | |||
| 35c80054d3 | |||
| 6cfa8b9f25 | |||
| 919363f4fa | |||
| 131ad10d63 | |||
| 47346ad98b | |||
| 9c5a5e5b86 | |||
| ce47ff1da3 | |||
| 55269d0856 | |||
| 0da55d93ae | |||
| 6f73fad098 | |||
| 9da91c24af | |||
| bd2e523bfe | |||
| 70de2df8f2 | |||
| 9a32c18941 | |||
| f67edb6529 | |||
| 7dbbb43c3b | |||
| 404ef33a96 |
@@ -49,3 +49,7 @@ 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).
|
||||
|
||||
@@ -154,3 +154,7 @@ 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).
|
||||
|
||||
@@ -16,7 +16,8 @@ from opendbc.car.ford.discovery import (normal_bus0_selection as ford_normal_bus
|
||||
normal_bus0_queries as ford_normal_bus0_queries, normal_bus_query_brand)
|
||||
from opendbc.car.volvo.discovery import normal_bus_topology as volvo_normal_bus_topology, v60_bus_topology as volvo_v60_bus_topology
|
||||
from opendbc.car.hyundai.discovery import normal_bus_topology
|
||||
from opendbc.car.honda.discovery import nidec_bus0_topology, normal_bus_topology as honda_normal_bus_topology
|
||||
from opendbc.car.honda.discovery import (eps_needs_obd as honda_eps_needs_obd, nidec_bus0_topology,
|
||||
normal_bus_topology as honda_normal_bus_topology)
|
||||
from opendbc.car.honda.values import CAR as HONDA, HondaFlags
|
||||
from opendbc.car.mazda.discovery import normal_bus0_topology as mazda_normal_bus0_topology
|
||||
from opendbc.car.chrysler.discovery import normal_bus_topology as chrysler_normal_bus_topology
|
||||
@@ -215,6 +216,12 @@ def fingerprint(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_mu
|
||||
else:
|
||||
car_fw = get_fw_versions(can_recv, can_send, set_obd_multiplexing,
|
||||
query_brand=normal_brand, normal_bus_only=True)
|
||||
if normal_brand == 'honda' and honda_eps_needs_obd(match_fw_to_car(car_fw, vin)[1], car_fw):
|
||||
# Read this car's VIN and EPS through the OBD port, as the generic path below does. Without the VIN
|
||||
# the result is never cached, so every start would repeat the query.
|
||||
set_obd_multiplexing(True)
|
||||
vin_rx_addr, vin_rx_bus, vin = get_vin(can_recv, can_send, (0, 1))
|
||||
car_fw = get_fw_versions(can_recv, can_send, set_obd_multiplexing, query_brand='honda')
|
||||
ecu_rx_addrs = {(fw.responseAddress, fw.subAddress or None, fw.bus) for fw in car_fw if fw.responseAddress > 0}
|
||||
else:
|
||||
full_scan = True
|
||||
|
||||
@@ -375,6 +375,7 @@ FW_VERSIONS = {
|
||||
b'68402704AB',
|
||||
b'68402707AB',
|
||||
b'68402708AB',
|
||||
b'68402710AB',
|
||||
b'68402714AB',
|
||||
b'68402736AB',
|
||||
b'68402971AD',
|
||||
@@ -421,6 +422,7 @@ FW_VERSIONS = {
|
||||
b'68412635AH ',
|
||||
b'68412660AD ',
|
||||
b'68412660AF ',
|
||||
b'68422857AD',
|
||||
b'68422860AB',
|
||||
b'68449435AE ',
|
||||
b'68496223AA ',
|
||||
@@ -435,6 +437,7 @@ FW_VERSIONS = {
|
||||
b'68419675AC',
|
||||
b'68419678AB',
|
||||
b'68423905AB',
|
||||
b'68423907AB',
|
||||
b'68449258AC',
|
||||
b'68495807AA',
|
||||
b'68495807AB',
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Recorded ECU identity for the EU 2019 Grand Cherokee, opendbc issue 4101."""
|
||||
import pytest
|
||||
|
||||
from opendbc.car import structs
|
||||
from opendbc.car.chrysler.interface import CarInterface
|
||||
from opendbc.car.chrysler.values import CAR, ChryslerFlags
|
||||
from opendbc.car.fingerprints import FW_VERSIONS
|
||||
from opendbc.car.fw_versions import match_fw_to_car
|
||||
|
||||
Ecu = structs.CarParams.Ecu
|
||||
RECORDED = (
|
||||
(Ecu.combinationMeter, 0x742, b'68402710AB'),
|
||||
(Ecu.srs, 0x744, b'68355363AB'),
|
||||
(Ecu.abs, 0x747, b'68408639AC'),
|
||||
(Ecu.fwdRadar, 0x753, b'04672788AA'),
|
||||
(Ecu.eps, 0x75a, b'68417281AA'),
|
||||
(Ecu.engine, 0x7e0, b'68422857AD'),
|
||||
(Ecu.transmission, 0x7e1, b'68423907AB'),
|
||||
)
|
||||
ADDED = {b'68402710AB', b'68422857AD', b'68423907AB'}
|
||||
|
||||
|
||||
def firmware():
|
||||
return [structs.CarParams.CarFw(ecu=ecu, address=address, fwVersion=version, brand='chrysler', bus=0)
|
||||
for ecu, address, version in RECORDED]
|
||||
|
||||
|
||||
def test_recorded_eu_diesel_is_a_unique_exact_match():
|
||||
fw = firmware()
|
||||
assert match_fw_to_car(fw, '', allow_fuzzy=False, log=False) == (True, {CAR.JEEP_GRAND_CHEROKEE_2019})
|
||||
# The route also contains unrelated cross-brand responses at the engine's neighbor.
|
||||
fw.append(structs.CarParams.CarFw(ecu=Ecu.transmission, address=0x7e1, fwVersion=b'\xf1\0\0E\x01\x01', brand='hyundai', bus=1))
|
||||
assert match_fw_to_car(fw, '', allow_fuzzy=False, log=False) == (True, {CAR.JEEP_GRAND_CHEROKEE_2019})
|
||||
|
||||
|
||||
@pytest.mark.parametrize('index', range(len(RECORDED)))
|
||||
def test_unknown_firmware_still_refuses_exact_match(index):
|
||||
fw = firmware()
|
||||
fw[index].fwVersion = b'UNRECOGNIZED'
|
||||
assert match_fw_to_car(fw, '', allow_fuzzy=False, log=False) == (True, set())
|
||||
|
||||
|
||||
def test_additions_are_scoped_to_the_existing_2019_jeep():
|
||||
for identity, ecus in FW_VERSIONS.items():
|
||||
found = {version for versions in ecus.values() for version in versions} & ADDED
|
||||
assert found == (ADDED if identity == CAR.JEEP_GRAND_CHEROKEE_2019 else set())
|
||||
|
||||
|
||||
@pytest.mark.parametrize('alpha_long', (False, True))
|
||||
def test_diesel_retains_stock_acc_pid_and_native_limits(alpha_long):
|
||||
cp = CarInterface.get_params(CAR.JEEP_GRAND_CHEROKEE_2019, {b: {} for b in range(8)}, firmware(), alpha_long, False, False)
|
||||
assert cp.pcmCruise and not cp.openpilotLongitudinalControl
|
||||
assert cp.safetyConfigs[0].safetyModel == structs.CarParams.SafetyModel.chrysler
|
||||
assert cp.safetyConfigs[0].safetyParam == 0
|
||||
assert cp.minSteerSpeed == 17.5 and cp.lateralTuning.which() == 'pid'
|
||||
assert cp.flags & ChryslerFlags.HIGHER_MIN_STEERING_SPEED
|
||||
assert not cp.flags & ChryslerFlags.STEERING_SPEED_BYPASS
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Normal-bus discovery for explicitly selected Ford CAN-FD vehicles."""
|
||||
"""Normal-bus discovery for Ford vehicles."""
|
||||
import time
|
||||
|
||||
from opendbc.car.ford.values import CAR, FordFlags
|
||||
@@ -42,7 +42,8 @@ def normal_bus0_selection(candidate):
|
||||
# diagnostic query family; live VIN, ECU responses and fingerprinting still
|
||||
# determine the vehicle and its control configuration.
|
||||
NORMAL_BUS0_LAYOUT = {(0, 0x82): 8, (0, 0x165): 8, (0, 0x204): 8,
|
||||
(0, 0x217): 8, (2, 0x3CA): 8, (2, 0x3D6): 8}
|
||||
(0, 0x217): 8, (2, 0x3CA): 8}
|
||||
CAMERA_STEERING_LAYOUT = {(2, 0x3D3): 8, (2, 0x3D6): 8}
|
||||
|
||||
|
||||
def normal_bus_query_brand(can_recv, hyundai_probe, *, gm_probe=None, volvo_probe=None, tesla_probe=None, clock=time.monotonic):
|
||||
@@ -55,6 +56,10 @@ def normal_bus_query_brand(can_recv, hyundai_probe, *, gm_probe=None, volvo_prob
|
||||
reads = 0
|
||||
deadline = clock() + .12
|
||||
|
||||
def complete():
|
||||
return (not malformed and NORMAL_BUS0_LAYOUT.items() <= received.items() and
|
||||
any(key in received for key in CAMERA_STEERING_LAYOUT))
|
||||
|
||||
def observe(**kwargs):
|
||||
nonlocal malformed, gm_malformed, reads
|
||||
reads += 1
|
||||
@@ -67,9 +72,9 @@ def normal_bus_query_brand(can_recv, hyundai_probe, *, gm_probe=None, volvo_prob
|
||||
length = len(frame.dat)
|
||||
gm_malformed |= frame.address in bus and bus[frame.address] != length
|
||||
bus[frame.address] = length
|
||||
if key in NORMAL_BUS0_LAYOUT:
|
||||
if (expected := NORMAL_BUS0_LAYOUT.get(key) or CAMERA_STEERING_LAYOUT.get(key)) is not None:
|
||||
length = len(frame.dat)
|
||||
malformed |= length != NORMAL_BUS0_LAYOUT[key]
|
||||
malformed |= length != expected
|
||||
received[key] = length
|
||||
return packets
|
||||
|
||||
@@ -77,11 +82,11 @@ def normal_bus_query_brand(can_recv, hyundai_probe, *, gm_probe=None, volvo_prob
|
||||
return 'hyundai'
|
||||
# Rejecting HKG or Ford does not reject GM. Finish the shared passive window
|
||||
# within its original budget even when an early frame excludes Ford.
|
||||
while not (not malformed and received == NORMAL_BUS0_LAYOUT) and reads < 24 and clock() < deadline:
|
||||
while not complete() and reads < 24 and clock() < deadline:
|
||||
if malformed and ((gm_probe is None and volvo_probe is None and tesla_probe is None) or gm_malformed):
|
||||
break
|
||||
observe(wait_for_one=True)
|
||||
if not malformed and received == NORMAL_BUS0_LAYOUT and normal_bus0_queries():
|
||||
if complete() and normal_bus0_queries():
|
||||
return 'ford'
|
||||
if gm_probe is not None and not gm_malformed and gm_probe(gm_received):
|
||||
return 'gm'
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
from opendbc.car import ACCEL_MAX_TAKEOFF
|
||||
|
||||
@@ -10,9 +12,12 @@ from opendbc.car.honda.nidec_interceptor import NidecInterceptor, create_command
|
||||
from opendbc.car.honda.bosch_longitudinal import BoschLongitudinal, qualified as bosch_long_qualified
|
||||
from opendbc.car.honda.values import CAR, CruiseButtons, HondaFlags, CarControllerParams
|
||||
from opendbc.car.interfaces import CarControllerBase
|
||||
from opendbc.car.lateral import apply_steer_angle_limits_vm, get_max_angle_delta_vm
|
||||
from opendbc.car.vehicle_model import VehicleModel
|
||||
|
||||
VisualAlert = structs.CarControl.HUDControl.VisualAlert
|
||||
LongCtrlState = structs.CarControl.Actuators.LongControlState
|
||||
SteerControlType = structs.CarParams.SteerControlType
|
||||
|
||||
|
||||
def compute_gb_honda_bosch(accel, speed):
|
||||
@@ -120,6 +125,54 @@ class CarController(CarControllerBase):
|
||||
self.brake = 0.0
|
||||
self.last_torque = 0.0
|
||||
|
||||
# Accord angle-loop EPS (interface.py sets steerControlType = angle)
|
||||
self.angle_mode = CP.steerControlType == SteerControlType.angle
|
||||
self.VM = VehicleModel(CP) if self.angle_mode else None
|
||||
self.apply_angle_last = None # None until the first frame seeds the limiter from the wheel
|
||||
self.angle_steer_req = False # STEER_TORQUE_REQUEST of the last angle frame
|
||||
|
||||
def _angle_hold_allowed(self, CC, CS) -> bool:
|
||||
# The panda blocks a nonzero 0xE4 field unless lateral_controls_allowed(). Without an AOL policy that is
|
||||
# controls_allowed (needs ACC main on and engagement); with one it is a session-acknowledged axis permission the
|
||||
# carcontroller cannot see, so the hold is sent only in the subset every policy allows: enabled with main on.
|
||||
return bool(CS.out.cruiseState.available) and bool(CC.enabled)
|
||||
|
||||
def _update_angle(self, CC, CS) -> tuple[float, int]:
|
||||
"""Angle setpoint (deg) and the 0xE4 STEER_TORQUE field."""
|
||||
p = self.params
|
||||
steering_angle = float(CS.out.steeringAngleDeg)
|
||||
angle_last = steering_angle if self.apply_angle_last is None else self.apply_angle_last
|
||||
desired = float(CC.actuators.steeringAngleDeg)
|
||||
if CC.latActive:
|
||||
# error clip first: it shapes the request, bounding the P torque the setpoint asks of the EPS
|
||||
error_max = float(np.interp(CS.out.vEgoRaw, p.ANGLE_ERROR_MAX_BP, p.ANGLE_ERROR_MAX_V))
|
||||
desired = float(np.clip(desired, steering_angle - error_max, steering_angle + error_max))
|
||||
# The lateral accel and jerk limits (3.589) are the last adjustment: applied to exactly what is sent and seeded
|
||||
# from the last value sent. The panda runs the same check on the frame (honda.h) and blocks one that exceeds it,
|
||||
# so nothing may change the setpoint after this line.
|
||||
apply_angle = apply_steer_angle_limits_vm(desired, angle_last, CS.out.vEgoRaw, steering_angle, CC.latActive, p, self.VM)
|
||||
self.angle_steer_req = bool(CC.latActive)
|
||||
if CC.latActive:
|
||||
v = max(float(CS.out.vEgoRaw), 1.0)
|
||||
max_delta = min(get_max_angle_delta_vm(v, self.VM, p), p.ANGLE_LIMITS.MAX_ANGLE_RATE)
|
||||
if abs(apply_angle - angle_last) > max_delta + 1e-6:
|
||||
# The accel limit is further from the last value sent than the jerk limit lets one frame move: the wheel is
|
||||
# past the limit as the request starts. No setpoint satisfies both, and the panda would drop the frame, so
|
||||
# the request waits at the wheel until the wheel is back inside.
|
||||
apply_angle = steering_angle
|
||||
self.angle_steer_req = False
|
||||
self.apply_angle_last = apply_angle
|
||||
|
||||
# raw = round(-10 * deg), half-up; left-positive degrees are negative raw
|
||||
if CC.latActive:
|
||||
raw = math.floor(-10.0 * apply_angle + 0.5)
|
||||
elif self._angle_hold_allowed(CC, CS):
|
||||
# idle hold: keep the setpoint at the wheel so engagement starts without a step
|
||||
raw = math.floor(-10.0 * steering_angle + 0.5)
|
||||
else:
|
||||
raw = 0 # the panda blocks a nonzero field here
|
||||
return apply_angle, int(np.clip(raw, -p.ANGLE_RAW_MAX, p.ANGLE_RAW_MAX))
|
||||
|
||||
def update(self, CC, CS, now_nanos):
|
||||
_projection = self.learning_projection_observer
|
||||
if _projection is not None:
|
||||
@@ -176,7 +229,12 @@ class CarController(CarControllerBase):
|
||||
can_sends.append(make_tester_present_msg(0x18DAB0F1, 1, suppress_response=True))
|
||||
|
||||
# Send steering command.
|
||||
can_sends.append(hondacan.create_steering_control(self.packer, self.CAN, apply_torque, CC.latActive, self.tja_control))
|
||||
if self.angle_mode:
|
||||
apply_angle, angle_raw = self._update_angle(CC, CS)
|
||||
can_sends.append(hondacan.create_steering_control(self.packer, self.CAN, angle_raw, self.angle_steer_req,
|
||||
self.tja_control, angle_arm=self.params.ANGLE_ARM))
|
||||
else:
|
||||
can_sends.append(hondacan.create_steering_control(self.packer, self.CAN, apply_torque, CC.latActive, self.tja_control))
|
||||
if _projection is not None:
|
||||
_projection.emit('honda.STEERING_CONTROL', apply_torque, CC.latActive, can_sends[-1])
|
||||
|
||||
@@ -286,6 +344,9 @@ class CarController(CarControllerBase):
|
||||
new_actuators.brake = self.brake
|
||||
new_actuators.torque = self.last_torque
|
||||
new_actuators.torqueOutputCan = apply_torque
|
||||
if self.angle_mode:
|
||||
new_actuators.steeringAngleDeg = apply_angle
|
||||
new_actuators.torqueOutputCan = angle_raw # the 0xE4 STEER_TORQUE field as sent (-10 x deg)
|
||||
|
||||
self.frame += 1
|
||||
if _projection is not None:
|
||||
|
||||
@@ -13,6 +13,7 @@ from opendbc.car.dashboard_speed_limit import Tracker as LimitTracker, honda_sig
|
||||
from opendbc.can.dbc import DBC as CANDBC
|
||||
|
||||
TransmissionType = structs.CarParams.TransmissionType
|
||||
SteerControlType = structs.CarParams.SteerControlType
|
||||
ButtonType = structs.CarState.ButtonEvent.Type
|
||||
|
||||
BUTTONS_DICT = {CruiseButtons.RES_ACCEL: ButtonType.accelCruise, CruiseButtons.DECEL_SET: ButtonType.decelCruise,
|
||||
@@ -120,6 +121,16 @@ class CarState(CarStateBase):
|
||||
ret.steerFaultPermanent = False
|
||||
ret.steerFaultTemporary = False
|
||||
|
||||
if self.CP.flags & HondaFlags.EPS_FW_UNREAD:
|
||||
ret.steerFaultPermanent = True
|
||||
|
||||
if self.CP.steerControlType == SteerControlType.angle and self.CP.flags & HondaFlags.EPS_ANGLE_LOOP_FW:
|
||||
# the angle-loop EPS's angle is a valid absolute angle only while all three sensor status bits read 1; outside
|
||||
# that the EPS would servo from a false angle, so do not steer
|
||||
sensors = cp.vl["STEERING_SENSORS"]
|
||||
if not all(sensors[f"STEER_SENSOR_STATUS_{i}"] == 1 for i in (1, 2, 3)):
|
||||
ret.steerFaultTemporary = True
|
||||
|
||||
# All Honda EPS cut off slightly above standstill, some much higher
|
||||
# Don't alert in the near-standstill range, but alert for per-vehicle configured minimums above that
|
||||
if CarControllerParams.STEER_GLOBAL_MIN_SPEED < ret.vEgo < (self.CP.minSteerSpeed + 0.5):
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from opendbc.car.honda.hondacan import honda_checksum
|
||||
from opendbc.car.honda.values import CAR
|
||||
|
||||
|
||||
# Classic Bosch: PT on bus 1 and the stock ACC camera on bus 2. This selects
|
||||
@@ -30,3 +31,9 @@ def normal_bus_topology(packets, *, layout=NORMAL_BUS_LAYOUT):
|
||||
|
||||
def nidec_bus0_topology(packets):
|
||||
return any(normal_bus_topology(packets, layout=layout) for layout in NIDEC_BUS0_LAYOUTS)
|
||||
|
||||
|
||||
def eps_needs_obd(candidates, car_fw) -> bool:
|
||||
"""The Accord's EPS answers only through the OBD port (never on the normal bus 1 wiring), and its firmware
|
||||
family decides between angle and torque steering. A normal-bus read that names the Accord is not complete."""
|
||||
return CAR.HONDA_ACCORD in candidates and not any(fw.ecu == "eps" and not fw.logging for fw in car_fw)
|
||||
|
||||
@@ -117,11 +117,15 @@ def create_acc_commands(packer, CAN, enabled, active, accel, gas, stopping_count
|
||||
return commands
|
||||
|
||||
|
||||
def create_steering_control(packer, CAN, apply_torque, lkas_active, tja_control):
|
||||
def create_steering_control(packer, CAN, apply_torque, lkas_active, tja_control, angle_arm=None):
|
||||
# angle_arm (Accord angle-loop EPS only): STEER_TORQUE is the angle setpoint, sent with the request off too, and
|
||||
# STEER_CONTROL_ARM carries the arm the EPS lane requires. None = the torque frame, unchanged.
|
||||
values = {
|
||||
"STEER_TORQUE": apply_torque if lkas_active else 0,
|
||||
"STEER_TORQUE": apply_torque if (lkas_active or angle_arm is not None) else 0,
|
||||
"STEER_TORQUE_REQUEST": lkas_active,
|
||||
}
|
||||
if angle_arm is not None:
|
||||
values["STEER_CONTROL_ARM"] = angle_arm
|
||||
|
||||
if tja_control:
|
||||
values["STEER_DOWN_TO_ZERO"] = lkas_active
|
||||
|
||||
@@ -7,7 +7,9 @@ from opendbc.car import Bus, get_safety_config, structs, uds
|
||||
from opendbc.car.common.conversions import Conversions as CV
|
||||
from opendbc.car.disable_ecu import disable_ecu
|
||||
from opendbc.car.honda.hondacan import CanBus
|
||||
from opendbc.car.honda.values import CarControllerParams, HondaFlags, CAR, HondaSafetyFlags, MANUAL_TRANS_CARS, MODIFIED_EPS_FW, DBC
|
||||
from opendbc.car.honda.values import CarControllerParams, HondaFlags, CAR, HondaSafetyFlags, MANUAL_TRANS_CARS, MODIFIED_EPS_FW, DBC, \
|
||||
is_accord_eps_angle_loop_fw
|
||||
from opendbc.car.lateral import MAX_LATERAL_ACCEL
|
||||
from opendbc.car.honda.carcontroller import CarController
|
||||
from opendbc.car.honda.carstate import CarState
|
||||
from opendbc.car.honda.radar_interface import RadarInterface
|
||||
@@ -100,7 +102,12 @@ class CarInterface(CarInterfaceBase):
|
||||
ret.longitudinalTuning.kiV = [1.2, 0.8, 0.5]
|
||||
|
||||
eps_observations = [fw for fw in car_fw if fw.ecu == "eps" and not fw.logging]
|
||||
modified_eps = any(b"," in fw.fwVersion for fw in eps_observations)
|
||||
# Accord angle-loop EPS firmware (39990-TVA,A16<letter>): the EPS closes the angle loop and openpilot sends the
|
||||
# setpoint. Not a torque-modified EPS, so it is kept out of the MODIFIED_EPS_FW allow-list check below (which would
|
||||
# otherwise make the car dashcam-only). Every EPS response must be the family; a mixed read falls through to it.
|
||||
eps_angle_loop_fw = (candidate == CAR.HONDA_ACCORD and len(eps_observations) > 0 and
|
||||
all(is_accord_eps_angle_loop_fw(fw.fwVersion) for fw in eps_observations))
|
||||
modified_eps = not eps_angle_loop_fw and any(b"," in fw.fwVersion for fw in eps_observations)
|
||||
eps_modified = bool(modified_eps) and all(
|
||||
fw.address == 0x18DA30F1 and fw.subAddress == 0 and
|
||||
fw.fwVersion in MODIFIED_EPS_FW.get(candidate, ()) for fw in eps_observations)
|
||||
@@ -121,6 +128,21 @@ class CarInterface(CarInterfaceBase):
|
||||
|
||||
elif candidate == CAR.HONDA_ACCORD:
|
||||
ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = ([[0.3], [0.09]] if eps_modified else [[0.6], [0.18]])
|
||||
if eps_angle_loop_fw:
|
||||
# angle-loop EPS firmware: the EPS closes the angle loop, openpilot sends the setpoint
|
||||
ret.flags |= HondaFlags.EPS_ANGLE_LOOP_FW.value
|
||||
ret.safetyConfigs[-1].safetyParam |= HondaSafetyFlags.ACCORD_ANGLE.value
|
||||
ret.steerControlType = structs.CarParams.SteerControlType.angle
|
||||
ret.steerActuatorDelay = CarControllerParams.ANGLE_STEER_ACTUATOR_DELAY
|
||||
# The torque fit's MAX_LAT_ACCEL_MEASURED (0.32 m/s^2) means nothing to an angle setpoint; the onroad torque
|
||||
# bar divides by this, so normalise it by the angle limit instead (3.589 m/s^2, where the setpoint clamp binds).
|
||||
# Measured engaged hands-off over 35 routes: p99.9 3.46 m/s^2, per-route maxima 3.4-4.1. Only the bar and the
|
||||
# car docs read maxLateralAccel; no controller or torque tune does.
|
||||
ret.maxLateralAccel = MAX_LATERAL_ACCEL
|
||||
elif not docs and not eps_observations:
|
||||
# EPS fw unread: an angle-loop EPS would ignore torque frames (engaged, no steering, no alert), so fault instead.
|
||||
# Note: upstream lists this EPS as non-essential (lost without comma power); such an Accord faults here too.
|
||||
ret.flags |= HondaFlags.EPS_FW_UNREAD.value
|
||||
|
||||
elif candidate == CAR.HONDA_ACCORD_11G:
|
||||
ret.longitudinalActuatorDelay = 0.05
|
||||
|
||||
@@ -37,8 +37,11 @@ MANUAL_SELECTION_PORTS = CLASSIC_BOSCH | NIDEC | RADARLESS | CANFD_STOCK | ALT_R
|
||||
# qualified() runs several times per 100 Hz frame in card and selfdrived, so
|
||||
# everything that depends only on this module is computed once, and its flag
|
||||
# tests use plain ints: IntFlag operators cost microseconds each in Python.
|
||||
# EPS_ANGLE_LOOP_FW / EPS_FW_UNREAD: Accord-only EPS-firmware detections (interface.py); the angle car keeps AOL, and
|
||||
# an unread EPS is already a permanent steer fault in carstate, so neither may drop the car out of these owners.
|
||||
_DETECTED = int(HondaFlags.BOSCH_EXT_HUD | HondaFlags.BOSCH_ALT_BRAKE | HondaFlags.HAS_BSM |
|
||||
HondaFlags.EPS_MODIFIED | HondaFlags.HYBRID | HondaFlags.GAS_INTERCEPTOR)
|
||||
HondaFlags.EPS_MODIFIED | HondaFlags.HYBRID | HondaFlags.GAS_INTERCEPTOR |
|
||||
HondaFlags.EPS_ANGLE_LOOP_FW | HondaFlags.EPS_FW_UNREAD)
|
||||
_ALLOWED_FLAGS = {str(car): int(car.config.flags) | _DETECTED
|
||||
for car in CLASSIC_BOSCH | NIDEC | RADARLESS | CANFD_STOCK | ALT_RADAR_STOCK | {CAR.HONDA_ACCORD_11G}}
|
||||
_BOSCH, _BOSCH_RADARLESS, _BOSCH_ALT_BRAKE = int(HondaFlags.BOSCH), int(HondaFlags.BOSCH_RADARLESS), int(HondaFlags.BOSCH_ALT_BRAKE)
|
||||
@@ -102,6 +105,8 @@ def qualified(cp, *, marked_only=False):
|
||||
safety.safetyModel == _HONDA_NIDEC and safety.safetyParam == expected)
|
||||
if fingerprint in CLASSIC_BOSCH and flags & _BOSCH and not flags & _BOSCH_RADARLESS:
|
||||
expected = int(bool(flags & _BOSCH_ALT_BRAKE))
|
||||
if fingerprint == CAR.HONDA_ACCORD and flags & int(HondaFlags.EPS_ANGLE_LOOP_FW):
|
||||
expected |= int(HondaSafetyFlags.ACCORD_ANGLE)
|
||||
if cp.openpilotLongitudinalControl:
|
||||
expected |= int(HondaSafetyFlags.BOSCH_LONG)
|
||||
if fingerprint == CAR.ACURA_RDX_3G:
|
||||
|
||||
@@ -39,9 +39,11 @@ def test_mixed_nonlogging_eps_still_refuses_modified_profile(other):
|
||||
assert not cp.flags & HondaFlags.EPS_MODIFIED
|
||||
|
||||
|
||||
def test_recorded_custom_angle_eps_remains_unsupported_in_mainline():
|
||||
def test_recorded_custom_angle_eps_steers_by_angle():
|
||||
cp = params(CAR.HONDA_ACCORD, [eps(ANGLE), eps(SERIAL, logging=True)])
|
||||
assert cp.dashcamOnly
|
||||
assert not cp.dashcamOnly
|
||||
assert cp.flags & HondaFlags.EPS_ANGLE_LOOP_FW
|
||||
assert cp.steerControlType == structs.CarParams.SteerControlType.angle
|
||||
assert not cp.flags & HondaFlags.EPS_MODIFIED
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,364 @@
|
||||
"""Accord on the angle-loop EPS firmware (39990-TVA,A16<letter>): detection, the 0xE4 frame, the setpoint limits."""
|
||||
import math
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from opendbc import get_generated_dbcs
|
||||
from opendbc.can import CANPacker
|
||||
from opendbc.car import Bus, gen_empty_fingerprint
|
||||
from opendbc.car.honda.carcontroller import CarController
|
||||
from opendbc.car.honda.carstate import CarState
|
||||
from opendbc.car.honda.hondacan import CanBus, create_steering_control
|
||||
from opendbc.car.honda.interface import CarInterface
|
||||
from opendbc.car.honda.values import CAR, DBC, CarControllerParams, HondaFlags, HondaSafetyFlags, is_accord_eps_angle_loop_fw, \
|
||||
accord_angle_steer_ratio, ACCORD_ANGLE_SR_BP, ACCORD_ANGLE_SR_V
|
||||
from opendbc.car.interfaces import get_torque_params
|
||||
from opendbc.car.lateral import MAX_LATERAL_ACCEL, apply_steer_angle_limits_vm, get_max_angle_delta_vm, get_max_angle_vm
|
||||
from opendbc.car.toyota.interface import CarInterface as ToyotaInterface
|
||||
from opendbc.car.toyota.values import CAR as TOYOTA
|
||||
from opendbc.car.structs import CarParams
|
||||
|
||||
P = CarControllerParams
|
||||
STEERING_CONTROL = 0xE4
|
||||
|
||||
|
||||
def _eps_fw(fw: bytes):
|
||||
return [CarParams.CarFw(ecu=CarParams.Ecu.eps, fwVersion=fw, address=0x18DA30F1, subAddress=0)]
|
||||
|
||||
|
||||
def accord_cp(eps_fw: bytes | None):
|
||||
car_fw = [] if eps_fw is None else _eps_fw(eps_fw)
|
||||
return CarInterface.get_params(CAR.HONDA_ACCORD, gen_empty_fingerprint(), car_fw, False, False, False)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fw, expected", [
|
||||
(b"39990-TVA,A16A\x00\x00", True), # V298, NUL-padded as the car reports it
|
||||
(b"39990-TVA,A16B\x00\x00", True), # V299
|
||||
(b"39990-TVA,A16C", True), # the release
|
||||
(b"39990-TVA,A160\x00\x00", False), # torque-map images
|
||||
(b"39990-TVA-A160\x00\x00", False), # stock
|
||||
(b"39990-TVA,A16", False),
|
||||
(b"39990-TVA,A16AB", False),
|
||||
(b"39990-TVA,A16a", False),
|
||||
(b"39990-TVB,A16A", False),
|
||||
])
|
||||
def test_fw_detection(fw, expected):
|
||||
assert is_accord_eps_angle_loop_fw(fw) is expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fw", [b"39990-TVA,A16A\x00\x00", b"39990-TVA,A16B\x00\x00", b"39990-TVA,A16C\x00\x00"])
|
||||
def test_angle_fw_selects_angle_control(fw):
|
||||
CP = accord_cp(fw)
|
||||
assert CP.steerControlType == CarParams.SteerControlType.angle
|
||||
assert CP.flags & HondaFlags.EPS_ANGLE_LOOP_FW
|
||||
assert CP.safetyConfigs[0].safetyParam & HondaSafetyFlags.ACCORD_ANGLE
|
||||
assert CP.steerActuatorDelay == pytest.approx(P.ANGLE_STEER_ACTUATOR_DELAY)
|
||||
# the angle fw carries a ',' but is not a torque-modified EPS: it must not hit the MODIFIED_EPS_FW dashcam fallback
|
||||
assert not CP.dashcamOnly
|
||||
assert not CP.flags & HondaFlags.EPS_MODIFIED
|
||||
assert not CP.flags & HondaFlags.EPS_FW_UNREAD
|
||||
|
||||
|
||||
def test_angle_fw_on_another_honda_is_not_angle_control():
|
||||
# the family is Accord-only; on any other platform the ',' read is the upstream modified-EPS path
|
||||
CP = CarInterface.get_params(CAR.HONDA_CIVIC_BOSCH, gen_empty_fingerprint(), _eps_fw(b"39990-TVA,A16C\x00\x00"),
|
||||
False, False, False)
|
||||
assert CP.steerControlType == CarParams.SteerControlType.torque
|
||||
assert not CP.flags & HondaFlags.EPS_ANGLE_LOOP_FW
|
||||
assert not CP.safetyConfigs[0].safetyParam & HondaSafetyFlags.ACCORD_ANGLE
|
||||
|
||||
|
||||
def test_mixed_eps_read_is_not_angle_control():
|
||||
car_fw = _eps_fw(b"39990-TVA,A16C\x00\x00") + _eps_fw(b"39990-TVA-A160\x00\x00")
|
||||
CP = CarInterface.get_params(CAR.HONDA_ACCORD, gen_empty_fingerprint(), car_fw, False, False, False)
|
||||
assert CP.steerControlType == CarParams.SteerControlType.torque
|
||||
assert not CP.flags & HondaFlags.EPS_ANGLE_LOOP_FW
|
||||
assert not CP.safetyConfigs[0].safetyParam & HondaSafetyFlags.ACCORD_ANGLE
|
||||
assert CP.dashcamOnly # upstream: a ',' EPS outside MODIFIED_EPS_FW
|
||||
|
||||
|
||||
def test_angle_control_needs_no_params():
|
||||
"""A fresh install selects angle control from the EPS fw alone and keeps the pid tuning block untouched.
|
||||
|
||||
Old tree (83fa2e68c8) also pinned this against stale torque-era toggles (ForceTorqueController, NNFF, NNFF Lite)
|
||||
passed into get_params; this tree's get_params takes no toggles and has no ForceTorqueController conversion at all,
|
||||
so only the fw-alone half of that test still has an API to exercise."""
|
||||
CP = CarInterface.get_params(CAR.HONDA_ACCORD, gen_empty_fingerprint(), _eps_fw(b"39990-TVA,A16C"), False, False, False)
|
||||
assert CP.steerControlType == CarParams.SteerControlType.angle
|
||||
assert CP.lateralTuning.which() == "pid"
|
||||
assert CarController({Bus.pt: DBC[CAR.HONDA_ACCORD][Bus.pt]}, CP).angle_mode
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fw", [None, b"39990-TVA-A160\x00\x00", b"39990-TVA,A160\x00\x00"])
|
||||
def test_other_fw_keeps_torque_control(fw):
|
||||
CP = accord_cp(fw)
|
||||
assert CP.steerControlType == CarParams.SteerControlType.torque
|
||||
assert not CP.flags & HondaFlags.EPS_ANGLE_LOOP_FW
|
||||
assert not CP.safetyConfigs[0].safetyParam & HondaSafetyFlags.ACCORD_ANGLE
|
||||
assert not CarController({Bus.pt: DBC[CAR.HONDA_ACCORD][Bus.pt]}, CP).angle_mode
|
||||
|
||||
|
||||
def test_max_lateral_accel_is_the_angle_limit_only_on_the_angle_fw():
|
||||
# the onroad torque bar divides by CP.maxLateralAccel; the torque fit's 0.32 m/s^2 pegged it on every turn
|
||||
torque_fit = get_torque_params()[CAR.HONDA_ACCORD]['MAX_LAT_ACCEL_MEASURED']
|
||||
assert torque_fit == pytest.approx(0.3247, abs=1e-4)
|
||||
assert accord_cp(b"39990-TVA,A16C").maxLateralAccel == pytest.approx(MAX_LATERAL_ACCEL)
|
||||
assert MAX_LATERAL_ACCEL == pytest.approx(3.589, abs=1e-3)
|
||||
for fw in (None, b"39990-TVA-A160\x00\x00", b"39990-TVA,A160\x00\x00"):
|
||||
assert accord_cp(fw).maxLateralAccel == pytest.approx(torque_fit)
|
||||
angle_fw = _eps_fw(b"39990-TVA,A16C")
|
||||
for car in (CAR.HONDA_CIVIC_BOSCH, CAR.HONDA_CRV_5G):
|
||||
CP = CarInterface.get_params(car, gen_empty_fingerprint(), angle_fw, False, False, False)
|
||||
assert CP.maxLateralAccel == pytest.approx(get_torque_params()[car]['MAX_LAT_ACCEL_MEASURED'])
|
||||
CP = ToyotaInterface.get_params(TOYOTA.TOYOTA_RAV4_TSS2, gen_empty_fingerprint(), [], False, False, False)
|
||||
assert CP.maxLateralAccel == pytest.approx(get_torque_params()[TOYOTA.TOYOTA_RAV4_TSS2]['MAX_LAT_ACCEL_MEASURED'])
|
||||
|
||||
|
||||
def _steer_faults(CP):
|
||||
# an unfed parser set: only the fault logic, not the bus contents, is under test
|
||||
CS = CarState(CP)
|
||||
ret = CS.update(CS.get_can_parsers(CP))
|
||||
return ret.steerFaultPermanent
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fw, angle, unread", [
|
||||
(b"39990-TVA,A16C\x00\x00", True, False), # angle EPS read -> angle mode
|
||||
(b"39990-TVA-A160\x00\x00", False, False), # stock EPS read -> torque mode, no fault
|
||||
(b"39990-TVA,A160\x00\x00", False, False), # torque-map EPS read -> torque mode, no fault
|
||||
(None, False, True), # no EPS fw at all -> permanent fault
|
||||
])
|
||||
def test_eps_fw_unread_faults(fw, angle, unread):
|
||||
CP = accord_cp(fw)
|
||||
assert (CP.steerControlType == CarParams.SteerControlType.angle) == angle
|
||||
assert bool(CP.flags & HondaFlags.EPS_FW_UNREAD) == unread
|
||||
if not angle:
|
||||
# same unfed bus for every case, so the fault is decided by the flag alone (the read cases are the control)
|
||||
assert _steer_faults(CP) == unread
|
||||
|
||||
|
||||
def test_docs_params_do_not_fault():
|
||||
CP = CarInterface.get_params(CAR.HONDA_ACCORD, gen_empty_fingerprint(), [], False, False, True)
|
||||
assert not CP.flags & HondaFlags.EPS_FW_UNREAD
|
||||
|
||||
|
||||
def _upstream_dbc(tmp_path):
|
||||
# the Accord DBC without STEER_CONTROL_ARM, i.e. as it was before the signal was added. The *_generated DBCs are
|
||||
# built in memory in this tree (opendbc.get_generated_dbcs), so the stripped copy is written out from that content.
|
||||
name = DBC[CAR.HONDA_ACCORD][Bus.pt]
|
||||
content = get_generated_dbcs()[name]
|
||||
assert "STEER_CONTROL_ARM" in content
|
||||
lines = [ln for ln in content.splitlines(keepends=True) if "STEER_CONTROL_ARM" not in ln]
|
||||
path = tmp_path / f"{name}.dbc"
|
||||
path.write_text("".join(lines), encoding="utf-8")
|
||||
return str(path)
|
||||
|
||||
|
||||
def test_torque_frame_unchanged_by_the_dbc_signal(tmp_path):
|
||||
CP = accord_cp(None)
|
||||
new = CANPacker(DBC[CAR.HONDA_ACCORD][Bus.pt])
|
||||
old = CANPacker(_upstream_dbc(tmp_path))
|
||||
can = CanBus(CP)
|
||||
for torque in range(-4096, 4097, 37):
|
||||
for active in (False, True):
|
||||
for tja in (False, True):
|
||||
assert create_steering_control(new, can, torque, active, tja) == create_steering_control(old, can, torque, active, tja)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("active", [False, True])
|
||||
def test_angle_frame_carries_the_arm_and_a_valid_checksum(active):
|
||||
packer = CANPacker(DBC[CAR.HONDA_ACCORD][Bus.pt])
|
||||
can = CanBus(accord_cp(b"39990-TVA,A16C"))
|
||||
for raw in (-4000, -1234, -1, 0, 1, 987, 4000):
|
||||
addr, dat, _ = create_steering_control(packer, can, raw, active, False, angle_arm=P.ANGLE_ARM)
|
||||
assert addr == STEERING_CONTROL
|
||||
assert (dat[2] >> 2) & 0x3 == P.ANGLE_ARM # byte 2 bits 3:2
|
||||
assert int.from_bytes(dat[0:2], "big", signed=True) == raw # setpoint sent with the request off too
|
||||
assert bool(dat[2] & 0x80) == active # STEER_TORQUE_REQUEST
|
||||
sig = packer.dbc.addr_to_msg[addr].sigs["CHECKSUM"]
|
||||
zeroed = bytearray(dat)
|
||||
zeroed[4] &= 0xF0
|
||||
assert sig.calc_checksum(addr, sig, zeroed) == dat[4] & 0xF # CHECKSUM 35|4 = byte 4 low nibble
|
||||
|
||||
|
||||
def _controller(aol=False):
|
||||
CP = accord_cp(b"39990-TVA,A16C")
|
||||
if aol:
|
||||
CP.alternativeExperience |= 32 # always-on lateral: the hold must NOT depend on it (the 7.0 panda predicate is a session grant)
|
||||
return CarController({Bus.pt: DBC[CAR.HONDA_ACCORD][Bus.pt]}, CP)
|
||||
|
||||
|
||||
def _cc_cs(desired, measured, v, lat_active, enabled=True, main_on=True):
|
||||
CC = SimpleNamespace(actuators=SimpleNamespace(steeringAngleDeg=desired), latActive=lat_active, enabled=enabled)
|
||||
CS = SimpleNamespace(out=SimpleNamespace(steeringAngleDeg=measured, vEgoRaw=v, cruiseState=SimpleNamespace(available=main_on)))
|
||||
return CC, CS
|
||||
|
||||
|
||||
def test_error_clip_then_the_accel_and_jerk_limits():
|
||||
# the error clip shapes the request, the accel/jerk limiter runs last on it, and what is sent is the limiter's output
|
||||
cc = _controller()
|
||||
assert cc.angle_mode
|
||||
v, measured = 20.0, 0.0
|
||||
err = float(np.interp(v, P.ANGLE_ERROR_MAX_BP, P.ANGLE_ERROR_MAX_V))
|
||||
state = measured
|
||||
for _ in range(400):
|
||||
state = apply_steer_angle_limits_vm(min(90.0, measured + err), state, v, measured, True, cc.params, cc.VM)
|
||||
apply_angle, raw = cc._update_angle(*_cc_cs(90.0, measured, v, True))
|
||||
assert apply_angle == cc.apply_angle_last == state
|
||||
assert raw == math.floor(-10.0 * apply_angle + 0.5)
|
||||
assert apply_angle == pytest.approx(measured + err) # the wheel never moved: the send settles on the clip
|
||||
|
||||
|
||||
@pytest.mark.parametrize("v", [1.0, 5.0, 10.0, 17.5, 26.9, 35.0])
|
||||
def test_what_is_sent_never_exceeds_the_accel_and_jerk_limits(v):
|
||||
# whatever the wheel does (a driver holding it far past the limit, or yanking it), every frame sent stays inside
|
||||
# the 3.589 lateral accel angle and steps no further than the 3.589 jerk limit from the previous frame sent
|
||||
rng = np.random.default_rng(int(v * 10))
|
||||
cc = _controller()
|
||||
max_angle = get_max_angle_vm(v, cc.VM, cc.params)
|
||||
max_delta = min(get_max_angle_delta_vm(v, cc.VM, cc.params), P.ANGLE_LIMITS.MAX_ANGLE_RATE)
|
||||
err = float(np.interp(v, P.ANGLE_ERROR_MAX_BP, P.ANGLE_ERROR_MAX_V))
|
||||
wheel = min(max_angle + err + 10.0, 390.0) # held past the limit: the case the old order got wrong
|
||||
prev, _ = cc._update_angle(*_cc_cs(0.0, 0.0, v, True))
|
||||
for i in range(600):
|
||||
if i > 200:
|
||||
wheel = float(np.clip(wheel + rng.normal(0.0, 3.0), -390.0, 390.0)) # then moving up to several hundred deg/s
|
||||
sent, raw = cc._update_angle(*_cc_cs(float(rng.uniform(-400.0, 400.0)), wheel, v, True))
|
||||
assert abs(sent) <= min(max_angle, P.ANGLE_LIMITS.STEER_ANGLE_MAX) + 1e-9
|
||||
assert abs(sent - prev) <= max_delta + 1e-9
|
||||
assert raw == math.floor(-10.0 * sent + 0.5)
|
||||
prev = sent
|
||||
|
||||
|
||||
def test_wheel_motion_inside_the_error_clip_does_not_feed_the_setpoint():
|
||||
# same command, different wheel paths that stay inside the clip: the setpoint must not depend on the wheel
|
||||
rng = np.random.default_rng(0)
|
||||
a, b = _controller(), _controller()
|
||||
a.apply_angle_last = b.apply_angle_last = 0.0
|
||||
err = float(np.interp(12.0, P.ANGLE_ERROR_MAX_BP, P.ANGLE_ERROR_MAX_V))
|
||||
for i in range(300):
|
||||
desired = 20.0 * math.sin(i / 20.0)
|
||||
wheel = float(np.clip(rng.normal(0.0, 10.0), -(err - 21.0), err - 21.0))
|
||||
a._update_angle(*_cc_cs(desired, 0.0, 12.0, True))
|
||||
b._update_angle(*_cc_cs(desired, wheel, 12.0, True))
|
||||
assert a.apply_angle_last == b.apply_angle_last
|
||||
|
||||
|
||||
def test_setpoint_returns_to_the_request_at_the_jerk_limit_after_the_clip_releases():
|
||||
# wheel pushed away (clip binds), then let go: the setpoint walks back, it does not jump
|
||||
cc = _controller()
|
||||
v = 20.0
|
||||
err = float(np.interp(v, P.ANGLE_ERROR_MAX_BP, P.ANGLE_ERROR_MAX_V))
|
||||
max_delta = get_max_angle_delta_vm(v, cc.VM, cc.params)
|
||||
cc.apply_angle_last = 0.0
|
||||
for _ in range(300):
|
||||
pushed, _ = cc._update_angle(*_cc_cs(0.0, err + 5.0, v, True))
|
||||
assert pushed == pytest.approx(5.0) # held at the clip edge, wheel - err
|
||||
back, _ = cc._update_angle(*_cc_cs(0.0, 0.0, v, True))
|
||||
assert back == pytest.approx(5.0 - max_delta)
|
||||
|
||||
|
||||
def test_request_waits_at_the_wheel_while_the_wheel_is_past_the_accel_limit():
|
||||
# lateral goes active with the wheel past the accel-limit angle: the limit is more than one jerk step away, so no
|
||||
# setpoint is legal. The frame holds the wheel with the request off, and the request starts once the wheel is inside.
|
||||
cc = _controller()
|
||||
v = 26.9
|
||||
max_angle = get_max_angle_vm(v, cc.VM, cc.params)
|
||||
max_delta = get_max_angle_delta_vm(v, cc.VM, cc.params)
|
||||
for wheel in (max_angle + 20.0, max_angle + 5.0, max_angle + max_delta + 0.1):
|
||||
sent, raw = cc._update_angle(*_cc_cs(0.0, wheel, v, True))
|
||||
assert not cc.angle_steer_req
|
||||
assert sent == wheel and raw == math.floor(-10.0 * wheel + 0.5)
|
||||
wheel = max_angle + 0.5 * max_delta
|
||||
cc._update_angle(*_cc_cs(0.0, wheel, v, True)) # the last value sent was the wheel further out: one more frame waits
|
||||
assert not cc.angle_steer_req
|
||||
sent, raw = cc._update_angle(*_cc_cs(0.0, wheel, v, True))
|
||||
assert cc.angle_steer_req
|
||||
assert sent == pytest.approx(wheel - max_delta) # one jerk step in from the wheel, inside the accel limit
|
||||
for _ in range(50): # and it stays on from there
|
||||
prev = sent
|
||||
sent, _ = cc._update_angle(*_cc_cs(0.0, wheel, v, True))
|
||||
assert cc.angle_steer_req and abs(sent - prev) <= max_delta + 1e-9 and abs(sent) <= max_angle + 1e-9
|
||||
|
||||
|
||||
def test_request_bit_follows_lat_active_otherwise():
|
||||
cc = _controller()
|
||||
cc._update_angle(*_cc_cs(3.0, 1.0, 20.0, True))
|
||||
assert cc.angle_steer_req
|
||||
cc._update_angle(*_cc_cs(3.0, 1.0, 20.0, False))
|
||||
assert not cc.angle_steer_req
|
||||
|
||||
|
||||
def test_each_step_is_bounded_by_the_rate_limit():
|
||||
# MAX_ANGLE_RATE = 2.5 deg/frame (250 deg/s): no frame may step further than that
|
||||
cc = _controller()
|
||||
prev = 0.0
|
||||
for _ in range(5):
|
||||
a, _ = cc._update_angle(*_cc_cs(90.0, 0.0, 3.0, True))
|
||||
assert abs(a - prev) <= P.ANGLE_LIMITS.MAX_ANGLE_RATE + 1e-9
|
||||
prev = a
|
||||
|
||||
|
||||
def test_first_frame_seeds_from_the_wheel():
|
||||
cc = _controller()
|
||||
a, _ = cc._update_angle(*_cc_cs(30.0, 25.0, 10.0, True))
|
||||
assert abs(a - 25.0) <= P.ANGLE_LIMITS.MAX_ANGLE_RATE + 1e-9
|
||||
|
||||
|
||||
@pytest.mark.parametrize("enabled, main_on, aol, holds", [
|
||||
(True, True, False, True),
|
||||
(False, True, True, False), # always-on lateral with ACC main on: the panda's grant is not visible here, so no hold
|
||||
(True, True, True, True),
|
||||
(False, True, False, False),
|
||||
(True, False, False, False), # the panda drops controls_allowed with main off
|
||||
(False, False, True, False),
|
||||
])
|
||||
def test_idle_hold(enabled, main_on, aol, holds):
|
||||
cc = _controller(aol)
|
||||
measured = -12.34
|
||||
apply_angle, raw = cc._update_angle(*_cc_cs(50.0, measured, 15.0, False, enabled, main_on))
|
||||
assert apply_angle == measured # lateral off: the limiter follows the wheel
|
||||
assert raw == (math.floor(-10.0 * measured + 0.5) if holds else 0)
|
||||
|
||||
|
||||
def test_raw_is_clipped():
|
||||
cc = _controller()
|
||||
cc.apply_angle_last = 399.0
|
||||
_, raw = cc._update_angle(*_cc_cs(400.0, 399.0, 1.0, True))
|
||||
assert raw == -P.ANGLE_RAW_MAX
|
||||
|
||||
|
||||
def test_steer_ratio_map_level():
|
||||
assert accord_angle_steer_ratio(0.0) == pytest.approx(16.84)
|
||||
for deg in (0.0, 45.0, 120.0, -200.0, 500.0):
|
||||
expected = float(np.interp(abs(deg), ACCORD_ANGLE_SR_BP, ACCORD_ANGLE_SR_V)) * 16.84 / 16.88
|
||||
assert accord_angle_steer_ratio(deg) == pytest.approx(expected)
|
||||
|
||||
|
||||
def test_error_clip_is_the_p_room_under_the_firmware_sum_clamp():
|
||||
# Operator rule (2026-10-21): the clip is the angle error where the V300 firmware's P term alone equals
|
||||
# Kmax - Imax (sum clamp 15360 after the 254/256 taper, so 15481 before it; I cap 4096 / 6144 / 8192 by
|
||||
# speed). Integer mirror of the image: E = 16 * 10 * deg, E' = (E * G(v)) >> 8, P = (E' * 112) >> 8.
|
||||
g_v = {3.1: 1178, 8.0: 1465, 10.0: 760, 11.75: 560, 17.5: 1068, 26.9: 2188}
|
||||
for v, clip in zip(P.ANGLE_ERROR_MAX_BP, P.ANGLE_ERROR_MAX_V, strict=True):
|
||||
imax = 4096 if v <= 6.0 else (6144 if v <= 12.5 else 8192)
|
||||
p_of = lambda deg, v=v: (((16 * round(10 * deg) * g_v[v]) >> 8) * 112) >> 8 # noqa: E731
|
||||
assert p_of(clip) >= 15481 - imax > p_of(clip - 0.1)
|
||||
|
||||
|
||||
def test_angle_frame_is_sent_by_the_controller():
|
||||
# the full update(): angle mode packs the setpoint with the arm; the projection observer is never installed on angle
|
||||
CP = accord_cp(b"39990-TVA,A16C")
|
||||
ci = CarInterface(CP)
|
||||
from opendbc.car import structs
|
||||
CC = structs.CarControl(enabled=True, latActive=True)
|
||||
CC.actuators.steeringAngleDeg = 5.0
|
||||
ci.update([])
|
||||
out, sends = ci.apply(CC.as_reader(), 1_000_000_000)
|
||||
steer = [s for s in sends if s[0] == STEERING_CONTROL]
|
||||
assert len(steer) == 1
|
||||
dat = steer[0][1]
|
||||
assert (dat[2] >> 2) & 0x3 == P.ANGLE_ARM
|
||||
assert int.from_bytes(dat[0:2], "big", signed=True) == out.torqueOutputCan
|
||||
assert out.steeringAngleDeg == pytest.approx(-out.torqueOutputCan / 10.0, abs=0.05)
|
||||
@@ -1,5 +1,6 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
@@ -33,6 +34,32 @@ class TestHondaNormalDiscovery(unittest.TestCase):
|
||||
generic_query.assert_not_called()
|
||||
self.assertIsNone(actual[0])
|
||||
|
||||
def _accord_discovery(self, normal_read, obd_read):
|
||||
from opendbc.car.honda.values import CAR
|
||||
switches = []
|
||||
with patch('opendbc.car.car_helpers.get_vin', return_value=(-1, -1, VIN_UNKNOWN)) as vin, \
|
||||
patch('opendbc.car.car_helpers.get_fw_versions', side_effect=[normal_read, obd_read]) as query, \
|
||||
patch('opendbc.car.car_helpers.match_fw_to_car', return_value=(True, {CAR.HONDA_ACCORD})), \
|
||||
patch('opendbc.car.car_helpers.can_fingerprint', return_value=(None, {})):
|
||||
actual = fingerprint(lambda wait_for_one=False: [recorded_frames()], lambda frames: None, switches.append, None)
|
||||
return switches, vin, query, actual
|
||||
|
||||
def test_accord_without_an_eps_read_queries_the_obd_port(self):
|
||||
radar = SimpleNamespace(ecu="fwdRadar", logging=False, responseAddress=0, subAddress=0, bus=1)
|
||||
eps = SimpleNamespace(ecu="eps", logging=False, responseAddress=0, subAddress=0, bus=1)
|
||||
switches, vin, query, actual = self._accord_discovery([radar], [radar, eps])
|
||||
self.assertEqual(switches, [False, True, False])
|
||||
self.assertEqual(vin.call_count, 2)
|
||||
self.assertEqual([call.kwargs for call in query.call_args_list],
|
||||
[{'query_brand': 'honda', 'normal_bus_only': True}, {'query_brand': 'honda'}])
|
||||
self.assertEqual(actual[3], [radar, eps])
|
||||
|
||||
def test_accord_with_an_eps_read_stays_on_normal_wiring(self):
|
||||
eps = SimpleNamespace(ecu="eps", logging=False, responseAddress=0, subAddress=0, bus=1)
|
||||
switches, vin, query, _ = self._accord_discovery([eps], AssertionError("no second query"))
|
||||
self.assertFalse(any(switches))
|
||||
query.assert_called_once()
|
||||
|
||||
def test_incomplete_or_invalid_traffic_cannot_select_honda(self):
|
||||
from opendbc.car.honda.discovery import normal_bus_topology
|
||||
frames = recorded_frames()
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum, IntFlag
|
||||
|
||||
import numpy as np
|
||||
|
||||
from opendbc.car import Bus, CarSpecs, DbcDict, PlatformConfig, Platforms, structs, uds
|
||||
from opendbc.car.common.conversions import Conversions as CV
|
||||
from opendbc.car.docs_definitions import CarFootnote, CarHarness, CarDocs, CarParts, Column
|
||||
from opendbc.car.fw_query_definitions import FwQueryConfig, Request, StdQueries, p16
|
||||
from opendbc.car.honda.firmware_validation import validate_fw_match
|
||||
from opendbc.car.lateral import AngleSteeringLimitsVM, MAX_LATERAL_ACCEL, MAX_LATERAL_JERK
|
||||
|
||||
Ecu = structs.CarParams.Ecu
|
||||
VisualAlert = structs.CarControl.HUDControl.VisualAlert
|
||||
@@ -41,6 +44,27 @@ class CarControllerParams:
|
||||
STEER_DELTA_DOWN = 3
|
||||
STEER_GLOBAL_MIN_SPEED = 3 * CV.MPH_TO_MS
|
||||
|
||||
# ---- Accord on the angle-loop EPS firmware (HondaFlags.EPS_ANGLE_LOOP_FW). 0xE4 STEER_TORQUE carries an angle
|
||||
# setpoint, raw = round(-10 * deg) in carState.steeringAngleDeg's frame, and the EPS closes a 1 kHz angle loop on it.
|
||||
# The panda checks every such frame (STEER_CONTROL_ARM == 2) against the same lateral accel and jerk limits with
|
||||
# the same vehicle model (honda.h, HONDA_ACCORD_ANGLE_PARAMS), and blocks one that exceeds them.
|
||||
ANGLE_LIMITS: AngleSteeringLimitsVM = AngleSteeringLimitsVM(
|
||||
400, # deg; the EPS clamps its setpoint at raw +-4096
|
||||
MAX_LATERAL_ACCEL=MAX_LATERAL_ACCEL, # 3.589 m/s^2
|
||||
MAX_LATERAL_JERK=MAX_LATERAL_JERK, # 3.589 m/s^3
|
||||
MAX_ANGLE_RATE=2.5, # deg/frame = 250 deg/s (V299 drives ran 250; Tesla and Rivian run 250 deg/s too)
|
||||
)
|
||||
# Error clip |setpoint - measured angle| <= ANGLE_ERROR_MAX(v): bounds the P torque the setpoint can demand. Each
|
||||
# knot = the error at which the firmware's P term alone fills the room left under the PID sum clamp when the
|
||||
# integral sits at its cap (operator rule, 2026-10-21): P = Kmax - Imax, read from the V300 image:
|
||||
# P = ((16*10*deg * G(v)) >> 8) * 112 >> 8, Kmax = 15360 after the 254/256 taper (15481 before it),
|
||||
# Imax = 4096 (<= 6 m/s), 6144 (6-12.5 m/s), 8192 (above, the ICL), G(v) = 1178/1465/760/560/1068/2188 at the knots.
|
||||
ANGLE_ERROR_MAX_BP = [3.1, 8.0, 10.0, 11.75, 17.5, 26.9] # m/s, the firmware gain-table knots
|
||||
ANGLE_ERROR_MAX_V = [35.4, 23.4, 45.0, 61.0, 25.0, 12.2] # deg (was 17.0, 15.5, 19.5, 17.0, 8.5, 4.5, model-sized)
|
||||
ANGLE_RAW_MAX = 4000 # raw clip before packing
|
||||
ANGLE_ARM = 2 # 0xE4 STEER_CONTROL_ARM: the EPS lane runs only while it reads 2; sent on every frame
|
||||
ANGLE_STEER_ACTUATOR_DELAY = 0.15 # s, the inner angle loop's lag (model value; lagd learns the rest)
|
||||
|
||||
def __init__(self, CP):
|
||||
self.BOSCH_GAS_LOOKUP_BP = list(type(self).BOSCH_GAS_LOOKUP_BP)
|
||||
gas_max = {CAR.HONDA_CIVIC_BOSCH: 750, CAR.HONDA_ODYSSEY_5G_MMR: 2000,
|
||||
@@ -92,6 +116,7 @@ class HondaSafetyFlags(IntFlag):
|
||||
RADARLESS = 8
|
||||
BOSCH_CANFD = 16
|
||||
BOSCH_CANFD_MVL = 64
|
||||
ACCORD_ANGLE = 4096
|
||||
CLASSIC_LONG_AOL = 2048 # Exact marked DEBUG classic Bosch alpha owner.
|
||||
ALT_RADAR_AOL = 1024 # Exact marked DEBUG alpha owner; physical EPS/gear token.
|
||||
NIDEC_PEDAL_AOL = 512 # Model1 only; distinct from model20 STOCK_TJA.
|
||||
@@ -121,6 +146,55 @@ class HondaFlags(IntFlag):
|
||||
BOSCH_TJA_CONTROL = 4096
|
||||
EPS_MODIFIED = 8192
|
||||
GAS_INTERCEPTOR = 16384
|
||||
EPS_ANGLE_LOOP_FW = 32768 # the Accord EPS reports the angle-loop firmware (is_accord_eps_angle_loop_fw)
|
||||
EPS_FW_UNREAD = 65536 # Accord with no EPS fw response: the firmware family is unknown, so do not steer
|
||||
|
||||
|
||||
# Accord EPS angle-loop firmware family: 39990-TVA,A16 + exactly one capital letter (A16A, A16B, A16C ...). Torque
|
||||
# images read 39990-TVA,A160 (a digit) and stock 39990-TVA-A1x0, so neither matches.
|
||||
ACCORD_EPS_ANGLE_LOOP_FW_FAMILY = b"39990-TVA,A16"
|
||||
|
||||
|
||||
def is_accord_eps_angle_loop_fw(fw_version: bytes) -> bool:
|
||||
v = bytes(fw_version).rstrip(b"\x00") # the EPS pads fwVersion with NULs
|
||||
family = ACCORD_EPS_ANGLE_LOOP_FW_FAMILY
|
||||
return len(v) == len(family) + 1 and v.startswith(family) and ord("A") <= v[-1] <= ord("Z")
|
||||
|
||||
|
||||
# ---- Accord, angle mode only (steerControlType == angle): the variable-ratio rack map.
|
||||
# In angle mode sR turns the model's curvature 1:1 into the angle setpoint, so the ratio is a tune here and the learner
|
||||
# is ignored. SHAPE: absolute ratios measured over 82 routes, V[0] = the on-centre nominal. Not measurements:
|
||||
# 0-23 deg (pinned by convention, not identified), 31-61 deg (interpolated across two bins that failed the lag test),
|
||||
# 236+ deg (frozen; above 303 deg the data is parking speed). A compensation curve for calc_curvature's k = d/L,
|
||||
# not the rack's true geometry. Bands: shape +/-0.12, level +/-0.57.
|
||||
ACCORD_ANGLE_SR_BP = [0.0, 23.0, 31.0, 61.0, 76.0, 95.0, 116.0, 151.0, 178.0, 227.0, 236.0, 303.0, 380.0] # deg
|
||||
ACCORD_ANGLE_SR_V = [16.88, 16.88, 16.88, 16.25, 15.97, 15.45, 15.03, 14.68, 14.45, 14.09, 14.25, 12.98, 12.31] # :1
|
||||
# LEVEL: the served on-centre ratio; the whole shape is scaled by LEVEL / V[0]. 16.84 = the SteerRatio every angle
|
||||
# drive ran (V298/V299 configs).
|
||||
ACCORD_ANGLE_SR_LEVEL = 16.84
|
||||
|
||||
|
||||
def accord_angle_steer_ratio(steer_angle_deg: float) -> float:
|
||||
"""Local ratio of the Accord's rack at this wheel angle (deg, offset removed)."""
|
||||
ratio = float(np.interp(abs(steer_angle_deg), ACCORD_ANGLE_SR_BP, ACCORD_ANGLE_SR_V))
|
||||
return ratio * ACCORD_ANGLE_SR_LEVEL / ACCORD_ANGLE_SR_V[0]
|
||||
|
||||
|
||||
def accord_angle_at_own_ratio(angle_vm_deg: float, sr_vm: float, max_passes: int = 10) -> float:
|
||||
"""The angle setpoint with the map evaluated at the DESIRED angle instead of the measured one.
|
||||
|
||||
controlsd sets VM.sR = map(measured angle) and get_steer_from_curvature is linear in sR, so the consistent setpoint
|
||||
is the fixed point theta = angle_vm_deg * map(theta) / sr_vm. Each pass shrinks the error by <= 0.44 (worst on the
|
||||
236-303 deg knot); stops within 0.01 deg, a tenth of the EPS setpoint quantum.
|
||||
"""
|
||||
theta = float(angle_vm_deg)
|
||||
for _ in range(max_passes):
|
||||
nxt = float(angle_vm_deg) * accord_angle_steer_ratio(theta) / sr_vm
|
||||
done = abs(nxt - theta) < 0.01
|
||||
theta = nxt
|
||||
if done:
|
||||
break
|
||||
return theta
|
||||
|
||||
|
||||
# Car button codes
|
||||
|
||||
@@ -124,6 +124,7 @@ class CarController(CarControllerBase):
|
||||
self.apply_angle_last = 0.0
|
||||
self.angle_gain_last = 0.0
|
||||
self.angle_fault_driver_override = False
|
||||
self.stock_angle_lka_active = False
|
||||
self.angle_tx_recovery = (AngleTxRecovery(0xCB, self.CAN.ECAN)
|
||||
if pe_long_qualified(CP) or ev9_long_qualified(CP) else AngleTxRecovery(0x110, self.CAN.ACAN)
|
||||
if CP.carFingerprint in (CAR.HYUNDAI_IONIQ_5_PE, CAR.KIA_EV9) and
|
||||
@@ -358,7 +359,8 @@ 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:
|
||||
if (self.frame - self.blended_camera_sent_frame >= 5 and camera_counter != self.blended_camera_sent_counter and
|
||||
(not CC.latActive or CS.blended_camera_updated)):
|
||||
can_sends.append(hyundaicanfd.create_suppress_lfa(self.packer, self.CAN, CS.lfa_block_msg, False))
|
||||
self.blended_camera_sent_frame = self.frame
|
||||
self.blended_camera_sent_counter = camera_counter
|
||||
@@ -543,7 +545,9 @@ class CarController(CarControllerBase):
|
||||
angle_active, self.params, self.angle_vm)
|
||||
self.angle_gain_last = angle_torque_reduction_gain(CS.out.steeringTorque, CS.out.vEgoRaw,
|
||||
angle_active, self.angle_gain_last)
|
||||
if not ccnc_ev_stock or ccnc_ev_replacement:
|
||||
stock_angle_handoff = angle_aol and lka_steering and not ccnc_ev_stock
|
||||
if ((not ccnc_ev_stock or ccnc_ev_replacement) and
|
||||
(not stock_angle_handoff or angle_active or self.stock_angle_lka_active)):
|
||||
can_sends.extend(
|
||||
hyundaicanfd.create_angle_steering_messages(
|
||||
self.packer,
|
||||
@@ -557,6 +561,7 @@ class CarController(CarControllerBase):
|
||||
CS.out.steeringAngleDeg,
|
||||
)
|
||||
)
|
||||
self.stock_angle_lka_active = stock_angle_handoff and angle_active
|
||||
else:
|
||||
steering_status_active = CC.enabled
|
||||
if ((self.CP.carFingerprint == CAR.KIA_CARNIVAL_2025 and self.CP.safetyConfigs[-1].safetyParam == 0x28B4) or
|
||||
|
||||
@@ -150,6 +150,7 @@ class CarState(CarStateBase):
|
||||
|
||||
self.params = CarControllerParams(CP)
|
||||
self.blended_camera_current = False
|
||||
self.blended_camera_updated = False
|
||||
self.ray_pedal_valid = False
|
||||
self.ray_pedal_state = 5
|
||||
|
||||
@@ -347,6 +348,7 @@ class CarState(CarStateBase):
|
||||
self.lfa_block_msg = copy.copy(cp_cam.vl["CAM_0x2a4"])
|
||||
from opendbc.car.hyundai.blended_stock_aol import camera_current
|
||||
self.blended_camera_current = camera_current(cp_cam)
|
||||
self.blended_camera_updated = bool(cp_cam.vl_all["CAM_0x2a4"]["COUNTER"])
|
||||
self.lkas11 = {}
|
||||
else:
|
||||
self.msg_364 = copy.copy(cp_cam.vl["ALERTS_364"])
|
||||
|
||||
@@ -67,7 +67,10 @@ class TestBlendedSender(unittest.TestCase):
|
||||
command.actuators.longControlState = structs.CarControl.Actuators.LongControlState.pid
|
||||
command.hudControl.setSpeed = 25.0
|
||||
for frame in range(32):
|
||||
actuators, messages = ci.apply(command.as_reader(), 2_000_000_000 + frame * 10_000_000)
|
||||
tick = 16 + frame
|
||||
camera = 16 + frame // 5 if frame % 5 == 0 else False
|
||||
feed(ci, tick, camera=camera)
|
||||
actuators, messages = ci.apply(command.as_reader(), 1_000_000_000 + tick * 10_000_000)
|
||||
wanted = []
|
||||
if frame % 100 == 0:
|
||||
wanted.append((0x730 if hdaii else 0x7D0, int(hdaii)))
|
||||
@@ -90,6 +93,8 @@ class TestBlendedSender(unittest.TestCase):
|
||||
wanted.append((0x485, 1))
|
||||
self.assertEqual([(address, bus) for address, _, bus in messages], wanted)
|
||||
packets = {address: data for address, data, _ in messages}
|
||||
if hdaii and frame % 5 == 0:
|
||||
self.assertEqual(decode(ci, 0x2A4, packets[0x2A4], 'COUNTER'), camera)
|
||||
for address, data, _ in messages:
|
||||
if address not in (0x730, 0x7D0, 0x50, 0x51, 0x2A4):
|
||||
self.assertEqual(data[0], hyundai_checksum(data[1:8]), hex(address))
|
||||
|
||||
@@ -256,7 +256,7 @@ def test_ae0_physical_tracker_is_inactive_until_final_ae32(hda2):
|
||||
|
||||
@pytest.mark.parametrize('hda2', (False, True))
|
||||
@pytest.mark.parametrize('corruption', ('crc', 'replay', 'wrong_bus', 'inactive'))
|
||||
def test_real_controller_invalid_replacement_does_not_acquire_forwarding(hda2, corruption):
|
||||
def test_real_controller_forwarding_requires_valid_replacement(hda2, corruption):
|
||||
cp = params(hda2)
|
||||
cp.alternativeExperience = 32
|
||||
ci = CarInterface(cp)
|
||||
@@ -295,7 +295,14 @@ def test_real_controller_invalid_replacement_does_not_acquire_forwarding(hda2, c
|
||||
elif corruption == 'wrong_bus':
|
||||
assert not safety.safety_tx_hook(libsafety_py.make_CANPacket(addr, 1, data))
|
||||
else:
|
||||
assert safety.safety_fwd_hook(2, addr) == 0
|
||||
if hda2:
|
||||
assert ((data[6] & 0x1F) << 7 | data[5] >> 1) == 1024
|
||||
assert safety.safety_tx_hook(libsafety_py.make_CANPacket(addr, bus, data))
|
||||
if hda2:
|
||||
assert safety.safety_fwd_hook(2, addr) == -1
|
||||
assert safety.safety_fwd_hook(2, 0x2A4) == 0
|
||||
safety.set_timer(((now // 1000) + 200_001) & 0xFFFFFFFF)
|
||||
assert safety.safety_fwd_hook(2, addr) == 0
|
||||
|
||||
|
||||
@@ -347,7 +354,11 @@ def test_real_controller_crc_fault_revokes_token_then_fresh_gesture_recovers(hda
|
||||
assert permission == 0 and not accepted
|
||||
assert safety.safety_fwd_hook(2, addr) == 0
|
||||
if 80 <= tick < 100:
|
||||
assert permission == 0 and safety.safety_fwd_hook(2, addr) == 0
|
||||
assert permission == 0
|
||||
if hda2:
|
||||
assert accepted and ((data[6] & 0x1F) << 7 | data[5] >> 1) == 1024
|
||||
assert safety.safety_fwd_hook(2, 0x2A4) == 0
|
||||
assert safety.safety_fwd_hook(2, addr) == (-1 if hda2 else 0)
|
||||
if tick >= 115:
|
||||
assert permission == 1 and accepted
|
||||
assert safety.safety_fwd_hook(2, addr) == -1
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import os
|
||||
from unittest.mock import Mock, patch
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -8,7 +9,7 @@ from opendbc.car.hyundai.canfd_owner import config_index
|
||||
from opendbc.car.hyundai.canfd_stock_aol import qualified_long
|
||||
from opendbc.car.hyundai.interface import CarInterface
|
||||
from opendbc.car.hyundai.values import CAR, HyundaiFlags
|
||||
from openpilot.starpilot.car.hyundai.aol import independent_cruise_buttons_supported, native_accepts_cp, policy_for
|
||||
from openpilot.starpilot.car.hyundai.aol import configure_kona_factory_handoff, independent_cruise_buttons_supported, native_accepts_cp, policy_for
|
||||
|
||||
CARS = (CAR.HYUNDAI_KONA_2ND_GEN, CAR.HYUNDAI_KONA_HEV_2ND_GEN)
|
||||
|
||||
@@ -226,3 +227,12 @@ def test_idle_handoff_omits_only_kona_steering_packet():
|
||||
assert [frame for frame in after if frame[0] != 0x12A] == [frame for frame in before if frame[0] != 0x12A]
|
||||
assert any(frame[0] == 0x12A for frame in before)
|
||||
assert [data[2] for addr, data, _ in after if addr == 0x12A] == ([] if expected is None else [expected])
|
||||
|
||||
@pytest.mark.parametrize('panda_type,faults,expected', [('cuatro', [], 0x1C0C), ('redPanda', [], 0x0C0C), ('cuatro', ['fault'], 0x0C0C)])
|
||||
def test_kona_factory_handoff_is_limited_to_healthy_internal_c4(panda_type, faults, expected):
|
||||
cp = kona_params(CARS[0])
|
||||
cp.alternativeExperience = 32
|
||||
cp.safetyConfigs[0].safetyParam = 0x0C0C
|
||||
panda = SimpleNamespace(pandaType=panda_type, faults=faults, ignitionLine=True, ignitionCan=False, controlsAllowed=False)
|
||||
configure_kona_factory_handoff(cp, [panda])
|
||||
assert cp.safetyConfigs[0].safetyParam == expected
|
||||
|
||||
@@ -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, 5, 10, 15) else {0x50})
|
||||
self.assertEqual(addresses, {0x50, 0x2A4} if tick in (0, 7, 12, 17) else {0x50})
|
||||
self.assertTrue(all(bus == 0 for _, _, bus in messages))
|
||||
else:
|
||||
self.assertEqual(addresses, {0x340, 0x364})
|
||||
@@ -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_follows_new_input_instead_of_free_running(self):
|
||||
def test_hda2_camera_copy_skips_samples_that_miss_the_send_slot(self):
|
||||
ci = CarInterface(params('hdaii'))
|
||||
for tick in range(12):
|
||||
feed(ci, tick)
|
||||
@@ -136,10 +136,10 @@ class TestPalisade2023(unittest.TestCase):
|
||||
copied = []
|
||||
for frame in range(20):
|
||||
tick = frame + 12
|
||||
feed(ci, tick, camera={0: 12, 6: 13, 11: 14, 16: 15}.get(frame, False))
|
||||
feed(ci, tick, camera={0: 12, 4: 13, 9: 14, 14: 15, 19: 16}.get(frame, False))
|
||||
_, messages = ci.apply(command.as_reader(), 1_000_000_000 + tick * 10_000_000)
|
||||
copied.extend((frame, data[2]) for address, data, _ in messages if address == 0x2A4)
|
||||
self.assertEqual(copied, [(0, 12), (6, 13), (11, 14), (16, 15)])
|
||||
self.assertEqual(copied, [(0, 12), (9, 14), (14, 15), (19, 16)])
|
||||
|
||||
def test_hda2_alpha_long_keeps_primary_steering_payload(self):
|
||||
from opendbc.car.hyundai.blended_longitudinal import candidate_from_stock
|
||||
|
||||
@@ -40,7 +40,8 @@ def card_publication_sequence(context):
|
||||
calls=[statement.value.func.attr for statement in statements if isinstance(statement,ast.Expr)]
|
||||
assert calls==['configure','finalize_aol_configuration','seal_publication']
|
||||
exec(compile(ast.Module(body=statements,type_ignores=[]),'actual-card-publication-order','exec'),
|
||||
{'self':context,'aol_policy':policy_for(context.CP), 'hyundai_aol_safety_config':hyundai_aol_safety_config})
|
||||
{'self':context,'aol_policy':policy_for(context.CP), 'HYUNDAI_CAR':CAR,
|
||||
'hyundai_aol_safety_config':hyundai_aol_safety_config})
|
||||
|
||||
|
||||
@pytest.fixture(params=[(CAR.KIA_EV6,EV6Startup),(CAR.GENESIS_GV70_ELECTRIFIED_1ST_GEN,GV70Startup)])
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""One bounded Legacy AVH ON request; 0x32B is status, never a TX command."""
|
||||
"""One bounded Subaru AVH ON request; 0x32B is status, never a TX command."""
|
||||
|
||||
AVH_REQUEST = 0x6BB
|
||||
AVH_STATUS = 0x32B
|
||||
@@ -132,13 +132,14 @@ class AvhStartup:
|
||||
|
||||
|
||||
def eligible(cp):
|
||||
from opendbc.car.subaru.startup import supported
|
||||
return bool(supported(cp) and cp.carFingerprint == 'SUBARU_LEGACY_2025')
|
||||
from opendbc.car.subaru.stock_aol import qualified
|
||||
from opendbc.car.subaru.values import CAR, FROGGER_ANGLE_SIBLINGS
|
||||
return bool(qualified(cp) and cp.carFingerprint in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_LEGACY_2025})
|
||||
|
||||
|
||||
def selected(cp):
|
||||
from opendbc.car.subaru.values import SubaruFlags
|
||||
return bool(eligible(cp) and cp.flags & SubaruFlags.AVH_STARTUP and cp.safetyConfigs[0].safetyParam in (1169, 1425))
|
||||
return bool(eligible(cp) and cp.flags & SubaruFlags.AVH_STARTUP and cp.safetyConfigs[0].safetyParam in (1041, 1169, 1425, 3089))
|
||||
|
||||
|
||||
def prepare(cp, enabled):
|
||||
|
||||
@@ -8,7 +8,7 @@ from opendbc.car.interfaces import CarControllerBase
|
||||
from opendbc.car.subaru import subarucan
|
||||
from opendbc.car.subaru.jacobw_angle import MAX_ANGLE as JACOBW_MAX_ANGLE, filter_angle as jacobw_filter_angle, limit_angle as jacobw_limit_angle
|
||||
from opendbc.car.subaru.stock_aol import qualified as subaru_aol_qualified
|
||||
from opendbc.car.subaru.values import CAR, DBC, GLOBAL_ES_ADDR, CanBus, CarControllerParams, SubaruFlags
|
||||
from opendbc.car.subaru.values import CAR, FROGGER_ANGLE_SIBLINGS, DBC, GLOBAL_ES_ADDR, CanBus, CarControllerParams, SubaruFlags
|
||||
from opendbc.car.vehicle_model import VehicleModel
|
||||
|
||||
# FIXME: These limits aren't exact. The real limit is more than likely over a larger time period and
|
||||
@@ -128,14 +128,15 @@ class CarController(CarControllerBase):
|
||||
return self.aol_dash_green_last
|
||||
|
||||
def _ascent_lkas_alert(self, CC, CS):
|
||||
if self.CP.carFingerprint not in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025) or not self.CP.flags & SubaruFlags.ASCENT_LKAS_ALERT:
|
||||
if (self.CP.carFingerprint not in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025} or
|
||||
not self.CP.flags & SubaruFlags.ASCENT_LKAS_ALERT):
|
||||
return None
|
||||
dat = CS.es_lkas_alert_dat
|
||||
is_legacy_2025 = self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025
|
||||
frogger_hud = self.CP.carFingerprint != CAR.SUBARU_ASCENT_2023
|
||||
lateral_active = self.angle_was_active and CC.latActive and (
|
||||
CC.enabled or subaru_aol_qualified(self.CP, marked_only=True)
|
||||
)
|
||||
if is_legacy_2025:
|
||||
if frogger_hud:
|
||||
armed = CS.out.cruiseState.available
|
||||
if self.CP.openpilotLongitudinalControl:
|
||||
acc_lead_visible = bool(CC.longActive and not CS.out.gasPressed and CC.hudControl.leadVisible)
|
||||
@@ -213,7 +214,7 @@ class CarController(CarControllerBase):
|
||||
not legacy_lateral_off and
|
||||
not CS.out.standstill and not CS.out.steerFaultTemporary and not CS.out.steerFaultPermanent)
|
||||
angle_active = self.angle_active(CS, angle_available)
|
||||
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025:
|
||||
if self.CP.carFingerprint in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_LEGACY_2025}:
|
||||
if angle_active and self.angle_was_active and abs(self.apply_angle_last - CS.out.steeringAngleDeg) > 5.0:
|
||||
self.eps_stall_count += 1
|
||||
if self.eps_stall_count >= 8:
|
||||
@@ -306,7 +307,8 @@ class CarController(CarControllerBase):
|
||||
can_sends.extend(send_sng(self, CC, CS, now_nanos))
|
||||
|
||||
# *** alerts and pcm cancel ***
|
||||
enabled_for_dash_2025 = False
|
||||
frogger_hud = self.CP.carFingerprint in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_LEGACY_2025}
|
||||
enabled_for_dash_2025 = self.angle_was_active
|
||||
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025:
|
||||
enabled_for_dash_2025 = self._legacy_2025_aol_dash_green(
|
||||
hud_control,
|
||||
@@ -341,13 +343,17 @@ class CarController(CarControllerBase):
|
||||
can_sends.append(subarucan.create_es_dashstatus(self.packer, self.frame // 10, CS.es_dashstatus_msg, CC.enabled,
|
||||
self.CP.openpilotLongitudinalControl, CC.longActive, hud_control.leadVisible))
|
||||
|
||||
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025:
|
||||
if frogger_hud:
|
||||
in_drive = CS.out.gearShifter in (structs.CarState.GearShifter.drive, structs.CarState.GearShifter.manumatic)
|
||||
cruise_available = CS.out.cruiseState.available
|
||||
lateral_off = self._legacy_2025_effective_lateral_off(CS, CC)
|
||||
aol_enabled = bool(getattr(CS, "aol_enabled", True))
|
||||
if self.CP.carFingerprint in FROGGER_ANGLE_SIBLINGS:
|
||||
aol_enabled = aol_enabled and subaru_aol_qualified(self.CP, marked_only=True)
|
||||
wheel_ready = bool(cruise_available and aol_enabled)
|
||||
if not (in_drive and cruise_available) or lateral_off or not hud_control.lanesVisible:
|
||||
lanes_visible = hud_control.lanesVisible or (
|
||||
self.CP.carFingerprint in FROGGER_ANGLE_SIBLINGS and self.angle_was_active)
|
||||
if not (in_drive and cruise_available) or lateral_off or not lanes_visible:
|
||||
left_line = 0
|
||||
right_line = 0
|
||||
left_depart = False
|
||||
@@ -376,7 +382,7 @@ class CarController(CarControllerBase):
|
||||
hud_control.leftLaneDepart, hud_control.rightLaneDepart))
|
||||
|
||||
if self.CP.flags & SubaruFlags.SEND_INFOTAINMENT:
|
||||
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025:
|
||||
if frogger_hud:
|
||||
can_sends.append(subarucan.create_es_infotainment(
|
||||
self.packer, self.frame // 10, CS.es_infotainment_msg, hud_control.visualAlert,
|
||||
audible_alert=hud_control.audibleAlert, legacy_2025=True,
|
||||
|
||||
@@ -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, EARLY_GLOBAL_TORQUE_CARS, GLOBAL_ES_ADDR, CanBus, SubaruFlags, SubaruSafetyFlags
|
||||
from opendbc.car.subaru.values import CAR, FROGGER_ANGLE_SIBLINGS, EARLY_GLOBAL_TORQUE_CARS, GLOBAL_ES_ADDR, CanBus, SubaruFlags, SubaruSafetyFlags
|
||||
|
||||
GEN2_ANGLE_PORTS = frozenset((CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_LEGACY_2025,
|
||||
CAR.SUBARU_ASCENT_2023, CAR.SUBARU_FORESTER_2022, CAR.SUBARU_OUTBACK_2023))
|
||||
@@ -59,7 +59,7 @@ class CarInterface(CarInterfaceBase):
|
||||
if not (ret.flags & SubaruFlags.PREGLOBAL) and 0x323 in fingerprint[2]:
|
||||
ret.flags |= SubaruFlags.SEND_INFOTAINMENT.value
|
||||
|
||||
if candidate in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025) and fingerprint[CanBus.camera].get(0x3C4) == 8:
|
||||
if candidate in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025} and fingerprint[CanBus.camera].get(0x3C4) == 8:
|
||||
ret.flags |= SubaruFlags.ASCENT_LKAS_ALERT.value
|
||||
|
||||
if ret.flags & SubaruFlags.PREGLOBAL:
|
||||
@@ -76,6 +76,8 @@ class CarInterface(CarInterfaceBase):
|
||||
ret.safetyConfigs[0].safetyParam |= SubaruSafetyFlags.LKAS_ANGLE.value
|
||||
if candidate in (CAR.SUBARU_LEGACY_2025, CAR.SUBARU_ASCENT_2023, CAR.SUBARU_OUTBACK_2023):
|
||||
ret.safetyConfigs[0].safetyParam |= SubaruSafetyFlags.FIXED_ANGLE_LIMITS.value
|
||||
if candidate in FROGGER_ANGLE_SIBLINGS and ret.flags & SubaruFlags.ASCENT_LKAS_ALERT:
|
||||
ret.safetyConfigs[0].safetyParam |= SubaruSafetyFlags.ASCENT_LKAS_ALERT.value
|
||||
if candidate == CAR.SUBARU_OUTBACK_2023:
|
||||
ret.safetyConfigs[0].safetyParam |= SubaruSafetyFlags.D_PLATFORM.value
|
||||
if candidate == CAR.SUBARU_ASCENT_2023:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Exact stock-cruise Subaru independent-lateral configuration contract."""
|
||||
from opendbc.car import structs
|
||||
from opendbc.car.subaru.values import CAR, EARLY_GLOBAL_TORQUE_CARS, SubaruFlags, SubaruSafetyFlags
|
||||
from opendbc.car.subaru.values import CAR, FROGGER_ANGLE_SIBLINGS, EARLY_GLOBAL_TORQUE_CARS, SubaruFlags, SubaruSafetyFlags
|
||||
|
||||
AOL_EXPERIENCE = 32
|
||||
IMPREZA_MAIN_AOL = 4096
|
||||
@@ -37,6 +37,12 @@ def qualified(cp, *, marked_only=False):
|
||||
expected |= int(SubaruSafetyFlags.AVH_STARTUP)
|
||||
if cp.flags & SubaruFlags.STOP_START_OFF:
|
||||
expected |= int(SubaruSafetyFlags.STOP_START_BUTTON)
|
||||
if cp.carFingerprint in FROGGER_ANGLE_SIBLINGS:
|
||||
allowed |= int(SubaruFlags.AVH_STARTUP | SubaruFlags.ASCENT_LKAS_ALERT)
|
||||
if cp.flags & SubaruFlags.AVH_STARTUP:
|
||||
expected |= int(SubaruSafetyFlags.AVH_STARTUP)
|
||||
if cp.flags & SubaruFlags.ASCENT_LKAS_ALERT:
|
||||
expected |= int(SubaruSafetyFlags.ASCENT_LKAS_ALERT)
|
||||
angle = cp.carFingerprint in ANGLE_CARS
|
||||
if angle:
|
||||
expected |= int(SubaruSafetyFlags.LKAS_ANGLE)
|
||||
|
||||
@@ -4,7 +4,7 @@ from opendbc.car import structs
|
||||
from opendbc.car.subaru.carcontroller import CarController
|
||||
from opendbc.car.subaru.carstate import CarState
|
||||
from opendbc.car.subaru.interface import CarInterface
|
||||
from opendbc.car.subaru.values import CAR, DBC, SubaruFlags, SubaruSafetyFlags
|
||||
from opendbc.car.subaru.values import CAR, DBC, FROGGER_ANGLE_SIBLINGS, SubaruFlags, SubaruSafetyFlags
|
||||
from opendbc.car.subaru import subarucan
|
||||
from opendbc.safety.tests.test_subaru_gen2_angle_pair import TestSubaruGen2AnglePair
|
||||
|
||||
@@ -18,8 +18,8 @@ class TestAscentLkasAlert(unittest.TestCase):
|
||||
def test_platform_bus_length_gate_preserves_native_identity(self):
|
||||
for car in CAR:
|
||||
cp = self.params(car)
|
||||
self.assertEqual(bool(cp.flags & SubaruFlags.ASCENT_LKAS_ALERT), car in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025))
|
||||
self.assertEqual(bool(cp.safetyConfigs[0].safetyParam & SubaruSafetyFlags.ASCENT_LKAS_ALERT), car == CAR.SUBARU_ASCENT_2023)
|
||||
self.assertEqual(bool(cp.flags & SubaruFlags.ASCENT_LKAS_ALERT), car in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025})
|
||||
self.assertEqual(bool(cp.safetyConfigs[0].safetyParam & SubaruSafetyFlags.ASCENT_LKAS_ALERT), car in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_ASCENT_2023})
|
||||
for bus, length in ((0, 8), (1, 8), (2, 4), (2, 16)):
|
||||
cp = self.params(bus=bus, length=length)
|
||||
self.assertFalse(cp.flags & SubaruFlags.ASCENT_LKAS_ALERT)
|
||||
|
||||
@@ -145,9 +145,10 @@ def test_hackathon_filter_updates_at_control_rate(speed, tau):
|
||||
assert not any(frame[0] == 0x124 for frame in odd_sends)
|
||||
assert controller.angle_filter.x == pytest.approx(.1 * (1. - (1. - alpha) ** 2))
|
||||
command.latActive = False
|
||||
state.out.steeringAngleDeg = .3
|
||||
command.actuators.steeringAngleDeg = -.2
|
||||
controller.update(command.as_reader(), state, 1_020_000_000)
|
||||
assert controller.angle_filter.x == command.actuators.steeringAngleDeg
|
||||
assert controller.angle_filter.x == state.out.steeringAngleDeg
|
||||
|
||||
|
||||
def test_hackathon_geometry_is_scoped_and_native_bound_remains_strict():
|
||||
|
||||
@@ -7,7 +7,7 @@ from opendbc.car import Bus, structs
|
||||
from opendbc.car.subaru import subarucan
|
||||
from opendbc.car.subaru.stock_aol import ANGLE_CARS, TORQUE_CARS
|
||||
from opendbc.car.subaru.tests.test_ascent_angle import setup_controller, step
|
||||
from opendbc.car.subaru.values import CAR, DBC, SubaruSafetyFlags
|
||||
from opendbc.car.subaru.values import CAR, DBC, FROGGER_ANGLE_SIBLINGS, SubaruSafetyFlags
|
||||
from opendbc.safety.tests import test_subaru_gen2_angle_pair as pair
|
||||
from opendbc.safety.tests.libsafety import libsafety_py
|
||||
|
||||
@@ -74,6 +74,9 @@ def test_dash_uses_current_request_without_mutating_physical_template(car, enabl
|
||||
if car == CAR.SUBARU_LEGACY_2025:
|
||||
assert bool(dash['LKAS_ACTIVE'])
|
||||
assert dash['LKAS_Dash_State'] == (2 if expected else (1 if state.out.cruiseState.available else 0))
|
||||
elif car in FROGGER_ANGLE_SIBLINGS:
|
||||
assert bool(dash['LKAS_ACTIVE'])
|
||||
assert dash['LKAS_Dash_State'] == (2 if expected else (1 if marked and state.out.cruiseState.available else 0))
|
||||
else:
|
||||
if car in ANGLE_CARS or marked or enabled:
|
||||
assert bool(dash['LKAS_ACTIVE']) == expected
|
||||
|
||||
@@ -69,6 +69,19 @@ class TestSupportedSubaruFirmware(unittest.TestCase):
|
||||
self.assertTrue(cp.pcmCruise)
|
||||
self.assertEqual(cp.safetyConfigs[0].safetyParam, word)
|
||||
|
||||
def test_early_crosstrek_shares_firmware_but_has_distinct_vehicle_params(self):
|
||||
platform = CAR.SUBARU_CROSSTREK_2018
|
||||
self.assertNotIn(platform, FW_VERSIONS)
|
||||
shared = FW_VERSIONS[CAR.SUBARU_IMPREZA]
|
||||
live = {(address, sub): {versions[0]} for (_, address, sub), versions in shared.items()}
|
||||
self.assertEqual(match_fw_to_car_exact(live, match_brand='subaru', log=False), {CAR.SUBARU_IMPREZA})
|
||||
for release in (False, True):
|
||||
cp = CarInterface.get_params(platform, {0: {}, 1: {}, 2: {}}, [], False, release, False)
|
||||
self.assertEqual(cp.carFingerprint, platform)
|
||||
self.assertFalse(cp.dashcamOnly)
|
||||
self.assertTrue(cp.pcmCruise)
|
||||
self.assertFalse(cp.openpilotLongitudinalControl or cp.alphaLongitudinalAvailable)
|
||||
|
||||
def test_three_byte_diagnostic_response_is_not_a_camera_identity(self):
|
||||
for platform in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025):
|
||||
for versions in FW_VERSIONS[platform].values():
|
||||
|
||||
@@ -280,6 +280,9 @@ 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,3 +1,4 @@
|
||||
import time
|
||||
import numpy as np
|
||||
from opendbc.car import ACCEL_MAX_TAKEOFF
|
||||
from opendbc.can import CANPacker
|
||||
@@ -10,6 +11,7 @@ from opendbc.car.tesla.hw1 import HW1CarController
|
||||
from opendbc.car.tesla.values import CAR, CarControllerParams, TeslaSafetyFlags
|
||||
from opendbc.car.tesla.coop_steering import CooperativeSteeringController
|
||||
from opendbc.car.vehicle_model import VehicleModel
|
||||
from opendbc.car.tesla.speed_sync import SpeedSynchronizer, selected as speed_sync_selected, sync_controller
|
||||
|
||||
|
||||
def get_safety_CP():
|
||||
@@ -22,6 +24,7 @@ def get_safety_CP():
|
||||
class CarController(CarControllerBase):
|
||||
def __init__(self, dbc_names, CP):
|
||||
super().__init__(dbc_names, CP)
|
||||
self.speed_sync = SpeedSynchronizer() if speed_sync_selected(CP) else None
|
||||
if CP.carFingerprint == CAR.TESLA_MODEL_S_PREAP:
|
||||
self.preap = PreAPStockCarController(dbc_names, CP)
|
||||
return
|
||||
@@ -91,6 +94,10 @@ class CarController(CarControllerBase):
|
||||
cntr = (CS.das_control["DAS_controlCounter"] + 1) % 8
|
||||
can_sends.append(self.tesla_can.create_longitudinal_command(13, 0, cntr, CS.out.vEgo, False))
|
||||
|
||||
# Speed sync: append-only mirror; never changes the selected target or actuators.
|
||||
if self.speed_sync is not None:
|
||||
can_sends.extend(sync_controller(self, CC, CS, time.clock_gettime_ns(time.CLOCK_BOOTTIME)))
|
||||
|
||||
# TODO: HUD control
|
||||
new_actuators = actuators.as_builder()
|
||||
new_actuators.steeringAngleDeg = getattr(self, "command_angle", self.apply_angle_last)
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import copy
|
||||
from opendbc.car.dashboard_speed_limit import Tracker as LimitTracker
|
||||
from opendbc.car.tesla.speed_limit import update_dashboard_limit
|
||||
from opendbc.can import CANDefine, CANParser
|
||||
from opendbc.car import Bus, create_button_events, structs
|
||||
from opendbc.car.common.conversions import Conversions as CV
|
||||
@@ -32,6 +34,7 @@ class CarState(CarStateBase):
|
||||
self.hands_on_level = 0
|
||||
self.das_control = {}
|
||||
return
|
||||
self.dashboard_limit = LimitTracker()
|
||||
self.cooperative_steering = (CP.carFingerprint in (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y) and
|
||||
bool(CP.safetyConfigs[0].safetyParam & TeslaSafetyFlags.COOP_STEERING))
|
||||
self.can_define = CANDefine(DBC[CP.carFingerprint][Bus.party])
|
||||
@@ -160,6 +163,9 @@ class CarState(CarStateBase):
|
||||
|
||||
# Buttons # ToDo: add Gap adjust button
|
||||
|
||||
if self.CP.carFingerprint in (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y):
|
||||
update_dashboard_limit(self.dashboard_limit, cp_party, cp_ap_party, speed_units)
|
||||
|
||||
# Messages needed by carcontroller
|
||||
self.das_control = copy.copy(cp_ap_party.vl["DAS_control"])
|
||||
|
||||
|
||||
@@ -13,6 +13,11 @@ class CarInterface(CarInterfaceBase):
|
||||
CarController = CarController
|
||||
RadarInterface = RadarInterface
|
||||
|
||||
def update(self, can_packets):
|
||||
if self.CC is not None and self.CC.speed_sync is not None:
|
||||
self.CC.speed_sync.observe(can_packets)
|
||||
return super().update(can_packets)
|
||||
|
||||
@staticmethod
|
||||
def _get_params(ret: structs.CarParams, candidate, fingerprint, car_fw, alpha_long, is_release, docs) -> structs.CarParams:
|
||||
ret.brand = "tesla"
|
||||
|
||||
@@ -1,10 +1,20 @@
|
||||
"""Exact modern Tesla screen harness capability and frozen safety selection."""
|
||||
from opendbc.car.tesla.values import CAR, TeslaFlags
|
||||
from opendbc.car.tesla.values import CAR, TeslaFlags, TeslaSafetyFlags
|
||||
|
||||
SCREEN_WORDS = frozenset((512, 513, 1536, 1537, 768, 769, 1792, 1793))
|
||||
BASE_WORDS = frozenset((0, 1, 256, 257))
|
||||
ORDINARY_WORDS = frozenset((2048, 2049, 2304, 2305, 3072, 3073, 3328, 3329))
|
||||
AOL_WORDS = SCREEN_WORDS | ORDINARY_WORDS
|
||||
SPEED_SYNC = int(TeslaSafetyFlags.SCROLL_SPEED_SYNC)
|
||||
# Exact native tesla_sync_param_valid words: scroll speed sync (4096) on a word that carries LONG_CONTROL.
|
||||
SYNC_WORDS = frozenset(SPEED_SYNC | word for word in (1, 257, 513, 769, 1537, 1793, 2049, 2305, 3073, 3329))
|
||||
KNOWN_FLAGS = int(TeslaFlags.MISSING_DAS_SETTINGS | TeslaFlags.HAS_VEHICLE_BUS | TeslaFlags.AOL_SCREEN_BUTTON)
|
||||
|
||||
|
||||
def speed_sync_allowed(cp, word):
|
||||
return bool(word in SYNC_WORDS and cp.carFingerprint in (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y) and cp.openpilotLongitudinalControl and
|
||||
cp.flags & TeslaFlags.HAS_VEHICLE_BUS and not cp.flags & ~KNOWN_FLAGS and
|
||||
bool(word & 512) == bool(cp.flags & TeslaFlags.AOL_SCREEN_BUTTON))
|
||||
|
||||
|
||||
def modern_aol_supported(cp):
|
||||
@@ -12,9 +22,13 @@ def modern_aol_supported(cp):
|
||||
if (cp.brand != 'tesla' or cp.carFingerprint not in (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y) or
|
||||
cp.passive or cp.dashcamOnly or cp.notCar or cp.alternativeExperience not in (0, 32) or len(cp.safetyConfigs) != 1 or
|
||||
int(cp.safetyConfigs[0].safetyModel.raw) != 10 or
|
||||
cp.flags & ~int(TeslaFlags.MISSING_DAS_SETTINGS | TeslaFlags.HAS_VEHICLE_BUS | TeslaFlags.AOL_SCREEN_BUTTON)):
|
||||
cp.flags & ~KNOWN_FLAGS):
|
||||
return False
|
||||
word = int(cp.safetyConfigs[0].safetyParam)
|
||||
if word & SPEED_SYNC:
|
||||
if not speed_sync_allowed(cp, word):
|
||||
return False
|
||||
word &= ~SPEED_SYNC
|
||||
return (word in BASE_WORDS | AOL_WORDS and
|
||||
bool(word & 1) == bool(cp.openpilotLongitudinalControl) and
|
||||
bool(word & 512) == bool(cp.flags & TeslaFlags.AOL_SCREEN_BUTTON) and
|
||||
@@ -31,12 +45,12 @@ modern_screen_supported = screen_tap_supported
|
||||
|
||||
|
||||
def screen_qualified(cp, *, marked_only=False):
|
||||
return bool(screen_tap_supported(cp) and int(cp.safetyConfigs[0].safetyParam) in SCREEN_WORDS and
|
||||
return bool(screen_tap_supported(cp) and (int(cp.safetyConfigs[0].safetyParam) & ~SPEED_SYNC) in SCREEN_WORDS and
|
||||
cp.alternativeExperience in ((32,) if marked_only else (0, 32)))
|
||||
|
||||
|
||||
def modern_aol_qualified(cp, *, marked_only=False):
|
||||
return bool(modern_aol_supported(cp) and int(cp.safetyConfigs[0].safetyParam) in AOL_WORDS and
|
||||
return bool(modern_aol_supported(cp) and (int(cp.safetyConfigs[0].safetyParam) & ~SPEED_SYNC) in AOL_WORDS and
|
||||
cp.alternativeExperience in ((32,) if marked_only else (0, 32)))
|
||||
|
||||
|
||||
@@ -44,7 +58,7 @@ def apply_modern_aol(cp, requested, screen, brake_disengage):
|
||||
if not modern_aol_supported(cp):
|
||||
return
|
||||
use_screen = requested and screen and screen_tap_supported(cp)
|
||||
base = int(cp.safetyConfigs[0].safetyParam) & 257
|
||||
base = int(cp.safetyConfigs[0].safetyParam) & (257 | SPEED_SYNC) # scroll speed sync rides on top of any AOL word
|
||||
cp.flags &= ~int(TeslaFlags.AOL_SCREEN_BUTTON)
|
||||
cp.safetyConfigs[0].safetyParam = base
|
||||
if requested:
|
||||
@@ -56,7 +70,7 @@ def apply_modern_aol(cp, requested, screen, brake_disengage):
|
||||
def apply_screen_button(cp, requested, brake_disengage):
|
||||
if not screen_tap_supported(cp):
|
||||
return
|
||||
base = int(cp.safetyConfigs[0].safetyParam) & 257
|
||||
base = int(cp.safetyConfigs[0].safetyParam) & (257 | SPEED_SYNC)
|
||||
cp.flags &= ~int(TeslaFlags.AOL_SCREEN_BUTTON)
|
||||
cp.safetyConfigs[0].safetyParam = base
|
||||
if requested:
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Tesla fused road-limit evidence for the 7.0 Dashboard producer."""
|
||||
import math
|
||||
from opendbc.car.dashboard_speed_limit import Status, parser_expiry
|
||||
|
||||
|
||||
def update_dashboard_limit(tracker, party, autopilot, speed_units):
|
||||
limit_ns, limit_expiry = parser_expiry(autopilot, 'DAS_status', 'DAS_fusedSpeedLimit')
|
||||
units_ns, units_expiry = parser_expiry(party, 'DI_state', 'DI_speedUnits')
|
||||
stamp = max(limit_ns, units_ns)
|
||||
if stamp <= tracker.observation.observed_ns:
|
||||
return
|
||||
status, speed = Status.UNKNOWN, 0.0
|
||||
expiry = min(limit_expiry, units_expiry)
|
||||
if (limit_ns > 0 and units_ns > 0 and expiry > stamp and party.can_valid and autopilot.can_valid
|
||||
and speed_units in ('MPH', 'KPH')):
|
||||
value = float(autopilot.vl['DAS_status']['DAS_fusedSpeedLimit'])
|
||||
# The DBC scales raw31/NONE to155; raw0 is UNKNOWN, never zero mph.
|
||||
if math.isfinite(value) and 0 < value <= 150:
|
||||
status, speed = Status.VALID, value * (0.44704 if speed_units == 'MPH' else 1 / 3.6)
|
||||
elif value == 155:
|
||||
status = Status.ABSENT
|
||||
tracker.update(stamp, status, speed, valid_until_ns=expiry)
|
||||
@@ -0,0 +1,730 @@
|
||||
"""Speed sync: one-way native selected-speed mirror for the Tesla Model 3/Y. Experimental.
|
||||
|
||||
No speed-control state is written here. Normal control packets are owned by the
|
||||
existing controller. Only a bounded relative wheel request can be returned.
|
||||
|
||||
Each request is one right-wheel frame: a single click (+-1 mph), or a fast flick
|
||||
(+-5 clicks) that moves the Tesla to the next multiple of 5. The Tesla only treats
|
||||
a flick as fast when it starts a new gesture: a scroll soon after the previous one
|
||||
moves the speed by 1. So fast steps are spaced, and the spacing
|
||||
is learned. The panda decides what may be sent. A request the panda does not transmit (no bus-129 return, or a
|
||||
bus-193 rejection) never reached the car, so it is cleared and retried later.
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
from collections import deque
|
||||
import math
|
||||
|
||||
from opendbc.car.tesla.values import TeslaFlags, TeslaSafetyFlags
|
||||
|
||||
SYNC_FLAG = int(TeslaSafetyFlags.SCROLL_SPEED_SYNC)
|
||||
MODELS = ("TESLA_MODEL_3", "TESLA_MODEL_Y")
|
||||
|
||||
|
||||
def eligible(cp):
|
||||
"""A Model 3/Y with StarPilot longitudinal control, its own cruise and the CAN add-on cable (Vehicle CAN)."""
|
||||
try:
|
||||
return bool(cp.brand == "tesla" and cp.carFingerprint in MODELS and cp.openpilotLongitudinalControl and cp.pcmCruise and
|
||||
not cp.passive and not cp.dashcamOnly and not cp.notCar and cp.flags & TeslaFlags.HAS_VEHICLE_BUS and
|
||||
len(cp.safetyConfigs) == 1 and cp.safetyConfigs[0].safetyParam & TeslaSafetyFlags.LONG_CONTROL)
|
||||
except (AttributeError, TypeError, ValueError, IndexError):
|
||||
return False
|
||||
|
||||
|
||||
def selected(cp):
|
||||
"""The car started with the scroll frame admitted, so the comma may own the set speed and scroll the Tesla's to match.
|
||||
Whether it does follows the saved switch (openpilot/starpilot/car/tesla/set_speed.py)."""
|
||||
try:
|
||||
return bool(eligible(cp) and cp.safetyConfigs[0].safetyParam & SYNC_FLAG)
|
||||
except (AttributeError, TypeError, ValueError, IndexError):
|
||||
return False
|
||||
|
||||
|
||||
def prepare(cp, requested):
|
||||
"""Admit the scroll frame in the car's parameters at startup (the panda sends it only with this bit)."""
|
||||
if eligible(cp):
|
||||
cp.safetyConfigs[0].safetyParam &= ~SYNC_FLAG
|
||||
if requested:
|
||||
cp.safetyConfigs[0].safetyParam |= SYNC_FLAG
|
||||
return cp
|
||||
|
||||
|
||||
NS = 1_000_000_000
|
||||
FRESH_NS = 250_000_000
|
||||
# No Tesla change by SETTLE_NS: the request went unanswered (the updated panda frees its own request after 0.8 s).
|
||||
SETTLE_NS = 1_000_000_000
|
||||
TOKENS_MAX = 30 # panda rate limit: burst of 30 requests...
|
||||
TOKEN_REFILL_NS = 1_050_000_000 # ...then one per second (a little slower here so the panda never refuses)
|
||||
FAST_PAUSE_NS = 2 * NS # after a refused fast step, single clicks for this long
|
||||
MANUAL_COMPLETION_NS = 2 * NS
|
||||
HANDOVER_NS = 100_000_000
|
||||
TEMPLATE_SEND_NS = 100_000_000 # one wheel-frame period (panda allows 250 ms)
|
||||
RETURN_NS = 100_000_000 # panda echoes a transmitted frame on bus 129 within ~5 ms
|
||||
BACKOFF_NS = 300_000_000 # wait after a request the panda refused,
|
||||
BACKOFF_MAX_NS = 2 * NS # doubling on each refusal in a row
|
||||
MANUAL_SETTLE_NS = 600_000_000 # let the Tesla apply the driver's own scroll first
|
||||
FAST_TICKS = 5
|
||||
# Fast-step spacing. Measured: a flick 0.1-0.24 s after the previous scroll moved
|
||||
# the Tesla by 1; the driver's own flicks 0.4 s apart all jumped 5. Start short and
|
||||
# lengthen on each fast step that lands as a single click; shorten again after a
|
||||
# run of good ones. Nothing here ever stops the sync.
|
||||
FAST_GAP_NS = 280_000_000
|
||||
FAST_GAP_STEP_NS = 100_000_000
|
||||
FAST_GAP_MAX_NS = 800_000_000
|
||||
FAST_GAP_RELAX = 30 # good fast steps in a row before trying a shorter gap
|
||||
FAST_RESPONSE_NS = 250_000_000 # Tesla applies a new gesture after ~0.23 s
|
||||
STREAM_STEP_NS = 100_000_000 # a click inside a gesture shows up at the next DI frame
|
||||
ENGAGE_DELAY_NS = 150_000_000 # pandad tells the panda about engagement at 10 Hz
|
||||
MAX_RETRIES = 3 # unanswered clicks retried at one speed before waiting
|
||||
|
||||
|
||||
def neutral_wheel(data):
|
||||
if len(data) != 8 or data[0] & 3 != 1:
|
||||
return False
|
||||
bits = int.from_bytes(data, "little")
|
||||
return (all((bits >> shift) & 3 == 1 for shift in (3, 5, 8, 10, 12, 14)) and
|
||||
data[2] & 63 == 0 and data[3] & 63 == 0 and data[4] & 15 == 0)
|
||||
|
||||
|
||||
def scroll_request(template, ticks):
|
||||
"""Copy a physical neutral frame and set only the right-wheel scroll count."""
|
||||
if not neutral_wheel(template) or ticks not in (-FAST_TICKS, -1, 1, FAST_TICKS):
|
||||
return None
|
||||
data = bytearray(template)
|
||||
data[3] = (data[3] & 0xC0) | (ticks & 0x3F)
|
||||
return (0x3C2, bytes(data), 1)
|
||||
|
||||
|
||||
def plan_step(native, target, allow_fast):
|
||||
"""Return (ticks, expected native) for the next step from native toward target.
|
||||
|
||||
A fast flick lands on the next multiple of 5 in that direction (measured: nearly
|
||||
every flick of 3+ clicks did this in one change). Use it only
|
||||
when that multiple does not pass the target and saves at least one click.
|
||||
"""
|
||||
sign = 1 if target > native else -1
|
||||
if allow_fast:
|
||||
nxt = (native // 5 + 1) * 5 if sign > 0 else ((native - 1) // 5) * 5
|
||||
if abs(nxt - native) >= 2 and (target - nxt) * sign >= 0:
|
||||
return sign * FAST_TICKS, nxt
|
||||
return sign, native + sign
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SyncAuthority:
|
||||
observed_boot_ns: int
|
||||
target_kph: float
|
||||
is_metric: bool
|
||||
configuration_id: str
|
||||
software_owned: bool
|
||||
document_hash: str = ""
|
||||
vehicle_hash: str = ""
|
||||
drive_start_ns: int = 0
|
||||
manual_receipts: tuple = ()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ManualReceipt:
|
||||
boot_ns: int
|
||||
frame_index: int
|
||||
name: str
|
||||
fast: bool
|
||||
worker_session: str
|
||||
sequence: int
|
||||
document_hash: str
|
||||
vehicle_hash: str
|
||||
drive_start_ns: int
|
||||
processed_boot_ns: int
|
||||
target_kph: float
|
||||
|
||||
|
||||
@dataclass
|
||||
class Pending:
|
||||
before: float
|
||||
direction: int
|
||||
units: int
|
||||
sent_ns: int
|
||||
data: bytes
|
||||
ticks: int = 0
|
||||
retry: bool = False
|
||||
returned: bool = False
|
||||
expected: int = 0
|
||||
gap_ns: int = 0 # time since the previous scroll when sent
|
||||
|
||||
|
||||
class SpeedSynchronizer:
|
||||
def __init__(self):
|
||||
self.template = None
|
||||
self.template_ns = 0
|
||||
self.driver_ns = 0
|
||||
self.native_ns = 0
|
||||
self.native = None
|
||||
self.units = None
|
||||
self.cruise_state = None
|
||||
self.autopark = None
|
||||
self.counter = None
|
||||
self.di_valid = False
|
||||
self.di_key = (0, -1)
|
||||
self.wheel_stamp = 0
|
||||
self.pending = None
|
||||
self.unanswered = None
|
||||
self.unanswered_count = 0
|
||||
self.last_sent = 0
|
||||
self.last_template_sent = 0
|
||||
self.last_update = 0
|
||||
self.backoff_until = 0
|
||||
self.target = None
|
||||
self.steps = 0
|
||||
self.blocked = None
|
||||
self.status = "idle"
|
||||
self.active = False
|
||||
self.authority_id = None
|
||||
self.manual_armed = False
|
||||
self.manual_active = None
|
||||
self.manual_queue = []
|
||||
self.manual_receipts = {}
|
||||
self.manual_receipt_acks = []
|
||||
self.manual_ack_key = (0, -1)
|
||||
self.wheel_key = (0, -1)
|
||||
self.wheel_held = False # the last wheel frame was a tilt or press without a scroll
|
||||
self.gas_was_pressed = False
|
||||
self.handover_until = 0
|
||||
self.response_ns = 0
|
||||
self.history = deque(maxlen=32)
|
||||
self.failure_logged = False
|
||||
# Nothing is switched off for good: a refusal only pauses that feature.
|
||||
self.fast_paused_until = 0
|
||||
self.retry_refused = False
|
||||
self.tokens = TOKENS_MAX
|
||||
self.refill_ns = 0
|
||||
self.last_scroll_ns = 0 # last scroll the Tesla saw: our sent request or the driver's
|
||||
self.fast_gap_ns = FAST_GAP_NS
|
||||
self.fast_streak = 0
|
||||
self.engaged_ns = 0
|
||||
self.refusals = 0
|
||||
self.notices = []
|
||||
self.noticed = set()
|
||||
|
||||
def observe(self, packets):
|
||||
"""Use original arrival timestamps; cached values never refresh freshness."""
|
||||
for stamp, frames in packets:
|
||||
if type(stamp) is not int or stamp <= 0:
|
||||
continue
|
||||
for frame_index, (address, data, bus) in enumerate(frames):
|
||||
if address == 0x3C2 and bus in (129, 193):
|
||||
# Panda echo of a frame we asked it to send: 129 = transmitted,
|
||||
# 193 = refused by safety. Exact bytes and clock must match.
|
||||
p = self.pending
|
||||
if p is not None and not p.returned and stamp >= p.sent_ns and bytes(data) == p.data:
|
||||
if bus == 129:
|
||||
p.returned = True
|
||||
self.last_scroll_ns = max(self.last_scroll_ns, p.sent_ns)
|
||||
self.refusals = 0
|
||||
self.steps += 1
|
||||
self.tokens = max(self.tokens - 1, 0)
|
||||
else:
|
||||
self._not_transmitted(p, "panda_rejected")
|
||||
continue
|
||||
if address == 0x3C2 and bus == 1:
|
||||
key = (stamp, frame_index)
|
||||
if key == self.wheel_key:
|
||||
continue
|
||||
if key < self.wheel_key:
|
||||
self.template = None
|
||||
self.blocked = "wheel_clock_reversal"
|
||||
continue
|
||||
self.wheel_key = key
|
||||
self.wheel_stamp = stamp
|
||||
if len(data) != 8:
|
||||
self.template = None
|
||||
if self.manual_active:
|
||||
self._pause_manual("ambiguous_manual_input")
|
||||
self.manual_armed = False
|
||||
continue
|
||||
mux = data[0] & 3
|
||||
if mux == 0:
|
||||
continue
|
||||
if mux != 1:
|
||||
self.template = None
|
||||
if self.manual_active:
|
||||
self._pause_manual("ambiguous_manual_input")
|
||||
self.manual_armed = False
|
||||
continue
|
||||
self._observe_manual(data, stamp, frame_index)
|
||||
if neutral_wheel(data):
|
||||
self.template, self.template_ns = bytes(data), stamp
|
||||
else:
|
||||
self.template = None
|
||||
self.driver_ns = stamp
|
||||
self.last_scroll_ns = max(self.last_scroll_ns, stamp)
|
||||
# Genuine controls take priority. The request stays outstanding
|
||||
# until the Tesla's speed changes; direction is then recomputed
|
||||
# from reality, so nothing is repeated blindly.
|
||||
if self.pending is not None:
|
||||
self._record("input_during_request", stamp)
|
||||
elif address == 0x286 and bus == 0:
|
||||
# Several DI frames can share one receive batch (same stamp), so
|
||||
# order by (stamp, index) like the wheel frames above.
|
||||
key = (stamp, frame_index)
|
||||
if key <= self.di_key:
|
||||
if key < self.di_key:
|
||||
self.blocked = "feedback_clock_reversal"
|
||||
self.native_ns = 0
|
||||
continue
|
||||
self.di_key = key
|
||||
if len(data) != 8 or data[0] != ((0x86 + 2 + sum(data[1:])) & 0xFF):
|
||||
self.di_valid = False
|
||||
continue
|
||||
counter = data[1] & 15
|
||||
advancing = self.counter is None or (counter - self.counter) % 16 == 1
|
||||
self.counter = counter
|
||||
# Same rule as the panda: a frame after a counter gap is not used,
|
||||
# and nothing may be sent until the next in-sequence frame.
|
||||
self.di_valid = advancing
|
||||
if not advancing:
|
||||
continue
|
||||
bits = int.from_bytes(data, "little")
|
||||
self.native = ((bits >> 15) & 511) * .5
|
||||
self.units = (bits >> 24) & 1 # 0 mph, 1 km/h
|
||||
self.cruise_state = (bits >> 12) & 7
|
||||
self.autopark = (bits >> 25) & 15
|
||||
self.native_ns = stamp
|
||||
|
||||
def _observe_manual(self, data, stamp, frame_index):
|
||||
right = data[3] & 63
|
||||
right = right - 64 if right >= 32 else right
|
||||
if right:
|
||||
released = bytearray(data)
|
||||
released[3] &= 0xC0
|
||||
name = "right_wheel_up" if right > 0 else "right_wheel_down"
|
||||
if self.manual_active is None and self.wheel_held and abs(right) == 1 and neutral_wheel(released):
|
||||
# A wheel tilted or pressed often clicks once as it springs back. That click ends the nudge and is not a
|
||||
# scroll: the comma does not act on it, so nothing waits for it, and the Tesla's change is corrected below.
|
||||
self._record("nudge_release_click", stamp)
|
||||
self.wheel_held = False
|
||||
self.manual_armed = False
|
||||
return
|
||||
if (not neutral_wheel(released) or
|
||||
self.manual_active is None and not (self.manual_armed and self.template is not None and
|
||||
0 < self.template_ns <= stamp <= self.template_ns + FRESH_NS) or
|
||||
self.manual_active is not None and self.manual_active[0] != name):
|
||||
self._pause_manual("ambiguous_manual_input")
|
||||
return
|
||||
peak = max(abs(right), self.manual_active[1] if self.manual_active else 0)
|
||||
self.manual_active = (name, peak)
|
||||
self.manual_armed = False
|
||||
self.wheel_held = False
|
||||
elif neutral_wheel(data):
|
||||
if self.manual_active:
|
||||
if len(self.manual_queue) >= 16:
|
||||
self._fail("manual_input_overflow")
|
||||
else:
|
||||
name, peak = self.manual_active
|
||||
self.manual_queue.append((stamp, frame_index, name, peak >= 2))
|
||||
self.manual_active = None
|
||||
self.manual_armed = True
|
||||
self.wheel_held = False
|
||||
else:
|
||||
if self.manual_active:
|
||||
self._pause_manual("ambiguous_manual_input")
|
||||
self.manual_active = None
|
||||
self.manual_armed = False
|
||||
self.wheel_held = True
|
||||
|
||||
def _pause_manual(self, reason):
|
||||
"""Wheel input that cannot be read as one clean scroll. The comma's own input reader ignores the same gesture, so
|
||||
nothing waits for it: sync carries on and, after the driver's settle time, puts the Tesla back on the comma's speed.
|
||||
Logged once per engagement."""
|
||||
self._notice(reason)
|
||||
self._record(reason, self.last_update)
|
||||
self.manual_active = None
|
||||
self.manual_armed = False
|
||||
|
||||
def accept_manual_receipts(self, authority, now_ns):
|
||||
# Metadata may arrive before Card sees the corresponding CAN batch. Cache
|
||||
# only bounded, validated receipts; never infer a gesture from the receipt.
|
||||
if type(authority.manual_receipts) is not tuple or len(authority.manual_receipts) > 16:
|
||||
self._fail("invalid_manual_receipts")
|
||||
return
|
||||
for receipt in authority.manual_receipts:
|
||||
if not isinstance(receipt, ManualReceipt):
|
||||
continue
|
||||
try:
|
||||
good = (
|
||||
type(receipt.boot_ns) is int and type(receipt.processed_boot_ns) is int and
|
||||
0 < receipt.boot_ns <= receipt.processed_boot_ns <= now_ns and
|
||||
type(receipt.frame_index) is int and 0 <= receipt.frame_index < 4096 and
|
||||
receipt.name in ("right_wheel_up", "right_wheel_down") and type(receipt.fast) is bool and
|
||||
type(receipt.worker_session) is str and len(receipt.worker_session) == 32 and
|
||||
all(c in "0123456789abcdef" for c in receipt.worker_session) and
|
||||
type(receipt.sequence) is int and receipt.sequence > 0 and
|
||||
receipt.document_hash == authority.document_hash and len(authority.document_hash) == 64 and
|
||||
receipt.vehicle_hash == authority.vehicle_hash and len(authority.vehicle_hash) == 64 and
|
||||
type(receipt.drive_start_ns) is int and receipt.drive_start_ns == authority.drive_start_ns > 0 and
|
||||
type(receipt.target_kph) in (int, float) and math.isfinite(receipt.target_kph) and
|
||||
0 < receipt.target_kph < 255)
|
||||
except (AttributeError, TypeError, ValueError):
|
||||
good = False
|
||||
if not good:
|
||||
continue
|
||||
if now_ns > receipt.boot_ns + MANUAL_COMPLETION_NS:
|
||||
# Validated but expired metadata cannot complete a gesture. Dispose of
|
||||
# it explicitly so it cannot occupy the producer queue indefinitely;
|
||||
# update() independently faults any unconfirmed observed gesture.
|
||||
self._ack_manual_receipt(receipt)
|
||||
continue
|
||||
key = (receipt.boot_ns, receipt.frame_index)
|
||||
if key <= self.manual_ack_key:
|
||||
self._ack_manual_receipt(receipt)
|
||||
continue
|
||||
if key not in self.manual_receipts and len(self.manual_receipts) >= 16:
|
||||
self._fail("manual_receipt_overflow")
|
||||
return
|
||||
if key in self.manual_receipts and self.manual_receipts[key] != receipt:
|
||||
self._fail("conflicting_manual_receipt")
|
||||
return
|
||||
self.manual_receipts[key] = receipt
|
||||
self._ack_manual_receipt(receipt)
|
||||
self.manual_receipts = {key: r for key, r in self.manual_receipts.items() if now_ns <= r.boot_ns + MANUAL_COMPLETION_NS}
|
||||
while self.manual_queue:
|
||||
stamp, index, name, fast = self.manual_queue[0]
|
||||
receipt = self.manual_receipts.get((stamp, index))
|
||||
if receipt is None:
|
||||
break
|
||||
if (receipt.name, receipt.fast) != (name, fast):
|
||||
self._fail("manual_receipt_mismatch")
|
||||
return
|
||||
self.manual_queue.pop(0)
|
||||
self.manual_receipts.pop((stamp, index))
|
||||
self.manual_ack_key = (stamp, index)
|
||||
self.target = None # Re-read the processed target; never write its owner.
|
||||
|
||||
def _ack_manual_receipt(self, receipt):
|
||||
# Acknowledge metadata custody only; this never acknowledges or repeats a
|
||||
# speed action. Card removes exactly these immutable receipts next frame.
|
||||
if receipt not in self.manual_receipt_acks:
|
||||
if len(self.manual_receipt_acks) >= 16:
|
||||
self._fail("manual_receipt_ack_overflow")
|
||||
else:
|
||||
self.manual_receipt_acks.append(receipt)
|
||||
|
||||
def take_manual_receipt_acks(self):
|
||||
result = tuple(self.manual_receipt_acks)
|
||||
self.manual_receipt_acks.clear()
|
||||
return result
|
||||
|
||||
def _fail(self, reason):
|
||||
if not self.blocked:
|
||||
self._record("fault", self.last_update, reason=reason)
|
||||
self.blocked = reason
|
||||
self.pending = None
|
||||
self.unanswered = None
|
||||
self._reset_handover()
|
||||
self.status = reason
|
||||
return None
|
||||
|
||||
def _notice(self, kind, **extra):
|
||||
# One log line per kind per engagement; these are recoverable pauses.
|
||||
if kind not in self.noticed:
|
||||
self.noticed.add(kind)
|
||||
self.notices.append(dict(kind=kind, native=self.native, target=self.target, **extra))
|
||||
|
||||
def _not_transmitted(self, p, reason):
|
||||
"""The panda never put this frame on the bus, so the car never saw it."""
|
||||
self.pending = None
|
||||
if abs(p.ticks) > 1:
|
||||
# Use single clicks for a while, then try fast steps again.
|
||||
self.fast_paused_until = self.last_update + FAST_PAUSE_NS
|
||||
self._notice("fast_step_refused", reason=reason)
|
||||
elif p.retry:
|
||||
# Wait for the Tesla's speed to change for this request only.
|
||||
self.retry_refused = True
|
||||
self._notice("retry_refused", reason=reason)
|
||||
else:
|
||||
self._notice("request_not_transmitted", reason=reason)
|
||||
self.backoff_until = self.last_update + min(BACKOFF_NS << min(self.refusals, 3), BACKOFF_MAX_NS)
|
||||
self.refusals += 1
|
||||
self._record("not_transmitted", self.last_update, reason=reason, ticks=p.ticks)
|
||||
|
||||
def _learn_fast_gap(self, p):
|
||||
landed = math.floor(self.native + .5)
|
||||
before = math.floor(p.before + .5)
|
||||
if landed == p.expected:
|
||||
self.fast_streak += 1
|
||||
if self.fast_streak >= FAST_GAP_RELAX and self.fast_gap_ns > FAST_GAP_NS:
|
||||
self.fast_gap_ns = max(self.fast_gap_ns - FAST_GAP_STEP_NS, FAST_GAP_NS)
|
||||
self.fast_streak = 0
|
||||
elif abs(landed - before) == 1 and abs(p.expected - before) >= 2:
|
||||
# The Tesla took it as part of the previous gesture: space them further.
|
||||
self.fast_streak = 0
|
||||
if p.gap_ns < FAST_GAP_MAX_NS:
|
||||
self.fast_gap_ns = min(max(self.fast_gap_ns, p.gap_ns) + FAST_GAP_STEP_NS, FAST_GAP_MAX_NS)
|
||||
self._notice("fast_step_landed_single", gap_ns=p.gap_ns, fast_gap_ns=self.fast_gap_ns)
|
||||
self._record("fast_landed_single", self.last_update, gap_ns=p.gap_ns, fast_gap_ns=self.fast_gap_ns)
|
||||
|
||||
def _reset_handover(self):
|
||||
self.gas_was_pressed = False
|
||||
self.handover_until = 0
|
||||
|
||||
def _record(self, event, now_ns, **extra):
|
||||
self.history.append(dict(event=event, boot_ns=now_ns, native=self.native,
|
||||
target=self.target, native_ns=self.native_ns,
|
||||
template_ns=self.template_ns, last_sent=self.last_sent,
|
||||
units=self.units, cruise_state=self.cruise_state, **extra))
|
||||
|
||||
def _resolve_pending(self, now_ns):
|
||||
"""Advance the outstanding request. Returns True while it still blocks sending."""
|
||||
p = self.pending
|
||||
if p is None:
|
||||
return False
|
||||
if self.units is not None and self.units != p.units:
|
||||
self._fail("units_changed_during_request")
|
||||
return True
|
||||
if not p.returned and now_ns - p.sent_ns >= RETURN_NS:
|
||||
self._not_transmitted(p, "no_bus_return")
|
||||
return True
|
||||
if self.native_ns > p.sent_ns and self.native != p.before:
|
||||
# Fresh selected-speed feedback releases one outstanding request.
|
||||
# This is not an acknowledgement of command delivery or input origin:
|
||||
# Tesla may change its selection independently. Recompute from reality.
|
||||
self.pending = None
|
||||
self.unanswered = None
|
||||
self.unanswered_count = 0
|
||||
self.retry_refused = False
|
||||
self.response_ns = self.native_ns
|
||||
if abs(p.ticks) == FAST_TICKS:
|
||||
self._learn_fast_gap(p)
|
||||
self._record("native_response", now_ns, before=p.before, sent_ns=p.sent_ns, ticks=p.ticks)
|
||||
self.status = "native_speed_changed"
|
||||
return False
|
||||
if now_ns - p.sent_ns >= SETTLE_NS:
|
||||
# Unanswered. The panda keeps its own request open until the speed
|
||||
# changes (or, with the updated firmware, until its 1 s timeout).
|
||||
self.pending = None
|
||||
self.unanswered = p
|
||||
self.unanswered_count += 1
|
||||
self._notice("no_native_response", before=p.before, ticks=p.ticks)
|
||||
self._record("unanswered", now_ns, before=p.before, ticks=p.ticks)
|
||||
return True
|
||||
self.status = "waiting_for_response"
|
||||
return True
|
||||
|
||||
def update(self, now_ns, *, target_kph, enabled, safe, longitudinal_active=True, gas_pressed=False):
|
||||
if not enabled:
|
||||
self.pending = None
|
||||
self.unanswered = None
|
||||
self.unanswered_count = 0
|
||||
self.retry_refused = False
|
||||
self.target = None
|
||||
self.steps = 0
|
||||
self.blocked = None
|
||||
self.active = False
|
||||
self.authority_id = None
|
||||
self._reset_handover()
|
||||
self.response_ns = 0
|
||||
self.backoff_until = 0
|
||||
self.engaged_ns = 0
|
||||
self.failure_logged = False
|
||||
self.noticed.clear()
|
||||
self.history.clear()
|
||||
self.manual_armed = bool(self.template is not None and
|
||||
0 < self.template_ns <= now_ns <= self.template_ns + FRESH_NS)
|
||||
self.manual_active = None
|
||||
self.manual_queue.clear()
|
||||
self.manual_receipts.clear()
|
||||
self.manual_receipt_acks.clear()
|
||||
self.manual_ack_key = self.wheel_key
|
||||
self.status = "inactive"
|
||||
self.last_update = now_ns
|
||||
return None
|
||||
if type(now_ns) is not int or now_ns <= 0 or (self.last_update and now_ns <= self.last_update):
|
||||
return self._fail("controller_clock_reversal")
|
||||
gap = bool(self.last_update and now_ns - self.last_update > FRESH_NS)
|
||||
self.last_update = now_ns
|
||||
self.active = True
|
||||
if not self.engaged_ns:
|
||||
self.engaged_ns = now_ns
|
||||
if self.blocked:
|
||||
self.status = self.blocked
|
||||
return None
|
||||
if self._resolve_pending(now_ns) and self.pending is not None:
|
||||
return None
|
||||
if self.blocked:
|
||||
return None
|
||||
if gap:
|
||||
# A late controller frame only pauses this frame; a request is never
|
||||
# sent on timing that has not been observed continuously.
|
||||
self._reset_handover()
|
||||
self.status = "controller_clock_gap"
|
||||
return None
|
||||
# Past this bound no matching receipt can pass accept_manual_receipts: the comma did not act on that scroll
|
||||
# (it refused it, or never saw it). Drop it and carry on; the Tesla's change is then corrected like any other
|
||||
# change of its own. Never infer completion or repeat the input.
|
||||
if self.manual_queue and now_ns > self.manual_queue[0][0] + MANUAL_COMPLETION_NS:
|
||||
dropped = [entry for entry in self.manual_queue if now_ns > entry[0] + MANUAL_COMPLETION_NS]
|
||||
self.manual_queue = [entry for entry in self.manual_queue if entry not in dropped]
|
||||
self.manual_ack_key = max(self.manual_ack_key, (dropped[-1][0], dropped[-1][1]))
|
||||
self._notice("manual_action_unconfirmed", dropped=len(dropped))
|
||||
self._record("manual_action_unconfirmed", now_ns, dropped=len(dropped))
|
||||
self.target = None
|
||||
if not safe:
|
||||
self._reset_handover()
|
||||
self.target = None
|
||||
self.status = "inhibited"
|
||||
return None
|
||||
if not (0 < self.native_ns <= now_ns <= self.native_ns + FRESH_NS and self.di_valid and
|
||||
self.native is not None and self.native > 0 and
|
||||
self.cruise_state in (2, 4) and self.autopark not in (3, 4, 9)):
|
||||
self._reset_handover()
|
||||
self.status = "waiting_for_native_speed"
|
||||
return None
|
||||
if not math.isfinite(target_kph) or not 0 < target_kph < 255:
|
||||
self._reset_handover()
|
||||
self.status = "invalid_target"
|
||||
return None
|
||||
# Match the displayed selected speed in Tesla's units, not actual vehicle
|
||||
# speed or a transient model/curve/lead slowdown.
|
||||
target = math.floor((target_kph if self.units else target_kph / 1.609344) + .5)
|
||||
if target <= 0:
|
||||
self.status = "invalid_target"
|
||||
return None
|
||||
target_key = (target, self.units)
|
||||
if self.target != target_key:
|
||||
self.target = target_key
|
||||
# Card and controls publish independently. A genuine pedal release may
|
||||
# precede longActive by a frame; never transmit while neither current
|
||||
# authority is present.
|
||||
if self.gas_was_pressed and not gas_pressed:
|
||||
self.handover_until = now_ns + HANDOVER_NS
|
||||
self.gas_was_pressed = bool(gas_pressed)
|
||||
authorized = bool(longitudinal_active or gas_pressed)
|
||||
if authorized:
|
||||
self.handover_until = 0
|
||||
elif not (self.handover_until and now_ns < self.handover_until):
|
||||
self._reset_handover()
|
||||
self.status = "inhibited"
|
||||
return None
|
||||
if self.manual_active is not None or self.manual_queue:
|
||||
self.status = "waiting_for_manual_processing"
|
||||
return None
|
||||
if not authorized:
|
||||
if self.status != "waiting_for_handover":
|
||||
self._record("handover_wait", now_ns, until_ns=self.handover_until)
|
||||
self.status = "waiting_for_handover"
|
||||
return None
|
||||
native = math.floor(self.native + .5)
|
||||
if native == target:
|
||||
self.unanswered = None
|
||||
self.unanswered_count = 0
|
||||
self.status = "matched"
|
||||
return None
|
||||
# The driver's own scroll takes 0.18-0.4 s to reach the Tesla's selected
|
||||
# speed (measured). A request in that window can cancel a fast flick, so
|
||||
# let the Tesla act on it first.
|
||||
if self.driver_ns and now_ns < self.driver_ns + MANUAL_SETTLE_NS:
|
||||
self.status = "waiting_for_driver_scroll"
|
||||
return None
|
||||
retry = False
|
||||
if self.unanswered is not None:
|
||||
u = self.unanswered
|
||||
# The Tesla moved, or the comma now wants the other way (the Tesla was at its own limit in the old direction):
|
||||
# the unanswered request says nothing about this one.
|
||||
if (self.native_ns > u.sent_ns and self.native != u.before) or u.direction != (1 if target > native else -1):
|
||||
self.unanswered = None
|
||||
self.unanswered_count = 0
|
||||
self.retry_refused = False
|
||||
elif self.retry_refused or self.unanswered_count > MAX_RETRIES:
|
||||
# e.g. the Tesla is at its own speed limit; don't keep scrolling.
|
||||
self.status = "waiting_for_native_change"
|
||||
return None
|
||||
else:
|
||||
retry = True
|
||||
if now_ns < self.backoff_until:
|
||||
self.status = "backoff"
|
||||
return None
|
||||
# The panda only learns that comma engaged from pandad's next heartbeat.
|
||||
if now_ns < self.engaged_ns + ENGAGE_DELAY_NS:
|
||||
self.status = "waiting_for_panda_engage"
|
||||
return None
|
||||
# Mirror the panda's rate limit so it never has to refuse a request.
|
||||
if self.refill_ns == 0:
|
||||
self.refill_ns = now_ns
|
||||
while self.tokens < TOKENS_MAX and now_ns - self.refill_ns >= TOKEN_REFILL_NS:
|
||||
self.tokens += 1
|
||||
self.refill_ns += TOKEN_REFILL_NS
|
||||
if self.tokens >= TOKENS_MAX:
|
||||
self.refill_ns = now_ns
|
||||
if self.tokens <= 0:
|
||||
self.status = "rate_limited"
|
||||
return None
|
||||
# Any physical neutral frame newer than the last one used, still current.
|
||||
if not (self.template is not None and 0 < self.template_ns <= now_ns <= self.template_ns + TEMPLATE_SEND_NS and
|
||||
self.template_ns > self.last_template_sent):
|
||||
self.status = "waiting_for_neutral_wheel"
|
||||
return None
|
||||
ticks, expected = plan_step(native, target, allow_fast=now_ns >= self.fast_paused_until and self.units == 0)
|
||||
gap_ns = now_ns - self.last_scroll_ns if self.last_scroll_ns else 10 * NS
|
||||
if abs(ticks) == FAST_TICKS and gap_ns < self.fast_gap_ns:
|
||||
# Too soon for the Tesla to start a new gesture. Clicks give 1 mph per
|
||||
# 0.1 s and each one restarts the gap, so while fast steps are quicker
|
||||
# overall (gap under 0.5 s) wait for them on any change of 5 or more.
|
||||
# For a short change, wait only if that beats clicking there.
|
||||
wait_ns = self.fast_gap_ns - gap_ns
|
||||
if ((self.fast_gap_ns < FAST_TICKS * STREAM_STEP_NS and abs(target - native) >= FAST_TICKS) or
|
||||
wait_ns + FAST_RESPONSE_NS <= abs(expected - native) * STREAM_STEP_NS):
|
||||
self.status = "waiting_for_fast_gap"
|
||||
return None
|
||||
ticks, expected = plan_step(native, target, allow_fast=False)
|
||||
message = scroll_request(self.template, ticks)
|
||||
if message is None:
|
||||
return self._fail("invalid_template")
|
||||
direction = 1 if ticks > 0 else -1
|
||||
self.pending = Pending(self.native, direction, self.units, now_ns, message[1], ticks=ticks, retry=retry,
|
||||
expected=expected, gap_ns=gap_ns)
|
||||
# A retry keeps the unanswered request on record until the speed changes,
|
||||
# so a refused retry falls back to waiting rather than retrying forever.
|
||||
self.last_sent = now_ns
|
||||
self.last_template_sent = self.template_ns
|
||||
self.status = "request_pending"
|
||||
self._record("request", now_ns, direction=direction, ticks=ticks, retry=retry, gap_ns=gap_ns)
|
||||
return message
|
||||
|
||||
|
||||
def sync_controller(controller, CC, CS, now_ns):
|
||||
"""Read-only mirror. now_ns is BOOTTIME, matching the CAN producer clock."""
|
||||
from opendbc.car.structs import CarState
|
||||
synchronizer = controller.speed_sync
|
||||
out = CS.out
|
||||
authority = getattr(controller, "speed_sync_authority", None)
|
||||
authority_valid = bool(
|
||||
isinstance(authority, SyncAuthority) and authority.software_owned is True and
|
||||
type(authority.observed_boot_ns) is int and
|
||||
0 < authority.observed_boot_ns <= now_ns <= authority.observed_boot_ns + 100_000_000 and
|
||||
type(authority.is_metric) is bool and synchronizer.units == int(authority.is_metric) and
|
||||
type(authority.target_kph) in (int, float) and math.isfinite(authority.target_kph) and authority.target_kph == float(out.vCruise) and
|
||||
type(authority.configuration_id) is str and len(authority.configuration_id) == 64 and all(c in "0123456789abcdef" for c in authority.configuration_id))
|
||||
if authority_valid and CC.enabled:
|
||||
if synchronizer.authority_id not in (None, authority.configuration_id):
|
||||
synchronizer._fail("configuration_changed")
|
||||
synchronizer.authority_id = authority.configuration_id
|
||||
synchronizer.accept_manual_receipts(authority, now_ns)
|
||||
safe = (authority_valid and out.canValid and not out.canTimeout and out.cruiseState.enabled and
|
||||
out.gearShifter == CarState.GearShifter.drive and
|
||||
not (out.standstill or out.brakePressed or out.accFaulted or out.stockAeb or out.stockFcw or
|
||||
out.espDisabled or out.espActive or out.vehicleSensorsInvalid or out.carNotReady or out.doorOpen or out.seatbeltUnlatched or
|
||||
out.steerFaultPermanent or out.steerFaultTemporary or out.stockLkas or
|
||||
out.invalidLkasSetting or CS.autopark))
|
||||
message = synchronizer.update(now_ns, target_kph=float(out.vCruise),
|
||||
enabled=bool(CC.enabled and not CC.cruiseControl.cancel), safe=bool(safe),
|
||||
longitudinal_active=bool(CC.longActive), gas_pressed=bool(out.gasPressed))
|
||||
if not authority_valid and CC.enabled and not synchronizer.blocked:
|
||||
synchronizer.status = "owner_or_config_ineligible"
|
||||
if synchronizer.notices or (synchronizer.blocked and not synchronizer.failure_logged):
|
||||
from opendbc.car.carlog import carlog
|
||||
for notice in synchronizer.notices:
|
||||
carlog.warning("speed sync paused: %s", dict(notice, boot_ns=now_ns, history=list(synchronizer.history)[-8:]))
|
||||
synchronizer.notices.clear()
|
||||
if synchronizer.blocked and not synchronizer.failure_logged:
|
||||
synchronizer.failure_logged = True
|
||||
carlog.warning("speed sync stopped: %s", {"reason": synchronizer.blocked, "boot_ns": now_ns,
|
||||
"native": synchronizer.native, "target": synchronizer.target, "history": list(synchronizer.history)})
|
||||
return [] if message is None else [message]
|
||||
@@ -0,0 +1,210 @@
|
||||
"""Startup preferences keep the exact speed-sync safety words: co-op steering and Always On Lateral compose with it."""
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
import pytest
|
||||
from opendbc.car import gen_empty_fingerprint
|
||||
from opendbc.car.structs import car
|
||||
from opendbc.car.tesla.interface import CarInterface
|
||||
from opendbc.car.tesla.carcontroller import CarController
|
||||
from opendbc.car.tesla.carstate import CarState
|
||||
from opendbc.car.tesla.screen_button import (SYNC_WORDS, apply_modern_aol, apply_screen_button, modern_aol_qualified, modern_aol_supported,
|
||||
screen_qualified, screen_tap_supported, speed_sync_allowed)
|
||||
from opendbc.car.tesla.speed_sync import SYNC_FLAG, prepare as apply_speed_sync, selected
|
||||
from opendbc.car.tesla.values import CAR, CANBUS, DBC, TeslaFlags
|
||||
from openpilot.starpilot.car.tesla.coop_preferences import prepare as apply_cooperative, supported
|
||||
|
||||
MODERN = (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y)
|
||||
# The words tesla_sync_param_valid accepts (safety/modes/tesla_speed_sync.h): 4096 on a word that carries LONG_CONTROL.
|
||||
NATIVE_SYNC_WORDS = frozenset(4096 | word for word in (1, 257, 513, 769, 1537, 1793, 2049, 2305, 3073, 3329))
|
||||
|
||||
|
||||
def sync_params(candidate=CAR.TESLA_MODEL_3, long=True):
|
||||
"""A Model 3/Y with the add-on cable, as it leaves startup with Comma can set speed on Tesla dashboard requested."""
|
||||
fingerprint = gen_empty_fingerprint()
|
||||
fingerprint[CANBUS.vehicle][0x3DF] = 8
|
||||
fingerprint[CANBUS.autopilot_party][0x489] = 8
|
||||
return apply_speed_sync(CarInterface.get_params(candidate, fingerprint, [], long, False, False), True)
|
||||
|
||||
|
||||
def raw(cp):
|
||||
return cp.as_reader().as_builder().to_bytes()
|
||||
|
||||
|
||||
def startup(cp, coop, screen=False, brake=False):
|
||||
apply_screen_button(cp, screen, brake)
|
||||
apply_cooperative(cp, coop)
|
||||
return cp
|
||||
|
||||
|
||||
def expected_word(coop, screen, brake):
|
||||
return 4097 | (256 if coop else 0) | ((512 | (1024 if brake else 0)) if screen else 0)
|
||||
|
||||
|
||||
def assert_rejected(cp):
|
||||
before = raw(cp)
|
||||
assert not supported(cp)
|
||||
assert not screen_tap_supported(cp)
|
||||
assert not screen_qualified(cp)
|
||||
assert not modern_aol_supported(cp)
|
||||
apply_cooperative(cp, True)
|
||||
apply_screen_button(cp, True, True)
|
||||
apply_modern_aol(cp, True, True, True)
|
||||
assert raw(cp) == before
|
||||
|
||||
|
||||
def test_python_words_mirror_the_native_list():
|
||||
assert SYNC_WORDS == NATIVE_SYNC_WORDS
|
||||
header = (Path(__file__).parents[3] / 'safety/modes/tesla_speed_sync.h').read_text()
|
||||
body = header[header.index('static bool tesla_sync_param_valid'):]
|
||||
assert frozenset(4096 | int(word) for word in re.findall(r'base == (\d+)U', body)) == SYNC_WORDS
|
||||
assert 'GET_FLAG(param, 4096U)' in body
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODERN)
|
||||
def test_selected_word_precondition(candidate):
|
||||
cp = sync_params(candidate)
|
||||
assert cp.safetyConfigs[0].safetyParam == 4097 and selected(cp)
|
||||
assert cp.openpilotLongitudinalControl
|
||||
assert cp.flags & TeslaFlags.HAS_VEHICLE_BUS
|
||||
assert speed_sync_allowed(cp, 4097)
|
||||
assert supported(cp) and screen_tap_supported(cp) and modern_aol_supported(cp) and not screen_qualified(cp)
|
||||
assert CarController(DBC[cp.carFingerprint], cp).speed_sync is not None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODERN)
|
||||
@pytest.mark.parametrize('coop', (False, True))
|
||||
def test_cooperative_on_off_keeps_sync(candidate, coop):
|
||||
cp = startup(sync_params(candidate), coop)
|
||||
assert cp.safetyConfigs[0].safetyParam == (4353 if coop else 4097)
|
||||
apply_cooperative(cp, not coop)
|
||||
assert cp.safetyConfigs[0].safetyParam == (4097 if coop else 4353)
|
||||
assert selected(cp)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODERN)
|
||||
@pytest.mark.parametrize('coop', (False, True))
|
||||
@pytest.mark.parametrize('screen', (False, True))
|
||||
@pytest.mark.parametrize('brake', (False, True))
|
||||
def test_screen_brake_matrix_composes_native_words(candidate, coop, screen, brake):
|
||||
cp = startup(sync_params(candidate), coop, screen, brake)
|
||||
expected = expected_word(coop, screen, brake)
|
||||
assert expected in NATIVE_SYNC_WORDS
|
||||
assert cp.safetyConfigs[0].safetyParam == expected
|
||||
assert supported(cp) and screen_tap_supported(cp) and selected(cp)
|
||||
assert screen_qualified(cp) == screen
|
||||
assert bool(cp.flags & TeslaFlags.AOL_SCREEN_BUTTON) == screen
|
||||
apply_screen_button(cp, not screen, brake)
|
||||
assert cp.safetyConfigs[0].safetyParam == expected_word(coop, not screen, brake)
|
||||
assert screen_qualified(cp) == (not screen)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODERN)
|
||||
@pytest.mark.parametrize('coop', (False, True))
|
||||
@pytest.mark.parametrize('screen', (False, True))
|
||||
@pytest.mark.parametrize('brake', (False, True))
|
||||
def test_always_on_lateral_composes_native_words(candidate, coop, screen, brake):
|
||||
# Ordinary Always On Lateral is 2048 and the screen tap 512; either one keeps speed sync on top.
|
||||
cp = sync_params(candidate)
|
||||
apply_modern_aol(cp, True, screen, brake)
|
||||
apply_cooperative(cp, coop)
|
||||
expected = 4097 | (512 if screen else 2048) | (1024 if brake else 0) | (256 if coop else 0)
|
||||
assert cp.safetyConfigs[0].safetyParam == expected and expected in NATIVE_SYNC_WORDS
|
||||
assert selected(cp) and supported(cp) and modern_aol_supported(cp) and modern_aol_qualified(cp)
|
||||
apply_modern_aol(cp, False, screen, brake)
|
||||
assert cp.safetyConfigs[0].safetyParam == 4097 | (256 if coop else 0)
|
||||
assert selected(cp) and not modern_aol_qualified(cp)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODERN)
|
||||
@pytest.mark.parametrize('order', ('sync last', 'sync first', 'sync between'))
|
||||
@pytest.mark.parametrize('aol', (None, 'ordinary', 'screen'))
|
||||
def test_any_startup_order_gives_the_same_word(candidate, order, aol):
|
||||
cp = sync_params(candidate)
|
||||
apply_speed_sync(cp, False)
|
||||
steps = [lambda: apply_modern_aol(cp, aol is not None, aol == 'screen', True), lambda: apply_cooperative(cp, True)]
|
||||
steps.insert({'sync first': 0, 'sync between': 1, 'sync last': 2}[order], lambda: apply_speed_sync(cp, True))
|
||||
for _ in range(2): # prepare, then finalize on the same parameters
|
||||
for step in steps:
|
||||
step()
|
||||
expected = 4097 | 256 | {None: 0, 'ordinary': 2048 | 1024, 'screen': 512 | 1024}[aol]
|
||||
assert cp.safetyConfigs[0].safetyParam == expected and expected in NATIVE_SYNC_WORDS
|
||||
|
||||
|
||||
@pytest.mark.parametrize('coop_first', (False, True))
|
||||
@pytest.mark.parametrize('brake', (False, True))
|
||||
def test_repeated_startup_ordering_preserves_sync(coop_first, brake):
|
||||
cp = sync_params()
|
||||
expected = expected_word(True, True, brake)
|
||||
for _ in range(3):
|
||||
if coop_first:
|
||||
apply_cooperative(cp, True)
|
||||
apply_screen_button(cp, True, brake)
|
||||
else:
|
||||
apply_screen_button(cp, True, brake)
|
||||
apply_cooperative(cp, True)
|
||||
assert cp.safetyConfigs[0].safetyParam == expected
|
||||
assert screen_qualified(cp)
|
||||
apply_cooperative(cp, False)
|
||||
assert cp.safetyConfigs[0].safetyParam == expected & ~256
|
||||
apply_screen_button(cp, False, brake)
|
||||
assert cp.safetyConfigs[0].safetyParam == 4097
|
||||
apply_cooperative(cp, True)
|
||||
assert cp.safetyConfigs[0].safetyParam == 4353
|
||||
|
||||
|
||||
def test_sync_longitudinal_off_rejected():
|
||||
for word in (4096, 4097, 4352):
|
||||
cp = sync_params(long=False)
|
||||
assert not cp.safetyConfigs[0].safetyParam & SYNC_FLAG, 'never requested without longitudinal control'
|
||||
cp.safetyConfigs[0].safetyParam = word
|
||||
assert_rejected(cp)
|
||||
cp = sync_params()
|
||||
cp.openpilotLongitudinalControl = False
|
||||
assert_rejected(cp)
|
||||
|
||||
|
||||
def test_sync_without_vehicle_bus_or_with_unknown_flag_rejected():
|
||||
cp = sync_params()
|
||||
cp.flags &= ~int(TeslaFlags.HAS_VEHICLE_BUS)
|
||||
assert_rejected(cp)
|
||||
cp = sync_params()
|
||||
cp.flags |= 64
|
||||
assert_rejected(cp)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('word', (4097 | 2, 4097 | 4, 4097 | 16, 4097 | 8192, 4097 | 1024, 4353 | 8192, 4097 | 512 | 2048))
|
||||
def test_sync_with_unknown_safety_bit_rejected(word):
|
||||
cp = sync_params()
|
||||
cp.safetyConfigs[0].safetyParam = word
|
||||
assert_rejected(cp)
|
||||
|
||||
|
||||
def test_screen_word_must_match_the_screen_flag():
|
||||
cp = sync_params()
|
||||
cp.safetyConfigs[0].safetyParam = 4097 | 512 # the screen word without the screen flag in CarParams
|
||||
assert_rejected(cp)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODERN)
|
||||
def test_real_controller_and_carstate_cooperate_after_sync_startup(candidate):
|
||||
cp = startup(sync_params(candidate), True)
|
||||
assert cp.safetyConfigs[0].safetyParam == 4353
|
||||
cs = CarState(cp)
|
||||
cs.hands_on_level = 0
|
||||
cs.das_control = {'DAS_controlCounter': 0}
|
||||
cs.out.vEgo = cs.out.vEgoRaw = 20.
|
||||
cs.out.steeringAngleDeg = 0.
|
||||
cs.out.gasPressed = False
|
||||
controller = CarController(DBC[candidate], cp)
|
||||
assert controller.coop_enabled and controller.speed_sync is not None
|
||||
cc = car.CarControl.new_message(latActive=True)
|
||||
for tick in range(10):
|
||||
cs.out.steeringTorque, cs.out.steeringDisengage = 1., False
|
||||
_, sends = controller.update(cc.as_reader(), cs, 1_000_000_000 + tick * 10_000_000)
|
||||
assert not [message for message in sends if message[0] == 0x3C2], 'no scroll request without the comma set speed context'
|
||||
assert controller.steering_limit_info.get('valid', False)
|
||||
cs.out.steeringTorque, cs.out.steeringDisengage = 5.1, True
|
||||
controller.update(cc.as_reader(), cs, 1_100_000_000)
|
||||
assert not controller.steering_limit_info.get('valid', False)
|
||||
assert cp.safetyConfigs[0].safetyParam == 4353
|
||||
@@ -0,0 +1,138 @@
|
||||
"""The Tesla longitudinal command and the dashboard speed limit: the real formatter, CAN parser and car state; no
|
||||
vehicle output. The command is the stock one for every Tesla, pedal or not: nothing in it follows the set-speed work."""
|
||||
import inspect
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from opendbc.can import CANPacker
|
||||
from opendbc.car import gen_empty_fingerprint
|
||||
from opendbc.car.structs import car
|
||||
from opendbc.car.tesla.interface import CarInterface
|
||||
from opendbc.car.tesla.carcontroller import CarController
|
||||
from opendbc.car.tesla.carstate import CarState
|
||||
from opendbc.car.tesla.speed_sync import prepare
|
||||
from opendbc.car.tesla.teslacan import TeslaCAN
|
||||
from opendbc.car.tesla.values import CAR, CANBUS, DBC, CarControllerParams
|
||||
from opendbc.car.dashboard_speed_limit import Status
|
||||
from openpilot.starpilot.speed_limits.runtime import dashboard_observation
|
||||
from openpilot.starpilot.speed_limits.acceptance import ObservationKind
|
||||
|
||||
MODERN = (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y)
|
||||
|
||||
|
||||
class Capture:
|
||||
"""Stands in for the CAN packer: returns the values the formatter chose."""
|
||||
def make_can_msg(self, name, bus, values):
|
||||
return name, bus, dict(values)
|
||||
|
||||
|
||||
def stock_command(acc_state, accel, counter, v_ego):
|
||||
"""The longitudinal command as the stock formatter builds it."""
|
||||
return {'DAS_setSpeed': min(max(v_ego + accel, 0) * 3.6, 400), 'DAS_accState': acc_state, 'DAS_aebEvent': 0,
|
||||
'DAS_jerkMin': -4.9, 'DAS_jerkMax': 4.9, 'DAS_accelMin': accel, 'DAS_accelMax': max(accel, 0),
|
||||
'DAS_controlCounter': counter}
|
||||
|
||||
|
||||
def test_the_formatter_takes_the_stock_arguments_and_keeps_no_state():
|
||||
parameters = list(inspect.signature(TeslaCAN.create_longitudinal_command).parameters.values())
|
||||
assert [(p.name, p.kind, p.default) for p in parameters] == [
|
||||
(name, inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.empty)
|
||||
for name in ('self', 'acc_state', 'accel', 'counter', 'v_ego', 'active')]
|
||||
assert sorted(vars(TeslaCAN(None, Capture()))) == ['CP', 'packer']
|
||||
assert (CarControllerParams.JERK_LIMIT_MIN, CarControllerParams.JERK_LIMIT_MAX) == (-4.9, 4.9)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('acc_state', [4, 13])
|
||||
@pytest.mark.parametrize('accel', [-3.48, -.1, 0., .8, 2.])
|
||||
@pytest.mark.parametrize('v_ego', [0., 1.5, 20., 45., 120.])
|
||||
@pytest.mark.parametrize('active', [False, True])
|
||||
def test_the_command_is_the_stock_one(acc_state, accel, v_ego, active):
|
||||
codec = TeslaCAN(None, Capture())
|
||||
for counter in range(16):
|
||||
name, bus, values = codec.create_longitudinal_command(acc_state, accel, counter % 8, v_ego, active)
|
||||
assert (name, bus) == ('DAS_control', CANBUS.party)
|
||||
assert values == pytest.approx(stock_command(acc_state, accel, counter % 8, v_ego)), 'the same on every call'
|
||||
assert set(values) == set(stock_command(acc_state, accel, 0, v_ego))
|
||||
|
||||
|
||||
def controller(candidate, *, selected, long=True):
|
||||
fingerprint = gen_empty_fingerprint()
|
||||
fingerprint[CANBUS.autopilot_party][0x489] = 8
|
||||
fingerprint[CANBUS.vehicle][0x3DF] = 8
|
||||
cp = prepare(CarInterface.get_params(candidate, fingerprint, [], long, False, False), selected)
|
||||
cs = CarState(cp)
|
||||
cs.hands_on_level = 0
|
||||
cs.das_control = {'DAS_controlCounter': 3}
|
||||
cs.out = car.CarState.new_message(vEgo=20., vEgoRaw=20., canValid=True)
|
||||
unit = CarController(DBC[candidate], cp)
|
||||
unit.tesla_can = TeslaCAN(cp, Capture())
|
||||
return unit, cs
|
||||
|
||||
|
||||
def commands(sends):
|
||||
return [message[2] for message in sends if message[0] == 'DAS_control']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODERN)
|
||||
@pytest.mark.parametrize('selected', [False, True])
|
||||
def test_the_real_controller_sends_the_stock_command_through_a_pedal_press_and_release(candidate, selected):
|
||||
unit, cs = controller(candidate, selected=selected)
|
||||
seen = []
|
||||
for frame in range(400):
|
||||
cs.out.gasPressed = 100 <= frame < 180
|
||||
cc = car.CarControl.new_message(enabled=True, longActive=not cs.out.gasPressed, actuators={'accel': .8})
|
||||
_, sends = unit.update(cc.as_reader(), cs, 1_000_000_000 + frame * 10_000_000)
|
||||
for values in commands(sends):
|
||||
assert values == pytest.approx(stock_command(4, .8, (frame // 4) % 8, 20.)), frame
|
||||
seen.append(frame)
|
||||
assert seen == list(range(0, 400, 4)), 'every fourth frame, pedal or not'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODERN)
|
||||
def test_the_real_controller_cancels_with_the_stock_command_without_longitudinal_control(candidate):
|
||||
unit, cs = controller(candidate, selected=False, long=False)
|
||||
cc = car.CarControl.new_message(enabled=False, cruiseControl={'cancel': True})
|
||||
_, sends = unit.update(cc.as_reader(), cs, 1_000_000_000)
|
||||
assert commands(sends) == [pytest.approx(stock_command(13, 0, 4, 20.))], 'from the first frame, with the full jerk limits'
|
||||
_, sends = unit.update(car.CarControl.new_message().as_reader(), cs, 1_010_000_000)
|
||||
assert commands(sends) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODERN)
|
||||
def test_the_car_state_and_controller_carry_nothing_for_a_pedal_hand_over(candidate):
|
||||
unit, cs = controller(candidate, selected=True)
|
||||
for holder in (unit, cs, unit.tesla_can):
|
||||
assert not [name for name in vars(holder) if 'handover' in name or 'gas_release' in name]
|
||||
with pytest.raises(ImportError):
|
||||
__import__('opendbc.car.tesla.pedal_handover')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', [CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y])
|
||||
@pytest.mark.parametrize('units,limit,expected', [(0, 30, 13.4112), (1, 50, 50 / 3.6), (0, 155, 0), (0, 0, 0)])
|
||||
def test_actual_carstate_publishes_fused_limit(candidate, units, limit, expected):
|
||||
cp = CarInterface.get_non_essential_params(candidate)
|
||||
state = CarState(cp)
|
||||
parsers = state.get_can_parsers(cp)
|
||||
state.update(parsers) # Register the production parser subscriptions.
|
||||
packers = {bus: CANPacker(parser.dbc.name) for bus, parser in parsers.items()}
|
||||
stamp = 0
|
||||
for i in range(30):
|
||||
stamp = 1_000_000_000 + i * 100_000_000
|
||||
for bus, parser in parsers.items():
|
||||
messages = []
|
||||
for address in sorted(parser.addresses):
|
||||
msg = parser.dbc.addr_to_msg[address].name
|
||||
values = {'DI_speedUnits': units} if msg == 'DI_state' else {'DAS_fusedSpeedLimit': limit} if msg == 'DAS_status' else {}
|
||||
messages.append(packers[bus].make_can_msg(msg, parser.bus, values))
|
||||
parser.update([stamp, messages])
|
||||
state.update(parsers)
|
||||
obs = state.dashboard_limit.observation
|
||||
assert obs.status == (Status.VALID if expected else Status.ABSENT if limit == 155 else Status.UNKNOWN)
|
||||
assert obs.speed_mps == pytest.approx(expected)
|
||||
evidence = SimpleNamespace(status=obs.status.value, speedMps=obs.speed_mps, observedMonoTime=obs.observed_ns,
|
||||
validUntilMonoTime=obs.valid_until_ns, episode=obs.episode, producerSessionId='real-parser')
|
||||
result = dashboard_observation(evidence, car_fingerprint=str(candidate), session_id='drive', now_ns=stamp)
|
||||
assert result.kind == (ObservationKind.VALID if expected else ObservationKind.ABSENT if limit == 155 else ObservationKind.UNKNOWN)
|
||||
if expected:
|
||||
stale = dashboard_observation(evidence, car_fingerprint=str(candidate), session_id='drive', now_ns=obs.valid_until_ns + 1)
|
||||
assert stale.kind is ObservationKind.STALE
|
||||
@@ -0,0 +1,331 @@
|
||||
"""Speed sync requests around the accelerator pedal, lost feedback and unanswered requests. Pure protocol: no device."""
|
||||
import pytest
|
||||
from opendbc.car.tesla.speed_sync import (ENGAGE_DELAY_NS, FAST_TICKS, FRESH_NS, HANDOVER_NS, MANUAL_COMPLETION_NS, MAX_RETRIES,
|
||||
TEMPLATE_SEND_NS, SpeedSynchronizer, neutral_wheel, plan_step, scroll_request)
|
||||
|
||||
NEUTRAL = bytes.fromhex('2955000000000040')
|
||||
|
||||
|
||||
def clicks(msg):
|
||||
"""The signed scroll count of a request."""
|
||||
ticks = msg[1][3] & 63
|
||||
return ticks - 64 if ticks >= 32 else ticks
|
||||
|
||||
|
||||
class Rig:
|
||||
def __init__(self, *, engaged=True):
|
||||
self.sync = SpeedSynchronizer()
|
||||
self.now = 1_000_000_000
|
||||
self.counter = 0
|
||||
self.speed, self.target, self.units = 45, 50, 1
|
||||
self.sent = []
|
||||
self.echo = True # the panda transmits each request and echoes it on bus 129
|
||||
self._echo = None
|
||||
if engaged:
|
||||
# Engaged without longitudinal authority for longer than the panda needs to hear about engagement.
|
||||
for _ in range(ENGAGE_DELAY_NS // 10_000_000 + 1):
|
||||
assert self.tick(long=False) is None
|
||||
|
||||
def tick(self, dt=10_000_000, *, long=True, gas=False, safe=True, enabled=True,
|
||||
feedback=True, wheel=NEUTRAL, wheel_bus=1):
|
||||
self.now += dt
|
||||
frames = []
|
||||
if self._echo is not None:
|
||||
frames.append((0x3c2, self._echo, 129))
|
||||
self._echo = None
|
||||
if feedback:
|
||||
self.counter = (self.counter + 1) % 16
|
||||
bits = (self.counter << 8) | (2 << 12) | (round(self.speed * 2) << 15) | (self.units << 24)
|
||||
di = bytearray(bits.to_bytes(8, 'little'))
|
||||
di[0] = (0x88 + sum(di[1:])) & 255
|
||||
frames.append((0x286, bytes(di), 0))
|
||||
if wheel is not None:
|
||||
frames.append((0x3c2, wheel, wheel_bus))
|
||||
self.sync.observe([(self.now, frames)])
|
||||
msg = self.sync.update(self.now, target_kph=self.target, enabled=enabled,
|
||||
safe=safe, longitudinal_active=long, gas_pressed=gas)
|
||||
if msg:
|
||||
self.sent.append((self.now, msg))
|
||||
if self.echo:
|
||||
self._echo = msg[1]
|
||||
return msg
|
||||
|
||||
|
||||
@pytest.mark.parametrize('before', [False, True])
|
||||
def test_pending_response_on_either_side_of_release(before):
|
||||
# A request sent under the pedal is answered before or after the release; nothing new is sent in the hand-over
|
||||
# window, and requests carry on once longitudinal control is back.
|
||||
r = Rig()
|
||||
assert r.tick(long=False, gas=True)
|
||||
if before:
|
||||
r.speed += 1
|
||||
assert r.tick(long=False) is None
|
||||
assert r.sync.blocked is None
|
||||
r.speed = 46
|
||||
for _ in range(15):
|
||||
msg = r.tick()
|
||||
if msg:
|
||||
break
|
||||
assert r.sync.blocked is None
|
||||
assert msg is not None and len(r.sent) == 2
|
||||
|
||||
|
||||
def test_no_initial_authority_and_held_pedal_engage():
|
||||
r = Rig()
|
||||
for _ in range(20):
|
||||
assert r.tick(long=False) is None
|
||||
assert not r.sent and r.sync.handover_until == 0
|
||||
assert r.tick(long=False, gas=True) is not None
|
||||
|
||||
|
||||
def test_no_new_command_during_handover_even_after_response():
|
||||
r = Rig()
|
||||
assert r.tick(long=False, gas=True)
|
||||
r.speed += 1
|
||||
for _ in range(8):
|
||||
assert r.tick(long=False) is None
|
||||
assert r.sync.pending is None and len(r.sent) == 1
|
||||
assert r.sync.status == 'waiting_for_handover'
|
||||
|
||||
|
||||
def test_grace_expires_once_not_renewed_by_false_samples():
|
||||
r = Rig()
|
||||
r.target = r.speed
|
||||
r.tick(long=False, gas=True)
|
||||
r.target = 50
|
||||
r.tick(long=False)
|
||||
deadline = r.sync.handover_until
|
||||
assert deadline == r.now + HANDOVER_NS
|
||||
for _ in range(9):
|
||||
assert r.tick(long=False) is None
|
||||
assert r.sync.handover_until == deadline and r.sync.status == 'waiting_for_handover'
|
||||
assert r.tick(long=False) is None
|
||||
assert r.now == deadline and r.sync.handover_until == 0 and r.sync.status == 'inhibited'
|
||||
for _ in range(20):
|
||||
assert r.tick(long=False) is None, 'no authority, no request'
|
||||
assert r.sync.blocked is None and not r.sent
|
||||
|
||||
|
||||
def test_release_with_a_request_open_sends_nothing_until_authority_returns():
|
||||
r = Rig()
|
||||
assert r.tick(long=False, gas=True)
|
||||
for _ in range(20):
|
||||
assert r.tick(long=False) is None
|
||||
r.speed += 1 # the Tesla answers after the release
|
||||
for _ in range(20):
|
||||
assert r.tick(long=False) is None
|
||||
assert r.sync.status == 'inhibited' and len(r.sent) == 1
|
||||
assert any(r.tick() for _ in range(5)), 'carries on with longitudinal control'
|
||||
|
||||
|
||||
def test_hard_failure_and_disengagement_clear_edge_history():
|
||||
r = Rig()
|
||||
r.target = r.speed
|
||||
r.tick(gas=True)
|
||||
r.tick(safe=False)
|
||||
r.target = 50
|
||||
assert r.tick(long=False) is None and r.sync.handover_until == 0
|
||||
r.tick(gas=True, enabled=False)
|
||||
assert r.tick(long=False) is None and r.sync.handover_until == 0
|
||||
|
||||
|
||||
def test_feedback_loss_pauses_until_fresh_feedback():
|
||||
r = Rig()
|
||||
r.target = r.speed
|
||||
for _ in range(30):
|
||||
assert r.tick(feedback=False) is None
|
||||
r.target = 50
|
||||
assert r.tick(feedback=False) is None
|
||||
assert r.sync.status == 'waiting_for_native_speed' and r.sync.blocked is None
|
||||
assert r.tick() is not None, 'carries on once the Tesla speed is fresh again'
|
||||
|
||||
|
||||
def test_units_change_inflight_is_not_handover():
|
||||
r = Rig()
|
||||
r.tick(gas=True)
|
||||
r.units = 0
|
||||
assert r.tick(long=False) is None
|
||||
assert r.sync.blocked == 'units_changed_during_request'
|
||||
|
||||
|
||||
def test_manual_input_during_a_request_wins():
|
||||
# The driver's own scroll is recorded and given time to land; the open request is not repeated.
|
||||
r = Rig()
|
||||
assert r.tick(gas=True)
|
||||
assert r.tick(long=False, wheel=scroll_request(NEUTRAL, -1)[1]) is None
|
||||
assert r.sync.blocked is None
|
||||
assert any(h['event'] == 'input_during_request' for h in r.sync.history)
|
||||
r.speed -= 1
|
||||
for _ in range(10):
|
||||
assert r.tick() is None
|
||||
assert r.sync.status == 'waiting_for_manual_processing', "waits for the comma to act on the driver's scroll"
|
||||
assert len(r.sent) == 1
|
||||
for _ in range(MANUAL_COMPLETION_NS // 10_000_000):
|
||||
r.tick()
|
||||
assert 'manual_action_unconfirmed' in r.sync.noticed and r.sync.blocked is None
|
||||
assert len(r.sent) > 1, "after the wait the Tesla is scrolled back to the comma's speed"
|
||||
|
||||
|
||||
def test_no_response_is_retried_a_few_times_then_waits_for_the_tesla():
|
||||
r = Rig()
|
||||
r.tick()
|
||||
for _ in range(100):
|
||||
r.tick(dt=100_000_000)
|
||||
assert r.sync.blocked is None and 'no_native_response' in r.sync.noticed
|
||||
assert r.sync.status == 'waiting_for_native_change'
|
||||
sent = len(r.sent)
|
||||
assert sent == MAX_RETRIES + 1, 'the first request and its retries'
|
||||
for _ in range(20):
|
||||
assert r.tick() is None
|
||||
r.speed += 1 # the Tesla moves: requests carry on
|
||||
assert any(r.tick() for _ in range(20))
|
||||
|
||||
|
||||
def test_an_unanswered_request_does_not_hold_back_the_other_direction():
|
||||
# The Tesla ignores scrolls one way (it is at its own lowest or highest set speed). A comma speed still on that side
|
||||
# keeps waiting; once it is on the other side of the Tesla's, sync carries on without the Tesla changing first.
|
||||
r = Rig()
|
||||
r.tick()
|
||||
for _ in range(100):
|
||||
r.tick(dt=100_000_000)
|
||||
assert r.sync.status == 'waiting_for_native_change'
|
||||
sent = len(r.sent)
|
||||
r.target = 55 # further the same way (the Tesla shows 45)
|
||||
for _ in range(20):
|
||||
assert r.tick() is None
|
||||
assert r.sync.status == 'waiting_for_native_change'
|
||||
r.target = 40 # now below the Tesla's
|
||||
assert any(r.tick() for _ in range(20))
|
||||
assert len(r.sent) == sent + 1 and clicks(r.sent[-1][1]) == -1
|
||||
r.speed -= 1 # the Tesla follows: nothing is left of the old wait
|
||||
assert any(r.tick() for _ in range(20)) and r.sync.unanswered is None
|
||||
|
||||
|
||||
def test_request_needs_a_new_physical_neutral_frame():
|
||||
r = Rig()
|
||||
r.tick()
|
||||
r.speed += 1
|
||||
assert r.tick(wheel=None) is None, 'no neutral frame newer than the one the last request copied'
|
||||
assert r.tick(wheel=NEUTRAL, wheel_bus=129) is None, "a bus-129 echo is not the driver's wheel"
|
||||
assert r.sync.status == 'waiting_for_neutral_wheel'
|
||||
assert r.tick() is not None
|
||||
|
||||
|
||||
def test_request_not_echoed_by_the_panda_is_not_transmitted():
|
||||
r = Rig()
|
||||
r.echo = False
|
||||
assert r.tick()
|
||||
for _ in range(9):
|
||||
assert r.tick() is None
|
||||
r.tick()
|
||||
assert any(h['event'] == 'not_transmitted' and h['reason'] == 'no_bus_return' for h in r.sync.history)
|
||||
assert r.sync.pending is None and r.sync.blocked is None
|
||||
|
||||
|
||||
def test_template_age_is_tighter_than_receive_freshness():
|
||||
r = Rig()
|
||||
r.target = r.speed
|
||||
r.tick()
|
||||
r.target = 50
|
||||
assert r.tick(dt=TEMPLATE_SEND_NS + 1, wheel=None) is None
|
||||
assert r.sync.status == 'waiting_for_neutral_wheel'
|
||||
assert r.tick() is not None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('direction', [-1, 1])
|
||||
def test_convergence_one_request_per_tesla_change(direction):
|
||||
r = Rig()
|
||||
r.target = r.speed + 10 * direction
|
||||
waiting = None
|
||||
for _ in range(400):
|
||||
msg = r.tick()
|
||||
if msg:
|
||||
assert waiting is None, 'never two requests open at once'
|
||||
waiting = r.speed
|
||||
elif waiting is not None and r.sync.pending is not None and r.now - r.sync.pending.sent_ns >= 30_000_000:
|
||||
r.speed += direction # the Tesla answers about 30 ms later
|
||||
waiting = None
|
||||
if r.sync.status == 'matched':
|
||||
break
|
||||
assert r.speed == r.target and len(r.sent) == 10
|
||||
assert len(r.sync.history) <= 32
|
||||
|
||||
|
||||
def test_same_rounded_target_never_sends():
|
||||
r = Rig()
|
||||
r.speed = 45.5
|
||||
r.target = 46
|
||||
for _ in range(10):
|
||||
assert r.tick() is None
|
||||
assert r.sync.status == 'matched'
|
||||
|
||||
|
||||
def test_controller_clock_gap_pauses_one_frame():
|
||||
r = Rig()
|
||||
r.tick(gas=True)
|
||||
r.speed += 1
|
||||
assert r.tick(dt=FRESH_NS + 1, long=False) is None
|
||||
assert r.sync.status == 'controller_clock_gap' and r.sync.blocked is None and r.sync.handover_until == 0
|
||||
|
||||
|
||||
def test_disengaging_clears_the_engagement():
|
||||
r = Rig()
|
||||
assert r.tick()
|
||||
assert r.tick(enabled=False) is None
|
||||
assert r.sync.status == 'inactive' and r.sync.pending is None and r.sync.target is None and not r.sync.active
|
||||
assert not r.sync.history and not r.sync.noticed
|
||||
|
||||
|
||||
@pytest.mark.parametrize('native,target,fast,expected', [
|
||||
(50, 51, True, (1, 51)), (50, 49, True, (-1, 49)),
|
||||
(50, 55, True, (FAST_TICKS, 55)), (50, 45, True, (-FAST_TICKS, 45)),
|
||||
(52, 60, True, (FAST_TICKS, 55)), (52, 44, True, (-FAST_TICKS, 50)),
|
||||
(52, 54, True, (1, 53)), (53, 51, True, (-1, 52)), # the next multiple of five would pass the target
|
||||
(54, 60, True, (1, 55)), (56, 50, True, (-1, 55)), # one away from the multiple: a click is as quick
|
||||
(50, 60, False, (1, 51)), (50, 40, False, (-1, 49)), # fast steps paused, or km/h
|
||||
])
|
||||
def test_next_step_toward_the_target(native, target, fast, expected):
|
||||
assert plan_step(native, target, fast) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize('ticks', [-FAST_TICKS, -1, 1, FAST_TICKS])
|
||||
def test_a_request_is_the_neutral_frame_with_only_the_scroll_count_set(ticks):
|
||||
address, data, bus = scroll_request(NEUTRAL, ticks)
|
||||
assert (address, bus) == (0x3C2, 1) and len(data) == 8
|
||||
assert data[3] == (NEUTRAL[3] & 0xC0) | (ticks & 0x3F)
|
||||
assert data[:3] == NEUTRAL[:3] and data[4:] == NEUTRAL[4:]
|
||||
assert not neutral_wheel(data), 'a scroll is not a template for the next request'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('ticks', [0, 2, 3, 4, 6, -2, -6, 31, -32])
|
||||
def test_only_one_click_or_one_fast_flick_is_ever_requested(ticks):
|
||||
assert scroll_request(NEUTRAL, ticks) is None
|
||||
|
||||
|
||||
def test_no_request_is_built_from_a_frame_that_is_not_neutral():
|
||||
assert neutral_wheel(NEUTRAL)
|
||||
pressed = bytearray(NEUTRAL)
|
||||
pressed[1] = (pressed[1] & ~0x03) | 0x02 # right wheel tilted left
|
||||
for frame in (bytes(pressed), scroll_request(NEUTRAL, 1)[1], NEUTRAL[:7], bytes(8)):
|
||||
assert not neutral_wheel(frame)
|
||||
assert scroll_request(frame, 1) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('direction', [-1, 1])
|
||||
def test_mph_convergence_uses_fast_steps_and_lands_on_the_target(direction):
|
||||
r = Rig(engaged=False)
|
||||
r.units, r.speed = 0, 52
|
||||
r.target = (52 + 14 * direction) * 1.609344
|
||||
for _ in range(ENGAGE_DELAY_NS // 10_000_000 + 1):
|
||||
assert r.tick(long=False) is None
|
||||
for _ in range(2000):
|
||||
r.tick()
|
||||
p = r.sync.pending
|
||||
if p is not None and p.returned and r.now - p.sent_ns >= 30_000_000:
|
||||
r.speed = p.expected # the Tesla answers about 30 ms later
|
||||
if r.sync.status == 'matched':
|
||||
break
|
||||
assert r.speed == 52 + 14 * direction and r.sync.blocked is None
|
||||
sizes = [abs(clicks(msg)) for _, msg in r.sent]
|
||||
assert FAST_TICKS in sizes and 1 in sizes
|
||||
assert len(r.sent) <= 5, 'far fewer requests than fourteen single clicks'
|
||||
@@ -0,0 +1,341 @@
|
||||
"""The driver's own scroll and speed sync. Wheel input that cannot be read as one clean scroll pauses sync; it never
|
||||
stops it until disengaging.
|
||||
|
||||
A right-wheel nudge that springs back with one scroll click is taken by the Tesla and not by the comma, so sync
|
||||
scrolls the Tesla back. A clean scroll waits for the comma: card's receipt for the step it applied releases it at
|
||||
once, and without one it is dropped after its window and corrected the same way.
|
||||
"""
|
||||
from dataclasses import replace
|
||||
|
||||
import pytest
|
||||
|
||||
from opendbc.car.tesla.speed_sync import MANUAL_COMPLETION_NS, MANUAL_SETTLE_NS, ManualReceipt, SpeedSynchronizer, SyncAuthority
|
||||
|
||||
MPH = 1.609344
|
||||
DOCUMENT, VEHICLE, SESSION, DRIVE = 'd' * 64, 'e' * 64, '0123456789abcdef' * 2, 100_000_000
|
||||
|
||||
NEUTRAL = bytes.fromhex('2955000000000040')
|
||||
TICK = 50_000_000
|
||||
|
||||
|
||||
def wheel(right_left=1, right_scroll=0):
|
||||
bits = int.from_bytes(NEUTRAL, 'little')
|
||||
bits = (bits & ~(3 << 8)) | (right_left << 8)
|
||||
bits = (bits & ~(63 << 24)) | ((right_scroll & 63) << 24)
|
||||
return bits.to_bytes(8, 'little')
|
||||
|
||||
|
||||
class Rig:
|
||||
"""The Tesla in mph at 77, the comma's set speed 77; nothing answers requests unless a test moves `speed`."""
|
||||
def __init__(self):
|
||||
self.sync = SpeedSynchronizer()
|
||||
self.now = 1_000_000_000
|
||||
self.counter = 0
|
||||
self.speed = self.target = 77
|
||||
self.sent = []
|
||||
|
||||
def tick(self, data=NEUTRAL):
|
||||
self.now += TICK
|
||||
self.counter = (self.counter + 1) % 16
|
||||
bits = (self.counter << 8) | (2 << 12) | (round(self.speed * 2) << 15)
|
||||
di = bytearray(bits.to_bytes(8, 'little'))
|
||||
di[0] = (0x88 + sum(di[1:])) & 255
|
||||
self.sync.observe([(self.now, [(0x286, bytes(di), 0), (0x3c2, data, 1)])])
|
||||
msg = self.sync.update(self.now, target_kph=self.target * 1.609344, enabled=True, safe=True, longitudinal_active=True)
|
||||
if msg:
|
||||
self.sent.append((self.now, msg))
|
||||
return msg
|
||||
|
||||
def settle(self, seconds):
|
||||
return [m for m in (self.tick() for _ in range(round(seconds * 1e9 / TICK))) if m]
|
||||
|
||||
|
||||
def clicks(msg):
|
||||
ticks = msg[1][3] & 63
|
||||
return ticks - 64 if ticks >= 32 else ticks
|
||||
|
||||
|
||||
def test_nudge_release_click_is_corrected_not_a_stop():
|
||||
r = Rig()
|
||||
assert not r.settle(1)
|
||||
r.tick(wheel(right_left=2))
|
||||
r.tick(wheel(right_left=2))
|
||||
r.tick(wheel(right_scroll=1)) # springs back with one click
|
||||
r.speed = 78 # the Tesla took it; the comma stays at 77
|
||||
sent = r.settle(1.5)
|
||||
assert r.sync.blocked is None
|
||||
assert 'ambiguous_manual_input' not in r.sync.noticed
|
||||
assert sent and clicks(sent[0]) == -1, 'sync puts the Tesla back on the comma speed'
|
||||
assert any(h['event'] == 'nudge_release_click' for h in r.sync.history)
|
||||
|
||||
|
||||
def test_unclear_scroll_pauses_and_sync_carries_on():
|
||||
r = Rig()
|
||||
r.settle(1)
|
||||
r.tick(wheel(right_left=2))
|
||||
r.tick(wheel(right_left=2, right_scroll=1)) # a scroll while the wheel is still tilted
|
||||
assert r.sync.blocked is None and 'ambiguous_manual_input' in r.sync.noticed
|
||||
r.tick()
|
||||
r.speed = 78
|
||||
sent = r.settle(1.5)
|
||||
assert r.sync.blocked is None and sent and clicks(sent[0]) == -1
|
||||
|
||||
|
||||
def test_a_driver_scroll_waits_its_window_and_is_then_dropped_with_a_notice():
|
||||
r = Rig()
|
||||
r.settle(1)
|
||||
r.tick(wheel(right_scroll=1)) # a clean scroll; the comma's own speed does not follow it here
|
||||
r.tick()
|
||||
r.speed = 78
|
||||
assert not r.settle(MANUAL_COMPLETION_NS / 1e9 - 0.2), "nothing is sent while the comma may still act on the driver's scroll"
|
||||
assert r.sync.status == 'waiting_for_manual_processing'
|
||||
sent = r.settle(1)
|
||||
assert r.sync.blocked is None and 'manual_action_unconfirmed' in r.sync.noticed
|
||||
assert any(h['event'] == 'manual_action_unconfirmed' and h['dropped'] == 1 for h in r.sync.history)
|
||||
assert not r.sync.manual_queue
|
||||
assert sent and clicks(sent[0]) == -1, "then the Tesla is put back on the comma's speed"
|
||||
|
||||
|
||||
def test_a_driver_scroll_the_comma_followed_needs_no_correction():
|
||||
r = Rig()
|
||||
r.settle(1)
|
||||
r.tick(wheel(right_scroll=1))
|
||||
r.tick()
|
||||
r.speed = r.target = 78 # the Tesla and the comma both took the scroll
|
||||
assert not r.settle(MANUAL_COMPLETION_NS / 1e9 + 1)
|
||||
assert r.sync.status == 'matched' and r.sync.blocked is None
|
||||
assert 'manual_action_unconfirmed' in r.sync.noticed, 'the wait always ends with the same notice'
|
||||
|
||||
|
||||
def test_a_fast_driver_scroll_is_one_gesture_and_one_notice_per_engagement():
|
||||
r = Rig()
|
||||
r.settle(1)
|
||||
for _ in range(2):
|
||||
r.tick(wheel(right_scroll=3))
|
||||
r.tick(wheel(right_scroll=2)) # the same flick, still turning
|
||||
r.tick()
|
||||
assert len(r.sync.manual_queue) == 1 and r.sync.manual_queue[0][2:] == ('right_wheel_up', True)
|
||||
r.settle(MANUAL_COMPLETION_NS / 1e9 + 0.2)
|
||||
assert not r.sync.manual_queue
|
||||
assert len([h for h in r.sync.history if h['event'] == 'manual_action_unconfirmed']) == 2
|
||||
assert [n['kind'] for n in r.sync.notices].count('manual_action_unconfirmed') == 1
|
||||
|
||||
|
||||
def test_nothing_is_sent_right_after_a_driver_scroll_that_was_never_queued():
|
||||
r = Rig()
|
||||
r.settle(1)
|
||||
r.tick(wheel(right_left=2, right_scroll=1)) # unclear input: paused, not queued
|
||||
r.tick()
|
||||
r.speed = 78
|
||||
assert not r.settle(MANUAL_SETTLE_NS / 1e9 - 0.15), "the Tesla gets time to apply the driver's own scroll first"
|
||||
assert r.sync.status == 'waiting_for_driver_scroll'
|
||||
assert r.settle(0.5)
|
||||
|
||||
|
||||
def test_clock_faults_still_stop():
|
||||
r = Rig()
|
||||
r.settle(0.5)
|
||||
r.sync.observe([(r.now - TICK, [(0x3c2, NEUTRAL, 1)])])
|
||||
assert r.sync.blocked == 'wheel_clock_reversal'
|
||||
|
||||
|
||||
# Card's receipts for the driver's own scrolls.
|
||||
|
||||
def scrolled(r, ticks=1):
|
||||
"""The driver scrolls once; returns the engine's record of it: (stamp, frame index, name, fast)."""
|
||||
r.settle(1)
|
||||
r.tick(wheel(right_scroll=ticks))
|
||||
r.tick()
|
||||
entry, = r.sync.manual_queue
|
||||
return entry
|
||||
|
||||
|
||||
def receipt_for(entry, **changes):
|
||||
"""What card records when it applies the comma step for that scroll, in the frame the scroll was seen."""
|
||||
stamp, index, name, fast = entry
|
||||
values = dict(boot_ns=stamp, frame_index=index, name=name, fast=fast, worker_session=SESSION, sequence=1,
|
||||
document_hash=DOCUMENT, vehicle_hash=VEHICLE, drive_start_ns=DRIVE, processed_boot_ns=stamp,
|
||||
target_kph=78 * MPH)
|
||||
values.update(changes)
|
||||
return ManualReceipt(**values)
|
||||
|
||||
|
||||
def authority(r, *receipts, **changes):
|
||||
values = dict(observed_boot_ns=r.now, target_kph=r.target * MPH, is_metric=False, configuration_id='a' * 64, software_owned=True,
|
||||
document_hash=DOCUMENT, vehicle_hash=VEHICLE, drive_start_ns=DRIVE, manual_receipts=tuple(receipts))
|
||||
values.update(changes)
|
||||
return SyncAuthority(**values)
|
||||
|
||||
|
||||
def test_a_receipt_releases_the_drivers_scroll_at_once():
|
||||
r = Rig()
|
||||
entry = scrolled(r)
|
||||
assert entry[1:] == (1, 'right_wheel_up', False) and r.sync.status == 'waiting_for_manual_processing'
|
||||
receipt = receipt_for(entry)
|
||||
r.speed = r.target = 78 # the Tesla and the comma both took it
|
||||
r.sync.target = ('stale',)
|
||||
r.sync.accept_manual_receipts(authority(r, receipt), r.now)
|
||||
assert not r.sync.manual_queue and r.sync.target is None, 'the comma target is read again'
|
||||
assert r.sync.take_manual_receipt_acks() == (receipt,) and r.sync.take_manual_receipt_acks() == ()
|
||||
r.tick()
|
||||
assert r.sync.status == 'matched' and r.sync.blocked is None
|
||||
assert not r.settle(MANUAL_COMPLETION_NS / 1e9 + .5)
|
||||
assert 'manual_action_unconfirmed' not in r.sync.noticed
|
||||
|
||||
|
||||
def test_with_a_receipt_a_difference_is_corrected_without_waiting_out_the_window():
|
||||
r = Rig()
|
||||
receipt = receipt_for(scrolled(r))
|
||||
r.speed, r.target = 79, 78 # the Tesla moved further than the comma did
|
||||
r.sync.accept_manual_receipts(authority(r, receipt), r.now)
|
||||
sent = r.settle(MANUAL_SETTLE_NS / 1e9 + .2)
|
||||
assert sent and clicks(sent[0]) == -1, "corrected as soon as the Tesla has applied the driver's own scroll"
|
||||
assert r.sent[0][0] - receipt.boot_ns < MANUAL_COMPLETION_NS // 2
|
||||
waiting = Rig()
|
||||
scrolled(waiting)
|
||||
waiting.speed, waiting.target = 79, 78
|
||||
assert not waiting.settle(MANUAL_SETTLE_NS / 1e9 + .2), 'without a receipt the scroll still waits'
|
||||
|
||||
|
||||
def test_a_receipt_may_arrive_before_the_scroll_is_seen_on_the_bus():
|
||||
r = Rig()
|
||||
r.settle(1)
|
||||
r.tick(wheel(right_scroll=3))
|
||||
early = receipt_for((r.now + TICK, 1, 'right_wheel_up', True), processed_boot_ns=r.now + TICK)
|
||||
r.now += TICK # card applied the step in the frame the release arrives in; speed sync sees that frame next
|
||||
r.sync.accept_manual_receipts(authority(r, early), r.now)
|
||||
assert r.sync.manual_receipts == {(early.boot_ns, 1): early} and r.sync.take_manual_receipt_acks() == (early,)
|
||||
r.now -= TICK
|
||||
r.tick()
|
||||
assert r.sync.manual_queue == [(early.boot_ns, 1, 'right_wheel_up', True)]
|
||||
r.sync.accept_manual_receipts(authority(r), r.now)
|
||||
assert not r.sync.manual_queue and not r.sync.manual_receipts and r.sync.blocked is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('changes', [dict(name='right_wheel_down'), dict(fast=True)])
|
||||
def test_a_receipt_for_a_different_scroll_at_the_same_frame_stops_sync(changes):
|
||||
r = Rig()
|
||||
receipt = receipt_for(scrolled(r), **changes)
|
||||
r.sync.accept_manual_receipts(authority(r, receipt), r.now)
|
||||
assert r.sync.blocked == 'manual_receipt_mismatch'
|
||||
assert not r.settle(3), 'stopped until disengaging'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('changes', [
|
||||
dict(document_hash='f' * 64), dict(vehicle_hash='f' * 64), dict(drive_start_ns=DRIVE + 1), dict(drive_start_ns=0),
|
||||
dict(worker_session='x' * 32), dict(worker_session='0' * 31), dict(sequence=0), dict(sequence=1.0),
|
||||
dict(name='right_wheel_left'), dict(name='left_wheel_up'), dict(fast=1),
|
||||
dict(frame_index=-1), dict(frame_index=4096), dict(frame_index=1.0),
|
||||
dict(target_kph=0), dict(target_kph=255), dict(target_kph=float('nan')), dict(target_kph='125'),
|
||||
dict(processed_boot_ns=0), dict(boot_ns=0), dict(boot_ns=1.5),
|
||||
])
|
||||
def test_a_receipt_that_fails_any_check_is_ignored_and_the_scroll_waits_out_its_window(changes):
|
||||
r = Rig()
|
||||
entry = scrolled(r)
|
||||
receipt = receipt_for(entry, **changes)
|
||||
r.sync.accept_manual_receipts(authority(r, receipt), r.now)
|
||||
assert r.sync.manual_queue == [entry] and r.sync.blocked is None
|
||||
assert r.sync.take_manual_receipt_acks() == (), 'never taken into custody'
|
||||
r.settle(MANUAL_COMPLETION_NS / 1e9 + .2)
|
||||
assert 'manual_action_unconfirmed' in r.sync.noticed and not r.sync.manual_queue
|
||||
|
||||
|
||||
def test_a_receipt_processed_in_the_future_or_before_its_scroll_is_ignored():
|
||||
r = Rig()
|
||||
entry = scrolled(r)
|
||||
for changes in (dict(processed_boot_ns=r.now + 1), dict(processed_boot_ns=entry[0] - 1)):
|
||||
r.sync.accept_manual_receipts(authority(r, receipt_for(entry, **changes)), r.now)
|
||||
assert r.sync.manual_queue == [entry] and r.sync.take_manual_receipt_acks() == ()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('changes', [dict(document_hash=''), dict(vehicle_hash=''), dict(document_hash='d' * 63)])
|
||||
def test_receipts_need_an_admission_that_names_the_assignments_and_the_car(changes):
|
||||
r = Rig()
|
||||
entry = scrolled(r)
|
||||
receipt = receipt_for(entry, **changes)
|
||||
r.sync.accept_manual_receipts(authority(r, receipt, **changes), r.now)
|
||||
assert r.sync.manual_queue == [entry] and r.sync.take_manual_receipt_acks() == ()
|
||||
|
||||
|
||||
def test_an_expired_receipt_is_disposed_of_and_completes_nothing():
|
||||
r = Rig()
|
||||
entry = scrolled(r)
|
||||
receipt = receipt_for(entry)
|
||||
r.now = entry[0] + MANUAL_COMPLETION_NS + 1
|
||||
r.sync.accept_manual_receipts(authority(r, receipt), r.now)
|
||||
assert r.sync.manual_queue == [entry] and not r.sync.manual_receipts
|
||||
assert r.sync.take_manual_receipt_acks() == (receipt,), 'handed back so card drops it'
|
||||
r.now = entry[0] + MANUAL_COMPLETION_NS
|
||||
r.sync.accept_manual_receipts(authority(r, receipt), r.now)
|
||||
assert not r.sync.manual_queue, 'exactly at the end of the window still counts'
|
||||
|
||||
|
||||
def test_a_receipt_for_a_scroll_already_dealt_with_is_handed_back():
|
||||
r = Rig()
|
||||
entry = scrolled(r)
|
||||
receipt = receipt_for(entry)
|
||||
r.sync.accept_manual_receipts(authority(r, receipt), r.now)
|
||||
r.sync.take_manual_receipt_acks()
|
||||
r.sync.accept_manual_receipts(authority(r, receipt), r.now) # card had not yet seen the acknowledgment
|
||||
assert r.sync.take_manual_receipt_acks() == (receipt,) and not r.sync.manual_receipts and r.sync.blocked is None
|
||||
|
||||
|
||||
def test_a_cached_receipt_expires_with_its_window():
|
||||
r = Rig()
|
||||
r.settle(1)
|
||||
early = receipt_for((r.now, 1, 'right_wheel_up', False), processed_boot_ns=r.now)
|
||||
r.sync.accept_manual_receipts(authority(r, early), r.now)
|
||||
assert r.sync.manual_receipts
|
||||
r.settle(MANUAL_COMPLETION_NS / 1e9 + .1)
|
||||
r.sync.accept_manual_receipts(authority(r), r.now)
|
||||
assert not r.sync.manual_receipts and r.sync.blocked is None
|
||||
|
||||
|
||||
def test_more_receipts_than_card_ever_holds_stop_sync():
|
||||
r = Rig()
|
||||
entry = scrolled(r)
|
||||
many = tuple(receipt_for(entry, sequence=index + 1) for index in range(17))
|
||||
r.sync.accept_manual_receipts(authority(r, *many), r.now)
|
||||
assert r.sync.blocked == 'invalid_manual_receipts'
|
||||
r = Rig()
|
||||
scrolled(r)
|
||||
r.sync.accept_manual_receipts(replace(authority(r), manual_receipts=[]), r.now)
|
||||
assert r.sync.blocked == 'invalid_manual_receipts', 'only a tuple, as card builds it'
|
||||
|
||||
|
||||
def test_sixteen_receipts_are_accepted():
|
||||
r = Rig()
|
||||
r.settle(1)
|
||||
receipts = tuple(receipt_for((r.now - index, index, 'right_wheel_up', False), processed_boot_ns=r.now, sequence=index + 1)
|
||||
for index in range(16))
|
||||
r.sync.accept_manual_receipts(authority(r, *receipts), r.now)
|
||||
assert r.sync.blocked is None and len(r.sync.manual_receipts) == 16
|
||||
assert r.sync.take_manual_receipt_acks() == receipts
|
||||
|
||||
|
||||
def test_two_different_receipts_for_one_scroll_stop_sync():
|
||||
r = Rig()
|
||||
r.settle(1)
|
||||
first = receipt_for((r.now, 1, 'right_wheel_up', False), processed_boot_ns=r.now)
|
||||
r.sync.accept_manual_receipts(authority(r, first), r.now)
|
||||
r.sync.accept_manual_receipts(authority(r, replace(first, sequence=2)), r.now)
|
||||
assert r.sync.blocked == 'conflicting_manual_receipt'
|
||||
|
||||
|
||||
def test_anything_that_is_not_a_receipt_is_skipped():
|
||||
r = Rig()
|
||||
entry = scrolled(r)
|
||||
receipt = receipt_for(entry)
|
||||
r.sync.accept_manual_receipts(authority(r, None, 'receipt', (1, 2), receipt), r.now)
|
||||
assert not r.sync.manual_queue and r.sync.take_manual_receipt_acks() == (receipt,)
|
||||
|
||||
|
||||
def test_disengaging_forgets_receipts_and_acknowledgments():
|
||||
r = Rig()
|
||||
r.settle(1)
|
||||
early = receipt_for((r.now, 1, 'right_wheel_up', False), processed_boot_ns=r.now)
|
||||
r.sync.accept_manual_receipts(authority(r, early), r.now)
|
||||
assert r.sync.manual_receipts and r.sync.manual_receipt_acks
|
||||
r.now += TICK
|
||||
r.sync.update(r.now, target_kph=77 * MPH, enabled=False, safe=True)
|
||||
assert not r.sync.manual_receipts and not r.sync.manual_receipt_acks and r.sync.take_manual_receipt_acks() == ()
|
||||
@@ -0,0 +1,161 @@
|
||||
"""Comma can set speed on Tesla dashboard: which cars can have it, and how the startup choice lands in CarParams."""
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from opendbc.car import gen_empty_fingerprint, get_safety_config, structs
|
||||
from opendbc.car.tesla.carcontroller import CarController
|
||||
from opendbc.car.tesla.interface import CarInterface
|
||||
from opendbc.car.tesla.speed_sync import MODELS, SYNC_FLAG, SpeedSynchronizer, eligible, prepare, selected
|
||||
from opendbc.car.tesla.values import CAR, CANBUS, DBC, TeslaFlags, TeslaSafetyFlags
|
||||
|
||||
MODERN = (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y)
|
||||
|
||||
|
||||
def tesla(candidate=CAR.TESLA_MODEL_3, *, cable=True, long=True):
|
||||
fingerprint = gen_empty_fingerprint()
|
||||
fingerprint[CANBUS.autopilot_party][0x489] = 8
|
||||
if cable:
|
||||
fingerprint[CANBUS.vehicle][0x3DF] = 8
|
||||
return CarInterface.get_params(candidate, fingerprint, [], long, False, False)
|
||||
|
||||
|
||||
def word(cp):
|
||||
return int(cp.safetyConfigs[0].safetyParam)
|
||||
|
||||
|
||||
def raw(cp):
|
||||
"""The whole CarParams as bytes, from a copy so the builder can be written again."""
|
||||
return cp.as_reader().as_builder().to_bytes()
|
||||
|
||||
|
||||
def two_configs(cp):
|
||||
cp.safetyConfigs = [get_safety_config(structs.CarParams.SafetyModel.tesla, 1 | SYNC_FLAG),
|
||||
get_safety_config(structs.CarParams.SafetyModel.tesla, 1 | SYNC_FLAG)]
|
||||
|
||||
|
||||
def no_configs(cp):
|
||||
cp.safetyConfigs = []
|
||||
|
||||
|
||||
# Each one alone takes the feature away from an otherwise eligible Model 3.
|
||||
MISSING = {
|
||||
'other brand': lambda cp: setattr(cp, 'brand', 'hyundai'),
|
||||
'model x': lambda cp: setattr(cp, 'carFingerprint', str(CAR.TESLA_MODEL_X)),
|
||||
'model s hw1': lambda cp: setattr(cp, 'carFingerprint', str(CAR.TESLA_MODEL_S_HW1)),
|
||||
'model s pre-ap': lambda cp: setattr(cp, 'carFingerprint', str(CAR.TESLA_MODEL_S_PREAP)),
|
||||
'unknown fingerprint': lambda cp: setattr(cp, 'carFingerprint', 'MOCK'),
|
||||
'stock longitudinal': lambda cp: setattr(cp, 'openpilotLongitudinalControl', False),
|
||||
'no car cruise': lambda cp: setattr(cp, 'pcmCruise', False),
|
||||
'passive': lambda cp: setattr(cp, 'passive', True),
|
||||
'dashcam': lambda cp: setattr(cp, 'dashcamOnly', True),
|
||||
'not a car': lambda cp: setattr(cp, 'notCar', True),
|
||||
'no cable': lambda cp: setattr(cp, 'flags', int(cp.flags) & ~int(TeslaFlags.HAS_VEHICLE_BUS)),
|
||||
'no safety config': no_configs,
|
||||
'two safety configs': two_configs,
|
||||
'safety word without longitudinal': lambda cp: setattr(cp.safetyConfigs[0], 'safetyParam', word(cp) & ~1),
|
||||
}
|
||||
|
||||
|
||||
def test_the_flag_is_its_own_bit():
|
||||
assert SYNC_FLAG == 4096 == int(TeslaSafetyFlags.SCROLL_SPEED_SYNC)
|
||||
others = [flag for flag in TeslaSafetyFlags if flag is not TeslaSafetyFlags.SCROLL_SPEED_SYNC]
|
||||
assert not any(SYNC_FLAG & int(flag) for flag in others)
|
||||
assert not SYNC_FLAG & 2048, 'ordinary Always On Lateral keeps 2048'
|
||||
assert MODELS == tuple(str(model) for model in MODERN)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODERN)
|
||||
def test_model_3_and_y_with_cable_and_longitudinal_are_eligible_and_start_unselected(candidate):
|
||||
cp = tesla(candidate)
|
||||
assert eligible(cp)
|
||||
assert word(cp) == 1 and not selected(cp), 'the car interface never selects it; startup preferences do'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODERN)
|
||||
@pytest.mark.parametrize('cable,long', [(False, True), (True, False), (False, False)])
|
||||
def test_cable_and_longitudinal_are_both_needed(candidate, cable, long):
|
||||
cp = tesla(candidate, cable=cable, long=long)
|
||||
before = raw(cp)
|
||||
assert not eligible(cp) and not selected(cp)
|
||||
assert prepare(cp, True) is cp and raw(cp) == before
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reason', MISSING)
|
||||
def test_every_condition_is_required(reason):
|
||||
cp = tesla()
|
||||
prepare(cp, True)
|
||||
assert selected(cp)
|
||||
MISSING[reason](cp)
|
||||
assert not eligible(cp), reason
|
||||
assert not selected(cp), 'a set bit alone selects nothing'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reason', MISSING)
|
||||
@pytest.mark.parametrize('requested', (False, True))
|
||||
def test_prepare_never_touches_a_car_that_is_not_eligible(reason, requested):
|
||||
cp = tesla()
|
||||
if reason not in ('no safety config', 'two safety configs'):
|
||||
cp.safetyConfigs[0].safetyParam = word(cp) | SYNC_FLAG # even a stale bit is left for the car's own code
|
||||
MISSING[reason](cp)
|
||||
before = raw(cp)
|
||||
assert prepare(cp, requested) is cp
|
||||
assert raw(cp) == before
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODERN)
|
||||
@pytest.mark.parametrize('base', (1, 257, 513, 769, 1537, 1793, 2049, 2305, 3073, 3329))
|
||||
def test_prepare_sets_and_clears_only_its_own_bit(candidate, base):
|
||||
cp = tesla(candidate)
|
||||
cp.safetyConfigs[0].safetyParam = base
|
||||
rest = raw(cp)
|
||||
for _ in range(2):
|
||||
assert prepare(cp, True) is cp
|
||||
assert word(cp) == base | SYNC_FLAG and selected(cp)
|
||||
for _ in range(2):
|
||||
assert prepare(cp, False) is cp
|
||||
assert word(cp) == base and not selected(cp) and eligible(cp)
|
||||
assert raw(cp) == rest, 'nothing else in CarParams moved'
|
||||
|
||||
|
||||
def test_prepare_clears_a_stale_selection():
|
||||
cp = tesla()
|
||||
cp.safetyConfigs[0].safetyParam = 4097
|
||||
prepare(cp, False)
|
||||
assert word(cp) == 1 and not selected(cp)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('cp', [None, object(), SimpleNamespace(), SimpleNamespace(brand='tesla'),
|
||||
SimpleNamespace(brand='tesla', carFingerprint='TESLA_MODEL_3', openpilotLongitudinalControl=True,
|
||||
pcmCruise=True, passive=False, dashcamOnly=False, notCar=False, flags=None,
|
||||
safetyConfigs=[])])
|
||||
def test_missing_or_malformed_car_parameters_are_not_eligible(cp):
|
||||
assert eligible(cp) is False and selected(cp) is False
|
||||
assert prepare(cp, True) is cp
|
||||
|
||||
|
||||
def test_a_reader_is_judged_like_its_builder():
|
||||
cp = tesla()
|
||||
assert eligible(cp.as_reader()) and not selected(cp.as_reader())
|
||||
prepare(cp, True)
|
||||
assert selected(cp.as_reader())
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODERN)
|
||||
def test_the_controller_builds_a_synchronizer_only_when_selected(candidate):
|
||||
cp = tesla(candidate)
|
||||
assert CarController(DBC[candidate], cp).speed_sync is None
|
||||
prepare(cp, True)
|
||||
assert isinstance(CarController(DBC[candidate], cp).speed_sync, SpeedSynchronizer)
|
||||
prepare(cp, False)
|
||||
assert CarController(DBC[candidate], cp).speed_sync is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', (CAR.TESLA_MODEL_X, CAR.TESLA_MODEL_S_HW1, CAR.TESLA_MODEL_S_PREAP))
|
||||
def test_other_teslas_never_get_a_synchronizer(candidate):
|
||||
cp = tesla(candidate)
|
||||
before = raw(cp)
|
||||
assert not eligible(cp) and not selected(cp)
|
||||
prepare(cp, True)
|
||||
assert raw(cp) == before
|
||||
assert CarController(DBC[candidate], cp).speed_sync is None
|
||||
@@ -132,6 +132,7 @@ class CarControllerParams:
|
||||
class TeslaSafetyFlags(IntFlag):
|
||||
LONG_CONTROL = 1
|
||||
HW1 = 16
|
||||
SCROLL_SPEED_SYNC = 4096 # 2048 is the ordinary AOL word
|
||||
COOP_STEERING = 256
|
||||
AOL_SCREEN_BUTTON = 512
|
||||
AOL_SCREEN_DISENGAGE_ON_BRAKE = 1024
|
||||
|
||||
@@ -22,6 +22,7 @@ from opendbc.car.mg.values import CAR as MG
|
||||
|
||||
# Configurations with source tests but no matching recorded route.
|
||||
unrecorded_route_gaps = {
|
||||
SUBARU.SUBARU_CROSSTREK_2018: "subaru/tests/test_supported_firmware.py",
|
||||
GM.CHEVROLET_VOLT_CC: "gm/tests/test_volt_cc_gas.py",
|
||||
GM.CHEVROLET_MALIBU_HYBRID_CC: "gm/tests/test_ordinary_cc.py",
|
||||
TOYOTA.TOYOTA_PRIUS_RETROFIT: "toyota/tests/test_retrofit.py",
|
||||
|
||||
@@ -4,6 +4,7 @@ from pathlib import Path
|
||||
from opendbc.car.values import PLATFORMS
|
||||
from opendbc.car.tests.routes import non_tested_cars, routes, unrecorded_route_gaps
|
||||
from opendbc.car.gm.values import CAR as GM
|
||||
from opendbc.car.subaru.values import CAR as SUBARU
|
||||
from opendbc.car.tesla.values import CAR as TESLA
|
||||
from opendbc.car.toyota.values import CAR as TOYOTA
|
||||
from opendbc.car.volvo.values import CAR as VOLVO
|
||||
@@ -20,7 +21,7 @@ class TestRoutes(unittest.TestCase):
|
||||
def test_explicit_unrecorded_configuration_gaps(self):
|
||||
self.assertEqual(set(unrecorded_route_gaps), {
|
||||
GM.CHEVROLET_VOLT_CC, GM.CHEVROLET_MALIBU_HYBRID_CC, TOYOTA.TOYOTA_PRIUS_RETROFIT, TESLA.TESLA_MODEL_S_HW1,
|
||||
VOLVO.VOLVO_XC40_RECHARGE, VOLVO.VOLVO_S60_RECHARGE, VOLVO.POLESTAR_2, VOLVO.VOLVO_V60,
|
||||
SUBARU.SUBARU_CROSSTREK_2018, VOLVO.VOLVO_XC40_RECHARGE, VOLVO.VOLVO_S60_RECHARGE, VOLVO.POLESTAR_2, VOLVO.VOLVO_V60,
|
||||
})
|
||||
self.assertFalse(set(unrecorded_route_gaps) & {route.car_model for route in routes})
|
||||
self.assertTrue(set(unrecorded_route_gaps) <= set(non_tested_cars))
|
||||
|
||||
@@ -31,6 +31,11 @@ TEMP_STEER_FAULTS = (0, 9, 11, 21, 25)
|
||||
PERM_STEER_FAULTS = (3, 17)
|
||||
|
||||
|
||||
def has_optional_prius_gap_button(CP):
|
||||
return (CP.carFingerprint == CAR.TOYOTA_PRIUS and not CP.openpilotLongitudinalControl and
|
||||
not CP.flags & (ToyotaFlags.LONG_FILTER | ToyotaFlags.FILTER_BUTTONS))
|
||||
|
||||
|
||||
class CarState(CarStateBase):
|
||||
def __init__(self, CP):
|
||||
super().__init__(CP)
|
||||
@@ -266,6 +271,10 @@ class CarState(CarStateBase):
|
||||
if self.CP.flags & ToyotaFlags.FILTER_BUTTONS or advert_filter.configured(self.CP) or prius_advert_filter.configured(self.CP):
|
||||
fresh = cp.advert_button_ns > 0 and 0 <= cp._last_update_nanos - cp.advert_button_ns <= 200_000_000
|
||||
self.distance_button = cp.advert_distance_button if fresh else 0
|
||||
elif not bypass and has_optional_prius_gap_button(self.CP):
|
||||
self.distance_button = cp_acc.vl["ACC_CONTROL"]["DISTANCE"]
|
||||
# A live gesture needs its source until the physical release arrives.
|
||||
cp_acc.message_states[0x343].ignore_alive = not self.distance_button
|
||||
else:
|
||||
self.distance_button = (cp.vl["SDSU"]["FD_BUTTON"] if self.CP.flags & ToyotaFlags.LONG_FILTER
|
||||
else cp_acc.vl["ACC_CONTROL"]["DISTANCE"])
|
||||
@@ -361,6 +370,10 @@ class CarState(CarStateBase):
|
||||
("BLINKERS_STATE", float('nan')),
|
||||
]
|
||||
|
||||
if has_optional_prius_gap_button(CP):
|
||||
# Factory cruise state and AEB are received on separate messages.
|
||||
pt_messages.append(("ACC_CONTROL", math.nan))
|
||||
|
||||
if CP.carFingerprint == CAR.TOYOTA_SIENNA_4TH_GEN:
|
||||
pt_messages.append(("PCM_CRUISE_4", 1))
|
||||
from opendbc.car.toyota import camera_2aa_filter
|
||||
|
||||
@@ -30,9 +30,19 @@ AUTO_RESUME_CARS = frozenset((CAR.TOYOTA_HIGHLANDER, CAR.TOYOTA_PRIUS_V, CAR.TOY
|
||||
WORDS = frozenset(word | stock for word in PROFILES.values() for stock in (0, 0x200))
|
||||
|
||||
|
||||
def corolla_startup_mirror(candidate, fingerprint):
|
||||
if candidate != CAR.TOYOTA_COROLLA:
|
||||
return False
|
||||
pt = fingerprint.get(0, {})
|
||||
return pt == fingerprint.get(2, {}) and all(pt.get(address) == length for address, length in
|
||||
((0xAA, 8), (0x262, 5), (0x1D3, 8), (0x343, 8), (0x4CB, 8)))
|
||||
|
||||
|
||||
def hardware_supported(candidate, fingerprint, car_fw):
|
||||
if candidate not in PROFILES or any(address in frames for frames in fingerprint.values() for address in (0x201, 0x2FF, 0x2AA)):
|
||||
return False
|
||||
if corolla_startup_mirror(candidate, fingerprint):
|
||||
return False
|
||||
camera = fingerprint.get(2, {})
|
||||
if not any(camera.get(address) == 8 for address in (0x343, 0x4CB)) or any(camera.get(address, 8) != 8 for address in (0x343, 0x4CB)):
|
||||
return False
|
||||
|
||||
@@ -29,6 +29,9 @@ def hardware_supported(candidate, fingerprint):
|
||||
return False
|
||||
if 0x2FF in frames and not (candidate == CAR.TOYOTA_CAMRY and _cluster_radar_bus(candidate, bus, frames)):
|
||||
return False
|
||||
from opendbc.car.toyota.dsu_bypass import corolla_startup_mirror
|
||||
if corolla_startup_mirror(candidate, fingerprint):
|
||||
return True
|
||||
camera = fingerprint.get(2, {})
|
||||
if 0x4CB in camera:
|
||||
return False
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import pytest
|
||||
|
||||
from opendbc.car import gen_empty_fingerprint, structs
|
||||
from opendbc.car.toyota.fingerprints import FW_VERSIONS
|
||||
from opendbc.car.toyota.interface import CarInterface
|
||||
from opendbc.car.toyota.values import CAR
|
||||
|
||||
|
||||
@pytest.mark.parametrize('mirrored,expected', ((True, 0x5358), (False, 0x8958)))
|
||||
def test_corolla_camera_relay_mirror_is_not_a_dsu_bypass(mirrored, expected):
|
||||
car = CAR.TOYOTA_COROLLA
|
||||
fp = gen_empty_fingerprint()
|
||||
fp[0].update({0xAA: 8, 0x262: 5, 0x1D3: 8, 0x343: 8, 0x4CB: 8, 0x283: 7})
|
||||
fp[2].update(fp[0] if mirrored else {0x343: 8, 0x4CB: 8})
|
||||
fw = [structs.CarParams.CarFw(ecu=ecu, address=addr, subAddress=sub or 0, fwVersion=versions[0], brand='toyota', bus=0)
|
||||
for (ecu, addr, sub), versions in FW_VERSIONS[car].items()]
|
||||
|
||||
cp = CarInterface.get_params(car, fp, fw, False, True, False)
|
||||
assert cp.safetyConfigs[0].safetyParam == expected
|
||||
assert cp.pcmCruise
|
||||
assert cp.openpilotLongitudinalControl is (not mirrored)
|
||||
@@ -0,0 +1,40 @@
|
||||
import pytest
|
||||
|
||||
from opendbc.can import CANPacker
|
||||
from opendbc.car import Bus, gen_empty_fingerprint, structs
|
||||
from opendbc.car.toyota.carstate import CarState
|
||||
from opendbc.car.toyota.interface import CarInterface
|
||||
from opendbc.car.toyota.values import CAR, DBC
|
||||
|
||||
|
||||
@pytest.mark.parametrize('stock_aol', (True, False))
|
||||
def test_prius_gap_button_requires_the_source_only_during_a_press(stock_aol):
|
||||
fp = gen_empty_fingerprint()
|
||||
if not stock_aol:
|
||||
fp[2][0x343] = 8
|
||||
cp = CarInterface.get_params(CAR.TOYOTA_PRIUS, fp, [], False, False, False)
|
||||
assert not cp.openpilotLongitudinalControl
|
||||
assert cp.safetyConfigs[0].safetyParam == (0x6242 if stock_aol else 0x242)
|
||||
state = CarState(cp)
|
||||
parsers = state.get_can_parsers(cp)
|
||||
packer = CANPacker(DBC[CAR.TOYOTA_PRIUS][Bus.pt])
|
||||
gap = structs.CarState.ButtonEvent.Type.gapAdjustCruise
|
||||
|
||||
def edges(stamp, value=None):
|
||||
frames = [] if value is None else [packer.make_can_msg('ACC_CONTROL', 0, {'DISTANCE': value})]
|
||||
for parser in parsers.values():
|
||||
parser.update([(stamp, frames)])
|
||||
return [event.pressed for event in state.update(parsers).buttonEvents if event.type == gap]
|
||||
|
||||
assert edges(1_000_000_000) == []
|
||||
assert parsers[Bus.pt].message_states[0x343].ignore_alive
|
||||
assert not parsers[Bus.pt].message_states[0x1D3].ignore_alive
|
||||
assert not parsers[Bus.pt].message_states[0x262].ignore_alive
|
||||
assert edges(1_030_000_000, 1) == [True]
|
||||
gap_message = parsers[Bus.pt].message_states[0x343]
|
||||
assert not gap_message.ignore_alive
|
||||
assert edges(12_000_000_000) == []
|
||||
assert not gap_message.valid(12_000_000_000, False)
|
||||
assert edges(12_030_000_000, 0) == [False]
|
||||
assert gap_message.ignore_alive
|
||||
assert gap_message.valid(23_000_000_000, False)
|
||||
@@ -2,6 +2,7 @@ BO_ 228 STEERING_CONTROL: 5 EON
|
||||
SG_ STEER_TORQUE : 7|16@0- (1,0) [-4096|4096] "" EPS
|
||||
SG_ DRIVER_OVERRIDE : 17|1@0+ (1,0) [0|1] "" XXX
|
||||
SG_ STEER_TORQUE_REQUEST : 23|1@0+ (1,0) [0|1] "" EPS
|
||||
SG_ STEER_CONTROL_ARM : 19|2@0+ (1,0) [0|3] "" EPS
|
||||
SG_ CONTROL_STATE : 26|3@0+ (1,0) [0|7] "" XXX
|
||||
SG_ CHECKSUM : 35|4@0+ (1,0) [0|15] "" EPS
|
||||
SG_ COUNTER : 37|2@0+ (1,0) [0|3] "" EPS
|
||||
@@ -206,6 +207,7 @@ BO_ 13275 LKAS_HUD_B: 8 ADAS
|
||||
SG_ COUNTER : 61|2@0+ (1,0) [0|3] "" BDY
|
||||
|
||||
CM_ SG_ 228 DRIVER_OVERRIDE "Appears to acknowledge STEER_STATUS.NO_TORQUE_ALERT_1";
|
||||
CM_ SG_ 228 STEER_CONTROL_ARM "Stock camera sends 0 or 1. The Accord angle-loop EPS firmware (39990-TVA,A16x) runs its lane only while this reads 2";
|
||||
CM_ SG_ 576 LINE_DISTANCE_VISIBLE "Length of line visible, undecoded";
|
||||
CM_ SG_ 577 LINE_FAR_EDGE_POSITION "Appears to be a measure of line thickness, indicates location of the portion of the line furthest from the car, undecoded";
|
||||
CM_ SG_ 577 LINE_PARAMETER "Unclear if this is low quality line curvature rate or if this is something else, but it is correlated with line curvature, undecoded";
|
||||
|
||||
@@ -232,6 +232,8 @@ typedef bool (*tx_hook)(const CANPacket_t *msg); // returns true if the message
|
||||
typedef bool (*fwd_hook)(int bus_num, int addr); // returns true if the message should be blocked from forwarding
|
||||
|
||||
typedef bool (*fwd_packet_hook)(const CANPacket_t *msg);
|
||||
typedef bool (*stage_tx_hook)(const CANPacket_t *msg);
|
||||
typedef bool (*fwd_output_hook)(const CANPacket_t *msg, CANPacket_t *output, bool *replaced);
|
||||
|
||||
typedef struct {
|
||||
safety_hook_init init;
|
||||
@@ -240,6 +242,8 @@ typedef struct {
|
||||
tx_hook tx;
|
||||
fwd_hook fwd;
|
||||
fwd_packet_hook fwd_packet;
|
||||
stage_tx_hook stage_tx;
|
||||
fwd_output_hook fwd_output;
|
||||
get_checksum_t get_checksum;
|
||||
compute_checksum_t compute_checksum;
|
||||
get_counter_t get_counter;
|
||||
@@ -371,6 +375,11 @@ extern safety_config current_safety_config;
|
||||
|
||||
int safety_fwd_hook(int bus_num, int addr);
|
||||
int safety_fwd_packet_hook(const CANPacket_t *msg);
|
||||
bool safety_uses_camera_slot(const CANPacket_t *msg);
|
||||
uint32_t safety_camera_release_delay(const CANPacket_t *msg, uint32_t now);
|
||||
bool safety_camera_release_current(const CANPacket_t *msg, uint32_t now);
|
||||
bool safety_stage_tx_hook(const CANPacket_t *msg);
|
||||
int safety_fwd_output_hook(const CANPacket_t *msg, CANPacket_t *output, bool *replaced);
|
||||
int set_safety_hooks(uint16_t mode, uint16_t param);
|
||||
|
||||
extern const safety_hooks body_hooks;
|
||||
|
||||
@@ -34,6 +34,8 @@ static bool honda_fwd_brake = false;
|
||||
static bool honda_bosch_long = false;
|
||||
static bool honda_bosch_radarless = false;
|
||||
static bool honda_bosch_canfd = false;
|
||||
static bool honda_accord_angle = false;
|
||||
#define HONDA_PARAM_ACCORD_ANGLE 4096U
|
||||
static bool honda_mvl_stock = false;
|
||||
static uint8_t honda_mvl_buttons_fresh = 0U;
|
||||
static bool honda_rdx_high_gas = false;
|
||||
@@ -101,6 +103,23 @@ static uint8_t honda_get_counter(const CANPacket_t *msg) {
|
||||
return (msg->data[counter_byte] >> 4U) & 0x3U;
|
||||
}
|
||||
|
||||
// The Accord angle-loop EPS firmware (39990-TVA,A16x) exists only on classic Bosch. On it a 0xE4 frame with
|
||||
// STEER_CONTROL_ARM == 2 carries an angle setpoint in bytes 0-1 (-0.1 deg); the EPS runs its angle lane on no other
|
||||
// frame, and the stock camera only ever sends 0 or 1 there.
|
||||
static bool honda_angle_setpoint_capable(void) {
|
||||
return (honda_hw == HONDA_BOSCH) && honda_accord_angle;
|
||||
}
|
||||
|
||||
// Wheel angle for the angle setpoint check: where a request may start from, and what a request-off frame may hold.
|
||||
// STEERING_SENSORS is not a required RX check on Honda, so it arrives here, and its checksum is verified here.
|
||||
static void honda_optional_rx_hook(const CANPacket_t *msg) {
|
||||
if (honda_angle_setpoint_capable() && msg_matches(msg, 0x14AU, honda_get_pt_bus(), 8U) &&
|
||||
(honda_get_checksum(msg) == honda_compute_checksum(msg))) {
|
||||
// STEER_ANGLE, -0.1 deg: the same units and sign as the 0xE4 setpoint
|
||||
update_sample(&angle_meas, to_signed((msg->data[0] << 8) | msg->data[1], 16));
|
||||
}
|
||||
}
|
||||
|
||||
static void honda_rx_hook(const CANPacket_t *msg) {
|
||||
const bool pcm_cruise = ((honda_hw == HONDA_BOSCH) && !honda_bosch_long) || ((honda_hw == HONDA_NIDEC) && !honda_interceptor);
|
||||
unsigned int pt_bus = honda_get_pt_bus();
|
||||
@@ -111,6 +130,14 @@ static void honda_rx_hook(const CANPacket_t *msg) {
|
||||
vehicle_moving = msg->data[0] | msg->data[1];
|
||||
}
|
||||
|
||||
// speed for the angle setpoint check (Accord angle-loop EPS)
|
||||
if (honda_angle_setpoint_capable()) {
|
||||
if (msg_matches(msg, 0x158U, pt_bus)) {
|
||||
// ENGINE_DATA XMISSION_SPEED, 0.01 kph
|
||||
UPDATE_VEHICLE_SPEED(((msg->data[0] << 8) | msg->data[1]) * 0.01 * KPH_TO_MS);
|
||||
}
|
||||
}
|
||||
|
||||
// check ACC main state
|
||||
// 0x326 for all Bosch and some Nidec, 0x1A6 for some Nidec
|
||||
if ((!aol_honda_bosch_long && ((msg->addr == 0x326U) || (msg->addr == 0x1A6U))) ||
|
||||
@@ -317,6 +344,40 @@ static bool honda_tx_hook(const CANPacket_t *msg) {
|
||||
}
|
||||
}
|
||||
|
||||
// STEER: angle setpoint frames (STEER_CONTROL_ARM == 2, Accord angle-loop EPS) must stay inside the lateral
|
||||
// acceleration and jerk limits, checked with the vehicle model on the value as sent
|
||||
if ((msg->addr == 0xE4U) && (((msg->data[2] >> 2) & 0x3U) == 2U)) {
|
||||
const AngleSteeringLimits HONDA_ACCORD_ANGLE_LIMITS = {
|
||||
.max_angle = 4000, // 400 deg, the EPS clamps its setpoint just above this
|
||||
.angle_deg_to_can = 10,
|
||||
.frequency = 100U,
|
||||
};
|
||||
|
||||
// NOTE: HONDA_ACCORD, must match openpilot's VehicleModel
|
||||
const AngleSteeringParams HONDA_ACCORD_ANGLE_PARAMS = {
|
||||
.slip_factor = -0.0006999872680281922, // calc_slip_factor(VM)
|
||||
.steer_ratio = 16.33,
|
||||
.wheelbase = 2.83,
|
||||
};
|
||||
|
||||
const int desired_angle = to_signed((msg->data[0] << 8) | msg->data[1], 16);
|
||||
const bool steer_req = GET_BIT(msg, 23U); // STEER_TORQUE_REQUEST
|
||||
|
||||
bool violation = !honda_angle_setpoint_capable();
|
||||
if (!violation) {
|
||||
if (!steer_req && (desired_angle == 0)) {
|
||||
// request off with a zero field: nothing is commanded, the next request starts from the wheel
|
||||
desired_angle_last = SAFETY_CLAMP(angle_meas.values[0], -HONDA_ACCORD_ANGLE_LIMITS.max_angle, HONDA_ACCORD_ANGLE_LIMITS.max_angle);
|
||||
} else {
|
||||
violation |= steer_angle_cmd_checks_vm(desired_angle, steer_req, HONDA_ACCORD_ANGLE_LIMITS, HONDA_ACCORD_ANGLE_PARAMS);
|
||||
violation |= safety_max_limit_check(desired_angle, HONDA_ACCORD_ANGLE_LIMITS.max_angle, -HONDA_ACCORD_ANGLE_LIMITS.max_angle);
|
||||
}
|
||||
}
|
||||
if (violation) {
|
||||
tx = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Bosch supplemental control check
|
||||
if (msg->addr == 0xE5U) {
|
||||
if ((GET_BYTES_64_LE(msg, 0, 8) & 0x00FFFFFFFFFFFFFFULL) != 0x0000000010800004ULL) {
|
||||
@@ -381,6 +442,7 @@ static safety_config honda_nidec_init(uint16_t param) {
|
||||
const uint16_t HONDA_PARAM_NIDEC_ALT = 4;
|
||||
|
||||
honda_hw = HONDA_NIDEC;
|
||||
honda_accord_angle = false;
|
||||
honda_brake = 0;
|
||||
honda_brake_switch_prev = false;
|
||||
honda_fwd_brake = false;
|
||||
@@ -426,7 +488,14 @@ static safety_config honda_nidec_init(uint16_t param) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
static safety_config honda_bosch_init(uint16_t param) {
|
||||
static safety_config honda_bosch_init(uint16_t requested_param) {
|
||||
// Apply the Accord flag only to the classic Bosch base configurations the host can select.
|
||||
const uint16_t param = (uint16_t)(requested_param & ~HONDA_PARAM_ACCORD_ANGLE);
|
||||
bool accord_base = (param == 0U) || (param == 1U);
|
||||
#ifdef ALLOW_DEBUG
|
||||
accord_base = accord_base || (param == 2U) || (param == 3U) || (param == 2082U) || (param == 2083U);
|
||||
#endif
|
||||
honda_accord_angle = GET_FLAG(requested_param, HONDA_PARAM_ACCORD_ANGLE) && accord_base;
|
||||
honda_mvl_stock = ((param == 80U) || (param == 81U)) && ((alternative_experience == 0) || (alternative_experience == 32));
|
||||
honda_mvl_buttons_fresh = 0U;
|
||||
honda_interceptor_reset(false);
|
||||
@@ -614,6 +683,7 @@ const safety_hooks honda_bosch_hooks = {
|
||||
.fwd = honda_mvl_stock_fwd_hook,
|
||||
.init = honda_bosch_init,
|
||||
.rx = honda_rx_hook,
|
||||
.optional_rx = honda_optional_rx_hook,
|
||||
.tx = honda_tx_hook,
|
||||
.get_counter = honda_get_counter,
|
||||
.get_checksum = honda_get_checksum,
|
||||
|
||||
@@ -19,6 +19,8 @@ static bool blended_aol_token = false;
|
||||
static bool blended_aol_claimed = false;
|
||||
static bool blended_aol_session = false;
|
||||
static bool blended_aol_request_seen = false;
|
||||
static bool blended_aol_brake_continuation = false;
|
||||
static bool blended_aol_idle_owned[2] = {false, false};
|
||||
static bool blended_aol_neutral[3] = {false, false, false};
|
||||
static bool blended_aol_pressed[3] = {false, false, false};
|
||||
static uint32_t blended_aol_source_ts[3] = {0U, 0U, 0U};
|
||||
@@ -44,6 +46,9 @@ static void blended_aol_clear(void) {
|
||||
blended_aol_claimed = false;
|
||||
blended_aol_session = false;
|
||||
blended_aol_request_seen = false;
|
||||
blended_aol_brake_continuation = false;
|
||||
blended_aol_idle_owned[0] = false;
|
||||
blended_aol_idle_owned[1] = false;
|
||||
blended_aol_token_ts = 0U;
|
||||
blended_aol_token_source = 3U;
|
||||
aol_host_axis_mask = 0U;
|
||||
@@ -71,6 +76,9 @@ static void blended_aol_reset(void) {
|
||||
|
||||
static void blended_aol_host_request(uint8_t mask) {
|
||||
blended_aol_request_seen |= mask != 0U;
|
||||
if ((mask & 1U) == 0U) {
|
||||
blended_aol_brake_continuation = false;
|
||||
}
|
||||
}
|
||||
|
||||
static uint8_t blended_aol_request_mask(void) {
|
||||
@@ -107,7 +115,7 @@ static uint8_t blended_aol_permission_mask(void) {
|
||||
(safety_get_ts_elapsed(microsecond_timer_get(), blended_aol_source_ts[blended_aol_token_source]) <= 300000U);
|
||||
if (!aol_rx_healthy() || (blended_aol_token && !source_current)) {
|
||||
blended_aol_clear();
|
||||
} else if (((blended_aol_request_mask() & 1U) != 0U) && (controls_allowed || blended_aol_token)) {
|
||||
} else if (((blended_aol_request_mask() & 1U) != 0U) && (controls_allowed || blended_aol_token || blended_aol_brake_continuation)) {
|
||||
result = 1U;
|
||||
} else {
|
||||
}
|
||||
@@ -145,6 +153,14 @@ static void blended_aol_rx(const CANPacket_t *msg) {
|
||||
if (blended_aol_enabled) {
|
||||
const unsigned int pt = blended_aol_hda2 ? 1U : 0U;
|
||||
const uint32_t now = microsecond_timer_get();
|
||||
if (blended_aol_hda2 && !blended_aol_long && msg_matches(msg, 0x394U, pt, 8U)) {
|
||||
const bool brake = ((msg->data[5] >> 5U) & 3U) == 2U;
|
||||
if (brake && !brake_pressed && controls_allowed && blended_aol_owned[0] &&
|
||||
(safety_get_ts_elapsed(now, blended_aol_tx_ts[0]) <= AOL_HOST_REQUEST_TIMEOUT_US) &&
|
||||
((blended_aol_request_mask() & 1U) != 0U) && aol_rx_healthy()) {
|
||||
blended_aol_brake_continuation = true;
|
||||
}
|
||||
}
|
||||
if (blended_aol_long && msg_matches(msg, 0x394U, pt, 8U)) {
|
||||
blended_aol_main_seen = true;
|
||||
blended_aol_main = ((msg->data[5] >> 3U) & 3U) == 0U;
|
||||
@@ -323,6 +339,19 @@ static void blended_aol_tx(const CANPacket_t *msg, bool accepted) {
|
||||
}
|
||||
}
|
||||
accepted_current &= active;
|
||||
if (blended_aol_hda2) {
|
||||
const bool zero_torque = (((msg->data[6] & 0xFU) << 7U) | (msg->data[5] >> 1U)) == 1024U;
|
||||
blended_aol_idle_owned[0] = accepted && !active && zero_torque && aol_rx_healthy() &&
|
||||
!safety_rx_checks_invalid && !relay_malfunction;
|
||||
if (!blended_aol_idle_owned[0]) {
|
||||
blended_aol_idle_owned[1] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (blended_aol_hda2 && (msg->addr == 0x2A4U) && (msg->bus == 0U) && !retain_camera_ownership) {
|
||||
blended_aol_idle_owned[1] = accepted && blended_aol_idle_owned[0] && aol_rx_healthy() &&
|
||||
!safety_rx_checks_invalid && !relay_malfunction &&
|
||||
(safety_get_ts_elapsed(microsecond_timer_get(), blended_aol_tx_ts[0]) <= AOL_HOST_REQUEST_TIMEOUT_US);
|
||||
}
|
||||
for (unsigned int i = 0U; i < count; i++) {
|
||||
const unsigned int bus = blended_aol_hda2 && (i >= 2U) ? 1U : 0U;
|
||||
@@ -339,6 +368,16 @@ static bool blended_aol_fwd(int bus, int addr) {
|
||||
bool blocked = blended_aol_long && !blended_aol_enabled && (bus == 2) &&
|
||||
((addr == (blended_aol_hda2 ? 0x50 : 0x340)) ||
|
||||
(addr == (blended_aol_hda2 ? 0x2A4 : 0x364)) || (!blended_aol_hda2 && (addr == 0x485)));
|
||||
if (blended_aol_enabled && blended_aol_hda2 && (bus == 2) &&
|
||||
aol_rx_healthy() && !safety_rx_checks_invalid && !relay_malfunction) {
|
||||
const uint32_t now = microsecond_timer_get();
|
||||
const bool primary_current = blended_aol_idle_owned[0] &&
|
||||
(safety_get_ts_elapsed(now, blended_aol_tx_ts[0]) <= AOL_HOST_REQUEST_TIMEOUT_US);
|
||||
if (primary_current) {
|
||||
blocked |= (addr == 0x50) || ((addr == 0x2A4) && blended_aol_idle_owned[1] &&
|
||||
(safety_get_ts_elapsed(now, blended_aol_tx_ts[1]) <= AOL_HOST_REQUEST_TIMEOUT_US));
|
||||
}
|
||||
}
|
||||
if (blended_aol_enabled && (bus == 2) && aol_rx_healthy() && (controls_allowed || (blended_aol_permission_mask() != 0U))) {
|
||||
const uint32_t addresses[4] = {blended_aol_hda2 ? 0x50U : 0x340U, blended_aol_hda2 ? 0x2A4U : 0x364U, 0x485U, 0x340U};
|
||||
const unsigned int count = blended_aol_hda2 ? 2U : 3U;
|
||||
|
||||
@@ -820,12 +820,15 @@ static safety_config hyundai_canfd_gv60_extend_tx(const safety_config original,
|
||||
}
|
||||
#endif
|
||||
|
||||
#define HYUNDAI_CANFD_STEER_MAX_TORQUE 409
|
||||
#define HYUNDAI_CANFD_STEER_MAX_RATE_UP 10
|
||||
|
||||
static bool hyundai_canfd_tx_hook_valid(const CANPacket_t *msg) {
|
||||
static uint8_t hyundai_canfd_ioniq6_lfa_mirror[4] = {0};
|
||||
const TorqueSteeringLimits HYUNDAI_CANFD_STEERING_LIMITS = {
|
||||
.max_torque = 409,
|
||||
.max_torque = HYUNDAI_CANFD_STEER_MAX_TORQUE,
|
||||
.max_rt_delta = 375,
|
||||
.max_rate_up = 10,
|
||||
.max_rate_up = HYUNDAI_CANFD_STEER_MAX_RATE_UP,
|
||||
.max_rate_down = 3,
|
||||
.driver_torque_allowance = 250,
|
||||
.driver_torque_multiplier = 2,
|
||||
@@ -1228,7 +1231,7 @@ static bool hyundai_canfd_tx_hook_valid(const CANPacket_t *msg) {
|
||||
return tx;
|
||||
}
|
||||
|
||||
#ifdef ALLOW_DEBUG
|
||||
#if defined(ALLOW_DEBUG) && !defined(STM32F4)
|
||||
static bool hyundai_kona_idle_handoff = false;
|
||||
static bool hyundai_kona_camera_seen = false;
|
||||
static bool hyundai_kona_output_seen = false;
|
||||
@@ -1237,6 +1240,11 @@ static uint32_t hyundai_kona_camera_ts = 0U;
|
||||
static uint32_t hyundai_kona_output_ts = 0U;
|
||||
static uint8_t hyundai_kona_camera_counter = 0U;
|
||||
static uint8_t hyundai_kona_output_counter = 0U;
|
||||
static bool hyundai_kona_pending = false;
|
||||
static bool hyundai_kona_emitting = false;
|
||||
static bool hyundai_kona_slot_owned = false;
|
||||
static uint32_t hyundai_kona_pending_ts = 0U;
|
||||
static CANPacket_t hyundai_kona_pending_msg;
|
||||
|
||||
static bool hyundai_kona_host_steering(void) {
|
||||
return controls_allowed || ((aol_get_permission_mask() & 1U) != 0U);
|
||||
@@ -1262,47 +1270,118 @@ static void hyundai_kona_track_output(uint32_t now, bool host, uint8_t counter)
|
||||
hyundai_kona_output_counter = counter;
|
||||
}
|
||||
|
||||
static bool hyundai_kona_camera_fwd(const CANPacket_t *msg) {
|
||||
static bool hyundai_kona_camera_without_slot(const CANPacket_t *msg) {
|
||||
return hyundai_kona_idle_handoff && (msg->bus == 2U) && (msg->addr == 0x12AU);
|
||||
}
|
||||
|
||||
static bool hyundai_kona_camera_release_current(const CANPacket_t *msg, uint32_t now) {
|
||||
return (msg->bus == 2U) && hyundai_kona_output_seen && hyundai_kona_host_output &&
|
||||
hyundai_kona_camera_seen && !relay_malfunction && !safety_rx_checks_invalid && aol_rx_healthy() &&
|
||||
!hyundai_kona_host_steering() && hyundai_kona_lfa_valid(msg) &&
|
||||
((uint8_t)(msg->data[2] - hyundai_kona_output_counter) == 1U) &&
|
||||
((uint8_t)(msg->data[2] - hyundai_kona_camera_counter) == 1U) &&
|
||||
(safety_get_ts_elapsed(now, hyundai_kona_camera_ts) <= 20000U);
|
||||
}
|
||||
|
||||
static bool hyundai_kona_stage_tx(const CANPacket_t *msg) {
|
||||
bool staged = false;
|
||||
if (hyundai_kona_idle_handoff && (msg->addr == 0x12AU) && (msg->bus == 0U)) {
|
||||
const uint32_t now = microsecond_timer_get();
|
||||
const uint8_t source_delta = (uint8_t)(hyundai_kona_camera_counter - msg->data[2]);
|
||||
staged = !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) <= 20000U) && (source_delta <= 1U);
|
||||
if (staged) {
|
||||
hyundai_kona_pending_msg = *msg;
|
||||
hyundai_kona_pending_ts = now;
|
||||
hyundai_kona_pending = true;
|
||||
} else {
|
||||
hyundai_kona_pending = false;
|
||||
}
|
||||
}
|
||||
return staged;
|
||||
}
|
||||
|
||||
static bool hyundai_kona_camera_output(const CANPacket_t *msg, CANPacket_t *output, bool *replaced) {
|
||||
bool blocked = false;
|
||||
if (hyundai_kona_idle_handoff && (msg->bus == 2U) && (msg->addr == 0x12AU)) {
|
||||
const uint32_t now = microsecond_timer_get();
|
||||
const bool valid = hyundai_kona_lfa_valid(msg);
|
||||
if (valid) {
|
||||
const uint8_t delta = (uint8_t)(msg->data[2] - hyundai_kona_camera_counter);
|
||||
if (!hyundai_kona_camera_seen ||
|
||||
(safety_get_ts_elapsed(now, hyundai_kona_camera_ts) > 50000U) ||
|
||||
((delta > 0U) && (delta <= 127U))) {
|
||||
hyundai_kona_camera_seen = true;
|
||||
hyundai_kona_camera_counter = msg->data[2];
|
||||
hyundai_kona_camera_ts = now;
|
||||
}
|
||||
}
|
||||
blocked = !valid || safety_rx_checks_invalid || !aol_rx_healthy() || hyundai_kona_host_steering() ||
|
||||
(msg->data[2] != hyundai_kona_camera_counter) ||
|
||||
!hyundai_kona_output_ready(now, false, msg->data[2]);
|
||||
const uint8_t counter = msg->data[2];
|
||||
const uint32_t camera_age = safety_get_ts_elapsed(now, hyundai_kona_camera_ts);
|
||||
const uint8_t delta = (uint8_t)(counter - hyundai_kona_camera_counter);
|
||||
const bool advancing = (delta > 0U) && (delta <= 127U);
|
||||
const bool consecutive = hyundai_kona_camera_seen && (delta == 1U) && (camera_age <= 20000U);
|
||||
blocked = !hyundai_kona_lfa_valid(msg) || safety_rx_checks_invalid || !aol_rx_healthy() ||
|
||||
(hyundai_kona_camera_seen && (camera_age <= 50000U) && !advancing);
|
||||
if (!blocked) {
|
||||
hyundai_kona_track_output(now, false, msg->data[2]);
|
||||
hyundai_kona_camera_counter = counter;
|
||||
hyundai_kona_camera_seen = true;
|
||||
hyundai_kona_camera_ts = now;
|
||||
|
||||
const bool authority = hyundai_kona_host_steering();
|
||||
if (!authority) {
|
||||
hyundai_kona_slot_owned = false;
|
||||
}
|
||||
if (authority && consecutive && hyundai_kona_pending &&
|
||||
(safety_get_ts_elapsed(now, hyundai_kona_pending_ts) <= 20000U)) {
|
||||
CANPacket_t candidate = hyundai_kona_pending_msg;
|
||||
const uint8_t source_delta = (uint8_t)(counter - candidate.data[2]);
|
||||
const uint8_t camera_grade = (msg->data[4] >> 6U) | ((msg->data[5] & 1U) << 2U);
|
||||
const bool camera_warning = (camera_grade >= 4U) || ((msg->data[7] & 0xF0U) != 0U);
|
||||
if (camera_warning) {
|
||||
candidate.data[4] = (candidate.data[4] & 0x3FU) | (msg->data[4] & 0xC0U);
|
||||
candidate.data[5] = (candidate.data[5] & 0xFEU) | (msg->data[5] & 0x01U);
|
||||
candidate.data[7] = (candidate.data[7] & 0x0FU) | (msg->data[7] & 0xF0U);
|
||||
}
|
||||
const unsigned int raw_torque = (((unsigned int)candidate.data[6] & 0xFU) << 7U) | (candidate.data[5] >> 1U);
|
||||
const int torque = (int)raw_torque - 1024;
|
||||
if ((source_delta <= 2U) &&
|
||||
!safety_max_limit_check(torque, HYUNDAI_CANFD_STEER_MAX_TORQUE, -HYUNDAI_CANFD_STEER_MAX_TORQUE)) {
|
||||
if (GET_BIT(&candidate, 52U)) {
|
||||
const int max_torque = SAFETY_MAX(desired_torque_last, 0) + HYUNDAI_CANFD_STEER_MAX_RATE_UP;
|
||||
const int min_torque = SAFETY_MIN(desired_torque_last, 0) - HYUNDAI_CANFD_STEER_MAX_RATE_UP;
|
||||
const unsigned int raw = (unsigned int)(SAFETY_CLAMP(torque, min_torque, max_torque) + 1024);
|
||||
candidate.data[5] = (candidate.data[5] & 0x01U) | (uint8_t)((raw & 0x7FU) << 1U);
|
||||
candidate.data[6] = (candidate.data[6] & 0xF0U) | (uint8_t)(raw >> 7U);
|
||||
}
|
||||
candidate.data[2] = counter;
|
||||
const uint16_t checksum = hyundai_common_canfd_compute_checksum(&candidate) ^ 0x041DU;
|
||||
candidate.data[0] = (uint8_t)checksum;
|
||||
candidate.data[1] = (uint8_t)(checksum >> 8U);
|
||||
hyundai_kona_emitting = true;
|
||||
*replaced = safety_tx_hook(&candidate);
|
||||
hyundai_kona_emitting = false;
|
||||
if (*replaced) {
|
||||
*output = candidate;
|
||||
hyundai_kona_slot_owned = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
hyundai_kona_pending = false;
|
||||
if (!*replaced) {
|
||||
const bool camera_neutral = ((msg->data[6] & 0x3FU) == 0x08U) && ((msg->data[5] & 0xFEU) == 0U);
|
||||
blocked = (hyundai_kona_slot_owned && !camera_neutral) ||
|
||||
!hyundai_kona_output_ready(now, false, counter);
|
||||
if (!blocked) {
|
||||
if (hyundai_kona_host_output) {
|
||||
desired_torque_last = 0;
|
||||
}
|
||||
hyundai_kona_track_output(now, false, counter);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
hyundai_kona_pending = false;
|
||||
}
|
||||
}
|
||||
return blocked;
|
||||
}
|
||||
#endif
|
||||
|
||||
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
|
||||
static bool hyundai_canfd_tx_hook_checked(const CANPacket_t *msg) {
|
||||
bool tx = false;
|
||||
const bool ordinary_angle_frame = hyundai_ordinary_angle_stock && ((msg->addr == 0x110U) || (msg->addr == 0x362U));
|
||||
bool ordinary_angle_valid = true;
|
||||
const bool stock_angle_hda2 = hyundai_angle_aol_enabled && hyundai_canfd_lka_steer_msg && !hyundai_canfd_ccnc_ev_long;
|
||||
const bool independent_command = hyundai_angle_aol_enabled &&
|
||||
((msg->addr == 0x50U) || (msg->addr == 0x110U) ||
|
||||
((msg->addr == 0x12AU) && !hyundai_canfd_angle_observed_adas) || (msg->addr == 0xCBU));
|
||||
@@ -1319,9 +1398,18 @@ static bool hyundai_canfd_tx_hook(const CANPacket_t *msg) {
|
||||
ordinary_angle_valid &= (delta > 0U) && (delta <= 127U);
|
||||
}
|
||||
} else {
|
||||
if (stock_angle_hda2) {
|
||||
const uint32_t xor_out = (GET_LEN(msg) == 16U) ? 0x041DU : 0U;
|
||||
ordinary_angle_valid = hyundai_ordinary_angle_owner_current() &&
|
||||
(hyundai_canfd_get_checksum(msg) == (hyundai_common_canfd_compute_checksum(msg) ^ xor_out));
|
||||
}
|
||||
hyundai_ordinary_angle_release();
|
||||
}
|
||||
}
|
||||
if (stock_angle_hda2 && ((msg->addr == 0x2A4U) || (msg->addr == 0x362U))) {
|
||||
ordinary_angle_valid = hyundai_ordinary_angle_owner_current() &&
|
||||
(hyundai_canfd_get_checksum(msg) == hyundai_common_canfd_compute_checksum(msg));
|
||||
}
|
||||
if (hyundai_ordinary_angle_stock && !hyundai_angle_aol_enabled) {
|
||||
// Core whitelisting precedes this hook; relay is its only final denial.
|
||||
ordinary_angle_valid = !relay_malfunction;
|
||||
@@ -1359,7 +1447,7 @@ static bool hyundai_canfd_tx_hook(const CANPacket_t *msg) {
|
||||
if (hyundai_angle_aol_enabled && independent_command && !tx) {
|
||||
hyundai_ordinary_angle_release();
|
||||
}
|
||||
#ifdef ALLOW_DEBUG
|
||||
#if defined(ALLOW_DEBUG) && !defined(STM32F4)
|
||||
if (hyundai_kona_idle_handoff && (msg->addr == 0x12AU) && tx && !relay_malfunction) {
|
||||
hyundai_kona_track_output(microsecond_timer_get(), true, msg->data[2]);
|
||||
}
|
||||
@@ -1367,6 +1455,24 @@ static bool hyundai_canfd_tx_hook(const CANPacket_t *msg) {
|
||||
return tx;
|
||||
}
|
||||
|
||||
static bool hyundai_canfd_tx_hook(const CANPacket_t *msg) {
|
||||
#if defined(ALLOW_DEBUG) && !defined(STM32F4)
|
||||
bool allowed = true;
|
||||
if (hyundai_kona_idle_handoff && (msg->addr == 0x12AU)) {
|
||||
const uint32_t now = microsecond_timer_get();
|
||||
allowed = hyundai_kona_emitting && !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
|
||||
#if defined(ALLOW_DEBUG) && !defined(STM32F4)
|
||||
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;
|
||||
@@ -1866,8 +1972,8 @@ static safety_config hyundai_canfd_init_validated(uint16_t supplied_param) {
|
||||
{0x1DA, 1, 32, .check_relay = false},
|
||||
};
|
||||
static const CanMsg ioniq6_long_lkas_alt_tx_msgs[] = {
|
||||
{0x110, 0, 32, .check_relay = true, .disable_static_blocking = true},
|
||||
{0x362, 0, 32, .check_relay = true, .disable_static_blocking = true},
|
||||
{0x110, 0, 32, .check_relay = true},
|
||||
{0x362, 0, 32, .check_relay = true},
|
||||
{0x12A, 1, 16, .check_relay = false},
|
||||
{0x1E0, 1, 16, .check_relay = false},
|
||||
{0x1A0, 1, 32, .check_relay = true, .check_relay_immediately = true},
|
||||
@@ -2314,48 +2420,46 @@ static safety_config hyundai_canfd_init_validated(uint16_t supplied_param) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
static safety_config hyundai_canfd_init(uint16_t param) {
|
||||
static safety_config hyundai_canfd_init(uint16_t raw_param) {
|
||||
hyundai_daw_init(true, false);
|
||||
hyundai_canfd_reset_ioniq6_state();
|
||||
hyundai_ordinary_angle_reset();
|
||||
#ifdef ALLOW_DEBUG
|
||||
hyundai_kona_idle_handoff = (param == 0x1C0CU) && (alternative_experience == 32);
|
||||
#if defined(ALLOW_DEBUG) && !defined(STM32F4) && !defined(PANDA_BODY)
|
||||
hyundai_kona_idle_handoff = (raw_param == 0x1C0CU) && (alternative_experience == 32);
|
||||
hyundai_kona_camera_seen = false;
|
||||
hyundai_kona_output_seen = false;
|
||||
if ((param == 0x1C0CU) && !hyundai_kona_idle_handoff) {
|
||||
return (safety_config){.disable_forwarding = true};
|
||||
}
|
||||
if (hyundai_kona_idle_handoff) {
|
||||
param = 0x0C0CU;
|
||||
}
|
||||
hyundai_kona_pending = false;
|
||||
hyundai_kona_emitting = false;
|
||||
hyundai_kona_slot_owned = false;
|
||||
const bool kona_profile_valid = (raw_param != 0x1C0CU) || hyundai_kona_idle_handoff;
|
||||
const uint16_t param = hyundai_kona_idle_handoff ? 0x0C0CU : raw_param;
|
||||
const bool valid = !GET_FLAG(param, 32768U) || (param == 0x8015U) || (param == 0x8095U) ||
|
||||
(param == 0x8815U) || (param == 0x8895U) ||
|
||||
hyundai_canfd_gv60_long_param(param);
|
||||
#else
|
||||
if (param == 0x1C0CU) {
|
||||
return (safety_config){.disable_forwarding = true};
|
||||
}
|
||||
const bool kona_profile_valid = raw_param != 0x1C0CU;
|
||||
const uint16_t param = raw_param;
|
||||
const bool valid = !GET_FLAG(param, 32768U);
|
||||
#endif
|
||||
safety_config ret = {0};
|
||||
safety_config ret = {.disable_forwarding = !kona_profile_valid};
|
||||
const bool marker_valid = GET_FLAG(param, 16384U) || !GET_FLAG(param, 2048U) ||
|
||||
hyundai_canfd_stock_torque_aol_param(param) ||
|
||||
#ifdef ALLOW_DEBUG
|
||||
(hyundai_canfd_torque_long_aol_param(param) && ((unsigned int)alternative_experience == 32U)) ||
|
||||
#endif
|
||||
(param == 0x8815U) || (param == 0x8895U);
|
||||
if (valid && marker_valid) {
|
||||
if (kona_profile_valid && valid && marker_valid) {
|
||||
ret = hyundai_canfd_init_validated(param);
|
||||
const bool daw_profile = (param == 0x0011U) || (param == 0x0091U) || (param == 0x0811U) || (param == 0x0891U) ||
|
||||
(param == 0x8015U) || (param == 0x8095U) || (param == 0x8815U) || (param == 0x8895U);
|
||||
ret = hyundai_daw_configure(ret, true, daw_profile);
|
||||
#ifdef ALLOW_DEBUG
|
||||
#if defined(ALLOW_DEBUG) && !defined(STM32F4)
|
||||
if (hyundai_kona_idle_handoff) {
|
||||
static CanMsg kona_tx[64];
|
||||
if (hyundai_canfd_angle_aol_capacity(&ret)) {
|
||||
for (int i = 0; i < ret.tx_msgs_len; i++) {
|
||||
kona_tx[i] = ret.tx_msgs[i];
|
||||
if (kona_tx[i].addr == 0x12AU) {
|
||||
if (kona_tx[i].addr == 0x12A) {
|
||||
kona_tx[i].disable_static_blocking = true;
|
||||
}
|
||||
}
|
||||
@@ -2373,8 +2477,10 @@ const safety_hooks hyundai_canfd_hooks = {
|
||||
.optional_rx = hyundai_canfd_optional_rx_hook,
|
||||
.tx = hyundai_canfd_tx_hook,
|
||||
.fwd = hyundai_canfd_fwd_hook,
|
||||
#ifdef ALLOW_DEBUG
|
||||
.fwd_packet = hyundai_kona_camera_fwd,
|
||||
#if defined(ALLOW_DEBUG) && !defined(STM32F4)
|
||||
.fwd_packet = hyundai_kona_camera_without_slot,
|
||||
.stage_tx = hyundai_kona_stage_tx,
|
||||
.fwd_output = hyundai_kona_camera_output,
|
||||
#endif
|
||||
.get_counter = hyundai_canfd_get_counter,
|
||||
.get_checksum = hyundai_canfd_get_checksum,
|
||||
|
||||
@@ -300,14 +300,15 @@ static safety_config subaru_init(uint16_t raw_param) {
|
||||
param &= ~4096U;
|
||||
}
|
||||
#ifdef ALLOW_DEBUG
|
||||
const bool avh = ((param == 1169U) || (param == 1425U)) &&
|
||||
const bool avh = ((param == 1169U) || (param == 1425U) || (param == 1041U) || (param == 3089U)) &&
|
||||
(((unsigned int)alternative_experience == 0U) || ((unsigned int)alternative_experience == 32U));
|
||||
#else
|
||||
const bool avh = false;
|
||||
#endif
|
||||
const bool stop_start = ((param == 401U) || (param == 465U) || (avh && (param == 1425U))) &&
|
||||
(((unsigned int)alternative_experience == 0U) || ((unsigned int)alternative_experience == 32U));
|
||||
const uint16_t base_param = stop_start ? ((param == 465U) ? 209U : 145U) : (avh ? 145U : param);
|
||||
const uint16_t base_param = stop_start ? ((param == 465U) ? 209U : 145U) : (avh ? (param & ~1024U) : param);
|
||||
const bool sibling_hud = (base_param == 2065U);
|
||||
static const CanMsg SUBARU_TX_MSGS[] = {
|
||||
SUBARU_BASE_TX_MSGS(SUBARU_MAIN_BUS, MSG_SUBARU_ES_LKAS)
|
||||
SUBARU_COMMON_TX_MSGS(SUBARU_MAIN_BUS)
|
||||
@@ -361,6 +362,10 @@ static safety_config subaru_init(uint16_t raw_param) {
|
||||
{0x390U, SUBARU_ALT_BUS, 8, .check_relay = false},
|
||||
};
|
||||
|
||||
static const CanMsg SUBARU_SIBLING_AVH_TX_MSGS[] = {
|
||||
SUBARU_GEN2_ANGLE_TX_MSGS(SUBARU_MAIN_BUS)
|
||||
{0x6BBU, SUBARU_ALT_BUS, 8, .check_relay = false},
|
||||
};
|
||||
static const CanMsg SUBARU_AVH_TX_MSGS[] = {
|
||||
SUBARU_GEN2_ANGLE_TX_MSGS(SUBARU_MAIN_BUS)
|
||||
{MSG_SUBARU_ES_LKAS_Alert, SUBARU_MAIN_BUS, 8, .check_relay = true},
|
||||
@@ -401,7 +406,7 @@ static safety_config subaru_init(uint16_t raw_param) {
|
||||
subaru_fixed_angle_limits = GET_FLAG(param, SUBARU_PARAM_FIXED_ANGLE);
|
||||
subaru_angle_invalid = (subaru_lkas_angle && (base_param != (SUBARU_PARAM_GEN2 | SUBARU_PARAM_LKAS_ANGLE)) &&
|
||||
(base_param != (SUBARU_PARAM_GEN2 | SUBARU_PARAM_LKAS_ANGLE | SUBARU_PARAM_FIXED_ANGLE)) &&
|
||||
(base_param != (SUBARU_PARAM_GEN2 | SUBARU_PARAM_LKAS_ANGLE | SUBARU_PARAM_FIXED_ANGLE | SUBARU_PARAM_ANGLE_MAIN_BUS)) && !ascent_alert && !subaru_forester_angle && !subaru_d_platform) ||
|
||||
(base_param != (SUBARU_PARAM_GEN2 | SUBARU_PARAM_LKAS_ANGLE | SUBARU_PARAM_FIXED_ANGLE | SUBARU_PARAM_ANGLE_MAIN_BUS)) && !ascent_alert && !sibling_hud && !subaru_forester_angle && !subaru_d_platform) ||
|
||||
((subaru_fixed_angle_limits || subaru_angle_main_bus) && !subaru_lkas_angle);
|
||||
|
||||
// TODO: re-enable once more work is done on the limits
|
||||
@@ -419,8 +424,8 @@ static safety_config subaru_init(uint16_t raw_param) {
|
||||
subaru_aol_legacy_2025 = legacy_2025;
|
||||
subaru_aol_enabled = ((unsigned int)alternative_experience == 32U) &&
|
||||
((param == 209U) || (param == 465U) || (param == 16U) || (param == 0U) || (param == 1U) || (param == 17U) || (param == 145U) ||
|
||||
avh || (param == 177U) || (param == 401U) || (param == 8U) || (param == 520U) || (param == 512U) || (param == 2225U));
|
||||
subaru_aol_main_arm = subaru_aol_enabled && ((param == 17U) || impreza_main || subaru_d_platform || legacy_2025 || subaru_early_global_torque);
|
||||
avh || sibling_hud || (param == 177U) || (param == 401U) || (param == 8U) || (param == 520U) || (param == 512U) || (param == 2225U));
|
||||
subaru_aol_main_arm = subaru_aol_enabled && ((base_param == 17U) || sibling_hud || impreza_main || subaru_d_platform || legacy_2025 || subaru_early_global_torque);
|
||||
if (subaru_aol_enabled) {
|
||||
static const AolSafetyPolicy policy = {
|
||||
.reset = subaru_aol_reset,
|
||||
@@ -454,10 +459,11 @@ static safety_config subaru_init(uint16_t raw_param) {
|
||||
ret = subaru_d_platform ? (stop_start ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_OUTBACK_STOP_START_TX_MSGS) :
|
||||
BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_ASCENT_ANGLE_TX_MSGS_LIST)) :
|
||||
subaru_forester_angle ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_FORESTER_ANGLE_TX_MSGS) :
|
||||
avh && (base_param == 17U) ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_SIBLING_AVH_TX_MSGS) :
|
||||
avh ? (stop_start ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_AVH_STOP_START_TX_MSGS) :
|
||||
BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_AVH_TX_MSGS)) :
|
||||
stop_start ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_STOP_START_TX_MSGS) :
|
||||
ascent_alert ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_ASCENT_ALERT_TX_MSGS) :
|
||||
(ascent_alert || sibling_hud) ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_ASCENT_ALERT_TX_MSGS) :
|
||||
legacy_2025 ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_LEGACY_ANGLE_TX_MSGS) :
|
||||
subaru_angle_main_bus ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_ASCENT_ANGLE_TX_MSGS_LIST) :
|
||||
BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_GEN2_ANGLE_TX_MSGS_LIST);
|
||||
@@ -493,7 +499,7 @@ static safety_config subaru_init(uint16_t raw_param) {
|
||||
}
|
||||
ret.rx_checks_len = rx_count;
|
||||
if ((((unsigned int)alternative_experience == 32U) && !subaru_aol_enabled) ||
|
||||
(impreza_main && ((unsigned int)alternative_experience != 32U)) || (early_global_bit && !subaru_early_global_torque)) {
|
||||
(impreza_main && ((unsigned int)alternative_experience != 32U)) || (early_global_bit && !subaru_early_global_torque) || (((param == 1041U) || (param == 3089U)) && !avh)) {
|
||||
ret.tx_msgs = NULL;
|
||||
ret.tx_msgs_len = 0;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include "opendbc/safety/declarations.h"
|
||||
#include "opendbc/safety/modes/tesla_screen_aol.h"
|
||||
#include "opendbc/safety/modes/tesla_speed_sync.h"
|
||||
|
||||
static bool tesla_longitudinal = false;
|
||||
static bool tesla_coop_steering = false;
|
||||
@@ -167,6 +168,7 @@ static void tesla_rx_hook(const CANPacket_t *msg) {
|
||||
}
|
||||
|
||||
tesla_screen_rx(msg, tesla_autopark);
|
||||
tesla_sync_rx(msg);
|
||||
|
||||
if (msg_matches(msg, 0x155U, 0U)) {
|
||||
vehicle_moving = !GET_BIT(msg, 41U); // ESP_vehicleStandstillSts
|
||||
@@ -195,6 +197,11 @@ static void tesla_rx_hook(const CANPacket_t *msg) {
|
||||
}
|
||||
}
|
||||
|
||||
static void tesla_optional_rx(const CANPacket_t *msg) {
|
||||
tesla_screen_optional_rx(msg);
|
||||
tesla_sync_optional_rx(msg);
|
||||
}
|
||||
|
||||
static bool tesla_tx_hook(const CANPacket_t *msg) {
|
||||
const AngleSteeringLimits TESLA_STEERING_LIMITS = {
|
||||
.max_angle = 3600, // 360 deg, EPAS faults above this
|
||||
@@ -290,6 +297,11 @@ static bool tesla_tx_hook(const CANPacket_t *msg) {
|
||||
tx = false;
|
||||
}
|
||||
|
||||
// Speed sync: the wheel frame is decided by its own gate alone (Autopark included); nothing above has a side effect for it
|
||||
if (msg->addr == 0x3C2U) {
|
||||
tx = tesla_sync_tx(msg, tesla_stock_aeb, tesla_autopark, tesla_stock_lkas);
|
||||
}
|
||||
|
||||
return tx;
|
||||
}
|
||||
|
||||
@@ -326,6 +338,7 @@ static safety_config tesla_init(uint16_t param) {
|
||||
};
|
||||
|
||||
static const CanMsg TESLA_M3_Y_LONG_TX_MSGS[] = {
|
||||
{0x3C2, 1, 8, .check_relay = false}, // speed sync: gated single-wheel-step capability
|
||||
{0x488, 0, 4, .check_relay = true, .disable_static_blocking = true}, // DAS_steeringControl
|
||||
{0x2b9, 0, 8, .check_relay = true, .disable_static_blocking = true}, // DAS_control
|
||||
{0x27D, 0, 3, .check_relay = true, .disable_static_blocking = true}, // APS_eacMonitor
|
||||
@@ -336,7 +349,8 @@ static safety_config tesla_init(uint16_t param) {
|
||||
#ifdef ALLOW_DEBUG
|
||||
tesla_longitudinal = GET_FLAG(param, 1U);
|
||||
#endif
|
||||
tesla_screen_configure(param);
|
||||
tesla_screen_configure(tesla_sync_base_param(param));
|
||||
tesla_sync_configure(param, tesla_longitudinal);
|
||||
tesla_stock_aeb = false;
|
||||
tesla_stock_lkas = false;
|
||||
tesla_stock_lkas_prev = false;
|
||||
@@ -369,7 +383,7 @@ static safety_config tesla_init(uint16_t param) {
|
||||
const safety_hooks tesla_hooks = {
|
||||
.init = tesla_init,
|
||||
.rx = tesla_rx_hook,
|
||||
.optional_rx = tesla_screen_optional_rx,
|
||||
.optional_rx = tesla_optional_rx,
|
||||
.tx = tesla_tx_hook,
|
||||
.fwd = tesla_fwd_hook,
|
||||
.get_counter = tesla_get_counter,
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
#pragma once
|
||||
// Speed sync: experimental wheel-only capability. No press/tilt/stalk authority.
|
||||
// Disabled unless the separate debug-only flag AND longitudinal mode are set.
|
||||
static bool tesla_sync_enabled = false;
|
||||
static bool tesla_sync_seen = false;
|
||||
static bool tesla_sync_di_seen = false;
|
||||
static bool tesla_sync_di_valid = false;
|
||||
static bool tesla_sync_neutral = false;
|
||||
static bool tesla_sync_blocked = false;
|
||||
static bool tesla_sync_pending = false;
|
||||
static bool tesla_sync_drive = false;
|
||||
static bool tesla_sync_occupant = false;
|
||||
static bool tesla_sync_native_active = false;
|
||||
static uint8_t tesla_sync_template[8];
|
||||
static uint32_t tesla_sync_wheel_ts = 0U;
|
||||
static uint32_t tesla_sync_di_ts = 0U;
|
||||
static uint32_t tesla_sync_last_template = 0U;
|
||||
// A request the Tesla never answered is released after this long, so the host
|
||||
// can try again instead of waiting for the driver to change the speed.
|
||||
#define TESLA_SYNC_PENDING_TIMEOUT_US 800000U
|
||||
static unsigned int tesla_sync_steps = 0U;
|
||||
// Rate limit instead of a per-session cap: a burst of up to 30 requests, then
|
||||
// one more every second. Normal syncing never runs out; a runaway host is held to
|
||||
// one request per second instead of being stopped for the rest of the drive.
|
||||
#define TESLA_SYNC_TOKENS_MAX 30U
|
||||
#define TESLA_SYNC_TOKEN_REFILL_US 1000000U
|
||||
static unsigned int tesla_sync_tokens = TESLA_SYNC_TOKENS_MAX;
|
||||
static uint32_t tesla_sync_refill_ts = 0U;
|
||||
static int tesla_sync_speed = 0;
|
||||
static unsigned int tesla_sync_units = 0U;
|
||||
static unsigned int tesla_sync_sent_units = 0U;
|
||||
|
||||
static bool tesla_sync_wheel_neutral(const uint8_t *d) {
|
||||
return ((d[0] & 3U) == 1U) &&
|
||||
(((d[0] >> 3U) & 3U) == 1U) && (((d[0] >> 5U) & 3U) == 1U) &&
|
||||
((d[1] & 3U) == 1U) && (((d[1] >> 2U) & 3U) == 1U) &&
|
||||
(((d[1] >> 4U) & 3U) == 1U) && (((d[1] >> 6U) & 3U) == 1U) &&
|
||||
((d[2] & 63U) == 0U) && ((d[3] & 63U) == 0U) && ((d[4] & 15U) == 0U);
|
||||
}
|
||||
|
||||
static void tesla_sync_configure(uint16_t param, bool longitudinal) {
|
||||
tesla_sync_enabled = false;
|
||||
#ifdef ALLOW_DEBUG
|
||||
tesla_sync_enabled = longitudinal && GET_FLAG(param, 4096U);
|
||||
#else
|
||||
(void)param;
|
||||
(void)longitudinal;
|
||||
#endif
|
||||
tesla_sync_seen = false;
|
||||
tesla_sync_di_seen = false;
|
||||
tesla_sync_di_valid = false;
|
||||
tesla_sync_neutral = false;
|
||||
tesla_sync_blocked = false;
|
||||
tesla_sync_pending = false;
|
||||
tesla_sync_drive = false;
|
||||
tesla_sync_occupant = false;
|
||||
tesla_sync_native_active = false;
|
||||
tesla_sync_wheel_ts = 0U;
|
||||
tesla_sync_di_ts = 0U;
|
||||
tesla_sync_last_template = 0U;
|
||||
tesla_sync_steps = 0U;
|
||||
tesla_sync_tokens = TESLA_SYNC_TOKENS_MAX;
|
||||
tesla_sync_refill_ts = microsecond_timer_get();
|
||||
}
|
||||
|
||||
static void tesla_sync_refill(uint32_t now) {
|
||||
uint32_t elapsed = safety_get_ts_elapsed(now, tesla_sync_refill_ts);
|
||||
while ((tesla_sync_tokens < TESLA_SYNC_TOKENS_MAX) && (elapsed >= TESLA_SYNC_TOKEN_REFILL_US)) {
|
||||
tesla_sync_tokens++;
|
||||
elapsed -= TESLA_SYNC_TOKEN_REFILL_US;
|
||||
tesla_sync_refill_ts += TESLA_SYNC_TOKEN_REFILL_US;
|
||||
}
|
||||
if (tesla_sync_tokens >= TESLA_SYNC_TOKENS_MAX) {
|
||||
tesla_sync_refill_ts = now;
|
||||
}
|
||||
}
|
||||
|
||||
static void tesla_sync_optional_rx(const CANPacket_t *msg) {
|
||||
if (tesla_sync_enabled && msg_matches(msg, 0x3C2U, 1U)) {
|
||||
if (GET_LEN(msg) != 8U) {
|
||||
tesla_sync_seen = false;
|
||||
} else {
|
||||
unsigned int mux = msg->data[0] & 3U;
|
||||
if ((mux == 2U) || (mux == 3U)) {
|
||||
tesla_sync_seen = false;
|
||||
tesla_sync_neutral = false;
|
||||
} else if (mux == 1U) {
|
||||
tesla_sync_seen = true;
|
||||
tesla_sync_wheel_ts = microsecond_timer_get();
|
||||
tesla_sync_neutral = tesla_sync_wheel_neutral(msg->data);
|
||||
if (tesla_sync_neutral) {
|
||||
for (unsigned int i = 0U; i < 8U; i++) {
|
||||
tesla_sync_template[i] = msg->data[i];
|
||||
}
|
||||
}
|
||||
// Driver input during a request no longer latches the sync off. The
|
||||
// request stays open until the speed changes or it times out, and the
|
||||
// host recomputes from the observed speed.
|
||||
} else {
|
||||
// Index 0 carries no wheel input.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void tesla_sync_rx(const CANPacket_t *msg) {
|
||||
if (tesla_sync_enabled) {
|
||||
if (msg_matches(msg, 0x118U, 0U, 8U)) {
|
||||
tesla_sync_drive = ((msg->data[2] >> 5U) & 7U) == 4U;
|
||||
}
|
||||
if (msg_matches(msg, 0x311U, 0U, 7U)) {
|
||||
// Occupant status is already part of the validated required RX set.
|
||||
// Exact bit positions are shared with tesla_screen_rx.
|
||||
tesla_sync_occupant = GET_BIT(msg, 13U) && !GET_BIT(msg, 28U);
|
||||
}
|
||||
if (msg_matches(msg, 0x286U, 0U, 8U)) {
|
||||
static unsigned int tesla_sync_counter = 0U;
|
||||
unsigned int counter = msg->data[1] & 15U;
|
||||
bool advancing = !tesla_sync_di_seen || (((counter - tesla_sync_counter) & 15U) == 1U);
|
||||
tesla_sync_counter = counter;
|
||||
tesla_sync_di_seen = true;
|
||||
tesla_sync_di_valid = advancing;
|
||||
if (advancing) {
|
||||
unsigned int state = (msg->data[1] >> 4U) & 7U;
|
||||
int speed = ((msg->data[2] << 1U) | (msg->data[1] >> 7U)); // half display units
|
||||
unsigned int units = msg->data[3] & 1U;
|
||||
tesla_sync_di_ts = microsecond_timer_get();
|
||||
tesla_sync_native_active = (state == 2U) || (state == 4U);
|
||||
if ((state == 0U) || (state == 1U)) {
|
||||
tesla_sync_pending = false;
|
||||
tesla_sync_blocked = false;
|
||||
tesla_sync_steps = 0U;
|
||||
}
|
||||
if (tesla_sync_pending && (units != tesla_sync_sent_units)) {
|
||||
tesla_sync_blocked = true;
|
||||
}
|
||||
if (tesla_sync_pending && (speed != tesla_sync_speed)) {
|
||||
// Feedback releases one request; it does not establish its origin.
|
||||
// The host must recompute direction from this newly observed speed.
|
||||
tesla_sync_pending = false;
|
||||
}
|
||||
tesla_sync_speed = speed;
|
||||
tesla_sync_units = units;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static bool tesla_sync_tx(const CANPacket_t *msg, bool stock_aeb, bool autopark, bool stock_lkas) {
|
||||
static uint32_t tesla_sync_sent_ts = 0U;
|
||||
uint32_t now = microsecond_timer_get();
|
||||
if (tesla_sync_pending && (safety_get_ts_elapsed(now, tesla_sync_sent_ts) > TESLA_SYNC_PENDING_TIMEOUT_US)) {
|
||||
tesla_sync_pending = false;
|
||||
}
|
||||
tesla_sync_refill(now);
|
||||
bool valid = tesla_sync_enabled && msg_matches(msg, 0x3C2U, 1U, 8U) &&
|
||||
controls_allowed && heartbeat_engaged && aol_rx_healthy() && !relay_malfunction &&
|
||||
vehicle_moving && !brake_pressed && !stock_aeb && !autopark && !stock_lkas &&
|
||||
tesla_sync_drive && tesla_sync_occupant && tesla_sync_native_active && tesla_sync_di_valid &&
|
||||
tesla_sync_seen && tesla_sync_neutral && !tesla_sync_blocked && !tesla_sync_pending &&
|
||||
(tesla_sync_tokens > 0U) && (tesla_sync_speed > 2) && (tesla_sync_speed < 508) &&
|
||||
(safety_get_ts_elapsed(now, tesla_sync_wheel_ts) <= 250000U) &&
|
||||
(safety_get_ts_elapsed(now, tesla_sync_di_ts) <= 250000U) &&
|
||||
((tesla_sync_steps == 0U) || (tesla_sync_wheel_ts != tesla_sync_last_template));
|
||||
unsigned int ticks = msg->data[3] & 63U;
|
||||
// One click (+-1), or one fast flick (+-5) that moves the Tesla to the next
|
||||
// multiple of 5. Both are a single frame, as the driver's own wheel sends.
|
||||
valid = valid && ((ticks == 1U) || (ticks == 63U) || (ticks == 5U) || (ticks == 59U));
|
||||
for (unsigned int i = 0U; i < 8U; i++) {
|
||||
uint8_t mask = (i == 3U) ? 0xC0U : 0xFFU;
|
||||
valid = valid && ((msg->data[i] & mask) == (tesla_sync_template[i] & mask));
|
||||
}
|
||||
if (valid) {
|
||||
tesla_sync_pending = true;
|
||||
tesla_sync_sent_units = tesla_sync_units;
|
||||
tesla_sync_last_template = tesla_sync_wheel_ts;
|
||||
tesla_sync_sent_ts = now;
|
||||
tesla_sync_tokens--;
|
||||
if (tesla_sync_steps < 0xFFFFU) {
|
||||
tesla_sync_steps++; // only marks that a request was sent this session
|
||||
}
|
||||
}
|
||||
return valid;
|
||||
}
|
||||
|
||||
#ifdef ALLOW_DEBUG
|
||||
static bool tesla_sync_param_valid(uint16_t param) {
|
||||
// Scroll speed sync is 4096 on a word with LONG_CONTROL: base 1/257, screen AOL 513/769/1537/1793 and ordinary AOL 2049/2305/3073/3329.
|
||||
const uint16_t base = (uint16_t)(param & ~4096U);
|
||||
return GET_FLAG(param, 4096U) &&
|
||||
((base == 1U) || (base == 257U) || (base == 513U) || (base == 769U) || (base == 1537U) || (base == 1793U) ||
|
||||
(base == 2049U) || (base == 2305U) || (base == 3073U) || (base == 3329U));
|
||||
}
|
||||
#endif
|
||||
|
||||
// A word outside the base Tesla namespace: screen or ordinary AOL, or one of the scroll speed sync words.
|
||||
// RELEASE has no speed sync word.
|
||||
static bool tesla_extended_param_valid(uint16_t param) {
|
||||
bool valid = tesla_screen_param_valid(param);
|
||||
#ifdef ALLOW_DEBUG
|
||||
valid = valid || tesla_sync_param_valid(param);
|
||||
#endif
|
||||
return valid;
|
||||
}
|
||||
|
||||
// Speed sync rides on top of a base, screen AOL or ordinary AOL word: that word configures everything else.
|
||||
static uint16_t tesla_sync_base_param(uint16_t param) {
|
||||
uint16_t base = param;
|
||||
#ifdef ALLOW_DEBUG
|
||||
if (tesla_sync_param_valid(param)) {
|
||||
base = (uint16_t)(param & ~4096U);
|
||||
}
|
||||
#endif
|
||||
return base;
|
||||
}
|
||||
@@ -366,6 +366,55 @@ int safety_fwd_packet_hook(const CANPacket_t *msg) {
|
||||
return destination_bus;
|
||||
}
|
||||
|
||||
#if !defined(STM32F4) && (defined(ALLOW_DEBUG) || !defined(STM32H7))
|
||||
bool safety_uses_camera_slot(const CANPacket_t *msg) {
|
||||
#ifdef ALLOW_DEBUG
|
||||
return (current_safety_mode == SAFETY_HYUNDAI_CANFD) && hyundai_kona_idle_handoff && (msg->addr == 0x12AU);
|
||||
#else
|
||||
(void)msg;
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool safety_camera_release_current(const CANPacket_t *msg, uint32_t now) {
|
||||
#ifdef ALLOW_DEBUG
|
||||
return safety_uses_camera_slot(msg) && hyundai_kona_camera_release_current(msg, now);
|
||||
#else
|
||||
(void)msg;
|
||||
(void)now;
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
uint32_t safety_camera_release_delay(const CANPacket_t *msg, uint32_t now) {
|
||||
#ifdef ALLOW_DEBUG
|
||||
const uint32_t age = safety_get_ts_elapsed(now, hyundai_kona_output_ts);
|
||||
return ((age >= 9000U) && (age < 10000U) && safety_camera_release_current(msg, now)) ? (10000U - age) : 0U;
|
||||
#else
|
||||
(void)msg;
|
||||
(void)now;
|
||||
return 0U;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool safety_stage_tx_hook(const CANPacket_t *msg) {
|
||||
return !relay_malfunction && (current_hooks->stage_tx != NULL) && current_hooks->stage_tx(msg);
|
||||
}
|
||||
|
||||
int safety_fwd_output_hook(const CANPacket_t *msg, CANPacket_t *output, bool *replaced) {
|
||||
int destination;
|
||||
if (current_hooks->fwd_output != NULL) {
|
||||
destination = safety_fwd_hook(msg->bus, msg->addr);
|
||||
if ((destination >= 0) && current_hooks->fwd_output(msg, output, replaced)) {
|
||||
destination = -1;
|
||||
}
|
||||
} else {
|
||||
destination = safety_fwd_packet_hook(msg);
|
||||
}
|
||||
return destination;
|
||||
}
|
||||
#endif
|
||||
|
||||
// 1Hz safety function called by main. Now just a check for lagging safety messages
|
||||
void safety_tick(void) {
|
||||
const uint8_t MAX_MISSED_MSGS = 10U;
|
||||
@@ -549,7 +598,7 @@ int set_safety_hooks(uint16_t mode, uint16_t param) {
|
||||
current_safety_param = 0;
|
||||
continue;
|
||||
}
|
||||
if ((mode == SAFETY_TESLA) && (((param & ~(TESLA_HW1_FLAG | 257U)) != 0U) || ((param & TESLA_HW1_FLAG) && (param & 256U))) && !tesla_screen_param_valid(param)) {
|
||||
if ((mode == SAFETY_TESLA) && (((param & ~(TESLA_HW1_FLAG | 257U)) != 0U) || ((param & TESLA_HW1_FLAG) && (param & 256U))) && !tesla_extended_param_valid(param)) {
|
||||
current_hooks = &nooutput_hooks;
|
||||
current_safety_mode = SAFETY_NOOUTPUT;
|
||||
current_safety_param = 0;
|
||||
|
||||
@@ -443,6 +443,15 @@ unsigned int tesla_preap_test_config_read(uint8_t *out) {
|
||||
return tesla_preap_pedal_config_read(out);
|
||||
}
|
||||
|
||||
// Tesla scroll speed sync state for native tests: one bit per flag in declaration
|
||||
// order, whether a request was sent this session, and the request tokens in bits 16-23.
|
||||
unsigned int safety_test_tesla_sync_state(void) {
|
||||
return (tesla_sync_enabled ? 1U : 0U) | (tesla_sync_seen ? 2U : 0U) | (tesla_sync_di_seen ? 4U : 0U) |
|
||||
(tesla_sync_di_valid ? 8U : 0U) | (tesla_sync_neutral ? 16U : 0U) | (tesla_sync_blocked ? 32U : 0U) |
|
||||
(tesla_sync_pending ? 64U : 0U) | (tesla_sync_drive ? 128U : 0U) | (tesla_sync_occupant ? 256U : 0U) |
|
||||
(tesla_sync_native_active ? 512U : 0U) | ((tesla_sync_steps != 0U) ? 1024U : 0U) | (tesla_sync_tokens << 16U);
|
||||
}
|
||||
|
||||
// A real foreign catalog must fail closed instead of acquiring the GV60 heartbeat.
|
||||
bool safety_test_hyundai_gv60_catalog_rejection(bool alternate) {
|
||||
bool rejected = false;
|
||||
|
||||
@@ -11,6 +11,11 @@ SAFETY_UNUSED(safety_rx_hook);
|
||||
SAFETY_UNUSED(safety_tx_hook);
|
||||
SAFETY_UNUSED(safety_fwd_hook);
|
||||
SAFETY_UNUSED(safety_fwd_packet_hook);
|
||||
SAFETY_UNUSED(safety_uses_camera_slot);
|
||||
SAFETY_UNUSED(safety_camera_release_current);
|
||||
SAFETY_UNUSED(safety_camera_release_delay);
|
||||
SAFETY_UNUSED(safety_stage_tx_hook);
|
||||
SAFETY_UNUSED(safety_fwd_output_hook);
|
||||
SAFETY_UNUSED(safety_tick);
|
||||
SAFETY_UNUSED(set_safety_hooks);
|
||||
// Exported to Panda's USB status handler and the native safety test library.
|
||||
|
||||
@@ -20,6 +20,7 @@ class TestGmSdgmStock(unittest.TestCase):
|
||||
return libsafety_py.make_CANPacket(msg[0], msg[2], msg[1])
|
||||
|
||||
def mode(self, cp):
|
||||
self.safety.set_alternative_experience(0)
|
||||
self.assertEqual(self.safety.set_safety_hooks(CarParams.SafetyModel.gm, cp.safetyConfigs[0].safetyParam), 0)
|
||||
self.safety.init_tests()
|
||||
self.safety.set_timer(1_000_000)
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Accord angle-loop EPS: the panda bounds the 0xE4 angle setpoint by the lateral accel and jerk limits."""
|
||||
import math
|
||||
import re
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
|
||||
from opendbc.car import Bus, gen_empty_fingerprint
|
||||
from opendbc.car.honda.carcontroller import CarController
|
||||
from opendbc.car.honda.interface import CarInterface
|
||||
from opendbc.car.honda.values import CAR, DBC, CarControllerParams, HondaSafetyFlags
|
||||
from opendbc.car.lateral import MAX_LATERAL_ACCEL, get_max_angle_delta_vm, get_max_angle_vm
|
||||
from opendbc.car.structs import CarParams
|
||||
from opendbc.car.vehicle_model import VehicleModel, calc_slip_factor
|
||||
from opendbc.safety.tests.libsafety import libsafety_py
|
||||
from opendbc.safety.tests import test_honda # the module, so its test classes are not collected again here
|
||||
|
||||
P = CarControllerParams
|
||||
ARM = P.ANGLE_ARM
|
||||
DT_US = 10_000 # 0xE4 is sent at 100 Hz
|
||||
SPEEDS = (1.0, 3.0, 5.0, 8.0, 10.0, 12.0, 17.5, 22.0, 26.9, 31.0, 38.0)
|
||||
|
||||
|
||||
def accord_cp():
|
||||
fw = [CarParams.CarFw(ecu=CarParams.Ecu.eps, fwVersion=b"39990-TVA,A16C", address=0x18DA30F1, subAddress=0)]
|
||||
return CarInterface.get_params(CAR.HONDA_ACCORD, gen_empty_fingerprint(), fw, False, False, False)
|
||||
|
||||
|
||||
class TestHondaAccordAngleSetpoint(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.fixture = test_honda.TestHondaBoschAltBrakeSafety('test_spam_cancel_safety_check')
|
||||
self.fixture.setUp()
|
||||
self.safety = self.fixture.safety
|
||||
self.packer = self.fixture.packer
|
||||
self.CP = accord_cp()
|
||||
self.angle_flag = self.CP.safetyConfigs[0].safetyParam
|
||||
self.assertNotEqual(self.angle_flag, 0)
|
||||
self.assertEqual(self.safety.set_safety_hooks(CarParams.SafetyModel.hondaBosch, self.angle_flag | 1), 0)
|
||||
self.safety.init_tests()
|
||||
self.VM = VehicleModel(self.CP)
|
||||
self.params = P(self.CP)
|
||||
self.t = 1_000_000
|
||||
self.safety.set_timer(self.t)
|
||||
|
||||
# ---- helpers
|
||||
def _angle_frame(self, raw, steer_req, arm=ARM, bus=None):
|
||||
values = {"STEER_TORQUE": raw, "STEER_TORQUE_REQUEST": steer_req, "STEER_CONTROL_ARM": arm}
|
||||
return self.packer.make_can_msg_safety("STEERING_CONTROL", self.fixture.STEER_BUS if bus is None else bus, values)
|
||||
|
||||
def _tx(self, raw, steer_req=True, arm=ARM, bus=None):
|
||||
self.t += DT_US
|
||||
self.safety.set_timer(self.t)
|
||||
return self.fixture._tx(self._angle_frame(raw, steer_req, arm, bus))
|
||||
|
||||
def _rx_speed(self, v_ms):
|
||||
self.fixture._rx(self.fixture._speed_msg(v_ms * 3.6))
|
||||
|
||||
def _rx_wheel(self, raw):
|
||||
# STEER_ANGLE is -0.1 deg per count: the raw count equals the 0xE4 raw for the same angle
|
||||
self.fixture._rx(self.packer.make_can_msg_safety("STEERING_SENSORS", self.fixture.PT_BUS, {"STEER_ANGLE": -raw / 10.0}))
|
||||
|
||||
def _settle(self, v_ms, wheel_raw=0):
|
||||
for _ in range(6):
|
||||
self._rx_speed(v_ms)
|
||||
self._rx_wheel(wheel_raw)
|
||||
|
||||
def _panda_max_angle_raw(self, v_ms):
|
||||
# the panda evaluates the model 1 m/s below its slowest speed sample and allows one count of rounding
|
||||
return int(get_max_angle_vm(max(v_ms - 1.0, 1.0), self.VM, self.params) * 10 + 1.0)
|
||||
|
||||
def _panda_max_delta_raw(self, v_ms):
|
||||
return int(get_max_angle_delta_vm(max(v_ms - 1.0, 1.0), self.VM, self.params) * 10 + 1.0)
|
||||
|
||||
def test_stock_profiles_and_incompatible_flag_combinations_reject_angle_frames(self):
|
||||
is_debug = self.safety.set_safety_hooks(CarParams.SafetyModel.allOutput, 0) == 0
|
||||
ordinary = (0, 1, 2, 3, 2082, 2083)
|
||||
invalid = (self.angle_flag | 8, self.angle_flag | 16, self.angle_flag | 128)
|
||||
if not is_debug:
|
||||
invalid += tuple(self.angle_flag | word for word in ordinary if word & 2)
|
||||
for word in ordinary + invalid:
|
||||
with self.subTest(word=word):
|
||||
self.assertEqual(self.safety.set_safety_hooks(CarParams.SafetyModel.hondaBosch, word), 0)
|
||||
self.safety.init_tests()
|
||||
self._settle(10.0)
|
||||
self.safety.set_controls_allowed(True)
|
||||
bus = int(bool(is_debug and word & 2))
|
||||
self.assertFalse(self._tx(10, bus=bus), word)
|
||||
self.assertFalse(self._tx(0, steer_req=False, bus=bus), word)
|
||||
if word in ordinary:
|
||||
self.assertTrue(self._tx(10, arm=0, bus=bus), word)
|
||||
|
||||
def test_flag_preserves_lateral_on_supported_classic_bosch_configurations(self):
|
||||
is_debug = self.safety.set_safety_hooks(CarParams.SafetyModel.allOutput, 0) == 0
|
||||
base_words = (0, 1, 2, 3, 2082, 2083) if is_debug else (0, 1)
|
||||
for base in base_words:
|
||||
with self.subTest(base=base):
|
||||
self.assertEqual(self.safety.set_safety_hooks(CarParams.SafetyModel.hondaBosch, self.angle_flag | base), 0)
|
||||
self.safety.init_tests()
|
||||
self._settle(10.0)
|
||||
self.safety.set_controls_allowed(True)
|
||||
self.assertTrue(self._tx(10, bus=int(bool(base & 2))), base)
|
||||
|
||||
# ---- the model the panda uses is the one openpilot uses
|
||||
def test_vehicle_model_constants_match_openpilot(self):
|
||||
src = (Path(__file__).parents[1] / "modes" / "honda.h").read_text(encoding="utf-8")
|
||||
block = src[src.index("HONDA_ACCORD_ANGLE_PARAMS = {"):]
|
||||
block = block[:block.index("};")]
|
||||
read = {k: float(v) for k, v in re.findall(r"\.(\w+)\s*=\s*(-?[\d.]+)", block)}
|
||||
self.assertAlmostEqual(read["slip_factor"], calc_slip_factor(self.VM), places=12)
|
||||
self.assertAlmostEqual(read["steer_ratio"], self.CP.steerRatio, places=5)
|
||||
self.assertAlmostEqual(read["wheelbase"], self.CP.wheelbase, places=5)
|
||||
self.assertAlmostEqual(MAX_LATERAL_ACCEL, 3.589, places=3)
|
||||
self.assertEqual(self.params.ANGLE_LIMITS.MAX_LATERAL_ACCEL, MAX_LATERAL_ACCEL)
|
||||
|
||||
# ---- lateral acceleration limit
|
||||
def test_setpoint_beyond_the_lateral_accel_limit_is_blocked(self):
|
||||
for v in SPEEDS:
|
||||
limit = self._panda_max_angle_raw(v)
|
||||
if limit > 4000:
|
||||
continue # below ~5 m/s the 400 deg ceiling binds first (covered below)
|
||||
for sign in (-1, 1):
|
||||
self._settle(v)
|
||||
self.safety.set_controls_allowed(True)
|
||||
self.safety.set_desired_angle_last(sign * limit)
|
||||
self.assertTrue(self._tx(sign * limit), (v, sign))
|
||||
self.assertFalse(self._tx(sign * (limit + 1)), (v, sign))
|
||||
# the first blocked frame resets the panda to the wheel; a setpoint this far out stays blocked
|
||||
self.assertFalse(self._tx(sign * (limit + 1)), (v, sign))
|
||||
|
||||
def test_the_old_order_counterexample_is_blocked(self):
|
||||
# 26.9 m/s, wheel held at 42 deg: the old code sent 29.8 deg (5.4 m/s^2) against a 19.8 deg limit
|
||||
v = 26.9
|
||||
self._settle(v, wheel_raw=420)
|
||||
self.safety.set_controls_allowed(True)
|
||||
self.safety.set_desired_angle_last(298)
|
||||
self.assertFalse(self._tx(298))
|
||||
self.assertGreater(298, self._panda_max_angle_raw(v))
|
||||
|
||||
def test_setpoint_beyond_400_deg_is_blocked(self):
|
||||
self._settle(1.0, wheel_raw=4000)
|
||||
self.safety.set_controls_allowed(True)
|
||||
for raw, ok in ((4000, True), (4001, False), (-4000, True), (-4001, False), (4096, False)):
|
||||
self.safety.set_desired_angle_last(raw)
|
||||
self.assertEqual(ok, self._tx(raw), raw)
|
||||
|
||||
# ---- lateral jerk limit
|
||||
def test_step_beyond_the_lateral_jerk_limit_is_blocked(self):
|
||||
for v in SPEEDS:
|
||||
delta = self._panda_max_delta_raw(v)
|
||||
for sign in (-1, 1):
|
||||
for start in (0, 50):
|
||||
if start + delta + 1 > min(self._panda_max_angle_raw(v), 4000):
|
||||
continue
|
||||
self._settle(v, wheel_raw=sign * start)
|
||||
self.safety.set_controls_allowed(True)
|
||||
self.safety.set_desired_angle_last(sign * start)
|
||||
self.assertTrue(self._tx(sign * (start + delta)), (v, sign, start))
|
||||
self.safety.set_desired_angle_last(sign * start)
|
||||
self.assertFalse(self._tx(sign * (start + delta + 1)), (v, sign, start))
|
||||
|
||||
def test_a_blocked_frame_restarts_from_the_wheel(self):
|
||||
v = 20.0
|
||||
self._settle(v, wheel_raw=30)
|
||||
self.safety.set_controls_allowed(True)
|
||||
self.safety.set_desired_angle_last(30)
|
||||
self.assertFalse(self._tx(30 + self._panda_max_delta_raw(v) + 1))
|
||||
self.assertEqual(self.safety.get_desired_angle_last(), 30)
|
||||
self.assertTrue(self._tx(30 + self._panda_max_delta_raw(v)))
|
||||
|
||||
# ---- request off
|
||||
def test_request_off_frames(self):
|
||||
v = 15.0
|
||||
self._settle(v, wheel_raw=-234)
|
||||
for allowed in (True, False):
|
||||
self.safety.set_controls_allowed(allowed)
|
||||
self.assertTrue(self._tx(0, steer_req=False)) # nothing commanded
|
||||
self.assertEqual(self.safety.get_desired_angle_last(), -234)
|
||||
self.assertEqual(allowed, self._tx(-234, steer_req=False)) # hold at the wheel: only while lateral is allowed
|
||||
self.assertFalse(self._tx(-200, steer_req=False)) # anything else is not the wheel
|
||||
self.assertFalse(self._tx(100, steer_req=False))
|
||||
|
||||
def test_request_needs_controls_allowed(self):
|
||||
self._settle(15.0, wheel_raw=0)
|
||||
self.safety.set_controls_allowed(False)
|
||||
self.assertFalse(self._tx(0, steer_req=True))
|
||||
self.assertFalse(self._tx(5, steer_req=True))
|
||||
self.safety.set_controls_allowed(True)
|
||||
self.assertTrue(self._tx(0, steer_req=True))
|
||||
|
||||
def test_engage_from_a_zero_field_starts_at_the_wheel(self):
|
||||
# always-on lateral case: the carcontroller sends a zero field until the request, then starts from the wheel
|
||||
v = 25.0
|
||||
self._settle(v, wheel_raw=150)
|
||||
self.safety.set_controls_allowed(True)
|
||||
for _ in range(5):
|
||||
self.assertTrue(self._tx(0, steer_req=False))
|
||||
self.assertTrue(self._tx(150 + self._panda_max_delta_raw(v), steer_req=True))
|
||||
|
||||
# ---- torque frames (arm 0 or 1) are not angle setpoints
|
||||
def test_torque_frames_are_unaffected(self):
|
||||
self._settle(30.0)
|
||||
self.safety.set_controls_allowed(True)
|
||||
for arm in (0, 1):
|
||||
for raw in (-4096, -1000, 0, 1000, 4096):
|
||||
self.assertTrue(self._tx(raw, steer_req=True, arm=arm), (arm, raw))
|
||||
self.safety.set_controls_allowed(False)
|
||||
self.assertTrue(self._tx(0, steer_req=False, arm=0))
|
||||
self.assertFalse(self._tx(1000, steer_req=True, arm=0))
|
||||
|
||||
# ---- message rate
|
||||
def test_message_rate_limit(self):
|
||||
self._settle(20.0)
|
||||
self.safety.set_controls_allowed(True)
|
||||
blocked = False
|
||||
for _ in range(40): # 40 frames inside one 250 ms window: more than 100 Hz allows
|
||||
blocked |= not self.fixture._tx(self._angle_frame(0, True))
|
||||
self.assertTrue(blocked)
|
||||
|
||||
# ---- the carcontroller's own output is what the panda checks, and it always passes
|
||||
def _controller_frames(self, v_of, wheel_of, desired_of, frames):
|
||||
cc = CarController({Bus.pt: DBC[CAR.HONDA_ACCORD][Bus.pt]}, self.CP)
|
||||
blocked = withheld = 0
|
||||
for i in range(frames):
|
||||
v, wheel = v_of(i), wheel_of(i)
|
||||
wheel_raw = math.floor(-10.0 * wheel + 0.5)
|
||||
self._rx_speed(v)
|
||||
self._rx_wheel(wheel_raw)
|
||||
active = i >= 12 # as on the road, request-off frames come first: they fill the panda's samples
|
||||
CC = SimpleNamespace(actuators=SimpleNamespace(steeringAngleDeg=desired_of(i)), latActive=active, enabled=True)
|
||||
# carState reads the angle off the same STEER_ANGLE counts and the speed off the wheels
|
||||
CS = SimpleNamespace(out=SimpleNamespace(steeringAngleDeg=-wheel_raw / 10.0, vEgoRaw=v,
|
||||
cruiseState=SimpleNamespace(available=True)))
|
||||
_, raw = cc._update_angle(CC, CS)
|
||||
withheld += active and not cc.angle_steer_req
|
||||
blocked += not self._tx(raw, steer_req=cc.angle_steer_req)
|
||||
return blocked, withheld
|
||||
|
||||
def test_carcontroller_output_is_never_blocked(self):
|
||||
self.safety.set_controls_allowed(True)
|
||||
rng = np.random.default_rng(1)
|
||||
cases = {
|
||||
"lane keeping": (lambda i: 28.0, lambda i: 2.0 * math.sin(i / 60.0), lambda i: 3.0 * math.sin(i / 50.0)),
|
||||
"saturating request": (lambda i: 20.0, lambda i: 0.0, lambda i: 300.0 * math.sin(i / 100.0)),
|
||||
"random request": (lambda i: 12.0, lambda i: 10.0 * math.sin(i / 40.0), lambda i: float(rng.uniform(-400, 400))),
|
||||
"tight turn": (lambda i: 4.0, lambda i: min(i * 2.0, 380.0), lambda i: 400.0),
|
||||
"driver past the limit": (lambda i: 26.9, lambda i: min(i * 0.3, 45.0), lambda i: 0.0),
|
||||
"driver yank": (lambda i: 17.5, lambda i: 60.0 * math.sin(i / 8.0), lambda i: 5.0),
|
||||
"braking": (lambda i: max(30.0 - i * 0.03, 2.0), lambda i: 5.0, lambda i: 400.0),
|
||||
"accelerating": (lambda i: min(3.0 + i * 0.03, 35.0), lambda i: 0.0, lambda i: -400.0),
|
||||
}
|
||||
for name, (v_of, wheel_of, desired_of) in cases.items():
|
||||
self.safety.set_controls_allowed(True)
|
||||
blocked, withheld = self._controller_frames(v_of, wheel_of, desired_of, 900)
|
||||
self.assertEqual(0, blocked, name)
|
||||
# the request is withheld only where the wheel is past the limit when it would start: the yank reaches 60 deg
|
||||
# against a 38 deg limit. Everywhere else every frame carries the request.
|
||||
self.assertEqual(name == "driver yank", withheld > 0, (name, withheld))
|
||||
|
||||
|
||||
class TestHondaAngleSetpointOnOtherBosch(unittest.TestCase):
|
||||
"""A radarless or CAN FD Honda has no angle-loop EPS: an armed frame is never sent, and is blocked if it is."""
|
||||
|
||||
def test_armed_frame_is_blocked(self):
|
||||
fixture = test_honda.TestHondaBoschRadarlessSafety('test_spam_cancel_safety_check')
|
||||
fixture.setUp()
|
||||
fixture.safety.set_safety_hooks(CarParams.SafetyModel.hondaBosch, HondaSafetyFlags.RADARLESS)
|
||||
fixture.safety.init_tests()
|
||||
fixture.safety.set_controls_allowed(True)
|
||||
for arm, ok in ((0, True), (1, True), (ARM, False)):
|
||||
# bytes 0-1 zero, STEER_TORQUE_REQUEST set, STEER_CONTROL_ARM in byte 2 bits 3:2
|
||||
packet = libsafety_py.make_CANPacket(0xE4, fixture.STEER_BUS, bytes([0, 0, 0x80 | (arm << 2), 0, 0]))
|
||||
self.assertEqual(ok, fixture._tx(packet), arm)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -221,3 +221,47 @@ class TestHyundaiBlendedStock(unittest.TestCase):
|
||||
self.safety.safety_rx_hook(common.make_msg(0, 0x50, 16))
|
||||
self.assertTrue(self.safety.get_relay_malfunction())
|
||||
self.safety.set_alternative_experience(0)
|
||||
|
||||
def _start_hda2_aol(self):
|
||||
self.safety.init_tests()
|
||||
self.safety.set_alternative_experience(32)
|
||||
self.assertEqual(self.safety.set_safety_hooks(CarParams.SafetyModel.hyundai, 0x2010), 0)
|
||||
self.safety.set_aol_test_heartbeat(True)
|
||||
self.steer_counter = 0
|
||||
self.bus = 1
|
||||
self._refresh_hda2_aol_rx(1_000_000)
|
||||
self.safety.aol_set_host_request(1)
|
||||
|
||||
def _refresh_hda2_aol_rx(self, now):
|
||||
self.safety.set_timer(now)
|
||||
for status in self.safety.rx_status:
|
||||
status.msg_seen = status.valid_checksum = status.valid_quality_flag = True
|
||||
status.last_timestamp = now
|
||||
|
||||
def test_hda2_brake_retains_aol_only_after_accepted_steering(self):
|
||||
for steering_before_brake in (False, True):
|
||||
self._start_hda2_aol()
|
||||
self.assertTrue(self.safety.safety_rx_hook(common.make_msg(1, 0x4F1, dat=bytes([1, 0, 0, 0]))))
|
||||
self.assertTrue(self.safety.safety_rx_hook(self.scc(0, True)))
|
||||
self.assertTrue(self.safety.get_controls_allowed())
|
||||
if steering_before_brake:
|
||||
self.assertTrue(self.safety.safety_tx_hook(self.steer(3)))
|
||||
self._refresh_hda2_aol_rx(1_010_000)
|
||||
brake = common.make_msg(1, 0x394, dat=bytes.fromhex('036c000003449798'))
|
||||
self.assertTrue(self.safety.safety_rx_hook(brake))
|
||||
self.assertFalse(self.safety.get_controls_allowed())
|
||||
self.assertEqual(bool(self.safety.safety_tx_hook(self.steer(3))), steering_before_brake)
|
||||
self.safety.aol_set_host_request(0)
|
||||
self.safety.aol_set_host_request(1)
|
||||
self.assertFalse(self.safety.safety_tx_hook(self.steer(3)))
|
||||
|
||||
def test_hda2_idle_blocks_duplicate_only_while_host_steering_is_fresh(self):
|
||||
self._start_hda2_aol()
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x50), 0)
|
||||
self.assertTrue(self.safety.safety_tx_hook(self.steer(0, False)))
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x50), -1)
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x421), 0)
|
||||
self._refresh_hda2_aol_rx(1_500_000)
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x50), 0)
|
||||
self.safety.set_relay_malfunction(True)
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x50), -1)
|
||||
|
||||
@@ -249,6 +249,26 @@ class TestHyundaiBlendedAlphaAol(unittest.TestCase):
|
||||
for _ in range(8):
|
||||
self.feed()
|
||||
|
||||
def test_hda2_idle_steering_has_one_forwarding_owner(self):
|
||||
if self.release:
|
||||
self.skipTest("Mixed Alpha Long requires the debug safety build")
|
||||
self.reset(0x2014)
|
||||
self.warm()
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x50), 0)
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x2A4), 0)
|
||||
steering = self.packer.make_can_msg_safety('LKAS', 0, {'COUNTER': 1, 'TORQUE_REQUEST': 0})
|
||||
self.assertTrue(self.safety.safety_tx_hook(steering))
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x50), -1)
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x2A4), 0)
|
||||
camera = self.packer.make_can_msg_safety('CAM_0x2a4', 0, {'COUNTER': self.counter - 1})
|
||||
self.assertTrue(self.safety.safety_tx_hook(camera))
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x2A4), -1)
|
||||
self.assertEqual(self.request(3), 0)
|
||||
self.now += 500_000
|
||||
self.warm()
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x50), 0)
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x2A4), 0)
|
||||
|
||||
def test_hdai_withdrawal_consumes_valid_counter_without_output_credit(self):
|
||||
from opendbc.car.hyundai.hyundaican import hyundai_checksum
|
||||
|
||||
|
||||
@@ -68,6 +68,19 @@ class TestHyundaiIoniq6Long(unittest.TestCase):
|
||||
self.assertTrue(self.safety.safety_rx_hook(self.packet(lamp)))
|
||||
return corner, lamp
|
||||
|
||||
def test_replacement_steering_blocks_factory_copies_for_both_hda2_topologies(self):
|
||||
if self.release:
|
||||
self.skipTest("RELEASE denies all four exact Ioniq 6 LONG profiles")
|
||||
for words in (RAW_LONG, RAW_AOL):
|
||||
for topology, word in words.items():
|
||||
with self.subTest(topology=topology, word=hex(word)):
|
||||
self.mode(word)
|
||||
addresses = (0x110, 0x362) if topology == "lkas_alt" else (0x50, 0x2A4)
|
||||
for address in addresses:
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, address), -1)
|
||||
self.assertEqual(self.safety.safety_fwd_hook(0, address), 2)
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x123), 0)
|
||||
|
||||
def test_bsm_all_sixteen_physical_states_and_exact_paired_frames(self):
|
||||
if self.release:
|
||||
self.skipTest("RELEASE denies all four exact Ioniq 6 LONG profiles")
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
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.assertFalse(self.safety.safety_uses_camera_slot(camera))
|
||||
self.assertFalse(self.safety.safety_camera_release_current(camera, 0))
|
||||
self.assertEqual(self.safety.safety_camera_release_delay(camera, 0), 0)
|
||||
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_release_library_camera_slot_helpers_are_inactive(self):
|
||||
release = libsafety_py.ffi.dlopen(libsafety_py._build_libsafety(release=True))
|
||||
release.set_alternative_experience(32)
|
||||
self.assertEqual(release.set_safety_hooks(structs.CarParams.SafetyModel.hyundaiCanfd, 0x1C0C), 0)
|
||||
camera = self.packet(2, 'a6770a1880001800000a000000900000')
|
||||
self.assertFalse(release.safety_uses_camera_slot(camera))
|
||||
self.assertFalse(release.safety_camera_release_current(camera, 10_000))
|
||||
self.assertEqual(release.safety_camera_release_delay(camera, 10_000), 0)
|
||||
self.assertEqual(release.safety_fwd_packet_hook(camera), -1)
|
||||
|
||||
def test_output_hook_preserves_default_forwarding(self):
|
||||
self.assertEqual(self.safety.set_safety_hooks(structs.CarParams.SafetyModel.hyundai, 0), 0)
|
||||
for source, destination in ((0, 2), (1, -1), (2, 0)):
|
||||
packet = libsafety_py.make_CANPacket(0x123, source, bytes(8))
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(packet), destination)
|
||||
self.assertEqual(self.forward(packet)[:2], (destination, False))
|
||||
|
||||
def forward(self, packet):
|
||||
output = libsafety_py.new_CANPacket()
|
||||
replaced = libsafety_py.ffi.new('bool *')
|
||||
bus = self.safety.safety_fwd_output_hook(packet, output, replaced)
|
||||
return bus, bool(replaced[0]), output
|
||||
|
||||
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.forward(camera)[0], -1)
|
||||
|
||||
self.mode(0x1C0C)
|
||||
self.safety.set_timer(1_000_000)
|
||||
self.assertEqual(self.forward(camera)[0], -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.forward(camera)[:2], (0, False))
|
||||
self.assertEqual(self.forward(camera)[0], -1)
|
||||
corrupt = self.packet(2, 'a6770a1881001800000a000000900000')
|
||||
self.assertEqual(self.forward(corrupt)[0], -1)
|
||||
self.assertFalse(self.safety.safety_stage_tx_hook(self.packet(0, 'a6770a1880001800000a000000900000')))
|
||||
warning = self.packet(2, '784d1400000108f0000a000000640000')
|
||||
self.assertEqual(self.forward(warning)[:2], (0, False))
|
||||
self.safety.set_controls_allowed(True)
|
||||
self.safety.set_aol_test_heartbeat(True)
|
||||
self.safety.aol_set_host_request(3)
|
||||
host = self.packet(0, 'a009150280001800000a000000900000')
|
||||
host[0].data[2] = 20
|
||||
from opendbc.car.hyundai.hyundaicanfd import hkg_can_fd_checksum
|
||||
crc = hkg_can_fd_checksum(0x12A, None, bytearray(host[0].data[0:16]))
|
||||
host[0].data[0], host[0].data[1] = crc & 255, crc >> 8
|
||||
self.safety.set_timer(1_005_000)
|
||||
self.assertFalse(self.safety.safety_tx_hook(host))
|
||||
self.assertTrue(self.safety.safety_stage_tx_hook(host))
|
||||
self.safety.set_timer(1_010_000)
|
||||
match = self.packet(2, '5ce51500000108f0000a000000640000')
|
||||
bus, replaced, output = self.forward(match)
|
||||
self.assertEqual((bus, replaced, output[0].data[2]), (0, True, 21))
|
||||
self.assertEqual(output[0].data[7] & 0xF0, 0xF0)
|
||||
|
||||
self.safety.set_controls_allowed(False)
|
||||
self.safety.aol_set_host_request(0)
|
||||
following = self.packet(2, '110d1600000108f0000a000000640000')
|
||||
self.safety.set_timer(1_019_999)
|
||||
self.assertEqual(self.safety.safety_camera_release_delay(following, 1_019_999), 1)
|
||||
self.safety.set_timer(1_020_000)
|
||||
self.assertEqual(self.forward(following)[:2], (0, False))
|
||||
self.assertEqual(self.forward(following)[0], -1)
|
||||
self.safety.set_relay_malfunction(True)
|
||||
self.assertEqual(self.forward(following)[0], -1)
|
||||
self.assertFalse(self.safety.safety_stage_tx_hook(host))
|
||||
@@ -4,6 +4,7 @@ import unittest
|
||||
|
||||
from opendbc.can import CANPacker
|
||||
from opendbc.car import structs
|
||||
from opendbc.car.hyundai.interface import CarInterface
|
||||
from opendbc.safety.tests.libsafety import libsafety_py
|
||||
|
||||
|
||||
@@ -98,6 +99,8 @@ class TestHyundaiStockAngleAol(unittest.TestCase):
|
||||
self.assertFalse(self.safety.safety_test_selected_fwd(2, address))
|
||||
self.assertTrue(self.safety.safety_tx_hook(self.command(word, 3)))
|
||||
self.assertTrue(self.safety.safety_tx_hook(self.command(word, 4, active=False)))
|
||||
if topology.startswith('lka'):
|
||||
self.assertFalse(self.safety.safety_tx_hook(self.command(word, 5, active=False)))
|
||||
self.assertFalse(self.safety.safety_test_selected_fwd(2, address))
|
||||
self.assertTrue(self.safety.safety_tx_hook(self.command(word, 5)))
|
||||
self.safety.set_timer(1_300_001)
|
||||
@@ -105,6 +108,38 @@ class TestHyundaiStockAngleAol(unittest.TestCase):
|
||||
self.assertEqual(self.safety.aol_get_permission_mask(), 0)
|
||||
self.assertFalse(self.safety.safety_tx_hook(self.command(word, 6)))
|
||||
|
||||
def test_hda2_controller_sends_only_one_inactive_release(self):
|
||||
car = angle_profiles.CARS[0]
|
||||
for topology, address, camera_name in (('lka', 0x50, 'CAM_0x2a4'), ('lka_alt', 0x110, 'CAM_0x362')):
|
||||
cp = angle_profiles.params(car, topology, hybrid=True)
|
||||
cp.alternativeExperience = 32
|
||||
word = cp.safetyConfigs[-1].safetyParam
|
||||
self.mode(word)
|
||||
self.sources(word)
|
||||
self.gesture(word)
|
||||
interface = CarInterface(cp)
|
||||
packer, frames = angle_profiles.source_frames(cp, topology)
|
||||
frames.append(packer.make_can_msg(camera_name, 2, {}))
|
||||
state = interface.update([(1_000_000_000, frames)])
|
||||
self.assertTrue(state.canValid)
|
||||
control = structs.CarControl()
|
||||
camera_frame = packer.make_can_msg(camera_name, 0, {})
|
||||
camera = self.packet(camera_frame)
|
||||
self.assertFalse(self.safety.safety_tx_hook(camera))
|
||||
for tick, (active, expected) in enumerate(((False, []), (True, [2]), (False, [1]), (False, []))):
|
||||
control.latActive = active
|
||||
_, sends = interface.apply(control.as_reader(), 1_000_000_000 + tick * 10_000_000)
|
||||
steering = [frame for frame in sends if frame[0] == address]
|
||||
self.assertEqual([(frame[1][9] >> 4) & 3 for frame in steering], expected)
|
||||
for frame in steering:
|
||||
self.assertTrue(self.safety.safety_tx_hook(self.packet(frame)))
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, address), -1 if active else 0)
|
||||
self.assertEqual(bool(self.safety.safety_tx_hook(camera)), active, (topology, tick))
|
||||
if active:
|
||||
bad_camera = self.packet(camera_frame)
|
||||
bad_camera[0].data[0] ^= 1
|
||||
self.assertFalse(self.safety.safety_tx_hook(bad_camera))
|
||||
|
||||
def test_non_angle_profile_rejects_cb_at_public_and_selected_hooks(self):
|
||||
self.safety.set_alternative_experience(0)
|
||||
self.assertEqual(self.safety.set_safety_hooks(structs.CarParams.SafetyModel.hyundaiCanfd, 0), 0)
|
||||
|
||||
@@ -380,7 +380,9 @@ def test_recorded_pe_stock_wheel_cutoff_withdraws_native_output_without_new_butt
|
||||
assert case.safety.aol_get_permission_mask() == int(moving)
|
||||
assert bool(case.safety.safety_tx_hook(case.command(word, counter))) is moving
|
||||
if not moving:
|
||||
assert case.safety.safety_tx_hook(case.command(word, counter, active=False))
|
||||
inactive = case.command(word, counter, active=False)
|
||||
assert not case.safety.safety_tx_hook(inactive)
|
||||
assert case.safety.safety_fwd_hook(2, inactive[0].addr) == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize('identity', ['HYUNDAI_IONIQ_5_PE', 'KIA_EV9'])
|
||||
|
||||
@@ -18,7 +18,7 @@ class TestSubaruAscentAlert(unittest.TestCase):
|
||||
return libsafety_py.make_CANPacket(0x3C4, bus, data)
|
||||
|
||||
def test_exact_parameter_bus_checksum_length_and_forwarding(self):
|
||||
for flags in (0, 1, 0x11, 0xB1, 0x800, 0x811, 0x891, 0x8B3, 0x9B1):
|
||||
for flags in (0, 1, 0x11, 0xB1, 0x800, 0x810, 0x815, 0x891, 0x8B3, 0x9B1):
|
||||
self.mode(flags)
|
||||
self.assertFalse(self.safety.safety_tx_hook(self.packet()), hex(flags))
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x3C4), 0)
|
||||
@@ -28,7 +28,7 @@ class TestSubaruAscentAlert(unittest.TestCase):
|
||||
self.mode(flags)
|
||||
self.assertFalse(self.safety.safety_tx_hook(self.packet()), hex(flags))
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x3C4), 0)
|
||||
for flags in (0x8B1, 0x91, 401) + ((1169, 1425) if debug else ()):
|
||||
for flags in (0x811, 0x8B1, 0x91, 401) + ((1169, 1425) if debug else ()):
|
||||
self.mode(flags)
|
||||
self.assertTrue(self.safety.safety_tx_hook(self.packet()), hex(flags))
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x3C4), -1)
|
||||
|
||||
@@ -139,7 +139,8 @@ class TestSubaruGen2AnglePair(unittest.TestCase):
|
||||
self.arm(cp, frames)
|
||||
_, steer, _ = self.controller(car, cp, frames)
|
||||
invalid_option = 0x200 if car == CAR.SUBARU_LEGACY_2025 else 0x100
|
||||
for flags in (SubaruSafetyFlags.LONG, 0x800, invalid_option):
|
||||
invalid_alert = 0x4000 if car in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025) else 0x800
|
||||
for flags in (SubaruSafetyFlags.LONG, invalid_alert, invalid_option):
|
||||
with self.subTest(car=car, flags=flags):
|
||||
self.mode(cp, extra_flags=flags)
|
||||
for frame in required:
|
||||
|
||||
@@ -36,6 +36,26 @@ def check_exact_current_and_hw1_profiles_keep_distinct_steering_encoding():
|
||||
assert lib.safety_tx_hook(packet(message))
|
||||
|
||||
|
||||
def check_speed_sync_bit_extends_only_modern_long_control_words():
|
||||
modern = TeslaCAN(None, CANPacker(DBC[CAR.TESLA_MODEL_3][Bus.party]))
|
||||
hw1 = ModelSHW1CAN(CANPacker(DBC[CAR.TESLA_MODEL_S_HW1][Bus.party]))
|
||||
debug = lib.set_safety_hooks(structs.CarParams.SafetyModel.allOutput, 0) == 0
|
||||
# Alone, on a stock or HW1 word, or beside an unknown flag, the bit selects nothing.
|
||||
for word in (4096, 4096 | 256, 4096 | 512, 4096 | 2048, 4096 | 16, 4096 | 17, 4096 | 3, 4096 | 1 | 0x8000, 8192 | 1):
|
||||
assert lib.set_safety_hooks(10, word) == -1
|
||||
assert not lib.get_controls_allowed()
|
||||
lib.set_controls_allowed(True)
|
||||
assert not lib.safety_tx_hook(packet(modern.create_steering_control(0., False)))
|
||||
assert not lib.safety_tx_hook(packet(hw1.create_steering_control(0., 0, False)))
|
||||
# The ten exact words keep the modern profile; RELEASE firmware has no such word.
|
||||
for base in (1, 257, 513, 769, 1537, 1793, 2049, 2305, 3073, 3329):
|
||||
assert lib.set_safety_hooks(10, 4096 | base) == (0 if debug else -1)
|
||||
lib.init_tests() # Clear the separate startup Autopark assumption for this encoding test.
|
||||
lib.set_controls_allowed(False)
|
||||
assert lib.safety_tx_hook(packet(modern.create_steering_control(0., False))) == debug
|
||||
assert lib.get_current_safety_param() == (4096 | base if debug else 0)
|
||||
|
||||
|
||||
class TestTeslaEncodingNamespace(unittest.TestCase):
|
||||
def tearDown(self):
|
||||
lib.init_tests()
|
||||
@@ -47,3 +67,6 @@ class TestTeslaEncodingNamespace(unittest.TestCase):
|
||||
|
||||
def test_exact_current_and_hw1_profiles_keep_distinct_steering_encoding(self):
|
||||
check_exact_current_and_hw1_profiles_keep_distinct_steering_encoding()
|
||||
|
||||
def test_speed_sync_bit_extends_only_modern_long_control_words(self):
|
||||
check_speed_sync_bit_extends_only_modern_long_control_words()
|
||||
|
||||
@@ -38,7 +38,10 @@ class TestModelSHW1Safety(unittest.TestCase):
|
||||
|
||||
def test_all_16bit_profile_words_are_isolated(self):
|
||||
debug = lib.set_safety_hooks(CarParams.SafetyModel.allOutput, 0) == 0
|
||||
supported = {0, 1, 16, 17, 256, 257, 512, 768, 1536, 1792, 2048, 2304, 3072, 3328} | ({513, 769, 1537, 1793, 2049, 2305, 3073, 3329} if debug else set())
|
||||
long_aol = {513, 769, 1537, 1793, 2049, 2305, 3073, 3329}
|
||||
# Scroll speed sync (4096) rides only on the ten modern LONG_CONTROL words, never on an HW1 or stock word.
|
||||
speed_sync = {4096 | word for word in {1, 257} | long_aol}
|
||||
supported = {0, 1, 16, 17, 256, 257, 512, 768, 1536, 1792, 2048, 2304, 3072, 3328} | (long_aol | speed_sync if debug else set())
|
||||
for param in range(65536):
|
||||
result = lib.set_safety_hooks(10, param)
|
||||
expected = 0 if param in supported else -1
|
||||
|
||||
@@ -0,0 +1,974 @@
|
||||
"""Tesla scroll speed sync: one gated right-wheel scroll frame (0x3C2 on bus 1) for the Model 3/Y."""
|
||||
import random
|
||||
import re
|
||||
import unittest
|
||||
from functools import cache
|
||||
from pathlib import Path
|
||||
|
||||
from opendbc.car.structs import CarParams
|
||||
from opendbc.car.tesla.screen_button import SYNC_WORDS
|
||||
from opendbc.car.tesla.speed_sync import neutral_wheel, scroll_request
|
||||
from opendbc.car.tesla.values import TeslaSafetyFlags
|
||||
from opendbc.safety.tests import test_tesla
|
||||
from opendbc.safety.tests import test_tesla_ordinary_aol as ordinary
|
||||
from opendbc.safety.tests import test_tesla_screen_button as screen
|
||||
from opendbc.safety.tests.common import CANPackerSafety, make_msg
|
||||
from opendbc.safety.tests.libsafety import libsafety_py
|
||||
|
||||
TESLA = CarParams.SafetyModel.tesla
|
||||
NO_OUTPUT = CarParams.SafetyModel.noOutput
|
||||
SYNC = int(TeslaSafetyFlags.SCROLL_SPEED_SYNC)
|
||||
WHEEL = 0x3C2
|
||||
|
||||
# The bit rides only on a word with LONG_CONTROL: base, screen AOL and ordinary AOL,
|
||||
# each with and without cooperative steering.
|
||||
BASES = (1, 257, 513, 769, 1537, 1793, 2049, 2305, 3073, 3329)
|
||||
WORDS = tuple(SYNC | base for base in BASES)
|
||||
STOCK_WORDS = (0, 256, 512, 768, 1536, 1792, 2048, 2304, 3072, 3328)
|
||||
|
||||
# VCLEFT_switchStatus, index 1: every tilt and press neutral, no scroll on either wheel.
|
||||
NEUTRAL = bytes.fromhex('2955000000000000')
|
||||
# The same neutral frame with every bit the panda does not interpret set.
|
||||
NEUTRAL_BUSY = bytes.fromhex('AD55C0C0F0FFFFFF')
|
||||
STEPS = (1, -1, 5, -5)
|
||||
TICKS = tuple(ticks & 0x3F for ticks in STEPS)
|
||||
|
||||
# safety_test_tesla_sync_state()
|
||||
ENABLED, SEEN, DI_SEEN, DI_VALID, NEUTRAL_SEEN, BLOCKED, PENDING, DRIVE, OCCUPANT, ACTIVE, SENT = (1 << bit for bit in range(11))
|
||||
READY = ENABLED | SEEN | DI_SEEN | DI_VALID | NEUTRAL_SEEN | DRIVE | OCCUPANT | ACTIVE
|
||||
TOKENS = 30
|
||||
|
||||
CAR = {'state': 2, 'speed': 120, 'units': 0, 'autopark': 0, 'gear': 4, 'door': False, 'belt': True, 'brake': False,
|
||||
'standstill': False, 'aeb': 0, 'stock_type': 0, 'kph': 80., 'esp_delta': 0., 'speed_valid': 1, 'angle': 0., 'hands': 0,
|
||||
'eps': 1, 'eps_error': 0, 'torque': 0., 'pedal': 0.}
|
||||
# What a drive can do to each of them: the driver, the stock systems and the car's own faults.
|
||||
EVENTS = {'state': (0, 1, 1, 3, 4, 4, 5, 6, 7), 'speed': (0, 2, 3, 121, 300, 507, 508), 'units': (1,), 'autopark': (1, 3, 4, 9),
|
||||
'gear': (0, 1, 2, 3, 7), 'door': (True,), 'belt': (False,), 'brake': (True,), 'standstill': (True,), 'aeb': (1, 2, 3),
|
||||
'stock_type': (1, 2, 3), 'kph': (0., 5., 120.), 'esp_delta': (12.,), 'speed_valid': (0,), 'angle': (5., -10., 30.),
|
||||
'hands': (1, 2, 3), 'eps': (0, 2, 3, 5), 'eps_error': (9,), 'torque': (1., -3., 5.5, -6.), 'pedal': (20.,)}
|
||||
|
||||
|
||||
def is_debug(lib):
|
||||
debug = lib.set_safety_hooks(CarParams.SafetyModel.allOutput, 0) == 0
|
||||
lib.set_safety_hooks(NO_OUTPUT, 0)
|
||||
return debug
|
||||
|
||||
|
||||
@cache
|
||||
def release_safety():
|
||||
default = libsafety_py.libsafety
|
||||
library = libsafety_py.ffi.dlopen(libsafety_py._build_libsafety(release=True))
|
||||
assert libsafety_py.libsafety is default
|
||||
return library
|
||||
|
||||
|
||||
class SyncFixture:
|
||||
WORD = SYNC | 1
|
||||
EXPERIENCE = 0
|
||||
|
||||
def setUp(self):
|
||||
self.lib = libsafety_py.libsafety
|
||||
self.packer = CANPackerSafety('tesla_model3_party')
|
||||
self.start(self.WORD)
|
||||
|
||||
def tearDown(self):
|
||||
self.lib.set_aol_test_heartbeat(False)
|
||||
self.lib.init_tests()
|
||||
self.lib.set_alternative_experience(0)
|
||||
self.lib.set_safety_hooks(NO_OUTPUT, 0)
|
||||
|
||||
def start(self, word, experience=None, ready=True, now=5_000_000):
|
||||
self.lib.init_tests()
|
||||
self.lib.set_alternative_experience(self.EXPERIENCE if experience is None else experience)
|
||||
self.now = now
|
||||
self.lib.set_timer(self.now & 0xFFFFFFFF)
|
||||
self.assertEqual(self.lib.set_safety_hooks(TESLA, word), 0, word)
|
||||
self.lib.set_aol_test_heartbeat(True)
|
||||
self.car = dict(CAR)
|
||||
self.packer.counters.clear()
|
||||
self.counter = 0
|
||||
self.template = NEUTRAL
|
||||
if ready:
|
||||
self.ready()
|
||||
|
||||
def ready(self):
|
||||
"""Engaged on the Tesla's own cruise with a current neutral wheel frame: a request must be admitted from here."""
|
||||
for _ in range(3):
|
||||
self.step(us=0)
|
||||
|
||||
def advance(self, us):
|
||||
self.now += us
|
||||
self.lib.set_timer(self.now & 0xFFFFFFFF)
|
||||
|
||||
def rx(self, name, bus, values):
|
||||
return bool(self.lib.safety_rx_hook(self.packer.make_can_msg_safety(name, bus, values)))
|
||||
|
||||
def di(self, counter=None, **changes):
|
||||
"""DI_state with its counter under test control. The selected speed is in half display units, as the panda keeps it."""
|
||||
self.car.update(changes)
|
||||
self.counter = (self.counter + 1) % 16 if counter is None else counter
|
||||
car = self.car
|
||||
return self.rx('DI_state', 0, {'DI_cruiseState': car['state'], 'DI_autoparkState': car['autopark'],
|
||||
'DI_digitalSpeed': car['speed'] * .5, 'DI_speedUnits': car['units'],
|
||||
'DI_locStatusCounter': self.counter})
|
||||
|
||||
def feed(self, skip=(), check=True, **changes):
|
||||
"""Every required message once, as the car sends them. Returns what the panda made of each."""
|
||||
self.car.update(changes)
|
||||
car = self.car
|
||||
frames = (
|
||||
('DAS_control', 2, {'DAS_aebEvent': car['aeb']}),
|
||||
('DAS_steeringControl', 2, {'DAS_steeringControlType': car['stock_type']}),
|
||||
('DI_speed', 0, {'DI_vehicleSpeed': car['kph']}),
|
||||
('ESP_B', 0, {'ESP_vehicleSpeed': car['kph'] + car['esp_delta'], 'ESP_wheelSpeedsQF': car['speed_valid'],
|
||||
'ESP_vehicleStandstillSts': int(car['standstill'])}),
|
||||
('EPAS3S_sysStatus', 0, {'EPAS3S_internalSAS': car['angle'], 'EPAS3S_eacStatus': car['eps'], 'EPAS3S_eacErrorCode': car['eps_error'],
|
||||
'EPAS3S_handsOnLevel': car['hands'], 'EPAS3S_torsionBarTorque': car['torque']}),
|
||||
('DI_systemStatus', 0, {'DI_gear': car['gear'], 'DI_accelPedalPos': car['pedal']}),
|
||||
('ESP_status', 0, {'ESP_driverBrakeApply': 2 if car['brake'] else 1}),
|
||||
('UI_warning', 0, {'anyDoorOpen': int(car['door']), 'buckleStatus': int(car['belt'])}),
|
||||
)
|
||||
results = [self.rx(name, bus, values) for name, bus, values in frames if name not in skip]
|
||||
if 'DI_state' not in skip:
|
||||
results.append(self.di())
|
||||
if check:
|
||||
self.assertTrue(all(results), results)
|
||||
self.lib.safety_tick()
|
||||
return results
|
||||
|
||||
def wheel(self, data=None, bus=1, address=WHEEL):
|
||||
"""A wheel frame from the car on the vehicle bus. The panda copies a neutral one as its template."""
|
||||
self.lib.safety_rx_hook(make_msg(bus, address, dat=self.template if data is None else bytes(data)))
|
||||
|
||||
def step(self, us=20_000, skip=(), wheel=True, **changes):
|
||||
"""One cycle of car traffic: the required messages, then a new neutral wheel frame."""
|
||||
self.advance(us)
|
||||
self.feed(skip, **changes)
|
||||
if wheel:
|
||||
self.wheel()
|
||||
|
||||
def answer(self, ticks=1, us=20_000):
|
||||
"""The Tesla moves its selected speed, which releases the outstanding request."""
|
||||
self.step(us=us, speed=self.car['speed'] + 2 * ticks)
|
||||
|
||||
def frame(self, ticks=1, template=None):
|
||||
data = bytearray(self.template if template is None else template)
|
||||
data[3] = (data[3] & 0xC0) | (ticks & 0x3F)
|
||||
return bytes(data)
|
||||
|
||||
def tx(self, ticks=1, data=None, bus=1):
|
||||
data = self.frame(ticks) if data is None else bytes(data)
|
||||
return bool(self.lib.safety_tx_hook(make_msg(bus, WHEEL, dat=data)))
|
||||
|
||||
def hook(self, ticks=1):
|
||||
"""The Tesla TX hook alone, without the shared relay and allow-list checks around it."""
|
||||
return bool(self.lib.safety_test_selected_tx(make_msg(1, WHEEL, dat=self.frame(ticks))))
|
||||
|
||||
def state(self, mask=0x7FF):
|
||||
return self.lib.safety_test_tesla_sync_state() & mask
|
||||
|
||||
def tokens(self):
|
||||
return self.lib.safety_test_tesla_sync_state() >> 16
|
||||
|
||||
def force_controls(self):
|
||||
self.lib.set_controls_allowed(True)
|
||||
|
||||
|
||||
class TestTeslaSpeedSyncWords(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.lib = libsafety_py.libsafety
|
||||
self.debug = is_debug(self.lib)
|
||||
|
||||
def tearDown(self):
|
||||
self.lib.set_safety_hooks(NO_OUTPUT, 0)
|
||||
|
||||
def test_only_the_ten_exact_words_carry_the_bit(self):
|
||||
self.assertEqual(frozenset(WORDS), SYNC_WORDS, 'the car port selects from the same ten words')
|
||||
for word in range(0x10000):
|
||||
if word & SYNC:
|
||||
valid = self.debug and word in WORDS
|
||||
self.assertEqual(self.lib.set_safety_hooks(TESLA, word), 0 if valid else -1, word)
|
||||
self.assertEqual(self.lib.get_current_safety_mode(), TESLA if valid else NO_OUTPUT, word)
|
||||
self.assertEqual(self.lib.get_current_safety_param(), word if valid else 0, word)
|
||||
if valid:
|
||||
self.assertEqual(self.lib.safety_test_tesla_sync_state(), ENABLED | (TOKENS << 16), word)
|
||||
|
||||
def test_near_miss_words_select_no_output(self):
|
||||
near = [SYNC, 2 * SYNC, SYNC | 16, SYNC | 17, SYNC | 273, SYNC | 1025, SYNC | 1281, SYNC | 2561, SYNC | 3585]
|
||||
near += [SYNC | word for word in STOCK_WORDS] # no LONG_CONTROL
|
||||
near += [word | extra for word in WORDS for extra in (2, 4, 8, 16, 32, 64, 128, 8192, 16384, 32768)]
|
||||
near += [word ^ flag for word in WORDS for flag in (1, 512, 1024, 2048) if word ^ flag not in WORDS]
|
||||
for word in near:
|
||||
self.assertNotIn(word, WORDS)
|
||||
self.assertEqual(self.lib.set_safety_hooks(TESLA, word), -1, word)
|
||||
self.assertEqual(self.lib.get_current_safety_mode(), NO_OUTPUT, word)
|
||||
self.lib.set_controls_allowed(True)
|
||||
self.assertFalse(self.lib.safety_tx_hook(make_msg(1, WHEEL, dat=NEUTRAL[:3] + b'\x01' + NEUTRAL[4:])), word)
|
||||
|
||||
def test_every_base_word_is_a_long_control_word_valid_on_its_own(self):
|
||||
for base in BASES:
|
||||
self.assertTrue(base & TeslaSafetyFlags.LONG_CONTROL)
|
||||
self.assertEqual(self.lib.set_safety_hooks(TESLA, base), 0 if self.debug else (0 if base in (1, 257) else -1), base)
|
||||
self.assertFalse(self.lib.safety_test_tesla_sync_state() & ENABLED, base)
|
||||
|
||||
|
||||
class TestTeslaSpeedSyncDisabled(SyncFixture, unittest.TestCase):
|
||||
WORD = 1
|
||||
|
||||
def setUp(self):
|
||||
self.debug = is_debug(libsafety_py.libsafety)
|
||||
super().setUp()
|
||||
|
||||
def scroll_frames_refused(self):
|
||||
self.force_controls()
|
||||
for ticks in STEPS:
|
||||
for bus in range(3):
|
||||
self.assertFalse(self.tx(ticks, bus=bus))
|
||||
self.assertFalse(self.hook(ticks))
|
||||
|
||||
def test_without_the_bit_no_wheel_frame_is_admitted_or_tracked(self):
|
||||
words = STOCK_WORDS + (BASES if self.debug else ())
|
||||
for word in words:
|
||||
for experience in (0, 32):
|
||||
with self.subTest(word=word, experience=experience):
|
||||
self.start(word, experience)
|
||||
for template in (NEUTRAL, NEUTRAL_BUSY):
|
||||
self.template = template
|
||||
self.step()
|
||||
self.assertTrue(self.lib.get_controls_allowed())
|
||||
self.assertEqual(self.state(), 0)
|
||||
self.assertEqual(self.tokens(), TOKENS)
|
||||
self.scroll_frames_refused()
|
||||
self.assertEqual(self.state(), 0)
|
||||
self.assertEqual(self.tokens(), TOKENS)
|
||||
|
||||
def test_release_firmware_refuses_the_bit_and_the_wheel_frame(self):
|
||||
release = release_safety()
|
||||
self.assertFalse(is_debug(release))
|
||||
for word in range(0x10000):
|
||||
if word & SYNC:
|
||||
self.assertEqual(release.set_safety_hooks(TESLA, word), -1, word)
|
||||
self.assertEqual(release.get_current_safety_mode(), NO_OUTPUT, word)
|
||||
native = TestTeslaSpeedSyncDisabled(methodName='test_without_the_bit_no_wheel_frame_is_admitted_or_tracked')
|
||||
native.lib = release
|
||||
native.packer = CANPackerSafety('tesla_model3_party')
|
||||
native.debug = False
|
||||
try:
|
||||
native.test_without_the_bit_no_wheel_frame_is_admitted_or_tracked()
|
||||
for word in BASES:
|
||||
self.assertEqual(release.set_safety_hooks(TESLA, word), 0 if word in (1, 257) else -1, word)
|
||||
release.set_controls_allowed(True)
|
||||
self.assertFalse(release.safety_tx_hook(make_msg(1, WHEEL, dat=native.frame())), word)
|
||||
finally:
|
||||
native.tearDown()
|
||||
self.assertIsNot(libsafety_py.libsafety, release)
|
||||
|
||||
def test_other_modes_never_send_the_wheel_frame_after_a_sync_session(self):
|
||||
if not self.debug:
|
||||
self.skipTest('RELEASE firmware refuses the sync words')
|
||||
for mode, word in ((TESLA, 1), (TESLA, 0), (TESLA, 17), (CarParams.SafetyModel.teslaPreap, 0), (NO_OUTPUT, 0),
|
||||
(CarParams.SafetyModel.silent, 0), (CarParams.SafetyModel.hondaBosch, 0)):
|
||||
with self.subTest(mode=mode, word=word):
|
||||
self.start(SYNC | 1)
|
||||
self.assertTrue(self.tx())
|
||||
self.answer()
|
||||
self.assertEqual(self.lib.set_safety_hooks(mode, word), 0)
|
||||
self.force_controls()
|
||||
for ticks in STEPS:
|
||||
for bus in range(3):
|
||||
self.assertFalse(self.tx(ticks, bus=bus))
|
||||
|
||||
|
||||
class TestTeslaSpeedSyncChangesNothingElse(SyncFixture, unittest.TestCase):
|
||||
"""Every eligible Model 3/Y carries the bit, switch on or off: apart from the wheel frame, the panda must behave as without it."""
|
||||
WORD = 1
|
||||
REQUIRED = ('DAS_control', 'DAS_steeringControl', 'DI_speed', 'ESP_B', 'EPAS3S_sysStatus', 'DI_systemStatus', 'ESP_status',
|
||||
'UI_warning', 'DI_state')
|
||||
FORWARDED = (0x488, 0x2b9, 0x27d, WHEEL, 0x3DF, 0x257)
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
if not is_debug(libsafety_py.libsafety):
|
||||
raise unittest.SkipTest('RELEASE firmware refuses the sync words')
|
||||
|
||||
def observe(self):
|
||||
"""Everything the panda decides or reports outside the speed sync state itself."""
|
||||
lib = self.lib
|
||||
return (bool(lib.get_controls_allowed()), lib.aol_get_request_mask(), lib.aol_get_permission_mask(), bool(lib.get_relay_malfunction()),
|
||||
bool(lib.get_gas_pressed_prev()), bool(lib.get_brake_pressed_prev()), bool(lib.get_regen_braking_prev()),
|
||||
bool(lib.get_steering_disengage_prev()), bool(lib.get_cruise_engaged_prev()), bool(lib.get_vehicle_moving()),
|
||||
lib.get_vehicle_speed_min(), lib.get_vehicle_speed_max(), lib.get_angle_meas_min(), lib.get_angle_meas_max(),
|
||||
lib.get_desired_angle_last(), lib.get_heartbeat_engaged_mismatches(), bool(lib.safety_config_valid()),
|
||||
lib.get_current_safety_mode(), lib.get_current_safety_param() & ~SYNC,
|
||||
tuple(lib.safety_fwd_hook(bus, address) for bus in range(3) for address in self.FORWARDED))
|
||||
|
||||
def assert_same(self, rows, plain, context):
|
||||
self.assertEqual(len(rows), len(plain), context)
|
||||
for step, (row, expected) in enumerate(zip(rows, plain, strict=True)):
|
||||
self.assertEqual(row, expected, (step, context))
|
||||
|
||||
def scripted_drive(self, word, experience):
|
||||
commands = CANPackerSafety('tesla_model3_party') # its own counters: the car's frames keep theirs
|
||||
script = ({'state': 0}, {'state': 1}, 'press', {'state': 2}, {'brake': True}, {'brake': False}, {'state': 0}, {'state': 1},
|
||||
{'state': 2}, 'press', {'door': True}, {'door': False}, {'state': 1}, {'state': 2}, {'gear': 1}, {'gear': 4},
|
||||
{'aeb': 1}, {'aeb': 0}, {'state': 1}, {'stock_type': 2}, {'state': 2}, {'stock_type': 0}, {'belt': False},
|
||||
{'belt': True}, {'state': 5}, {'state': 0}, {'state': 2}, {'torque': 5.5}, {'torque': 0.}, {'state': 1}, {'state': 2},
|
||||
{'hands': 3}, {'hands': 0}, {'state': 1}, {'state': 2}, {'standstill': True}, {'state': 4})
|
||||
self.start(word, experience, ready=False)
|
||||
rows = []
|
||||
for item in script:
|
||||
if item == 'press':
|
||||
for count in (0, 3):
|
||||
self.lib.safety_rx_hook(make_msg(1, 0x3DF, dat=bytes((0, 0, 0, count, 0, 0, 0, 0))))
|
||||
else:
|
||||
self.step(**item)
|
||||
self.lib.aol_set_host_request(3)
|
||||
steering = commands.make_can_msg_safety('DAS_steeringControl', 0, {'DAS_steeringAngleRequest': 0, 'DAS_steeringControlType': 1})
|
||||
accel = commands.make_can_msg_safety('DAS_control', 0, {'DAS_accelMin': 1, 'DAS_accelMax': 1})
|
||||
rows.append((bool(self.lib.safety_tx_hook(steering)), bool(self.lib.safety_tx_hook(accel)), *self.observe()))
|
||||
return rows
|
||||
|
||||
def random_drive(self, word, experience, seed, scroll, steps=300):
|
||||
"""A seeded drive of faults, driver inputs and commands. With `scroll` the host also asks for wheel steps; without it
|
||||
the owner's switch is off. Returns every answer and report except the answers to those wheel requests."""
|
||||
rng = random.Random(seed)
|
||||
commands = CANPackerSafety('tesla_model3_party')
|
||||
keys = sorted(EVENTS) + 4 * ['state'] + 2 * ['stock_type', 'units']
|
||||
# Mostly neutral wheel frames; also a scroll, a tilt, the other indexes, a short frame and a missing one.
|
||||
wheels = 7 * (NEUTRAL,) + 2 * (NEUTRAL_BUSY,) + (NEUTRAL[:3] + b'\x02' + NEUTRAL[4:], b'\x31' + NEUTRAL[1:], b'\x2a' + NEUTRAL[1:],
|
||||
bytes(8), NEUTRAL[:6], None)
|
||||
self.start(word, experience, ready=False)
|
||||
rows, admitted, engage = [], 0, False
|
||||
for _ in range(steps):
|
||||
roll = rng.random()
|
||||
if engage:
|
||||
self.car['state'], engage = 2, False
|
||||
elif roll < .3:
|
||||
key = rng.choice(keys)
|
||||
self.car[key] = rng.choice(EVENTS[key])
|
||||
elif roll < .5:
|
||||
self.car, engage = dict(CAR, state=1), True # everything normal again; the driver engages on the next cycle
|
||||
self.advance(rng.choice((10_000, 20_000, 20_000, 20_000, 40_000, 120_000)))
|
||||
if rng.random() < .03:
|
||||
self.counter = (self.counter + 1) % 16 # a DI_state frame went missing
|
||||
row = self.feed((rng.choice(self.REQUIRED),) if rng.random() < .03 else (), check=False)
|
||||
if rng.random() < .3:
|
||||
row.append(bool(self.lib.safety_rx_hook(make_msg(1, 0x3DF, dat=bytes((0, 0, 0, rng.choice((0, 3, 3, 1)), 0, 0, 0, 0))))))
|
||||
wheel = rng.choice(wheels)
|
||||
if wheel is not None:
|
||||
row.append(bool(self.lib.safety_rx_hook(make_msg(1, WHEEL, dat=wheel))))
|
||||
if neutral_wheel(wheel):
|
||||
self.template = wheel
|
||||
if rng.random() < .6:
|
||||
self.lib.aol_set_host_request(rng.choice((0, 1, 2, 3, 3, 3, 7)))
|
||||
heartbeat = rng.random()
|
||||
if heartbeat < .03 or heartbeat > .7:
|
||||
self.lib.set_aol_test_heartbeat(heartbeat > .7)
|
||||
angle = self.car['angle'] + rng.choice((0., 0., .2, -.3, 2., -15.))
|
||||
low, high = rng.choice(((0., 0.), (1., 1.), (-1., 1.5), (-2., -1.), (0., 3.6), (-3.6, 0.), (-.5, 0.)))
|
||||
for name, values in (
|
||||
('DAS_steeringControl', {'DAS_steeringAngleRequest': angle, 'DAS_steeringControlType': rng.choice((1, 1, 1, 0, 2, 3))}),
|
||||
('DAS_control', {'DAS_setSpeed': 100, 'DAS_accState': rng.choice((4, 4, 13)), 'DAS_aebEvent': rng.choice((0, 0, 0, 0, 1)),
|
||||
'DAS_accelMin': low, 'DAS_accelMax': high}),
|
||||
('APS_eacMonitor', {}),
|
||||
):
|
||||
row.append(bool(self.lib.safety_tx_hook(commands.make_can_msg_safety(name, 0, values))))
|
||||
ticks = rng.choice((1, 1, 1, -1, 5, -5, 0, 7))
|
||||
if rng.random() < .6 and scroll:
|
||||
admitted += self.tx(ticks)
|
||||
rows.append((*row, *self.observe()))
|
||||
return rows, admitted
|
||||
|
||||
def test_scripted_drive_is_identical_with_and_without_the_bit(self):
|
||||
for base in BASES:
|
||||
for experience in (0, 32):
|
||||
with self.subTest(base=base, experience=experience):
|
||||
plain = self.scripted_drive(base, experience)
|
||||
self.assert_same(self.scripted_drive(SYNC | base, experience), plain, base)
|
||||
# The script is a real drive: steering and acceleration are each allowed and refused in it,
|
||||
# and a screen or ordinary AOL word with its saved opt-in grants its own permission.
|
||||
for column in (0, 1):
|
||||
self.assertEqual({row[column] for row in plain}, {False, True})
|
||||
self.assertEqual(any(row[4] for row in plain), experience == 32 and base > 257)
|
||||
|
||||
def test_random_drives_are_identical_with_and_without_the_bit(self):
|
||||
# From the end of a row: the three command answers, then observe().
|
||||
columns = {'steering': -23, 'acceleration': -22, 'eac monitor': -21, 'controls': -20, 'gas': -16, 'brake': -15,
|
||||
'steering disengage': -13, 'cruise': -12, 'moving': -11, 'receive health': -4}
|
||||
reached = {name: set() for name in columns}
|
||||
for index, base in enumerate(BASES):
|
||||
for experience in (0, 32):
|
||||
with self.subTest(base=base, experience=experience):
|
||||
seed = 64 * index + experience
|
||||
plain, admitted = self.random_drive(base, experience, seed, scroll=True)
|
||||
self.assertEqual(admitted, 0, 'no wheel request without the bit')
|
||||
for scroll in (True, False):
|
||||
rows, admitted = self.random_drive(SYNC | base, experience, seed, scroll)
|
||||
self.assert_same(rows, plain, (base, experience, scroll))
|
||||
self.assertEqual(admitted > 0, scroll, 'the wheel request is the only difference')
|
||||
for name, column in columns.items():
|
||||
reached[name] |= {row[column] for row in plain}
|
||||
self.assertEqual(any(row[-18] for row in plain), experience == 32 and base > 257, 'AOL permission')
|
||||
self.assertEqual({row[-20] for row in plain}, {False, True})
|
||||
# Together the drives reach both answers of every command and report they compare.
|
||||
self.assertEqual(reached, {name: {False, True} for name in columns})
|
||||
|
||||
def test_speed_sync_state_is_private_to_its_header(self):
|
||||
"""Outside its header the feature is five calls in tesla.h and one in safety.h; inside, it assigns only what it
|
||||
declares and calls only helpers that change nothing. So no other Tesla decision can depend on the bit."""
|
||||
safety = Path(__file__).parents[1]
|
||||
uses = {}
|
||||
for path in sorted(safety.rglob('*.h')):
|
||||
found = re.findall(r'\b(?:tesla_sync_\w+|tesla_extended_param_valid)\b', path.read_text())
|
||||
if found and path.name != 'tesla_speed_sync.h':
|
||||
uses[path.relative_to(safety).as_posix()] = found
|
||||
self.assertEqual(uses, {'modes/tesla.h': ['tesla_sync_rx', 'tesla_sync_optional_rx', 'tesla_sync_tx', 'tesla_sync_base_param',
|
||||
'tesla_sync_configure'],
|
||||
'safety.h': ['tesla_extended_param_valid']})
|
||||
# The request decision reaches only the wheel frame, and it is the hook's last word on it.
|
||||
last_word = ' if (msg->addr == 0x3C2U) {\n tx = tesla_sync_tx(msg, tesla_stock_aeb, tesla_autopark, tesla_stock_lkas);\n }\n\n return tx;\n}\n'
|
||||
self.assertIn(last_word, (safety / 'modes/tesla.h').read_text())
|
||||
code = re.sub(r'//[^\n]*', '', (safety / 'modes/tesla_speed_sync.h').read_text())
|
||||
declared = set(re.findall(r'\b(?:bool|int|uint8_t|uint16_t|uint32_t)\s+(\w+)(?:\[\w+\])?\s*[=;]', code))
|
||||
assigned = set(re.findall(r'\b([A-Za-z_]\w*)(?:\[\w+\])?\s*(?:(?:[-+*/%&|^]|<<|>>)?=(?!=)|\+\+|--)', code))
|
||||
self.assertTrue(assigned)
|
||||
self.assertLessEqual(assigned, declared, 'the header assigns only what it declares')
|
||||
lasting = set(re.findall(r'\bstatic\s+(?:const\s+)?(?:unsigned\s+)?\w+\s+(\w+)(?:\[\w+\])?\s*[=;]', code))
|
||||
self.assertTrue(lasting and all(name.startswith('tesla_sync_') for name in lasting), 'what outlives a call is its own')
|
||||
called = set(re.findall(r'\b([A-Za-z_]\w*)\s*\(', code)) - {'if', 'else', 'while', 'for', 'return'}
|
||||
self.assertEqual({name for name in called if not name.startswith('tesla_sync_') and name != 'tesla_extended_param_valid'},
|
||||
{'msg_matches', 'GET_LEN', 'GET_BIT', 'GET_FLAG', 'microsecond_timer_get', 'safety_get_ts_elapsed',
|
||||
'aol_rx_healthy', 'tesla_screen_param_valid'})
|
||||
|
||||
def test_upstream_aol_cases_hold_with_the_bit_on_every_long_word(self):
|
||||
"""Upstream's own screen and ordinary AOL cases, with the bit added to every LONG_CONTROL word they select."""
|
||||
selected = set()
|
||||
for case_class in (screen.TestTeslaScreenButton, ordinary.TestTeslaOrdinaryAol):
|
||||
for name in unittest.TestLoader().getTestCaseNames(case_class):
|
||||
with self.subTest(case=case_class.__name__, test=name):
|
||||
case = case_class(methodName=name)
|
||||
|
||||
def start(word, case=case):
|
||||
word |= SYNC if word & 1 else 0
|
||||
screen.TestTeslaScreenButton.start(case, word)
|
||||
self.assertEqual(bool(case.lib.safety_test_tesla_sync_state() & ENABLED), bool(word & SYNC))
|
||||
selected.add(word)
|
||||
case.start = start
|
||||
case.setUp()
|
||||
try:
|
||||
getattr(case, name)()
|
||||
finally:
|
||||
case.tearDown()
|
||||
self.assertLessEqual({SYNC | 513, SYNC | 1537, SYNC | 2049, SYNC | 3073}, selected)
|
||||
|
||||
|
||||
class TestTeslaLongitudinalSpeedSyncSafety(test_tesla.TestTeslaLongitudinalSafety):
|
||||
"""Upstream's complete Tesla longitudinal suite with the bit set and no wheel request made: nothing in it may differ."""
|
||||
SAFETY_PARAM = TeslaSafetyFlags.LONG_CONTROL | TeslaSafetyFlags.SCROLL_SPEED_SYNC
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
super().setUpClass()
|
||||
if not is_debug(libsafety_py.libsafety):
|
||||
raise unittest.SkipTest('RELEASE firmware refuses the sync words')
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.assertTrue(self.safety.safety_test_tesla_sync_state() & ENABLED)
|
||||
|
||||
|
||||
class TestTeslaSpeedSync(SyncFixture, unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
if not is_debug(libsafety_py.libsafety):
|
||||
raise unittest.SkipTest('RELEASE firmware refuses the sync words')
|
||||
|
||||
def blocked_until(self, fault, clear):
|
||||
"""One fault refuses the request and spends nothing; clearing it admits the same request."""
|
||||
self.start(self.WORD)
|
||||
self.step()
|
||||
fault()
|
||||
self.assertFalse(self.tx())
|
||||
self.assertFalse(self.hook())
|
||||
self.assertFalse(self.state(PENDING | SENT))
|
||||
self.assertEqual(self.tokens(), TOKENS)
|
||||
clear()
|
||||
self.assertTrue(self.tx())
|
||||
|
||||
# ***** admitted requests *****
|
||||
|
||||
def test_ready_state_admits_one_request_and_records_it(self):
|
||||
self.assertEqual(self.state(), READY)
|
||||
self.assertEqual(self.tokens(), TOKENS)
|
||||
self.assertTrue(self.tx())
|
||||
self.assertEqual(self.state(), READY | PENDING | SENT)
|
||||
self.assertEqual(self.tokens(), TOKENS - 1)
|
||||
|
||||
def test_every_word_admits_the_four_steps_the_sender_builds(self):
|
||||
for word in WORDS:
|
||||
for experience in (0, 32):
|
||||
for template in (NEUTRAL, NEUTRAL_BUSY):
|
||||
with self.subTest(word=word, experience=experience, template=template.hex()):
|
||||
self.start(word, experience)
|
||||
self.template = template
|
||||
for ticks in STEPS:
|
||||
self.step()
|
||||
address, data, bus = scroll_request(template, ticks)
|
||||
self.assertEqual((address, bus, data), (WHEEL, 1, self.frame(ticks)))
|
||||
self.assertTrue(self.lib.safety_tx_hook(make_msg(bus, address, dat=data)))
|
||||
self.answer(ticks)
|
||||
self.assertEqual(self.tokens(), TOKENS - len(STEPS))
|
||||
|
||||
def test_override_state_and_both_units_are_admitted(self):
|
||||
for changes in ({'state': 4}, {'units': 1}, {'state': 4, 'units': 1}):
|
||||
with self.subTest(changes=changes):
|
||||
self.start(self.WORD)
|
||||
self.step(**changes)
|
||||
self.assertEqual(self.state(), READY)
|
||||
self.assertTrue(self.tx())
|
||||
|
||||
def test_first_request_is_admitted_with_a_template_stamped_zero(self):
|
||||
self.start(self.WORD, now=0)
|
||||
self.assertEqual(self.state(), READY)
|
||||
self.assertTrue(self.tx())
|
||||
self.step(us=0, speed=self.car['speed'] + 2)
|
||||
self.assertFalse(self.state(PENDING))
|
||||
self.assertFalse(self.tx(), 'the same wheel frame cannot carry a second request')
|
||||
|
||||
# ***** frame shape *****
|
||||
|
||||
def test_frame_must_copy_the_template_with_one_legal_scroll_count(self):
|
||||
for template in (NEUTRAL, NEUTRAL_BUSY):
|
||||
with self.subTest(template=template.hex()):
|
||||
self.start(self.WORD)
|
||||
self.template = template
|
||||
for ticks in range(64):
|
||||
self.step(us=5_000)
|
||||
self.assertEqual(self.tx(ticks), ticks in TICKS, ticks)
|
||||
if ticks in TICKS:
|
||||
self.answer(us=5_000)
|
||||
self.assertEqual(self.tokens(), TOKENS - len(TICKS))
|
||||
self.step()
|
||||
for bit in range(64):
|
||||
if bit not in range(24, 30):
|
||||
data = bytearray(self.frame())
|
||||
data[bit // 8] ^= 1 << (bit % 8)
|
||||
self.assertFalse(self.tx(data=data), bit)
|
||||
for bus in (0, 2, 3):
|
||||
self.assertFalse(self.tx(bus=bus), bus)
|
||||
for length in range(8):
|
||||
self.assertFalse(self.tx(data=self.frame()[:length]), length)
|
||||
self.assertFalse(self.tx(data=self.frame() + bytes(4)))
|
||||
self.assertFalse(self.tx(data=self.template), 'a neutral frame is not a request')
|
||||
self.assertEqual(self.tokens(), TOKENS - len(TICKS))
|
||||
self.assertFalse(self.state(PENDING))
|
||||
self.assertTrue(self.tx())
|
||||
|
||||
def test_frame_built_from_an_older_template_is_refused(self):
|
||||
self.template = NEUTRAL_BUSY
|
||||
self.step()
|
||||
self.assertFalse(self.tx(data=self.frame(template=NEUTRAL)))
|
||||
self.assertTrue(self.tx())
|
||||
|
||||
# ***** engagement and vehicle state *****
|
||||
|
||||
def test_engagement_gates(self):
|
||||
gates = {
|
||||
'controls': (lambda: self.lib.set_controls_allowed(False), self.force_controls),
|
||||
'heartbeat': (lambda: self.lib.set_aol_test_heartbeat(False), lambda: self.lib.set_aol_test_heartbeat(True)),
|
||||
'relay': (lambda: self.lib.set_relay_malfunction(True), lambda: self.lib.set_relay_malfunction(False)),
|
||||
'standstill': (lambda: self.step(standstill=True), lambda: self.step(standstill=False)),
|
||||
'stock AEB': (lambda: self.step(aeb=1), lambda: self.step(aeb=0)),
|
||||
'door': (lambda: self.step(door=True), lambda: self.step(door=False)),
|
||||
'belt': (lambda: self.step(belt=False), lambda: self.step(belt=True)),
|
||||
}
|
||||
for gear in (0, 1, 2, 3, 5, 6, 7):
|
||||
gates[f'gear {gear}'] = (lambda gear=gear: self.step(gear=gear), lambda: self.step(gear=4))
|
||||
for name, (fault, clear) in gates.items():
|
||||
with self.subTest(gate=name):
|
||||
self.blocked_until(fault, clear)
|
||||
self.assertTrue(self.lib.get_controls_allowed())
|
||||
|
||||
def test_brake_blocks_even_with_controls_forced(self):
|
||||
def brake():
|
||||
self.step(brake=True)
|
||||
self.assertFalse(self.lib.get_controls_allowed())
|
||||
self.force_controls()
|
||||
|
||||
def release():
|
||||
self.step(brake=False)
|
||||
self.force_controls()
|
||||
self.blocked_until(brake, release)
|
||||
|
||||
def test_required_message_health_is_part_of_every_request(self):
|
||||
def stale():
|
||||
# EPAS3S_sysStatus is a 100 Hz source: older than 100 ms is unhealthy long before it is lagging.
|
||||
self.step(us=60_000, skip=('EPAS3S_sysStatus',))
|
||||
self.step(us=40_001, skip=('EPAS3S_sysStatus',))
|
||||
self.assertTrue(self.lib.get_controls_allowed())
|
||||
self.blocked_until(stale, self.step)
|
||||
|
||||
def test_stock_lkas_blocks_while_engaged(self):
|
||||
def stock_lkas():
|
||||
self.step(state=1)
|
||||
self.step(stock_type=2) # rising edge while not engaged latches stock LKAS
|
||||
self.step(state=2)
|
||||
self.assertTrue(self.lib.get_controls_allowed())
|
||||
self.blocked_until(stock_lkas, lambda: self.step(stock_type=0))
|
||||
|
||||
def test_autopark_blocks_even_with_controls_forced(self):
|
||||
def autopark():
|
||||
self.step(state=1)
|
||||
self.step(autopark=3)
|
||||
self.step(state=2)
|
||||
self.assertFalse(self.lib.get_controls_allowed())
|
||||
self.assertTrue(self.state(ACTIVE))
|
||||
self.force_controls()
|
||||
self.blocked_until(autopark, lambda: self.step(autopark=0))
|
||||
|
||||
def test_only_enabled_and_override_cruise_states_are_active(self):
|
||||
for state in (0, 1, 3, 5, 6, 7):
|
||||
with self.subTest(state=state):
|
||||
def inactive(state=state):
|
||||
self.step(state=state)
|
||||
self.assertFalse(self.state(ACTIVE))
|
||||
self.force_controls()
|
||||
self.blocked_until(inactive, lambda: self.step(state=2))
|
||||
|
||||
def test_selected_speed_bounds(self):
|
||||
for refused, admitted in ((2, 3), (508, 507), (0, 4), (511, 506)):
|
||||
with self.subTest(refused=refused, admitted=admitted):
|
||||
self.blocked_until(lambda refused=refused: self.step(speed=refused), lambda admitted=admitted: self.step(speed=admitted))
|
||||
|
||||
# ***** DI_state tracking *****
|
||||
|
||||
def test_counter_gap_withholds_the_frame_and_the_request(self):
|
||||
for gap in (0, 2, 15):
|
||||
with self.subTest(gap=gap):
|
||||
def skipped(gap=gap):
|
||||
self.advance(20_000)
|
||||
self.assertTrue(self.di(counter=(self.counter + gap) % 16, speed=2, state=1, units=1))
|
||||
self.assertEqual(self.state(), READY & ~DI_VALID, 'a frame out of sequence updates nothing but the counter')
|
||||
self.force_controls() # the shared cruise check has no such counter rule
|
||||
self.blocked_until(skipped, lambda: self.step(speed=120, state=2, units=0))
|
||||
self.assertEqual(self.state(), READY | PENDING | SENT)
|
||||
|
||||
def test_out_of_sequence_frame_cannot_release_or_block_a_request(self):
|
||||
self.assertTrue(self.tx())
|
||||
self.advance(20_000)
|
||||
self.assertTrue(self.di(counter=(self.counter + 5) % 16, speed=130, units=1))
|
||||
self.assertEqual(self.state(), (READY & ~DI_VALID) | PENDING | SENT)
|
||||
self.assertTrue(self.di(speed=120, units=0))
|
||||
self.assertEqual(self.state(), READY | PENDING | SENT)
|
||||
|
||||
def test_first_frame_of_a_session_is_taken_whatever_its_counter(self):
|
||||
self.step()
|
||||
self.assertEqual(self.counter, 4)
|
||||
self.assertEqual(self.lib.set_safety_hooks(TESLA, self.WORD), 0)
|
||||
self.lib.set_aol_test_heartbeat(True)
|
||||
self.assertEqual(self.state(), ENABLED)
|
||||
self.advance(20_000)
|
||||
self.feed(skip=('DI_state',))
|
||||
self.assertTrue(self.di(counter=9))
|
||||
self.lib.safety_tick()
|
||||
self.wheel()
|
||||
self.assertEqual(self.state(), READY)
|
||||
self.assertTrue(self.tx())
|
||||
|
||||
def test_gear_and_occupant_tracking(self):
|
||||
for gear in range(8):
|
||||
self.step(gear=gear)
|
||||
self.assertEqual(bool(self.state(DRIVE)), gear == 4, gear)
|
||||
for door in (False, True):
|
||||
for belt in (False, True):
|
||||
self.step(door=door, belt=belt)
|
||||
self.assertEqual(bool(self.state(OCCUPANT)), belt and not door, (door, belt))
|
||||
for state in range(8):
|
||||
self.step(state=state)
|
||||
self.assertEqual(bool(self.state(ACTIVE)), state in (2, 4), state)
|
||||
|
||||
# ***** wheel frame tracking *****
|
||||
|
||||
def test_wheel_frame_is_needed_before_any_request(self):
|
||||
self.start(self.WORD, ready=False)
|
||||
for _ in range(3):
|
||||
self.step(wheel=False)
|
||||
self.assertEqual(self.state(), READY & ~(SEEN | NEUTRAL_SEEN))
|
||||
self.assertFalse(self.tx())
|
||||
for bus in (0, 2):
|
||||
self.wheel(bus=bus)
|
||||
for address in (0x3C1, 0x3C3, 0x3DF):
|
||||
self.wheel(address=address)
|
||||
self.assertEqual(self.state(), READY & ~(SEEN | NEUTRAL_SEEN))
|
||||
self.assertFalse(self.tx())
|
||||
self.wheel()
|
||||
self.assertEqual(self.state(), READY)
|
||||
self.assertTrue(self.tx())
|
||||
|
||||
def test_malformed_and_other_index_wheel_frames(self):
|
||||
for length in (*range(8), 12, 16):
|
||||
with self.subTest(length=length):
|
||||
self.blocked_until(lambda length=length: self.wheel(data=(NEUTRAL + bytes(8))[:length]), self.wheel)
|
||||
for index in (2, 3):
|
||||
with self.subTest(index=index):
|
||||
def other(index=index):
|
||||
self.wheel(data=bytes((NEUTRAL[0] & 0xFC | index,)) + NEUTRAL[1:])
|
||||
self.assertEqual(self.state(), READY & ~(SEEN | NEUTRAL_SEEN))
|
||||
self.blocked_until(other, self.wheel)
|
||||
|
||||
def test_index_zero_frame_is_ignored(self):
|
||||
self.wheel(data=bytes(8))
|
||||
self.wheel(data=bytes((0xFC,)) + bytes(7 * (0xFF,)))
|
||||
self.assertEqual(self.state(), READY)
|
||||
self.assertTrue(self.tx())
|
||||
# It is not a wheel frame: it neither refreshes the template nor counts as a newer one.
|
||||
self.advance(20_000)
|
||||
self.feed(speed=self.car['speed'] + 2)
|
||||
self.wheel(data=bytes(8))
|
||||
self.assertFalse(self.state(PENDING))
|
||||
self.assertFalse(self.tx())
|
||||
self.wheel()
|
||||
self.assertTrue(self.tx())
|
||||
|
||||
def test_any_driver_input_on_the_wheel_refuses_until_neutral_again(self):
|
||||
checked = (*range(3, 7), *range(8, 22), *range(24, 30), *range(32, 36))
|
||||
for bit in range(2, 64):
|
||||
with self.subTest(bit=bit):
|
||||
self.start(self.WORD)
|
||||
self.step()
|
||||
data = bytearray(NEUTRAL)
|
||||
data[bit // 8] ^= 1 << (bit % 8)
|
||||
self.wheel(data=data)
|
||||
self.assertEqual(bool(self.state(NEUTRAL_SEEN)), bit not in checked)
|
||||
self.assertTrue(self.state(SEEN))
|
||||
if bit in checked:
|
||||
self.assertFalse(self.tx())
|
||||
self.assertFalse(self.tx(data=self.frame(template=data)))
|
||||
self.wheel()
|
||||
self.assertTrue(self.tx())
|
||||
else:
|
||||
self.assertFalse(self.tx(), 'the newest neutral frame is the template')
|
||||
self.assertTrue(self.tx(data=self.frame(template=data)))
|
||||
|
||||
def test_neutral_matches_the_sender_for_every_two_bit_deviation(self):
|
||||
for first in range(2, 64):
|
||||
for second in range(first, 64):
|
||||
data = bytearray(NEUTRAL)
|
||||
data[first // 8] ^= 1 << (first % 8)
|
||||
if second != first:
|
||||
data[second // 8] ^= 1 << (second % 8)
|
||||
self.wheel(data=data)
|
||||
self.assertEqual(bool(self.state(NEUTRAL_SEEN)), neutral_wheel(bytes(data)), data.hex())
|
||||
self.assertEqual(scroll_request(bytes(data), 1) is not None, neutral_wheel(bytes(data)))
|
||||
|
||||
# ***** freshness *****
|
||||
|
||||
def test_wheel_frame_is_current_for_250ms(self):
|
||||
for age, admitted in ((250_000, True), (250_001, False)):
|
||||
with self.subTest(age=age):
|
||||
self.start(self.WORD)
|
||||
self.step()
|
||||
self.step(us=200_000, wheel=False)
|
||||
self.advance(age - 200_000)
|
||||
self.assertEqual(self.tx(), admitted)
|
||||
if not admitted:
|
||||
self.assertEqual(self.state(), READY)
|
||||
self.wheel()
|
||||
self.assertTrue(self.tx())
|
||||
|
||||
def test_selected_speed_is_current_for_250ms(self):
|
||||
for age, admitted in ((250_000, True), (250_001, False)):
|
||||
with self.subTest(age=age):
|
||||
self.start(self.WORD)
|
||||
self.step()
|
||||
self.step(us=200_000, skip=('DI_state',))
|
||||
self.advance(age - 200_000)
|
||||
self.assertEqual(self.tx(), admitted)
|
||||
if not admitted:
|
||||
self.assertEqual(self.state(), READY)
|
||||
self.assertTrue(self.di())
|
||||
self.assertTrue(self.tx())
|
||||
|
||||
# ***** one request at a time *****
|
||||
|
||||
def test_request_stays_open_until_the_selected_speed_moves(self):
|
||||
self.assertTrue(self.tx())
|
||||
for _ in range(5):
|
||||
self.step()
|
||||
self.assertTrue(self.state(PENDING))
|
||||
self.assertFalse(self.tx())
|
||||
self.assertEqual(self.tokens(), TOKENS - 1)
|
||||
self.answer(-1)
|
||||
self.assertFalse(self.state(PENDING))
|
||||
self.assertTrue(self.tx())
|
||||
self.assertEqual(self.tokens(), TOKENS - 2)
|
||||
|
||||
def test_unanswered_request_is_released_after_800ms(self):
|
||||
self.assertTrue(self.tx())
|
||||
for _ in range(8):
|
||||
self.step(us=100_000)
|
||||
self.assertFalse(self.tx(), 'still open at exactly 800 ms')
|
||||
self.assertTrue(self.state(PENDING))
|
||||
self.advance(1)
|
||||
self.assertTrue(self.tx())
|
||||
self.assertEqual(self.tokens(), TOKENS - 2)
|
||||
|
||||
def test_each_request_needs_a_newer_wheel_frame(self):
|
||||
self.assertTrue(self.tx())
|
||||
self.advance(20_000)
|
||||
self.feed(speed=self.car['speed'] + 2)
|
||||
self.assertEqual(self.state(), READY | SENT)
|
||||
self.assertFalse(self.tx())
|
||||
self.advance(1)
|
||||
self.wheel()
|
||||
self.assertTrue(self.tx())
|
||||
|
||||
def test_cruise_off_or_standby_closes_the_request(self):
|
||||
for state in (0, 1):
|
||||
with self.subTest(state=state):
|
||||
self.start(self.WORD)
|
||||
self.assertTrue(self.tx())
|
||||
self.step(state=state)
|
||||
self.assertEqual(self.state(), READY & ~ACTIVE)
|
||||
self.step(state=2)
|
||||
self.assertTrue(self.tx())
|
||||
|
||||
def test_units_change_during_a_request_blocks_until_cruise_is_off(self):
|
||||
for release in (0, 1):
|
||||
for moved in (0, 2):
|
||||
with self.subTest(release=release, moved=moved):
|
||||
self.start(self.WORD)
|
||||
self.assertTrue(self.tx())
|
||||
self.step(units=1, speed=self.car['speed'] + moved)
|
||||
self.assertEqual(self.state(), READY | BLOCKED | SENT | (0 if moved else PENDING))
|
||||
self.answer()
|
||||
for state in (2, 3, 4, 6, 7, 5):
|
||||
self.step(state=state)
|
||||
self.assertTrue(self.state(BLOCKED), state)
|
||||
self.step(state=2)
|
||||
self.force_controls()
|
||||
self.assertFalse(self.tx())
|
||||
self.assertEqual(self.tokens(), TOKENS - 1)
|
||||
self.step(state=release)
|
||||
self.assertFalse(self.state(BLOCKED | PENDING | SENT))
|
||||
self.step(state=2)
|
||||
self.assertTrue(self.tx())
|
||||
|
||||
def test_units_change_with_no_request_open_does_not_block(self):
|
||||
self.assertTrue(self.tx())
|
||||
self.answer()
|
||||
self.step(units=1)
|
||||
self.assertEqual(self.state(), READY | SENT)
|
||||
self.assertTrue(self.tx())
|
||||
self.step(units=1, speed=self.car['speed'] + 2)
|
||||
self.assertEqual(self.state(), READY | SENT)
|
||||
|
||||
# ***** rate limit *****
|
||||
|
||||
def burst(self, count):
|
||||
for sent in range(count):
|
||||
self.assertTrue(self.tx(), sent)
|
||||
self.answer(1 if sent % 2 else -1, us=5_000)
|
||||
|
||||
def test_thirty_requests_then_one_per_second(self):
|
||||
self.step(us=10_000_000) # an idle start earns nothing above the full bucket
|
||||
start = self.now
|
||||
self.burst(TOKENS)
|
||||
self.assertEqual(self.tokens(), 0)
|
||||
self.assertFalse(self.tx())
|
||||
for second in (1, 2, 3):
|
||||
self.step(us=start + second * 1_000_000 - 1 - self.now, speed=self.car['speed'] + 2)
|
||||
self.assertFalse(self.tx(), 'one microsecond early')
|
||||
self.assertEqual(self.tokens(), 0)
|
||||
self.advance(1)
|
||||
self.assertTrue(self.tx())
|
||||
self.assertEqual(self.tokens(), 0)
|
||||
# Five idle seconds earn five requests, not a new burst.
|
||||
self.step(us=start + 8_000_000 - self.now, speed=self.car['speed'] + 2)
|
||||
self.burst(5)
|
||||
self.assertFalse(self.tx())
|
||||
self.assertEqual(self.tokens(), 0)
|
||||
# However long the pause, the bucket never holds more than thirty.
|
||||
self.step(us=600_000_000)
|
||||
self.burst(TOKENS)
|
||||
self.assertFalse(self.tx())
|
||||
self.assertEqual(self.tokens(), 0)
|
||||
|
||||
def test_refused_attempts_do_not_earn_or_spend_tokens(self):
|
||||
self.burst(3)
|
||||
spent = self.now
|
||||
for _ in range(40):
|
||||
self.step(us=20_000)
|
||||
self.assertFalse(self.tx(0))
|
||||
self.assertFalse(self.tx(bus=0))
|
||||
self.assertLess(self.now - spent, 1_000_000)
|
||||
self.assertEqual(self.tokens(), TOKENS - 3)
|
||||
self.assertFalse(self.state(PENDING))
|
||||
|
||||
def test_timer_wraparound_keeps_every_window(self):
|
||||
self.start(self.WORD, now=(1 << 32) - 300_000)
|
||||
self.assertTrue(self.tx())
|
||||
for _ in range(8):
|
||||
self.step(us=100_000)
|
||||
self.assertGreater(self.now, 1 << 32)
|
||||
self.assertFalse(self.tx())
|
||||
self.advance(1)
|
||||
self.assertTrue(self.tx())
|
||||
self.answer()
|
||||
self.step(us=200_000, wheel=False)
|
||||
self.advance(50_001)
|
||||
self.assertFalse(self.tx())
|
||||
self.wheel()
|
||||
self.assertTrue(self.tx())
|
||||
self.assertEqual(self.tokens(), TOKENS - 2, 'three sent, one earned back a second after the first')
|
||||
|
||||
# ***** resets *****
|
||||
|
||||
def test_reselecting_the_mode_starts_cold(self):
|
||||
self.assertTrue(self.tx())
|
||||
self.step(units=1)
|
||||
self.assertEqual(self.state(), READY | PENDING | BLOCKED | SENT)
|
||||
self.assertEqual(self.tokens(), TOKENS - 1)
|
||||
used = self.frame()
|
||||
for word in (self.WORD, SYNC | 3329, 1, self.WORD):
|
||||
with self.subTest(word=word):
|
||||
self.assertEqual(self.lib.set_safety_hooks(TESLA, word), 0)
|
||||
self.assertEqual(self.state(), ENABLED if word & SYNC else 0)
|
||||
self.assertEqual(self.tokens(), TOKENS)
|
||||
self.lib.set_aol_test_heartbeat(True)
|
||||
self.force_controls()
|
||||
self.assertFalse(self.tx(data=used), 'nothing from the last session may be sent')
|
||||
self.assertFalse(self.hook())
|
||||
# A new session needs its own traffic: the required messages, then a wheel frame.
|
||||
self.advance(20_000)
|
||||
self.feed(units=0)
|
||||
self.assertEqual(self.state(), READY & ~(SEEN | NEUTRAL_SEEN))
|
||||
self.assertFalse(self.tx(data=used))
|
||||
self.wheel()
|
||||
self.assertTrue(self.tx())
|
||||
self.assertEqual(self.tokens(), TOKENS - 1)
|
||||
|
||||
def test_wheel_frame_is_never_forwarded_or_a_relay_fault(self):
|
||||
self.lib.init_tests() # counts the mode as settled, so relay checks are live
|
||||
self.lib.set_timer(self.now & 0xFFFFFFFF)
|
||||
for _ in range(5):
|
||||
self.step()
|
||||
self.assertTrue(self.tx())
|
||||
self.assertFalse(self.lib.get_relay_malfunction())
|
||||
self.assertEqual([self.lib.safety_fwd_hook(bus, WHEEL) for bus in range(3)], [2, -1, 0])
|
||||
|
||||
|
||||
class TestTeslaSpeedSyncScreenAol(TestTeslaSpeedSync):
|
||||
"""The same request rules on a screen AOL word with its opt-in saved, as most cars in the field will run."""
|
||||
WORD = SYNC | 1793
|
||||
EXPERIENCE = 32
|
||||
|
||||
|
||||
class TestTeslaSpeedSyncOrdinaryAol(TestTeslaSpeedSync):
|
||||
"""The same request rules on an ordinary AOL word with its opt-in saved."""
|
||||
WORD = SYNC | 3329
|
||||
EXPERIENCE = 32
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -480,6 +480,21 @@ struct SlcAction @0x9ccdc8676701b412 {
|
||||
sourceCarStateMonoTime @10 :UInt64;
|
||||
carParamsFingerprint @11 :Text;
|
||||
targetSpeedMps @12 :Float32;
|
||||
stepUnits @13 :Int8; # Tesla scroll: +-1 display unit, or +-5 to the next multiple of five
|
||||
sourceTeslaGesture @14 :TeslaGesture; # optional Tesla wheel-gesture provenance; never an action
|
||||
}
|
||||
|
||||
struct TeslaGesture {
|
||||
version @0 :UInt16;
|
||||
workerSession @1 :Text;
|
||||
sequence @2 :UInt64;
|
||||
sourceCanBootTime @3 :UInt64;
|
||||
sourceCanFrameIndex @4 :UInt16;
|
||||
name @5 :Text;
|
||||
fast @6 :Bool;
|
||||
assignmentsHash @7 :Text;
|
||||
vehicleHash @8 :Text;
|
||||
driveStartMonoTime @9 :UInt64;
|
||||
}
|
||||
|
||||
struct ConditionalManualAction {
|
||||
@@ -512,6 +527,7 @@ struct SlcAction @0x9ccdc8676701b412 {
|
||||
forceCoastToggle @10;
|
||||
pulseGlideToggle @11;
|
||||
disengageRequest @12;
|
||||
cruiseStep @13;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6385,7 +6385,7 @@ const ::capnp::_::RawSchema s_9a4b2a0189fe1224 = {
|
||||
};
|
||||
#endif // !CAPNP_LITE
|
||||
CAPNP_DEFINE_ENUM(Choice_9a4b2a0189fe1224, 9a4b2a0189fe1224);
|
||||
static const ::capnp::_::AlignedData<176> b_9ccdc8676701b412 = {
|
||||
static const ::capnp::_::AlignedData<180> b_9ccdc8676701b412 = {
|
||||
{ 0, 0, 0, 0, 5, 0, 6, 0,
|
||||
18, 180, 1, 103, 103, 200, 205, 156,
|
||||
13, 0, 0, 0, 1, 0, 5, 0,
|
||||
@@ -6393,24 +6393,28 @@ static const ::capnp::_::AlignedData<176> b_9ccdc8676701b412 = {
|
||||
4, 0, 7, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
21, 0, 0, 0, 186, 0, 0, 0,
|
||||
29, 0, 0, 0, 55, 0, 0, 0,
|
||||
29, 0, 0, 0, 71, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
77, 0, 0, 0, 255, 1, 0, 0,
|
||||
93, 0, 0, 0, 255, 1, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
99, 117, 115, 116, 111, 109, 46, 99,
|
||||
97, 112, 110, 112, 58, 83, 108, 99,
|
||||
65, 99, 116, 105, 111, 110, 0, 0,
|
||||
12, 0, 0, 0, 1, 0, 1, 0,
|
||||
16, 0, 0, 0, 1, 0, 1, 0,
|
||||
105, 30, 140, 170, 192, 231, 57, 181,
|
||||
17, 0, 0, 0, 186, 0, 0, 0,
|
||||
25, 0, 0, 0, 186, 0, 0, 0,
|
||||
172, 250, 175, 77, 32, 114, 213, 254,
|
||||
29, 0, 0, 0, 106, 0, 0, 0,
|
||||
169, 174, 255, 224, 77, 245, 161, 139,
|
||||
21, 0, 0, 0, 194, 0, 0, 0,
|
||||
29, 0, 0, 0, 194, 0, 0, 0,
|
||||
149, 27, 24, 102, 230, 217, 203, 184,
|
||||
25, 0, 0, 0, 42, 0, 0, 0,
|
||||
33, 0, 0, 0, 42, 0, 0, 0,
|
||||
67, 111, 110, 116, 114, 111, 108, 108,
|
||||
101, 114, 67, 114, 117, 105, 115, 101,
|
||||
65, 99, 116, 105, 111, 110, 0, 0,
|
||||
84, 101, 115, 108, 97, 71, 101, 115,
|
||||
116, 117, 114, 101, 0, 0, 0, 0,
|
||||
67, 111, 110, 100, 105, 116, 105, 111,
|
||||
110, 97, 108, 77, 97, 110, 117, 97,
|
||||
108, 65, 99, 116, 105, 111, 110, 0,
|
||||
@@ -6573,21 +6577,21 @@ static const ::capnp::_::RawSchema* const d_9ccdc8676701b412[] = {
|
||||
static const uint16_t m_9ccdc8676701b412[] = {5, 6, 7, 2, 4, 3, 1, 0, 8};
|
||||
static const uint16_t i_9ccdc8676701b412[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
|
||||
const ::capnp::_::RawSchema s_9ccdc8676701b412 = {
|
||||
0x9ccdc8676701b412, b_9ccdc8676701b412.words, 176, d_9ccdc8676701b412, m_9ccdc8676701b412,
|
||||
0x9ccdc8676701b412, b_9ccdc8676701b412.words, 180, d_9ccdc8676701b412, m_9ccdc8676701b412,
|
||||
3, 9, i_9ccdc8676701b412, nullptr, nullptr, { &s_9ccdc8676701b412, nullptr, nullptr, 0, 0, nullptr }, false
|
||||
};
|
||||
#endif // !CAPNP_LITE
|
||||
static const ::capnp::_::AlignedData<234> b_b539e7c0aa8c1e69 = {
|
||||
static const ::capnp::_::AlignedData<267> b_b539e7c0aa8c1e69 = {
|
||||
{ 0, 0, 0, 0, 5, 0, 6, 0,
|
||||
105, 30, 140, 170, 192, 231, 57, 181,
|
||||
23, 0, 0, 0, 1, 0, 7, 0,
|
||||
18, 180, 1, 103, 103, 200, 205, 156,
|
||||
4, 0, 7, 0, 0, 0, 0, 0,
|
||||
5, 0, 7, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
21, 0, 0, 0, 114, 1, 0, 0,
|
||||
41, 0, 0, 0, 7, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
37, 0, 0, 0, 223, 2, 0, 0,
|
||||
37, 0, 0, 0, 79, 3, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
99, 117, 115, 116, 111, 109, 46, 99,
|
||||
@@ -6597,98 +6601,112 @@ static const ::capnp::_::AlignedData<234> b_b539e7c0aa8c1e69 = {
|
||||
114, 67, 114, 117, 105, 115, 101, 65,
|
||||
99, 116, 105, 111, 110, 0, 0, 0,
|
||||
0, 0, 0, 0, 1, 0, 1, 0,
|
||||
52, 0, 0, 0, 3, 0, 4, 0,
|
||||
60, 0, 0, 0, 3, 0, 4, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 1, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
93, 1, 0, 0, 66, 0, 0, 0,
|
||||
149, 1, 0, 0, 66, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
88, 1, 0, 0, 3, 0, 1, 0,
|
||||
100, 1, 0, 0, 2, 0, 1, 0,
|
||||
144, 1, 0, 0, 3, 0, 1, 0,
|
||||
156, 1, 0, 0, 2, 0, 1, 0,
|
||||
1, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 1, 0, 1, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
97, 1, 0, 0, 82, 0, 0, 0,
|
||||
153, 1, 0, 0, 82, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
96, 1, 0, 0, 3, 0, 1, 0,
|
||||
108, 1, 0, 0, 2, 0, 1, 0,
|
||||
152, 1, 0, 0, 3, 0, 1, 0,
|
||||
164, 1, 0, 0, 2, 0, 1, 0,
|
||||
2, 0, 0, 0, 1, 0, 0, 0,
|
||||
0, 0, 1, 0, 2, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
105, 1, 0, 0, 74, 0, 0, 0,
|
||||
161, 1, 0, 0, 74, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
104, 1, 0, 0, 3, 0, 1, 0,
|
||||
116, 1, 0, 0, 2, 0, 1, 0,
|
||||
160, 1, 0, 0, 3, 0, 1, 0,
|
||||
172, 1, 0, 0, 2, 0, 1, 0,
|
||||
3, 0, 0, 0, 2, 0, 0, 0,
|
||||
0, 0, 1, 0, 3, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
113, 1, 0, 0, 138, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
116, 1, 0, 0, 3, 0, 1, 0,
|
||||
128, 1, 0, 0, 2, 0, 1, 0,
|
||||
4, 0, 0, 0, 3, 0, 0, 0,
|
||||
0, 0, 1, 0, 4, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
125, 1, 0, 0, 154, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
128, 1, 0, 0, 3, 0, 1, 0,
|
||||
140, 1, 0, 0, 2, 0, 1, 0,
|
||||
5, 0, 0, 0, 4, 0, 0, 0,
|
||||
0, 0, 1, 0, 5, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
137, 1, 0, 0, 154, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
140, 1, 0, 0, 3, 0, 1, 0,
|
||||
152, 1, 0, 0, 2, 0, 1, 0,
|
||||
6, 0, 0, 0, 1, 0, 0, 0,
|
||||
0, 0, 1, 0, 6, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
149, 1, 0, 0, 122, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
148, 1, 0, 0, 3, 0, 1, 0,
|
||||
160, 1, 0, 0, 2, 0, 1, 0,
|
||||
7, 0, 0, 0, 5, 0, 0, 0,
|
||||
0, 0, 1, 0, 7, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
157, 1, 0, 0, 202, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
164, 1, 0, 0, 3, 0, 1, 0,
|
||||
176, 1, 0, 0, 2, 0, 1, 0,
|
||||
8, 0, 0, 0, 2, 0, 0, 0,
|
||||
0, 0, 1, 0, 8, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
173, 1, 0, 0, 90, 0, 0, 0,
|
||||
169, 1, 0, 0, 138, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
172, 1, 0, 0, 3, 0, 1, 0,
|
||||
184, 1, 0, 0, 2, 0, 1, 0,
|
||||
9, 0, 0, 0, 2, 0, 0, 0,
|
||||
0, 0, 1, 0, 9, 0, 0, 0,
|
||||
4, 0, 0, 0, 3, 0, 0, 0,
|
||||
0, 0, 1, 0, 4, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
181, 1, 0, 0, 82, 0, 0, 0,
|
||||
181, 1, 0, 0, 154, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
180, 1, 0, 0, 3, 0, 1, 0,
|
||||
192, 1, 0, 0, 2, 0, 1, 0,
|
||||
10, 0, 0, 0, 6, 0, 0, 0,
|
||||
0, 0, 1, 0, 10, 0, 0, 0,
|
||||
184, 1, 0, 0, 3, 0, 1, 0,
|
||||
196, 1, 0, 0, 2, 0, 1, 0,
|
||||
5, 0, 0, 0, 4, 0, 0, 0,
|
||||
0, 0, 1, 0, 5, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
189, 1, 0, 0, 186, 0, 0, 0,
|
||||
193, 1, 0, 0, 154, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
192, 1, 0, 0, 3, 0, 1, 0,
|
||||
204, 1, 0, 0, 2, 0, 1, 0,
|
||||
11, 0, 0, 0, 3, 0, 0, 0,
|
||||
0, 0, 1, 0, 11, 0, 0, 0,
|
||||
196, 1, 0, 0, 3, 0, 1, 0,
|
||||
208, 1, 0, 0, 2, 0, 1, 0,
|
||||
6, 0, 0, 0, 1, 0, 0, 0,
|
||||
0, 0, 1, 0, 6, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
201, 1, 0, 0, 170, 0, 0, 0,
|
||||
205, 1, 0, 0, 122, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
204, 1, 0, 0, 3, 0, 1, 0,
|
||||
216, 1, 0, 0, 2, 0, 1, 0,
|
||||
7, 0, 0, 0, 5, 0, 0, 0,
|
||||
0, 0, 1, 0, 7, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
213, 1, 0, 0, 202, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
220, 1, 0, 0, 3, 0, 1, 0,
|
||||
232, 1, 0, 0, 2, 0, 1, 0,
|
||||
8, 0, 0, 0, 2, 0, 0, 0,
|
||||
0, 0, 1, 0, 8, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
229, 1, 0, 0, 90, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
228, 1, 0, 0, 3, 0, 1, 0,
|
||||
240, 1, 0, 0, 2, 0, 1, 0,
|
||||
9, 0, 0, 0, 2, 0, 0, 0,
|
||||
0, 0, 1, 0, 9, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
237, 1, 0, 0, 82, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
236, 1, 0, 0, 3, 0, 1, 0,
|
||||
248, 1, 0, 0, 2, 0, 1, 0,
|
||||
10, 0, 0, 0, 6, 0, 0, 0,
|
||||
0, 0, 1, 0, 10, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
245, 1, 0, 0, 186, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
248, 1, 0, 0, 3, 0, 1, 0,
|
||||
4, 2, 0, 0, 2, 0, 1, 0,
|
||||
11, 0, 0, 0, 3, 0, 0, 0,
|
||||
0, 0, 1, 0, 11, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
1, 2, 0, 0, 170, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
4, 2, 0, 0, 3, 0, 1, 0,
|
||||
16, 2, 0, 0, 2, 0, 1, 0,
|
||||
12, 0, 0, 0, 1, 0, 0, 0,
|
||||
0, 0, 1, 0, 12, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
213, 1, 0, 0, 122, 0, 0, 0,
|
||||
13, 2, 0, 0, 122, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
212, 1, 0, 0, 3, 0, 1, 0,
|
||||
224, 1, 0, 0, 2, 0, 1, 0,
|
||||
12, 2, 0, 0, 3, 0, 1, 0,
|
||||
24, 2, 0, 0, 2, 0, 1, 0,
|
||||
13, 0, 0, 0, 3, 0, 0, 0,
|
||||
0, 0, 1, 0, 13, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
21, 2, 0, 0, 82, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
20, 2, 0, 0, 3, 0, 1, 0,
|
||||
32, 2, 0, 0, 2, 0, 1, 0,
|
||||
14, 0, 0, 0, 4, 0, 0, 0,
|
||||
0, 0, 1, 0, 14, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
29, 2, 0, 0, 154, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
32, 2, 0, 0, 3, 0, 1, 0,
|
||||
44, 2, 0, 0, 2, 0, 1, 0,
|
||||
118, 101, 114, 115, 105, 111, 110, 0,
|
||||
7, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
@@ -6810,16 +6828,228 @@ static const ::capnp::_::AlignedData<234> b_b539e7c0aa8c1e69 = {
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
10, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
115, 116, 101, 112, 85, 110, 105, 116,
|
||||
115, 0, 0, 0, 0, 0, 0, 0,
|
||||
2, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
2, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
115, 111, 117, 114, 99, 101, 84, 101,
|
||||
115, 108, 97, 71, 101, 115, 116, 117,
|
||||
114, 101, 0, 0, 0, 0, 0, 0,
|
||||
16, 0, 0, 0, 0, 0, 0, 0,
|
||||
172, 250, 175, 77, 32, 114, 213, 254,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
16, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, }
|
||||
};
|
||||
::capnp::word const* const bp_b539e7c0aa8c1e69 = b_b539e7c0aa8c1e69.words;
|
||||
#if !CAPNP_LITE
|
||||
static const uint16_t m_b539e7c0aa8c1e69[] = {8, 9, 6, 11, 5, 3, 2, 1, 7, 10, 12, 4, 0};
|
||||
static const uint16_t i_b539e7c0aa8c1e69[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
|
||||
static const ::capnp::_::RawSchema* const d_b539e7c0aa8c1e69[] = {
|
||||
&s_fed572204daffaac,
|
||||
};
|
||||
static const uint16_t m_b539e7c0aa8c1e69[] = {8, 9, 6, 11, 5, 3, 2, 1, 7, 10, 14, 13, 12, 4, 0};
|
||||
static const uint16_t i_b539e7c0aa8c1e69[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
|
||||
const ::capnp::_::RawSchema s_b539e7c0aa8c1e69 = {
|
||||
0xb539e7c0aa8c1e69, b_b539e7c0aa8c1e69.words, 234, nullptr, m_b539e7c0aa8c1e69,
|
||||
0, 13, i_b539e7c0aa8c1e69, nullptr, nullptr, { &s_b539e7c0aa8c1e69, nullptr, nullptr, 0, 0, nullptr }, false
|
||||
0xb539e7c0aa8c1e69, b_b539e7c0aa8c1e69.words, 267, d_b539e7c0aa8c1e69, m_b539e7c0aa8c1e69,
|
||||
1, 15, i_b539e7c0aa8c1e69, nullptr, nullptr, { &s_b539e7c0aa8c1e69, nullptr, nullptr, 0, 0, nullptr }, false
|
||||
};
|
||||
#endif // !CAPNP_LITE
|
||||
static const ::capnp::_::AlignedData<179> b_fed572204daffaac = {
|
||||
{ 0, 0, 0, 0, 5, 0, 6, 0,
|
||||
172, 250, 175, 77, 32, 114, 213, 254,
|
||||
23, 0, 0, 0, 1, 0, 4, 0,
|
||||
18, 180, 1, 103, 103, 200, 205, 156,
|
||||
4, 0, 7, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
21, 0, 0, 0, 34, 1, 0, 0,
|
||||
37, 0, 0, 0, 7, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
33, 0, 0, 0, 55, 2, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
99, 117, 115, 116, 111, 109, 46, 99,
|
||||
97, 112, 110, 112, 58, 83, 108, 99,
|
||||
65, 99, 116, 105, 111, 110, 46, 84,
|
||||
101, 115, 108, 97, 71, 101, 115, 116,
|
||||
117, 114, 101, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 1, 0, 1, 0,
|
||||
40, 0, 0, 0, 3, 0, 4, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 1, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
9, 1, 0, 0, 66, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
4, 1, 0, 0, 3, 0, 1, 0,
|
||||
16, 1, 0, 0, 2, 0, 1, 0,
|
||||
1, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 1, 0, 1, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
13, 1, 0, 0, 114, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
12, 1, 0, 0, 3, 0, 1, 0,
|
||||
24, 1, 0, 0, 2, 0, 1, 0,
|
||||
2, 0, 0, 0, 1, 0, 0, 0,
|
||||
0, 0, 1, 0, 2, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
21, 1, 0, 0, 74, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
20, 1, 0, 0, 3, 0, 1, 0,
|
||||
32, 1, 0, 0, 2, 0, 1, 0,
|
||||
3, 0, 0, 0, 2, 0, 0, 0,
|
||||
0, 0, 1, 0, 3, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
29, 1, 0, 0, 146, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
32, 1, 0, 0, 3, 0, 1, 0,
|
||||
44, 1, 0, 0, 2, 0, 1, 0,
|
||||
4, 0, 0, 0, 1, 0, 0, 0,
|
||||
0, 0, 1, 0, 4, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
41, 1, 0, 0, 162, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
44, 1, 0, 0, 3, 0, 1, 0,
|
||||
56, 1, 0, 0, 2, 0, 1, 0,
|
||||
5, 0, 0, 0, 1, 0, 0, 0,
|
||||
0, 0, 1, 0, 5, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
53, 1, 0, 0, 42, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
48, 1, 0, 0, 3, 0, 1, 0,
|
||||
60, 1, 0, 0, 2, 0, 1, 0,
|
||||
6, 0, 0, 0, 32, 0, 0, 0,
|
||||
0, 0, 1, 0, 6, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
57, 1, 0, 0, 42, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
52, 1, 0, 0, 3, 0, 1, 0,
|
||||
64, 1, 0, 0, 2, 0, 1, 0,
|
||||
7, 0, 0, 0, 2, 0, 0, 0,
|
||||
0, 0, 1, 0, 7, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
61, 1, 0, 0, 130, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
60, 1, 0, 0, 3, 0, 1, 0,
|
||||
72, 1, 0, 0, 2, 0, 1, 0,
|
||||
8, 0, 0, 0, 3, 0, 0, 0,
|
||||
0, 0, 1, 0, 8, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
69, 1, 0, 0, 98, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
68, 1, 0, 0, 3, 0, 1, 0,
|
||||
80, 1, 0, 0, 2, 0, 1, 0,
|
||||
9, 0, 0, 0, 3, 0, 0, 0,
|
||||
0, 0, 1, 0, 9, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
77, 1, 0, 0, 154, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
80, 1, 0, 0, 3, 0, 1, 0,
|
||||
92, 1, 0, 0, 2, 0, 1, 0,
|
||||
118, 101, 114, 115, 105, 111, 110, 0,
|
||||
7, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
7, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
119, 111, 114, 107, 101, 114, 83, 101,
|
||||
115, 115, 105, 111, 110, 0, 0, 0,
|
||||
12, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
12, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
115, 101, 113, 117, 101, 110, 99, 101,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
9, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
9, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
115, 111, 117, 114, 99, 101, 67, 97,
|
||||
110, 66, 111, 111, 116, 84, 105, 109,
|
||||
101, 0, 0, 0, 0, 0, 0, 0,
|
||||
9, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
9, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
115, 111, 117, 114, 99, 101, 67, 97,
|
||||
110, 70, 114, 97, 109, 101, 73, 110,
|
||||
100, 101, 120, 0, 0, 0, 0, 0,
|
||||
7, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
7, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
110, 97, 109, 101, 0, 0, 0, 0,
|
||||
12, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
12, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
102, 97, 115, 116, 0, 0, 0, 0,
|
||||
1, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
1, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
97, 115, 115, 105, 103, 110, 109, 101,
|
||||
110, 116, 115, 72, 97, 115, 104, 0,
|
||||
12, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
12, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
118, 101, 104, 105, 99, 108, 101, 72,
|
||||
97, 115, 104, 0, 0, 0, 0, 0,
|
||||
12, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
12, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
100, 114, 105, 118, 101, 83, 116, 97,
|
||||
114, 116, 77, 111, 110, 111, 84, 105,
|
||||
109, 101, 0, 0, 0, 0, 0, 0,
|
||||
9, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
9, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, }
|
||||
};
|
||||
::capnp::word const* const bp_fed572204daffaac = b_fed572204daffaac.words;
|
||||
#if !CAPNP_LITE
|
||||
static const uint16_t m_fed572204daffaac[] = {7, 9, 6, 5, 2, 3, 4, 8, 0, 1};
|
||||
static const uint16_t i_fed572204daffaac[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
|
||||
const ::capnp::_::RawSchema s_fed572204daffaac = {
|
||||
0xfed572204daffaac, b_fed572204daffaac.words, 179, nullptr, m_fed572204daffaac,
|
||||
0, 10, i_fed572204daffaac, nullptr, nullptr, { &s_fed572204daffaac, nullptr, nullptr, 0, 0, nullptr }, false
|
||||
};
|
||||
#endif // !CAPNP_LITE
|
||||
static const ::capnp::_::AlignedData<236> b_8ba1f54de0ffaea9 = {
|
||||
@@ -7072,7 +7302,7 @@ const ::capnp::_::RawSchema s_8ba1f54de0ffaea9 = {
|
||||
1, 13, i_8ba1f54de0ffaea9, nullptr, nullptr, { &s_8ba1f54de0ffaea9, nullptr, nullptr, 0, 0, nullptr }, false
|
||||
};
|
||||
#endif // !CAPNP_LITE
|
||||
static const ::capnp::_::AlignedData<85> b_b8cbd9e666181b95 = {
|
||||
static const ::capnp::_::AlignedData<90> b_b8cbd9e666181b95 = {
|
||||
{ 0, 0, 0, 0, 5, 0, 6, 0,
|
||||
149, 27, 24, 102, 230, 217, 203, 184,
|
||||
23, 0, 0, 0, 2, 0, 0, 0,
|
||||
@@ -7082,7 +7312,7 @@ static const ::capnp::_::AlignedData<85> b_b8cbd9e666181b95 = {
|
||||
21, 0, 0, 0, 226, 0, 0, 0,
|
||||
33, 0, 0, 0, 7, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
29, 0, 0, 0, 63, 1, 0, 0,
|
||||
29, 0, 0, 0, 87, 1, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
99, 117, 115, 116, 111, 109, 46, 99,
|
||||
@@ -7090,45 +7320,48 @@ static const ::capnp::_::AlignedData<85> b_b8cbd9e666181b95 = {
|
||||
65, 99, 116, 105, 111, 110, 46, 75,
|
||||
105, 110, 100, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 1, 0, 1, 0,
|
||||
52, 0, 0, 0, 1, 0, 2, 0,
|
||||
56, 0, 0, 0, 1, 0, 2, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
149, 0, 0, 0, 66, 0, 0, 0,
|
||||
161, 0, 0, 0, 66, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
1, 0, 0, 0, 0, 0, 0, 0,
|
||||
141, 0, 0, 0, 58, 0, 0, 0,
|
||||
153, 0, 0, 0, 58, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
2, 0, 0, 0, 0, 0, 0, 0,
|
||||
133, 0, 0, 0, 58, 0, 0, 0,
|
||||
145, 0, 0, 0, 58, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
3, 0, 0, 0, 0, 0, 0, 0,
|
||||
125, 0, 0, 0, 50, 0, 0, 0,
|
||||
137, 0, 0, 0, 50, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
4, 0, 0, 0, 0, 0, 0, 0,
|
||||
117, 0, 0, 0, 170, 0, 0, 0,
|
||||
129, 0, 0, 0, 170, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
5, 0, 0, 0, 0, 0, 0, 0,
|
||||
117, 0, 0, 0, 122, 0, 0, 0,
|
||||
129, 0, 0, 0, 122, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
6, 0, 0, 0, 0, 0, 0, 0,
|
||||
113, 0, 0, 0, 122, 0, 0, 0,
|
||||
125, 0, 0, 0, 122, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
7, 0, 0, 0, 0, 0, 0, 0,
|
||||
109, 0, 0, 0, 146, 0, 0, 0,
|
||||
121, 0, 0, 0, 146, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
8, 0, 0, 0, 0, 0, 0, 0,
|
||||
109, 0, 0, 0, 170, 0, 0, 0,
|
||||
121, 0, 0, 0, 170, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
9, 0, 0, 0, 0, 0, 0, 0,
|
||||
109, 0, 0, 0, 82, 0, 0, 0,
|
||||
121, 0, 0, 0, 82, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
10, 0, 0, 0, 0, 0, 0, 0,
|
||||
105, 0, 0, 0, 138, 0, 0, 0,
|
||||
117, 0, 0, 0, 138, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
11, 0, 0, 0, 0, 0, 0, 0,
|
||||
105, 0, 0, 0, 138, 0, 0, 0,
|
||||
117, 0, 0, 0, 138, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
12, 0, 0, 0, 0, 0, 0, 0,
|
||||
105, 0, 0, 0, 138, 0, 0, 0,
|
||||
117, 0, 0, 0, 138, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
13, 0, 0, 0, 0, 0, 0, 0,
|
||||
117, 0, 0, 0, 90, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
117, 110, 107, 110, 111, 119, 110, 0,
|
||||
97, 99, 99, 101, 112, 116, 0, 0,
|
||||
@@ -7157,14 +7390,16 @@ static const ::capnp::_::AlignedData<85> b_b8cbd9e666181b95 = {
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
100, 105, 115, 101, 110, 103, 97, 103,
|
||||
101, 82, 101, 113, 117, 101, 115, 116,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, }
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
99, 114, 117, 105, 115, 101, 83, 116,
|
||||
101, 112, 0, 0, 0, 0, 0, 0, }
|
||||
};
|
||||
::capnp::word const* const bp_b8cbd9e666181b95 = b_b8cbd9e666181b95.words;
|
||||
#if !CAPNP_LITE
|
||||
static const uint16_t m_b8cbd9e666181b95[] = {1, 3, 4, 6, 5, 9, 12, 10, 11, 2, 8, 7, 0};
|
||||
static const uint16_t m_b8cbd9e666181b95[] = {1, 3, 4, 6, 5, 9, 13, 12, 10, 11, 2, 8, 7, 0};
|
||||
const ::capnp::_::RawSchema s_b8cbd9e666181b95 = {
|
||||
0xb8cbd9e666181b95, b_b8cbd9e666181b95.words, 85, nullptr, m_b8cbd9e666181b95,
|
||||
0, 13, nullptr, nullptr, nullptr, { &s_b8cbd9e666181b95, nullptr, nullptr, 0, 0, nullptr }, false
|
||||
0xb8cbd9e666181b95, b_b8cbd9e666181b95.words, 90, nullptr, m_b8cbd9e666181b95,
|
||||
0, 14, nullptr, nullptr, nullptr, { &s_b8cbd9e666181b95, nullptr, nullptr, 0, 0, nullptr }, false
|
||||
};
|
||||
#endif // !CAPNP_LITE
|
||||
CAPNP_DEFINE_ENUM(Kind_b8cbd9e666181b95, b8cbd9e666181b95);
|
||||
@@ -23035,6 +23270,18 @@ constexpr ::capnp::_::RawSchema const* SlcAction::ControllerCruiseAction::_capnp
|
||||
#endif // !CAPNP_NEED_REDUNDANT_CONSTEXPR_DECL
|
||||
#endif // !CAPNP_LITE
|
||||
|
||||
// SlcAction::TeslaGesture
|
||||
#if CAPNP_NEED_REDUNDANT_CONSTEXPR_DECL
|
||||
constexpr uint16_t SlcAction::TeslaGesture::_capnpPrivate::dataWordSize;
|
||||
constexpr uint16_t SlcAction::TeslaGesture::_capnpPrivate::pointerCount;
|
||||
#endif // !CAPNP_NEED_REDUNDANT_CONSTEXPR_DECL
|
||||
#if !CAPNP_LITE
|
||||
#if CAPNP_NEED_REDUNDANT_CONSTEXPR_DECL
|
||||
constexpr ::capnp::Kind SlcAction::TeslaGesture::_capnpPrivate::kind;
|
||||
constexpr ::capnp::_::RawSchema const* SlcAction::TeslaGesture::_capnpPrivate::schema;
|
||||
#endif // !CAPNP_NEED_REDUNDANT_CONSTEXPR_DECL
|
||||
#endif // !CAPNP_LITE
|
||||
|
||||
// SlcAction::ConditionalManualAction
|
||||
#if CAPNP_NEED_REDUNDANT_CONSTEXPR_DECL
|
||||
constexpr uint16_t SlcAction::ConditionalManualAction::_capnpPrivate::dataWordSize;
|
||||
|
||||
@@ -95,6 +95,7 @@ enum class Choice_9a4b2a0189fe1224: uint16_t {
|
||||
CAPNP_DECLARE_ENUM(Choice, 9a4b2a0189fe1224);
|
||||
CAPNP_DECLARE_SCHEMA(9ccdc8676701b412);
|
||||
CAPNP_DECLARE_SCHEMA(b539e7c0aa8c1e69);
|
||||
CAPNP_DECLARE_SCHEMA(fed572204daffaac);
|
||||
CAPNP_DECLARE_SCHEMA(8ba1f54de0ffaea9);
|
||||
CAPNP_DECLARE_SCHEMA(b8cbd9e666181b95);
|
||||
enum class Kind_b8cbd9e666181b95: uint16_t {
|
||||
@@ -111,6 +112,7 @@ enum class Kind_b8cbd9e666181b95: uint16_t {
|
||||
FORCE_COAST_TOGGLE,
|
||||
PULSE_GLIDE_TOGGLE,
|
||||
DISENGAGE_REQUEST,
|
||||
CRUISE_STEP,
|
||||
};
|
||||
CAPNP_DECLARE_ENUM(Kind, b8cbd9e666181b95);
|
||||
CAPNP_DECLARE_SCHEMA(cd96dafb67a082d0);
|
||||
@@ -841,6 +843,7 @@ struct SlcAction {
|
||||
class Builder;
|
||||
class Pipeline;
|
||||
struct ControllerCruiseAction;
|
||||
struct TeslaGesture;
|
||||
struct ConditionalManualAction;
|
||||
typedef ::capnp::schemas::Kind_b8cbd9e666181b95 Kind;
|
||||
|
||||
@@ -861,7 +864,22 @@ struct SlcAction::ControllerCruiseAction {
|
||||
class Pipeline;
|
||||
|
||||
struct _capnpPrivate {
|
||||
CAPNP_DECLARE_STRUCT_HEADER(b539e7c0aa8c1e69, 7, 4)
|
||||
CAPNP_DECLARE_STRUCT_HEADER(b539e7c0aa8c1e69, 7, 5)
|
||||
#if !CAPNP_LITE
|
||||
static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; }
|
||||
#endif // !CAPNP_LITE
|
||||
};
|
||||
};
|
||||
|
||||
struct SlcAction::TeslaGesture {
|
||||
TeslaGesture() = delete;
|
||||
|
||||
class Reader;
|
||||
class Builder;
|
||||
class Pipeline;
|
||||
|
||||
struct _capnpPrivate {
|
||||
CAPNP_DECLARE_STRUCT_HEADER(fed572204daffaac, 4, 4)
|
||||
#if !CAPNP_LITE
|
||||
static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; }
|
||||
#endif // !CAPNP_LITE
|
||||
@@ -5885,6 +5903,11 @@ public:
|
||||
|
||||
inline float getTargetSpeedMps() const;
|
||||
|
||||
inline ::int8_t getStepUnits() const;
|
||||
|
||||
inline bool hasSourceTeslaGesture() const;
|
||||
inline ::cereal::SlcAction::TeslaGesture::Reader getSourceTeslaGesture() const;
|
||||
|
||||
private:
|
||||
::capnp::_::StructReader _reader;
|
||||
template <typename, ::capnp::Kind>
|
||||
@@ -5968,6 +5991,16 @@ public:
|
||||
inline float getTargetSpeedMps();
|
||||
inline void setTargetSpeedMps(float value);
|
||||
|
||||
inline ::int8_t getStepUnits();
|
||||
inline void setStepUnits( ::int8_t value);
|
||||
|
||||
inline bool hasSourceTeslaGesture();
|
||||
inline ::cereal::SlcAction::TeslaGesture::Builder getSourceTeslaGesture();
|
||||
inline void setSourceTeslaGesture( ::cereal::SlcAction::TeslaGesture::Reader value);
|
||||
inline ::cereal::SlcAction::TeslaGesture::Builder initSourceTeslaGesture();
|
||||
inline void adoptSourceTeslaGesture(::capnp::Orphan< ::cereal::SlcAction::TeslaGesture>&& value);
|
||||
inline ::capnp::Orphan< ::cereal::SlcAction::TeslaGesture> disownSourceTeslaGesture();
|
||||
|
||||
private:
|
||||
::capnp::_::StructBuilder _builder;
|
||||
template <typename, ::capnp::Kind>
|
||||
@@ -5986,6 +6019,148 @@ public:
|
||||
inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless)
|
||||
: _typeless(kj::mv(typeless)) {}
|
||||
|
||||
inline ::cereal::SlcAction::TeslaGesture::Pipeline getSourceTeslaGesture();
|
||||
private:
|
||||
::capnp::AnyPointer::Pipeline _typeless;
|
||||
friend class ::capnp::PipelineHook;
|
||||
template <typename, ::capnp::Kind>
|
||||
friend struct ::capnp::ToDynamic_;
|
||||
};
|
||||
#endif // !CAPNP_LITE
|
||||
|
||||
class SlcAction::TeslaGesture::Reader {
|
||||
public:
|
||||
typedef TeslaGesture Reads;
|
||||
|
||||
Reader() = default;
|
||||
inline explicit Reader(::capnp::_::StructReader base): _reader(base) {}
|
||||
|
||||
inline ::capnp::MessageSize totalSize() const {
|
||||
return _reader.totalSize().asPublic();
|
||||
}
|
||||
|
||||
#if !CAPNP_LITE
|
||||
inline ::kj::StringTree toString() const {
|
||||
return ::capnp::_::structString(_reader, *_capnpPrivate::brand());
|
||||
}
|
||||
#endif // !CAPNP_LITE
|
||||
|
||||
inline ::uint16_t getVersion() const;
|
||||
|
||||
inline bool hasWorkerSession() const;
|
||||
inline ::capnp::Text::Reader getWorkerSession() const;
|
||||
|
||||
inline ::uint64_t getSequence() const;
|
||||
|
||||
inline ::uint64_t getSourceCanBootTime() const;
|
||||
|
||||
inline ::uint16_t getSourceCanFrameIndex() const;
|
||||
|
||||
inline bool hasName() const;
|
||||
inline ::capnp::Text::Reader getName() const;
|
||||
|
||||
inline bool getFast() const;
|
||||
|
||||
inline bool hasAssignmentsHash() const;
|
||||
inline ::capnp::Text::Reader getAssignmentsHash() const;
|
||||
|
||||
inline bool hasVehicleHash() const;
|
||||
inline ::capnp::Text::Reader getVehicleHash() const;
|
||||
|
||||
inline ::uint64_t getDriveStartMonoTime() const;
|
||||
|
||||
private:
|
||||
::capnp::_::StructReader _reader;
|
||||
template <typename, ::capnp::Kind>
|
||||
friend struct ::capnp::ToDynamic_;
|
||||
template <typename, ::capnp::Kind>
|
||||
friend struct ::capnp::_::PointerHelpers;
|
||||
template <typename, ::capnp::Kind>
|
||||
friend struct ::capnp::List;
|
||||
friend class ::capnp::MessageBuilder;
|
||||
friend class ::capnp::Orphanage;
|
||||
};
|
||||
|
||||
class SlcAction::TeslaGesture::Builder {
|
||||
public:
|
||||
typedef TeslaGesture Builds;
|
||||
|
||||
Builder() = delete; // Deleted to discourage incorrect usage.
|
||||
// You can explicitly initialize to nullptr instead.
|
||||
inline Builder(decltype(nullptr)) {}
|
||||
inline explicit Builder(::capnp::_::StructBuilder base): _builder(base) {}
|
||||
inline operator Reader() const { return Reader(_builder.asReader()); }
|
||||
inline Reader asReader() const { return *this; }
|
||||
|
||||
inline ::capnp::MessageSize totalSize() const { return asReader().totalSize(); }
|
||||
#if !CAPNP_LITE
|
||||
inline ::kj::StringTree toString() const { return asReader().toString(); }
|
||||
#endif // !CAPNP_LITE
|
||||
|
||||
inline ::uint16_t getVersion();
|
||||
inline void setVersion( ::uint16_t value);
|
||||
|
||||
inline bool hasWorkerSession();
|
||||
inline ::capnp::Text::Builder getWorkerSession();
|
||||
inline void setWorkerSession( ::capnp::Text::Reader value);
|
||||
inline ::capnp::Text::Builder initWorkerSession(unsigned int size);
|
||||
inline void adoptWorkerSession(::capnp::Orphan< ::capnp::Text>&& value);
|
||||
inline ::capnp::Orphan< ::capnp::Text> disownWorkerSession();
|
||||
|
||||
inline ::uint64_t getSequence();
|
||||
inline void setSequence( ::uint64_t value);
|
||||
|
||||
inline ::uint64_t getSourceCanBootTime();
|
||||
inline void setSourceCanBootTime( ::uint64_t value);
|
||||
|
||||
inline ::uint16_t getSourceCanFrameIndex();
|
||||
inline void setSourceCanFrameIndex( ::uint16_t value);
|
||||
|
||||
inline bool hasName();
|
||||
inline ::capnp::Text::Builder getName();
|
||||
inline void setName( ::capnp::Text::Reader value);
|
||||
inline ::capnp::Text::Builder initName(unsigned int size);
|
||||
inline void adoptName(::capnp::Orphan< ::capnp::Text>&& value);
|
||||
inline ::capnp::Orphan< ::capnp::Text> disownName();
|
||||
|
||||
inline bool getFast();
|
||||
inline void setFast(bool value);
|
||||
|
||||
inline bool hasAssignmentsHash();
|
||||
inline ::capnp::Text::Builder getAssignmentsHash();
|
||||
inline void setAssignmentsHash( ::capnp::Text::Reader value);
|
||||
inline ::capnp::Text::Builder initAssignmentsHash(unsigned int size);
|
||||
inline void adoptAssignmentsHash(::capnp::Orphan< ::capnp::Text>&& value);
|
||||
inline ::capnp::Orphan< ::capnp::Text> disownAssignmentsHash();
|
||||
|
||||
inline bool hasVehicleHash();
|
||||
inline ::capnp::Text::Builder getVehicleHash();
|
||||
inline void setVehicleHash( ::capnp::Text::Reader value);
|
||||
inline ::capnp::Text::Builder initVehicleHash(unsigned int size);
|
||||
inline void adoptVehicleHash(::capnp::Orphan< ::capnp::Text>&& value);
|
||||
inline ::capnp::Orphan< ::capnp::Text> disownVehicleHash();
|
||||
|
||||
inline ::uint64_t getDriveStartMonoTime();
|
||||
inline void setDriveStartMonoTime( ::uint64_t value);
|
||||
|
||||
private:
|
||||
::capnp::_::StructBuilder _builder;
|
||||
template <typename, ::capnp::Kind>
|
||||
friend struct ::capnp::ToDynamic_;
|
||||
friend class ::capnp::Orphanage;
|
||||
template <typename, ::capnp::Kind>
|
||||
friend struct ::capnp::_::PointerHelpers;
|
||||
};
|
||||
|
||||
#if !CAPNP_LITE
|
||||
class SlcAction::TeslaGesture::Pipeline {
|
||||
public:
|
||||
typedef TeslaGesture Pipelines;
|
||||
|
||||
inline Pipeline(decltype(nullptr)): _typeless(nullptr) {}
|
||||
inline explicit Pipeline(::capnp::AnyPointer::Pipeline&& typeless)
|
||||
: _typeless(kj::mv(typeless)) {}
|
||||
|
||||
private:
|
||||
::capnp::AnyPointer::Pipeline _typeless;
|
||||
friend class ::capnp::PipelineHook;
|
||||
@@ -22326,6 +22501,279 @@ inline void SlcAction::ControllerCruiseAction::Builder::setTargetSpeedMps(float
|
||||
::capnp::bounded<1>() * ::capnp::ELEMENTS, value);
|
||||
}
|
||||
|
||||
inline ::int8_t SlcAction::ControllerCruiseAction::Reader::getStepUnits() const {
|
||||
return _reader.getDataField< ::int8_t>(
|
||||
::capnp::bounded<3>() * ::capnp::ELEMENTS);
|
||||
}
|
||||
|
||||
inline ::int8_t SlcAction::ControllerCruiseAction::Builder::getStepUnits() {
|
||||
return _builder.getDataField< ::int8_t>(
|
||||
::capnp::bounded<3>() * ::capnp::ELEMENTS);
|
||||
}
|
||||
inline void SlcAction::ControllerCruiseAction::Builder::setStepUnits( ::int8_t value) {
|
||||
_builder.setDataField< ::int8_t>(
|
||||
::capnp::bounded<3>() * ::capnp::ELEMENTS, value);
|
||||
}
|
||||
|
||||
inline bool SlcAction::ControllerCruiseAction::Reader::hasSourceTeslaGesture() const {
|
||||
return !_reader.getPointerField(
|
||||
::capnp::bounded<4>() * ::capnp::POINTERS).isNull();
|
||||
}
|
||||
inline bool SlcAction::ControllerCruiseAction::Builder::hasSourceTeslaGesture() {
|
||||
return !_builder.getPointerField(
|
||||
::capnp::bounded<4>() * ::capnp::POINTERS).isNull();
|
||||
}
|
||||
inline ::cereal::SlcAction::TeslaGesture::Reader SlcAction::ControllerCruiseAction::Reader::getSourceTeslaGesture() const {
|
||||
return ::capnp::_::PointerHelpers< ::cereal::SlcAction::TeslaGesture>::get(_reader.getPointerField(
|
||||
::capnp::bounded<4>() * ::capnp::POINTERS));
|
||||
}
|
||||
inline ::cereal::SlcAction::TeslaGesture::Builder SlcAction::ControllerCruiseAction::Builder::getSourceTeslaGesture() {
|
||||
return ::capnp::_::PointerHelpers< ::cereal::SlcAction::TeslaGesture>::get(_builder.getPointerField(
|
||||
::capnp::bounded<4>() * ::capnp::POINTERS));
|
||||
}
|
||||
#if !CAPNP_LITE
|
||||
inline ::cereal::SlcAction::TeslaGesture::Pipeline SlcAction::ControllerCruiseAction::Pipeline::getSourceTeslaGesture() {
|
||||
return ::cereal::SlcAction::TeslaGesture::Pipeline(_typeless.getPointerField(4));
|
||||
}
|
||||
#endif // !CAPNP_LITE
|
||||
inline void SlcAction::ControllerCruiseAction::Builder::setSourceTeslaGesture( ::cereal::SlcAction::TeslaGesture::Reader value) {
|
||||
::capnp::_::PointerHelpers< ::cereal::SlcAction::TeslaGesture>::set(_builder.getPointerField(
|
||||
::capnp::bounded<4>() * ::capnp::POINTERS), value);
|
||||
}
|
||||
inline ::cereal::SlcAction::TeslaGesture::Builder SlcAction::ControllerCruiseAction::Builder::initSourceTeslaGesture() {
|
||||
return ::capnp::_::PointerHelpers< ::cereal::SlcAction::TeslaGesture>::init(_builder.getPointerField(
|
||||
::capnp::bounded<4>() * ::capnp::POINTERS));
|
||||
}
|
||||
inline void SlcAction::ControllerCruiseAction::Builder::adoptSourceTeslaGesture(
|
||||
::capnp::Orphan< ::cereal::SlcAction::TeslaGesture>&& value) {
|
||||
::capnp::_::PointerHelpers< ::cereal::SlcAction::TeslaGesture>::adopt(_builder.getPointerField(
|
||||
::capnp::bounded<4>() * ::capnp::POINTERS), kj::mv(value));
|
||||
}
|
||||
inline ::capnp::Orphan< ::cereal::SlcAction::TeslaGesture> SlcAction::ControllerCruiseAction::Builder::disownSourceTeslaGesture() {
|
||||
return ::capnp::_::PointerHelpers< ::cereal::SlcAction::TeslaGesture>::disown(_builder.getPointerField(
|
||||
::capnp::bounded<4>() * ::capnp::POINTERS));
|
||||
}
|
||||
|
||||
inline ::uint16_t SlcAction::TeslaGesture::Reader::getVersion() const {
|
||||
return _reader.getDataField< ::uint16_t>(
|
||||
::capnp::bounded<0>() * ::capnp::ELEMENTS);
|
||||
}
|
||||
|
||||
inline ::uint16_t SlcAction::TeslaGesture::Builder::getVersion() {
|
||||
return _builder.getDataField< ::uint16_t>(
|
||||
::capnp::bounded<0>() * ::capnp::ELEMENTS);
|
||||
}
|
||||
inline void SlcAction::TeslaGesture::Builder::setVersion( ::uint16_t value) {
|
||||
_builder.setDataField< ::uint16_t>(
|
||||
::capnp::bounded<0>() * ::capnp::ELEMENTS, value);
|
||||
}
|
||||
|
||||
inline bool SlcAction::TeslaGesture::Reader::hasWorkerSession() const {
|
||||
return !_reader.getPointerField(
|
||||
::capnp::bounded<0>() * ::capnp::POINTERS).isNull();
|
||||
}
|
||||
inline bool SlcAction::TeslaGesture::Builder::hasWorkerSession() {
|
||||
return !_builder.getPointerField(
|
||||
::capnp::bounded<0>() * ::capnp::POINTERS).isNull();
|
||||
}
|
||||
inline ::capnp::Text::Reader SlcAction::TeslaGesture::Reader::getWorkerSession() const {
|
||||
return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_reader.getPointerField(
|
||||
::capnp::bounded<0>() * ::capnp::POINTERS));
|
||||
}
|
||||
inline ::capnp::Text::Builder SlcAction::TeslaGesture::Builder::getWorkerSession() {
|
||||
return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_builder.getPointerField(
|
||||
::capnp::bounded<0>() * ::capnp::POINTERS));
|
||||
}
|
||||
inline void SlcAction::TeslaGesture::Builder::setWorkerSession( ::capnp::Text::Reader value) {
|
||||
::capnp::_::PointerHelpers< ::capnp::Text>::set(_builder.getPointerField(
|
||||
::capnp::bounded<0>() * ::capnp::POINTERS), value);
|
||||
}
|
||||
inline ::capnp::Text::Builder SlcAction::TeslaGesture::Builder::initWorkerSession(unsigned int size) {
|
||||
return ::capnp::_::PointerHelpers< ::capnp::Text>::init(_builder.getPointerField(
|
||||
::capnp::bounded<0>() * ::capnp::POINTERS), size);
|
||||
}
|
||||
inline void SlcAction::TeslaGesture::Builder::adoptWorkerSession(
|
||||
::capnp::Orphan< ::capnp::Text>&& value) {
|
||||
::capnp::_::PointerHelpers< ::capnp::Text>::adopt(_builder.getPointerField(
|
||||
::capnp::bounded<0>() * ::capnp::POINTERS), kj::mv(value));
|
||||
}
|
||||
inline ::capnp::Orphan< ::capnp::Text> SlcAction::TeslaGesture::Builder::disownWorkerSession() {
|
||||
return ::capnp::_::PointerHelpers< ::capnp::Text>::disown(_builder.getPointerField(
|
||||
::capnp::bounded<0>() * ::capnp::POINTERS));
|
||||
}
|
||||
|
||||
inline ::uint64_t SlcAction::TeslaGesture::Reader::getSequence() const {
|
||||
return _reader.getDataField< ::uint64_t>(
|
||||
::capnp::bounded<1>() * ::capnp::ELEMENTS);
|
||||
}
|
||||
|
||||
inline ::uint64_t SlcAction::TeslaGesture::Builder::getSequence() {
|
||||
return _builder.getDataField< ::uint64_t>(
|
||||
::capnp::bounded<1>() * ::capnp::ELEMENTS);
|
||||
}
|
||||
inline void SlcAction::TeslaGesture::Builder::setSequence( ::uint64_t value) {
|
||||
_builder.setDataField< ::uint64_t>(
|
||||
::capnp::bounded<1>() * ::capnp::ELEMENTS, value);
|
||||
}
|
||||
|
||||
inline ::uint64_t SlcAction::TeslaGesture::Reader::getSourceCanBootTime() const {
|
||||
return _reader.getDataField< ::uint64_t>(
|
||||
::capnp::bounded<2>() * ::capnp::ELEMENTS);
|
||||
}
|
||||
|
||||
inline ::uint64_t SlcAction::TeslaGesture::Builder::getSourceCanBootTime() {
|
||||
return _builder.getDataField< ::uint64_t>(
|
||||
::capnp::bounded<2>() * ::capnp::ELEMENTS);
|
||||
}
|
||||
inline void SlcAction::TeslaGesture::Builder::setSourceCanBootTime( ::uint64_t value) {
|
||||
_builder.setDataField< ::uint64_t>(
|
||||
::capnp::bounded<2>() * ::capnp::ELEMENTS, value);
|
||||
}
|
||||
|
||||
inline ::uint16_t SlcAction::TeslaGesture::Reader::getSourceCanFrameIndex() const {
|
||||
return _reader.getDataField< ::uint16_t>(
|
||||
::capnp::bounded<1>() * ::capnp::ELEMENTS);
|
||||
}
|
||||
|
||||
inline ::uint16_t SlcAction::TeslaGesture::Builder::getSourceCanFrameIndex() {
|
||||
return _builder.getDataField< ::uint16_t>(
|
||||
::capnp::bounded<1>() * ::capnp::ELEMENTS);
|
||||
}
|
||||
inline void SlcAction::TeslaGesture::Builder::setSourceCanFrameIndex( ::uint16_t value) {
|
||||
_builder.setDataField< ::uint16_t>(
|
||||
::capnp::bounded<1>() * ::capnp::ELEMENTS, value);
|
||||
}
|
||||
|
||||
inline bool SlcAction::TeslaGesture::Reader::hasName() const {
|
||||
return !_reader.getPointerField(
|
||||
::capnp::bounded<1>() * ::capnp::POINTERS).isNull();
|
||||
}
|
||||
inline bool SlcAction::TeslaGesture::Builder::hasName() {
|
||||
return !_builder.getPointerField(
|
||||
::capnp::bounded<1>() * ::capnp::POINTERS).isNull();
|
||||
}
|
||||
inline ::capnp::Text::Reader SlcAction::TeslaGesture::Reader::getName() const {
|
||||
return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_reader.getPointerField(
|
||||
::capnp::bounded<1>() * ::capnp::POINTERS));
|
||||
}
|
||||
inline ::capnp::Text::Builder SlcAction::TeslaGesture::Builder::getName() {
|
||||
return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_builder.getPointerField(
|
||||
::capnp::bounded<1>() * ::capnp::POINTERS));
|
||||
}
|
||||
inline void SlcAction::TeslaGesture::Builder::setName( ::capnp::Text::Reader value) {
|
||||
::capnp::_::PointerHelpers< ::capnp::Text>::set(_builder.getPointerField(
|
||||
::capnp::bounded<1>() * ::capnp::POINTERS), value);
|
||||
}
|
||||
inline ::capnp::Text::Builder SlcAction::TeslaGesture::Builder::initName(unsigned int size) {
|
||||
return ::capnp::_::PointerHelpers< ::capnp::Text>::init(_builder.getPointerField(
|
||||
::capnp::bounded<1>() * ::capnp::POINTERS), size);
|
||||
}
|
||||
inline void SlcAction::TeslaGesture::Builder::adoptName(
|
||||
::capnp::Orphan< ::capnp::Text>&& value) {
|
||||
::capnp::_::PointerHelpers< ::capnp::Text>::adopt(_builder.getPointerField(
|
||||
::capnp::bounded<1>() * ::capnp::POINTERS), kj::mv(value));
|
||||
}
|
||||
inline ::capnp::Orphan< ::capnp::Text> SlcAction::TeslaGesture::Builder::disownName() {
|
||||
return ::capnp::_::PointerHelpers< ::capnp::Text>::disown(_builder.getPointerField(
|
||||
::capnp::bounded<1>() * ::capnp::POINTERS));
|
||||
}
|
||||
|
||||
inline bool SlcAction::TeslaGesture::Reader::getFast() const {
|
||||
return _reader.getDataField<bool>(
|
||||
::capnp::bounded<32>() * ::capnp::ELEMENTS);
|
||||
}
|
||||
|
||||
inline bool SlcAction::TeslaGesture::Builder::getFast() {
|
||||
return _builder.getDataField<bool>(
|
||||
::capnp::bounded<32>() * ::capnp::ELEMENTS);
|
||||
}
|
||||
inline void SlcAction::TeslaGesture::Builder::setFast(bool value) {
|
||||
_builder.setDataField<bool>(
|
||||
::capnp::bounded<32>() * ::capnp::ELEMENTS, value);
|
||||
}
|
||||
|
||||
inline bool SlcAction::TeslaGesture::Reader::hasAssignmentsHash() const {
|
||||
return !_reader.getPointerField(
|
||||
::capnp::bounded<2>() * ::capnp::POINTERS).isNull();
|
||||
}
|
||||
inline bool SlcAction::TeslaGesture::Builder::hasAssignmentsHash() {
|
||||
return !_builder.getPointerField(
|
||||
::capnp::bounded<2>() * ::capnp::POINTERS).isNull();
|
||||
}
|
||||
inline ::capnp::Text::Reader SlcAction::TeslaGesture::Reader::getAssignmentsHash() const {
|
||||
return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_reader.getPointerField(
|
||||
::capnp::bounded<2>() * ::capnp::POINTERS));
|
||||
}
|
||||
inline ::capnp::Text::Builder SlcAction::TeslaGesture::Builder::getAssignmentsHash() {
|
||||
return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_builder.getPointerField(
|
||||
::capnp::bounded<2>() * ::capnp::POINTERS));
|
||||
}
|
||||
inline void SlcAction::TeslaGesture::Builder::setAssignmentsHash( ::capnp::Text::Reader value) {
|
||||
::capnp::_::PointerHelpers< ::capnp::Text>::set(_builder.getPointerField(
|
||||
::capnp::bounded<2>() * ::capnp::POINTERS), value);
|
||||
}
|
||||
inline ::capnp::Text::Builder SlcAction::TeslaGesture::Builder::initAssignmentsHash(unsigned int size) {
|
||||
return ::capnp::_::PointerHelpers< ::capnp::Text>::init(_builder.getPointerField(
|
||||
::capnp::bounded<2>() * ::capnp::POINTERS), size);
|
||||
}
|
||||
inline void SlcAction::TeslaGesture::Builder::adoptAssignmentsHash(
|
||||
::capnp::Orphan< ::capnp::Text>&& value) {
|
||||
::capnp::_::PointerHelpers< ::capnp::Text>::adopt(_builder.getPointerField(
|
||||
::capnp::bounded<2>() * ::capnp::POINTERS), kj::mv(value));
|
||||
}
|
||||
inline ::capnp::Orphan< ::capnp::Text> SlcAction::TeslaGesture::Builder::disownAssignmentsHash() {
|
||||
return ::capnp::_::PointerHelpers< ::capnp::Text>::disown(_builder.getPointerField(
|
||||
::capnp::bounded<2>() * ::capnp::POINTERS));
|
||||
}
|
||||
|
||||
inline bool SlcAction::TeslaGesture::Reader::hasVehicleHash() const {
|
||||
return !_reader.getPointerField(
|
||||
::capnp::bounded<3>() * ::capnp::POINTERS).isNull();
|
||||
}
|
||||
inline bool SlcAction::TeslaGesture::Builder::hasVehicleHash() {
|
||||
return !_builder.getPointerField(
|
||||
::capnp::bounded<3>() * ::capnp::POINTERS).isNull();
|
||||
}
|
||||
inline ::capnp::Text::Reader SlcAction::TeslaGesture::Reader::getVehicleHash() const {
|
||||
return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_reader.getPointerField(
|
||||
::capnp::bounded<3>() * ::capnp::POINTERS));
|
||||
}
|
||||
inline ::capnp::Text::Builder SlcAction::TeslaGesture::Builder::getVehicleHash() {
|
||||
return ::capnp::_::PointerHelpers< ::capnp::Text>::get(_builder.getPointerField(
|
||||
::capnp::bounded<3>() * ::capnp::POINTERS));
|
||||
}
|
||||
inline void SlcAction::TeslaGesture::Builder::setVehicleHash( ::capnp::Text::Reader value) {
|
||||
::capnp::_::PointerHelpers< ::capnp::Text>::set(_builder.getPointerField(
|
||||
::capnp::bounded<3>() * ::capnp::POINTERS), value);
|
||||
}
|
||||
inline ::capnp::Text::Builder SlcAction::TeslaGesture::Builder::initVehicleHash(unsigned int size) {
|
||||
return ::capnp::_::PointerHelpers< ::capnp::Text>::init(_builder.getPointerField(
|
||||
::capnp::bounded<3>() * ::capnp::POINTERS), size);
|
||||
}
|
||||
inline void SlcAction::TeslaGesture::Builder::adoptVehicleHash(
|
||||
::capnp::Orphan< ::capnp::Text>&& value) {
|
||||
::capnp::_::PointerHelpers< ::capnp::Text>::adopt(_builder.getPointerField(
|
||||
::capnp::bounded<3>() * ::capnp::POINTERS), kj::mv(value));
|
||||
}
|
||||
inline ::capnp::Orphan< ::capnp::Text> SlcAction::TeslaGesture::Builder::disownVehicleHash() {
|
||||
return ::capnp::_::PointerHelpers< ::capnp::Text>::disown(_builder.getPointerField(
|
||||
::capnp::bounded<3>() * ::capnp::POINTERS));
|
||||
}
|
||||
|
||||
inline ::uint64_t SlcAction::TeslaGesture::Reader::getDriveStartMonoTime() const {
|
||||
return _reader.getDataField< ::uint64_t>(
|
||||
::capnp::bounded<3>() * ::capnp::ELEMENTS);
|
||||
}
|
||||
|
||||
inline ::uint64_t SlcAction::TeslaGesture::Builder::getDriveStartMonoTime() {
|
||||
return _builder.getDataField< ::uint64_t>(
|
||||
::capnp::bounded<3>() * ::capnp::ELEMENTS);
|
||||
}
|
||||
inline void SlcAction::TeslaGesture::Builder::setDriveStartMonoTime( ::uint64_t value) {
|
||||
_builder.setDataField< ::uint64_t>(
|
||||
::capnp::bounded<3>() * ::capnp::ELEMENTS, value);
|
||||
}
|
||||
|
||||
inline ::uint16_t SlcAction::ConditionalManualAction::Reader::getVersion() const {
|
||||
return _reader.getDataField< ::uint16_t>(
|
||||
::capnp::bounded<0>() * ::capnp::ELEMENTS);
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -85,8 +85,10 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
|
||||
{"UsageStatsState", {PERSISTENT | DONT_LOG, JSON}},
|
||||
{"UsageStatsStatus", {CLEAR_ON_MANAGER_START | DONT_LOG, JSON}},
|
||||
{"TeslaCoopSteering", {PERSISTENT, BOOL, "0"}},
|
||||
{"TeslaAOLScreenTap", {PERSISTENT, BOOL, "0"}},
|
||||
{"TeslaAOLScreenTap", {PERSISTENT, BOOL, "1"}},
|
||||
{"TeslaAOLDisengageOnBrake", {PERSISTENT, BOOL, "0"}},
|
||||
{"TeslaSpeedSync", {PERSISTENT, BOOL, "0"}},
|
||||
{"CarControlAssignments", {PERSISTENT | DONT_LOG, JSON}},
|
||||
{"ForceStopDistanceOffset", {PERSISTENT, INT, "0"}},
|
||||
{"LeadApproachBuffer", {PERSISTENT, BOOL, "0"}},
|
||||
{"FasterLeadTakeoff", {PERSISTENT, BOOL, "0"}},
|
||||
@@ -134,6 +136,7 @@ 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,6 +1,8 @@
|
||||
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.
|
||||
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.
|
||||
The official upstream source fonts are licensed under Noto-OFL.txt.
|
||||
|
||||
NotoSansCJKjp-Regular.otf
|
||||
@@ -12,3 +14,8 @@ 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
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,36 @@
|
||||
from opendbc.car.can_definitions import CanData, CanRecvCallable, CanSendCallable
|
||||
from opendbc.car.fw_versions import ObdCallback
|
||||
from opendbc.car.hyundai.ioniq6_handoff import TimestampedCanPacket
|
||||
from openpilot.cereal import messaging
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
from openpilot.selfdrive.pandad import can_list_to_can_capnp
|
||||
|
||||
|
||||
def obd_callback(params: Params) -> ObdCallback:
|
||||
def set_obd_multiplexing(obd_multiplexing: bool):
|
||||
if params.get_bool("ObdMultiplexingEnabled") != obd_multiplexing:
|
||||
cloudlog.warning(f"Setting OBD multiplexing to {obd_multiplexing}")
|
||||
params.remove("ObdMultiplexingChanged")
|
||||
params.put_bool("ObdMultiplexingEnabled", obd_multiplexing, block=True)
|
||||
params.get_bool("ObdMultiplexingChanged", block=True)
|
||||
cloudlog.warning("OBD multiplexing set successfully")
|
||||
return set_obd_multiplexing
|
||||
|
||||
|
||||
def can_comm_callbacks(logcan: messaging.SubSocket, sendcan: messaging.PubSocket) -> tuple[CanRecvCallable, CanSendCallable]:
|
||||
def can_recv(wait_for_one: bool = False) -> list[list[CanData]]:
|
||||
"""
|
||||
wait_for_one: wait the normal logcan socket timeout for a CAN packet, may return empty list if nothing comes
|
||||
|
||||
Returns: CAN packets comprised of CanData objects for easy access
|
||||
"""
|
||||
ret = []
|
||||
for can in messaging.drain_sock(logcan, wait_for_one=wait_for_one):
|
||||
ret.append(TimestampedCanPacket([CanData(msg.address, msg.dat, msg.src) for msg in can.can], int(can.logMonoTime)))
|
||||
return ret
|
||||
|
||||
def can_send(msgs: list[CanData]) -> None:
|
||||
sendcan.send(can_list_to_can_capnp(msgs, msgtype='sendcan'))
|
||||
|
||||
return can_recv, can_send
|
||||
@@ -4,6 +4,7 @@ import os
|
||||
import time
|
||||
import threading
|
||||
import uuid
|
||||
from importlib import import_module
|
||||
from typing import cast
|
||||
|
||||
import openpilot.cereal.messaging as messaging
|
||||
@@ -16,15 +17,13 @@ from openpilot.common.realtime import config_realtime_process, Priority, Ratekee
|
||||
from openpilot.common.swaglog import cloudlog, ForwardingHandler
|
||||
|
||||
from opendbc.car import DT_CTRL, structs
|
||||
from opendbc.car.can_definitions import CanData, CanRecvCallable, CanSendCallable
|
||||
from opendbc.car.carlog import carlog
|
||||
from opendbc.car.fw_versions import ObdCallback
|
||||
from opendbc.car.car_helpers import get_car, interfaces
|
||||
from opendbc.car.gm.distance_button import GMDistanceButtons
|
||||
from opendbc.car.gm.interface import CarInterface as GMInterface
|
||||
from opendbc.car.gm.profiles import profiles_supported as gm_profiles_supported
|
||||
from opendbc.car.hyundai.ioniq6_handoff import (IONIQ6_LONG_PREARM_ENABLED, HandoffOutcome,
|
||||
TimestampedCanPacket, build_ioniq6_hda2_long_candidate,
|
||||
build_ioniq6_hda2_long_candidate,
|
||||
confirm_ioniq6_prepared_takeover, restore_ioniq6_adas,
|
||||
finalize_ioniq6_prepublication, Ioniq6StartupKeepalive,
|
||||
inspect_ioniq6_long_sources)
|
||||
@@ -33,8 +32,9 @@ from opendbc.car.hyundai.ioniq6_media import Ioniq6MediaButtons
|
||||
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.can_callbacks import can_comm_callbacks, obd_callback
|
||||
from openpilot.selfdrive.car.cruise import LOW_SPEED_CRUISE_ON_SET, SlcWheelContext, VCruiseHelper, slc_target_kph
|
||||
from openpilot.starpilot.speed_limits import physical_actions as slc_physical
|
||||
from openpilot.starpilot.speed_limits import physical_actions as slc_physical, tesla_set_speed_card
|
||||
from openpilot.starpilot.aol.intent import AolProcessFaultContext, independent_axis_requested, read_settings
|
||||
from openpilot.starpilot.aol.transport_pause import TransportPauseFeedback, cp_identity
|
||||
from opendbc.car.honda.stock_aol import qualified as qualified_honda_stock_aol, native_observation as honda_native_observation
|
||||
@@ -95,35 +95,6 @@ DISTANCE_GESTURE_KEYS = {Press.SHORT: ('DistanceButtonControl', 0),
|
||||
carlog.addHandler(ForwardingHandler(cloudlog))
|
||||
|
||||
|
||||
def obd_callback(params: Params) -> ObdCallback:
|
||||
def set_obd_multiplexing(obd_multiplexing: bool):
|
||||
if params.get_bool("ObdMultiplexingEnabled") != obd_multiplexing:
|
||||
cloudlog.warning(f"Setting OBD multiplexing to {obd_multiplexing}")
|
||||
params.remove("ObdMultiplexingChanged")
|
||||
params.put_bool("ObdMultiplexingEnabled", obd_multiplexing, block=True)
|
||||
params.get_bool("ObdMultiplexingChanged", block=True)
|
||||
cloudlog.warning("OBD multiplexing set successfully")
|
||||
return set_obd_multiplexing
|
||||
|
||||
|
||||
def can_comm_callbacks(logcan: messaging.SubSocket, sendcan: messaging.PubSocket) -> tuple[CanRecvCallable, CanSendCallable]:
|
||||
def can_recv(wait_for_one: bool = False) -> list[list[CanData]]:
|
||||
"""
|
||||
wait_for_one: wait the normal logcan socket timeout for a CAN packet, may return empty list if nothing comes
|
||||
|
||||
Returns: CAN packets comprised of CanData objects for easy access
|
||||
"""
|
||||
ret = []
|
||||
for can in messaging.drain_sock(logcan, wait_for_one=wait_for_one):
|
||||
ret.append(TimestampedCanPacket([CanData(msg.address, msg.dat, msg.src) for msg in can.can], int(can.logMonoTime)))
|
||||
return ret
|
||||
|
||||
def can_send(msgs: list[CanData]) -> None:
|
||||
sendcan.send(can_list_to_can_capnp(msgs, msgtype='sendcan'))
|
||||
|
||||
return can_recv, can_send
|
||||
|
||||
|
||||
curve_press_receipt = slc_physical.curve_press_receipt
|
||||
|
||||
|
||||
@@ -242,9 +213,7 @@ class Car:
|
||||
def pre_create_hook(cp, candidate, fingerprints, car_fw):
|
||||
initialize_aol_preference(cp)
|
||||
if candidate == HYUNDAI_CAR.HYUNDAI_IONIQ_6:
|
||||
# This decision must precede CarInterface parser/controller construction
|
||||
# and the first CarParams publication below. The exact opt-in is
|
||||
# still subject to current source and restore verification.
|
||||
# Verify the opt-in before constructing the interface and publishing CarParams.
|
||||
eligible = alpha_long_allowed and IONIQ6_LONG_PREARM_ENABLED and not is_release and openpilot_enabled_toggle and not self.params.get_bool("IsOffroad")
|
||||
if eligible:
|
||||
self.sm.update(0)
|
||||
@@ -261,8 +230,7 @@ class Car:
|
||||
preflight = inspect_ioniq6_long_sources(self.can_callbacks[0], ecan_bus=HyundaiCanBus(cp).ECAN)
|
||||
cloudlog.event('ioniq6_long_preflight', reason=preflight.reason)
|
||||
if preflight.source_period is None or preflight.vehicle_ready is not False:
|
||||
# Reboot in READY retains original stock CP before CI/parsers and
|
||||
# publication. Unknown evidence cannot be treated as Ready=False.
|
||||
# READY or unknown keeps stock CarParams.
|
||||
long_cp = None
|
||||
if long_cp is not None:
|
||||
initialize_aol_preference(long_cp)
|
||||
@@ -397,6 +365,11 @@ class Car:
|
||||
raise RuntimeError('AOL requires the exact vehicle safety configuration')
|
||||
config.safetyParam |= aol_policy.safety_param_addition
|
||||
self.CP.alternativeExperience |= aol_policy.alternative_experience_addition
|
||||
if self.CP.carFingerprint == HYUNDAI_CAR.HYUNDAI_KONA_2ND_GEN and config.safetyParam == 0x0C0C and not is_release:
|
||||
from openpilot.starpilot.car.hyundai.aol import configure_kona_factory_handoff
|
||||
self.sm.update(0)
|
||||
if self.sm.valid['pandaStates'] and self.sm.alive['pandaStates']:
|
||||
configure_kona_factory_handoff(self.CP, self.sm['pandaStates'])
|
||||
self.vehicle_startup.finalize_aol_configuration(self.CI)
|
||||
from openpilot.starpilot.car.hyundai.redneck_cruise import configure
|
||||
self.redneck_cruise = configure(self, subscribed_services)
|
||||
@@ -404,12 +377,14 @@ class Car:
|
||||
self.learning_send_mono_ns = self.learning_send_committed_mono_ns = 0
|
||||
self.learning_car_state_source_ns = 0
|
||||
self.learning_applied_evidence = self.learning_previous_applied_evidence = None
|
||||
self.learning_feedback_factory = None
|
||||
try:
|
||||
from openpilot.starpilot.lateral.learning_preferences import read_preference
|
||||
preference = read_preference(self.params, self.CP)
|
||||
if preference.valid and preference.enabled:
|
||||
from opendbc.car.steering_projection import install_observer
|
||||
self.learning_stamp_observer = self.record_learning_send_stamp if install_observer(self.CI) else None
|
||||
self._prepare_feedback_capture()
|
||||
except Exception:
|
||||
pass # Optional learning setup cannot stop native startup.
|
||||
self.aol_transport_feedback = TransportPauseFeedback(self.CP) if self.aol_replay else None
|
||||
@@ -453,6 +428,7 @@ class Car:
|
||||
self.controller_cruise_consumer = CruiseActionConsumer()
|
||||
self.controller_cruise_sock = messaging.sub_sock('slcAction', conflate=False) if cruise_action_eligible(self.CP) else None
|
||||
self.v_cruise_helper = VCruiseHelper(self.CP)
|
||||
self.slc_set_speed = tesla_set_speed_card.attach(self)
|
||||
self.v_cruise_helper.intervals = read_cruise_intervals(self.params, self.CP)
|
||||
|
||||
self.experimental_mode = self.params.get_bool("ExperimentalMode")
|
||||
@@ -592,7 +568,8 @@ class Car:
|
||||
break
|
||||
self.controller_cruise_consumer.apply(request, self.CP, CS, self.sm, self.v_cruise_helper,
|
||||
now_ns=now_ns, is_metric=self.is_metric,
|
||||
enabled=bool(host_control_enabled and can_rcv_valid and not self.params.get_bool("SafeMode")))
|
||||
enabled=bool((host_control_enabled or cruise_helper.tesla_set_speed and host_enabled) and
|
||||
can_rcv_valid and not self.params.get_bool("SafeMode")))
|
||||
if self.slc_replay:
|
||||
self.apply_slc_adopt(now_ns, host_control_enabled=host_control_enabled, after_ns=floor_ns)
|
||||
consumed = self.v_cruise_helper.slc_consumed_button
|
||||
@@ -811,6 +788,7 @@ class Car:
|
||||
slc_replay=self.slc_replay, host_long_active=host_long_active, observed_ns=now_ns)
|
||||
if curve_receipt is not None:
|
||||
self.slc_receipts.append(curve_receipt)
|
||||
tesla_set_speed_card.apply_commands(self, CS, observation, now_ns, long_active=slc_long_active, after_ns=floor_ns)
|
||||
blocked_keys = set()
|
||||
if self.manual_receipt is not None:
|
||||
blocked_keys.add(key_for(self.manual_receipt[0]))
|
||||
@@ -853,8 +831,9 @@ class Car:
|
||||
if self.sm['carControl'].enabled and not self.CC_prev.enabled:
|
||||
target, initial = None, None
|
||||
now_ns = int(self.can_log_mono_time) if REPLAY and hasattr(self, 'can_log_mono_time') else time.monotonic_ns()
|
||||
if (getattr(self, 'slc_match_on_engage', False) and getattr(self, 'slc_control_enabled', False) and
|
||||
not self.CP.pcmCruise and self.CP.openpilotLongitudinalControl and
|
||||
rule = tesla_set_speed_card.rule(self)
|
||||
if ((rule or getattr(self, 'slc_match_on_engage', False) and not self.CP.pcmCruise) and
|
||||
getattr(self, 'slc_control_enabled', False) and self.CP.openpilotLongitudinalControl and
|
||||
CS.canValid and not CS.canTimeout and CS.cruiseState.available and
|
||||
self.sm.valid['carControl'] and self.sm.alive['carControl'] and
|
||||
0 < int(self.sm.logMonoTime['carControl']) <= now_ns and
|
||||
@@ -868,7 +847,7 @@ class Car:
|
||||
evidence = getattr(self.CI.CS, 'dashboard_limit', None)
|
||||
target, initial = slc_physical.engagement_target(
|
||||
self.sm, evidence.observation if evidence is not None else None, self.slc_producer_session,
|
||||
now_ns, after_ns=getattr(self, 'slc_source_floor_ns', 0))
|
||||
now_ns, after_ns=getattr(self, 'slc_source_floor_ns', 0), current_only=rule)
|
||||
adopted = self.v_cruise_helper.initialize_v_cruise(
|
||||
self.CS_prev, self.experimental_mode, resume=self.vehicle_startup.consume_cruise_resume(), initial_speed=self.initial_cruise_speed,
|
||||
slc_target_mps=target, is_metric=self.is_metric)
|
||||
@@ -1161,10 +1140,9 @@ class Car:
|
||||
publication = getattr(self, 'learning_feedback_publication', None)
|
||||
if publication is not None:
|
||||
try:
|
||||
from openpilot.starpilot.flm.feedback_wire import write_publication
|
||||
feedback_companion = (companion.as_reader().as_builder() if companion is not None else
|
||||
messaging.new_message('starpilotCarState', valid=bool(cs_send.valid), logMonoTime=int(cs_send.logMonoTime)))
|
||||
write_publication(feedback_companion.starpilotCarState, publication)
|
||||
self.learning_feedback_writer(feedback_companion.starpilotCarState, publication)
|
||||
companion = feedback_companion
|
||||
except Exception:
|
||||
self.learning_feedback_publication = None
|
||||
@@ -1237,6 +1215,8 @@ class Car:
|
||||
record.decisionId = int(detail.decisionId)
|
||||
record.presentationId = int(detail.presentationId)
|
||||
record.button = 'decel'
|
||||
else:
|
||||
tesla_set_speed_card.write_receipt(record, kind, detail)
|
||||
self.pm.send('slcCruiseEvent', event)
|
||||
|
||||
if getattr(self, 'conditional_replay', False) and self.manual_receipt is not None:
|
||||
@@ -1482,15 +1462,26 @@ class Car:
|
||||
(not ps.safetyRxChecksInvalid or inactive_keepalive and self.gm_startup_keepalive())
|
||||
for ps, cfg in zip(pandas, self.CP.safetyConfigs, strict=True)))
|
||||
|
||||
def _prepare_feedback_capture(self):
|
||||
from openpilot.starpilot.flm.feedback_observation import card_capture_for
|
||||
from openpilot.starpilot.flm.feedback_wire import write_publication
|
||||
from openpilot.starpilot.flm.runtime_adapter_registry import car_params_digest
|
||||
|
||||
# The first calibrated receipt can arrive after lateral is active.
|
||||
import_module('openpilot.starpilot.flm.learning_wire')
|
||||
import_module('openpilot.starpilot.flm.physical_input_observation')
|
||||
self._feedback_cp_sha256 = car_params_digest(self.CP)
|
||||
self.learning_feedback_writer = write_publication
|
||||
self.learning_feedback_factory = card_capture_for
|
||||
|
||||
def _feedback_capture(self, now_ns):
|
||||
# Default OFF performs no feedback-module import, digest or witness allocation.
|
||||
try:
|
||||
source = self.sm['autoSteeringLearning'].learning.sourceReceipt
|
||||
if not source.enabled or source.manual:
|
||||
factory = self.learning_feedback_factory
|
||||
if factory is None or not source.enabled or source.manual:
|
||||
self.learning_feedback_capture = None
|
||||
return None
|
||||
from openpilot.starpilot.flm.feedback_observation import card_capture_for
|
||||
return card_capture_for(self, now_ns)
|
||||
return factory(self, now_ns)
|
||||
except Exception:
|
||||
self.learning_feedback_capture = None
|
||||
return None
|
||||
@@ -1893,6 +1884,9 @@ class Car:
|
||||
self.can_log_mono_time if REPLAY else
|
||||
time.clock_gettime_ns(time.CLOCK_BOOTTIME) if self.volt_startup_keepalive() or monitored_steering else
|
||||
int(time.monotonic() * 1e9))
|
||||
if getattr(self.CI.CC, "speed_sync", None) is not None:
|
||||
from openpilot.starpilot.car.tesla_speed_sync_context import publish_context
|
||||
publish_context(self, CS)
|
||||
learning_snapshot = None
|
||||
try:
|
||||
from openpilot.starpilot.flm.evidence_hooks import begin_applied_frame, applied_snapshot
|
||||
@@ -1991,6 +1985,7 @@ class Car:
|
||||
if getattr(self, 'slc_transport_available', False):
|
||||
self.slc_match_on_engage = self.read_slc_match_on_engage()
|
||||
self.v_cruise_helper.intervals = read_cruise_intervals(self.params, self.CP)
|
||||
tesla_set_speed_card.refresh(self)
|
||||
for name in ('bluepilot_inputs', 'hands_free_cluster_input'):
|
||||
source = getattr(self.CI.CC, name, None)
|
||||
if source is not None:
|
||||
|
||||
@@ -63,6 +63,11 @@ class VCruiseHelper:
|
||||
self.CP = CP
|
||||
from opendbc.car.hyundai.software_cruise import selected as hyundai_software_selected
|
||||
self.hyundai_software_cruise = hyundai_software_selected(CP)
|
||||
# Tesla Model 3/Y with Comma can set speed on Tesla dashboard on: the comma owns SET and the car's is scrolled to
|
||||
# match. Card keeps this current from the saved switch (speed_limits/tesla_set_speed_card.py).
|
||||
self.tesla_set_speed = False
|
||||
self.tesla_pedal_hold = False # After an accelerator override: Hold the speed you reached, applied by card there
|
||||
self.slc_pcm = False # live Speed Limit Controller writes SET on that Tesla
|
||||
self.intervals = CruiseIntervals()
|
||||
self.low_speed_on_set = False
|
||||
self.v_cruise_kph = V_CRUISE_UNSET
|
||||
@@ -88,8 +93,9 @@ class VCruiseHelper:
|
||||
def update_v_cruise(self, CS, enabled, is_metric, slc_pending: SlcPendingConfirmation | None = None, *,
|
||||
slc_enabled: bool = False, wheel_context: SlcWheelContext | None = None):
|
||||
from opendbc.car.subaru.software_cruise import selected as subaru_software_selected
|
||||
stock_software = subaru_software_selected(self.CP) or self.hyundai_software_cruise
|
||||
stock_software = subaru_software_selected(self.CP) or self.hyundai_software_cruise or self.tesla_set_speed
|
||||
software_cruise = not self.CP.pcmCruise or stock_software
|
||||
self.slc_pcm = bool(slc_enabled and self.tesla_set_speed)
|
||||
self.slc_cruise_change = None
|
||||
self.slc_consumed_button = None
|
||||
self.slc_released_suppressed = False
|
||||
@@ -242,7 +248,7 @@ class VCruiseHelper:
|
||||
def adjust_v_cruise(self, button_type, CS, is_metric: bool, *, long_press: bool = False) -> bool:
|
||||
"""Apply the normal software cruise step without synthesizing button events."""
|
||||
from opendbc.car.subaru.software_cruise import selected as subaru_software_selected
|
||||
stock_software = subaru_software_selected(self.CP) or self.hyundai_software_cruise
|
||||
stock_software = subaru_software_selected(self.CP) or self.hyundai_software_cruise or self.tesla_set_speed
|
||||
if ((self.CP.pcmCruise and not stock_software) or button_type not in (ButtonType.accelCruise, ButtonType.decelCruise) or
|
||||
not 0 < self.v_cruise_kph < V_CRUISE_UNSET or
|
||||
(button_type == ButtonType.accelCruise and CS.cruiseState.standstill)):
|
||||
@@ -298,8 +304,9 @@ class VCruiseHelper:
|
||||
if (not self.CP.openpilotLongitudinalControl or slc_target_mps is None or type(slc_target_mps) not in (int, float) or
|
||||
not math.isfinite(slc_target_mps) or not V_CRUISE_MIN / 3.6 - 1e-5 <= slc_target_mps <= V_CRUISE_MAX / 3.6 + 1e-5):
|
||||
slc_target_mps = None
|
||||
# Native cruise owns PCM SET, including when SLC supplies a planner cap.
|
||||
if self.CP.pcmCruise:
|
||||
# Native cruise owns PCM SET, including when SLC supplies a planner cap. On a Tesla where SLC writes SET (slc_pcm),
|
||||
# engaging starts SET at the current limit.
|
||||
if self.CP.pcmCruise and (not self.slc_pcm or slc_target_mps is None):
|
||||
return False
|
||||
# A car-owned acknowledgment can outlive the physical button event.
|
||||
if resume is None:
|
||||
@@ -307,7 +314,7 @@ class VCruiseHelper:
|
||||
resume = (0 < self.pending_resume_ns and 0 <= age <= 500_000_000) or any(
|
||||
b.type in (ButtonType.accelCruise, ButtonType.resumeCruise) for b in CS.buttonEvents)
|
||||
self.pending_resume_ns = 0
|
||||
if resume and self.v_cruise_initialized:
|
||||
if resume and self.v_cruise_initialized and not (self.slc_pcm and slc_target_mps is not None):
|
||||
self.v_cruise_kph = self.v_cruise_kph_last
|
||||
self.v_cruise_cluster_kph = self.v_cruise_kph
|
||||
return False
|
||||
|
||||
@@ -21,8 +21,18 @@ RECORDED = (
|
||||
)
|
||||
|
||||
|
||||
def recorded_frames():
|
||||
return [CanData(address, bytes.fromhex(data), bus) for bus, address, data in RECORDED]
|
||||
MAVERICK_RECORDED = (
|
||||
(0, 130, '69081400b2004000'),
|
||||
(0, 357, '50c0000000000000'),
|
||||
(0, 516, 'f8727d00007c0000'),
|
||||
(0, 535, '052004a6050c048d'),
|
||||
(2, 970, '1e80080000000000'),
|
||||
(2, 979, '7d10007ce0801000'),
|
||||
)
|
||||
|
||||
|
||||
def recorded_frames(layout=RECORDED):
|
||||
return [CanData(address, bytes.fromhex(data), bus) for bus, address, data in layout]
|
||||
|
||||
|
||||
def brand(frames):
|
||||
@@ -33,17 +43,19 @@ def test_recorded_normal_harness_selects_ford_queries_only():
|
||||
assert brand(recorded_frames()) == 'ford'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('layout', [RECORDED, MAVERICK_RECORDED])
|
||||
@pytest.mark.parametrize('missing', range(6))
|
||||
def test_partial_layout_does_not_choose_ford(missing):
|
||||
frames = recorded_frames()
|
||||
def test_partial_layout_does_not_choose_ford(layout, missing):
|
||||
frames = recorded_frames(layout)
|
||||
del frames[missing]
|
||||
assert brand(frames) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('layout', [RECORDED, MAVERICK_RECORDED])
|
||||
@pytest.mark.parametrize('bad', range(6))
|
||||
def test_wrong_bus_dlc_and_returned_frames_do_not_choose_ford(bad):
|
||||
def test_wrong_bus_dlc_and_returned_frames_do_not_choose_ford(layout, bad):
|
||||
for bus_delta, size in ((1, 8), (128, 8), (0, 7), (0, 12)):
|
||||
frames = recorded_frames()
|
||||
frames = recorded_frames(layout)
|
||||
original = frames[bad]
|
||||
frames[bad] = CanData(original.address, bytes(size), original.src + bus_delta)
|
||||
assert brand(frames) is None
|
||||
@@ -77,14 +89,21 @@ def test_shared_probe_uses_existing_read_bound():
|
||||
|
||||
|
||||
@pytest.mark.parametrize('firmware_known', [False, True])
|
||||
def test_cold_automatic_uses_real_vin_isotp_fw_and_identity_matching(firmware_known):
|
||||
@pytest.mark.parametrize('candidate', [CAR.FORD_MUSTANG_MACH_E_MK1, CAR.FORD_MAVERICK_MK1])
|
||||
def test_cold_automatic_uses_real_vin_isotp_fw_and_identity_matching(firmware_known, candidate):
|
||||
firmware = {(0x706, b'\x22\xf1\x88'): b'RJ6T-14H102-BAE'.ljust(24, b'\0'),
|
||||
(0x730, b'\x22\xf1\x88'): b'LJ9C-14D003-FA'.ljust(24, b'\0'),
|
||||
(0x760, b'\x22\xf1\x88'): b'LK9C-2D053-CN'.ljust(24, b'\0'),
|
||||
(0x764, b'\x22\xf1\x88'): b'ML3T-14D049-AL'.ljust(24, b'\0')}
|
||||
layout = RECORDED
|
||||
if candidate == CAR.FORD_MAVERICK_MK1:
|
||||
firmware = {(address, b'\x22\xf1\x88'): version.ljust(24, b'\0') for address, version in (
|
||||
(0x706, b'NZ6T-14F397-AC'), (0x730, b'NZ6C-14D003-AL'),
|
||||
(0x760, b'PZ6C-2D053-EF'), (0x764, b'NZ6T-14D049-AA'))}
|
||||
layout = MAVERICK_RECORDED
|
||||
if not firmware_known:
|
||||
firmware = dict.fromkeys(firmware, b'unknown')
|
||||
transport = FordEcus(firmware=firmware, background=recorded_frames())
|
||||
transport = FordEcus(firmware=firmware, background=recorded_frames(layout))
|
||||
with mock.patch.dict(car_helpers.os.environ, {'FINGERPRINT': '', 'SKIP_FW_QUERY': '', 'DISABLE_FW_CACHE': ''}), \
|
||||
mock.patch.object(car_helpers.time, 'monotonic', side_effect=lambda: transport.clock), \
|
||||
mock.patch.object(car_helpers.time, 'sleep', side_effect=transport.sleep):
|
||||
@@ -93,12 +112,12 @@ def test_cold_automatic_uses_real_vin_isotp_fw_and_identity_matching(firmware_kn
|
||||
assert transport.sent and all(frame.src in (0, 4) for frame in transport.sent)
|
||||
assert any(frame.dat[0] >> 4 == 3 for frame in transport.sent)
|
||||
if firmware_known:
|
||||
assert ci.CP.carFingerprint == CAR.FORD_MUSTANG_MACH_E_MK1
|
||||
assert ci.CP.carFingerprint == candidate
|
||||
assert ci.CP.fingerprintSource == structs.CarParams.FingerprintSource.fw
|
||||
assert ci.CP.carVin == VIN
|
||||
assert {(fw.address, fw.fwVersion) for fw in ci.CP.carFw} == {(address, data) for (address, _), data in firmware.items()}
|
||||
else:
|
||||
assert ci.CP.carFingerprint != CAR.FORD_MUSTANG_MACH_E_MK1
|
||||
assert ci.CP.carFingerprint != candidate
|
||||
assert not ci.CP.safetyConfigs or ci.CP.safetyConfigs[-1].safetyModel != structs.CarParams.SafetyModel.ford
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
from unittest.mock import patch
|
||||
|
||||
from opendbc.car import structs
|
||||
from openpilot.cereal import messaging
|
||||
from openpilot.selfdrive.car.card import Car
|
||||
from openpilot.starpilot.flm.learning_wire import write_source_receipt
|
||||
from openpilot.starpilot.flm.runtime_adapter_registry import SourceState
|
||||
|
||||
|
||||
def test_first_calibrated_feedback_uses_startup_preparation():
|
||||
card = Car.__new__(Car)
|
||||
card.CP = structs.CarParams.new_message(brand='gm', carFingerprint='CHEVROLET_BOLT_ACC_2022_2023')
|
||||
card.learning_feedback_factory = None
|
||||
card._prepare_feedback_capture()
|
||||
|
||||
stamp = 10_000_000_000
|
||||
service = 'autoSteeringLearning'
|
||||
packet = messaging.new_message(service, valid=True, logMonoTime=stamp)
|
||||
source = SourceState(True, False, 'boot', 'a' * 64, stamp, stamp + 500_000_000,
|
||||
card._feedback_cp_sha256, (0., 0., 0.))
|
||||
write_source_receipt(packet, source)
|
||||
sm = messaging.SubMaster([service])
|
||||
sm.update_msgs(stamp / 1e9, [packet.as_reader()])
|
||||
sm.alive[service] = sm.freq_ok[service] = True
|
||||
card.sm = sm
|
||||
|
||||
with patch('openpilot.starpilot.flm.runtime_adapter_registry.car_params_digest', side_effect=AssertionError):
|
||||
capture = card._feedback_capture(stamp)
|
||||
assert capture is not None
|
||||
output = messaging.new_message('carOutput', valid=True, logMonoTime=stamp)
|
||||
companion = messaging.new_message('starpilotCarState', valid=True, logMonoTime=stamp)
|
||||
card.learning_feedback_writer(companion.starpilotCarState, capture.publication(output))
|
||||
assert companion.starpilotCarState.feedbackPublication.version == 1
|
||||
assert not companion.starpilotCarState.feedbackPublication.outputKnown
|
||||
assert card._feedback_capture(stamp + 500_000_001) is None
|
||||
@@ -16,6 +16,7 @@ from openpilot.selfdrive.controls.lib.cycle_timing import ControlCycleTiming, PU
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
|
||||
from opendbc.car.car_helpers import interfaces
|
||||
from opendbc.car.honda.values import CAR as HONDA_CAR, accord_angle_steer_ratio
|
||||
from opendbc.car.vehicle_model import VehicleModel
|
||||
from openpilot.selfdrive.controls.lib.drive_helpers import clip_curvature
|
||||
from openpilot.selfdrive.controls.lib.highway_correction_gain import HighwayCorrectionGain, predicted_lateral_accels, read_gain
|
||||
@@ -357,6 +358,9 @@ class Controls:
|
||||
torque_extension = getattr(self.LaC, 'starpilot_extension', None)
|
||||
if torque_extension is not None:
|
||||
sr = torque_extension.vehicle_model_ratio(sr, CS.vEgo)
|
||||
if self.CP.carFingerprint == HONDA_CAR.HONDA_ACCORD and self.CP.steerControlType == car.CarParams.SteerControlType.angle:
|
||||
# angle-loop EPS: the variable-ratio rack map at the measured angle replaces the learner
|
||||
sr = accord_angle_steer_ratio(CS.steeringAngleDeg - lp.angleOffsetDeg)
|
||||
self.VM.update_params(x, sr)
|
||||
|
||||
steer_angle_without_offset = math.radians(CS.steeringAngleDeg - lp.angleOffsetDeg)
|
||||
@@ -633,6 +637,13 @@ 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:
|
||||
@@ -656,12 +667,13 @@ 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()
|
||||
@@ -723,12 +735,6 @@ 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,7 +28,17 @@ class DesireHelper:
|
||||
def get_lane_change_direction(CS):
|
||||
return LaneChangeDirection.left if CS.leftBlinker else LaneChangeDirection.right
|
||||
|
||||
def update(self, carstate, lateral_active, lane_change_prob, *, auto_evidence=False, engaged=False, navigation_turn=False):
|
||||
def lane_change_speed(self):
|
||||
return max(MINIMUM_SPEED_MPS, self.policy.minimum_speed_mps,
|
||||
20 * CV.MPH_TO_MS if self.policy.turn_signal_guidance else 0.0)
|
||||
|
||||
def waiting_for_lane(self, carstate):
|
||||
return (self.policy.enabled and carstate.vEgo >= self.lane_change_speed() and
|
||||
carstate.leftBlinker != carstate.rightBlinker and
|
||||
(self.lane_change_state == LaneChangeState.preLaneChange or
|
||||
(self.lane_change_state == LaneChangeState.off and not self.prev_one_blinker)))
|
||||
|
||||
def update(self, carstate, lateral_active, lane_change_prob, *, auto_evidence=False, engaged=False, navigation_turn=False, route_turn=False):
|
||||
v_ego = carstate.vEgo
|
||||
one_blinker = carstate.leftBlinker != carstate.rightBlinker
|
||||
if not carstate.leftBlinker and not carstate.rightBlinker:
|
||||
@@ -41,8 +51,7 @@ class DesireHelper:
|
||||
self.auto_signal_blocked = True
|
||||
self.last_signal_direction = signal_direction
|
||||
self.auto_status = "manualRequired"
|
||||
below_lane_change_speed = v_ego < max(MINIMUM_SPEED_MPS, self.policy.minimum_speed_mps,
|
||||
20 * CV.MPH_TO_MS if self.policy.turn_signal_guidance else 0.0)
|
||||
below_lane_change_speed = v_ego < self.lane_change_speed()
|
||||
|
||||
if not self.policy.enabled or not lateral_active or below_lane_change_speed or self.lane_change_timer > LANE_CHANGE_TIME_MAX:
|
||||
self.lane_change_state = LaneChangeState.off
|
||||
@@ -50,12 +59,12 @@ class DesireHelper:
|
||||
self.lane_change_timer = 0.0
|
||||
self.pre_lane_change_timer = 0.0
|
||||
else:
|
||||
if navigation_turn and self.lane_change_state == LaneChangeState.preLaneChange:
|
||||
if navigation_turn and not route_turn and self.lane_change_state == LaneChangeState.preLaneChange:
|
||||
self.lane_change_state = LaneChangeState.off
|
||||
self.lane_change_direction = LaneChangeDirection.none
|
||||
self.pre_lane_change_timer = 0.0
|
||||
if (self.lane_change_state == LaneChangeState.off and one_blinker and not self.prev_one_blinker and
|
||||
not below_lane_change_speed and not navigation_turn and not (self.policy.one_per_signal and self.lane_change_performed)):
|
||||
not below_lane_change_speed and (route_turn or not navigation_turn) and not (self.policy.one_per_signal and self.lane_change_performed)):
|
||||
self.lane_change_state = LaneChangeState.preLaneChange
|
||||
self.lane_change_timer = 0.0
|
||||
self.pre_lane_change_timer = 0.0
|
||||
@@ -101,7 +110,7 @@ class DesireHelper:
|
||||
|
||||
if lane_change_prob < 0.02 and self.lane_change_timer >= LANE_CHANGE_START_TIME:
|
||||
self.lane_change_timer = 0.0
|
||||
if one_blinker and not (self.policy.one_per_signal and self.lane_change_performed):
|
||||
if one_blinker and not route_turn and not (self.policy.one_per_signal and self.lane_change_performed):
|
||||
self.lane_change_state = LaneChangeState.preLaneChange
|
||||
self.lane_change_direction = self.get_lane_change_direction(carstate)
|
||||
else:
|
||||
|
||||
@@ -25,6 +25,7 @@ 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"
|
||||
@@ -83,9 +84,11 @@ 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) -> float:
|
||||
predicted: tuple[float, ...] | None = None, *, steering_limited: bool = False, actuator_delay_s: float = 0.0) -> float:
|
||||
if not lat_active:
|
||||
self.reset(curvature)
|
||||
return curvature
|
||||
@@ -117,8 +120,19 @@ 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.weight = self.bypass_weight * _smoothstep(v_ego, SPEED_OFF, SPEED_ON) * gate * self.limit_recovery
|
||||
k = 1.0 - self.weight * (1.0 - gain)
|
||||
if k >= 1.0:
|
||||
return curvature
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import math
|
||||
|
||||
from openpilot.cereal import log
|
||||
from opendbc.car.honda.values import CAR as HONDA_CAR, HondaFlags, accord_angle_at_own_ratio
|
||||
from openpilot.selfdrive.controls.lib.latcontrol import LatControl
|
||||
from openpilot.starpilot.car.subaru.angle_tune import _ascent_angle_tracking_target, _ascent_low_speed_angle_target
|
||||
|
||||
@@ -14,7 +15,11 @@ class LatControlAngle(LatControl):
|
||||
self.is_ascent = CP.brand == 'subaru' and CP.carFingerprint == 'SUBARU_ASCENT_2023'
|
||||
self.ascent_angle_target = None
|
||||
self.sat_check_min_speed = 5.
|
||||
self.use_steer_limited_by_safety = CP.brand in ("tesla", "hyundai")
|
||||
# Accord on the angle-loop EPS: the EPS angle loop lags 0.3-0.6 s, so a raw angle-error rule flags ordinary turn
|
||||
# entries; its carcontroller limits the setpoint itself (lateral accel/jerk, error clip), so use carOutput instead
|
||||
self.is_accord_angle_loop = CP.brand == "honda" and bool(CP.flags & HondaFlags.EPS_ANGLE_LOOP_FW)
|
||||
self.use_steer_limited_by_safety = CP.brand in ("tesla", "hyundai") or self.is_accord_angle_loop
|
||||
self.is_accord = CP.carFingerprint == HONDA_CAR.HONDA_ACCORD
|
||||
|
||||
def update(self, active, CS, VM, params, steer_limited_by_safety, desired_curvature, curvature_limited, lat_delay):
|
||||
angle_log = log.ControlsState.LateralAngleState.new_message()
|
||||
@@ -26,6 +31,9 @@ class LatControlAngle(LatControl):
|
||||
else:
|
||||
angle_log.active = True
|
||||
angle_steers_des = math.degrees(VM.get_steer_from_curvature(-desired_curvature, CS.vEgo, params.roll))
|
||||
if self.is_accord:
|
||||
# controlsd took sR from the rack map at the MEASURED angle; re-evaluate it at the desired angle
|
||||
angle_steers_des = accord_angle_at_own_ratio(angle_steers_des, VM.sR)
|
||||
angle_steers_des += params.angleOffsetDeg
|
||||
if self.is_ascent:
|
||||
if self.ascent_angle_target is None:
|
||||
|
||||
@@ -7,6 +7,8 @@ from openpilot.cereal import log
|
||||
from opendbc.car import structs
|
||||
from opendbc.car.hyundai.values import CAR, HyundaiFlags
|
||||
from opendbc.car.lateral import FRICTION_THRESHOLD, get_friction
|
||||
from opendbc.car.toyota import legacy_advert_filter
|
||||
from opendbc.car.toyota.values import CAR as TOYOTA_CAR
|
||||
from openpilot.common.constants import ACCELERATION_DUE_TO_GRAVITY, CV
|
||||
from openpilot.common.filter_simple import FirstOrderFilter
|
||||
from openpilot.selfdrive.controls.lib.latcontrol import LatControl
|
||||
@@ -52,6 +54,8 @@ class LatControlTorque(LatControl):
|
||||
and not (CP.notCar or CP.passive or CP.dashcamOnly)
|
||||
)
|
||||
self.controller_mode = default_selection(CP).mode if controller_mode is None else ControllerMode(controller_mode)
|
||||
self.sienna_center_friction = (self.controller_mode == ControllerMode.STANDARD and
|
||||
CP.carFingerprint == TOYOTA_CAR.TOYOTA_SIENNA and legacy_advert_filter.enabled(CP))
|
||||
self.controller_policy = policy_for(CP)
|
||||
if self.controller_mode == ControllerMode.STARPILOT and self.controller_policy is None:
|
||||
raise ValueError('No StarPilot torque policy for CarParams')
|
||||
@@ -98,7 +102,12 @@ class LatControlTorque(LatControl):
|
||||
weight *= np.interp(abs(setpoint), [0.25, 0.65], [1.0, 0.0])
|
||||
threshold += max(np.interp(CS.vEgo, [65 * CV.MPH_TO_MS, 75 * CV.MPH_TO_MS], [0.65, 0.78]) - threshold, 0.0) * weight
|
||||
error = math.copysign(max(abs(error) - 0.04 * weight, 0.0), error)
|
||||
return get_friction(error, deadzone, threshold, self.torque_params)
|
||||
friction = get_friction(error, deadzone, threshold, self.torque_params)
|
||||
if self.sienna_center_friction and not CS.steeringPressed:
|
||||
speed_weight = np.interp(CS.vEgo * CV.MS_TO_MPH, [34., 39., 50., 56.], [0., 1., 1., 0.])
|
||||
center_weight = np.interp(abs(setpoint), [0.22, 0.58], [1., 0.])
|
||||
friction *= 1.0 - 0.5 * speed_weight * center_weight
|
||||
return friction
|
||||
|
||||
def update(self, active, CS, VM, params, steer_limited_by_safety, desired_curvature, curvature_limited, lat_delay):
|
||||
self.flm_surface = self.flm_source.sample(active=active, speed=CS.vEgo)
|
||||
|
||||
@@ -53,8 +53,10 @@ A_CRUISE_MAX_BP = [0., 10.0, 25., 40.]
|
||||
J_CRUISE_VALS = [1.6, 1.2, 0.8, 0.6]
|
||||
A_CRUISE_MIN = -0.5
|
||||
CRUISE_ACCEL_RESPONSE_TIME = 2.0
|
||||
MODEL_Y_SPEED_STEP_JERK = 0.45
|
||||
MODEL_Y_SPEED_STEP_DURATION_NS = 2_000_000_000
|
||||
MODEL_Y_HANDOFF_COAST_TOLERANCE = 0.2
|
||||
MODEL_Y_SPEED_STEP_JERK = 0.25
|
||||
MODEL_Y_SPEED_STEP_LIFT_ACCEL = 0.15
|
||||
MODEL_Y_SPEED_STEP_DURATION_NS = 4_000_000_000
|
||||
SLC_BRAKE_ONSET_JERK = 0.15 # m/s^3: how fast braking may build after an SLC overshoot
|
||||
SLC_BRAKE_ONSET_ACCEL = -0.3 # m/s^2: past this the brakes are engaged and normal jerk resumes
|
||||
CONTROL_N_T_IDX = ModelConstants.T_IDXS[:CONTROL_N]
|
||||
@@ -112,7 +114,7 @@ def get_cruise_accel(e2e, v_cruise, v_ego, a_cruise_prev, angle_steers, CP, dt,
|
||||
speed_error /= CRUISE_ACCEL_RESPONSE_TIME # correct an SLC overshoot as gradually as an approach
|
||||
target_accel = np.clip(speed_error, cruise_min, max_accel)
|
||||
j_cruise = np.interp(v_ego, A_CRUISE_MAX_BP, J_CRUISE_VALS)
|
||||
if speed_step and (v_cruise > v_ego or a_cruise_prev <= 0.0):
|
||||
if speed_step and (v_cruise > v_ego or a_cruise_prev <= MODEL_Y_SPEED_STEP_LIFT_ACCEL):
|
||||
j_cruise = min(j_cruise, MODEL_Y_SPEED_STEP_JERK)
|
||||
decel_start = a_cruise_prev if a_target_prev is None else min(a_cruise_prev, a_target_prev)
|
||||
lower = decel_start - j_cruise * dt
|
||||
@@ -152,6 +154,7 @@ class LongitudinalPlanner:
|
||||
|
||||
self.v_desired_filter = FirstOrderFilter(init_v, 2.0, self.dt)
|
||||
self.a_cruise = init_a
|
||||
self.model_y_handoff_preview_until_ns = 0
|
||||
self.previous_manual_cruise_kph: float | None = None
|
||||
self.manual_cruise_step_until_ns = 0
|
||||
self.output_a_target = init_a
|
||||
@@ -461,16 +464,38 @@ class LongitudinalPlanner:
|
||||
if downhill_error is not None and navigation_ceiling(
|
||||
sm, self.CP, sample_now_ns, limit + .25, slowdown_percent=self.navigation_slowdown_percent) is not None:
|
||||
downhill_error = None
|
||||
cruise_seed = self.a_cruise
|
||||
speed_step = False
|
||||
if self.CP.carFingerprint == 'TESLA_MODEL_Y':
|
||||
cs = sm['carState']
|
||||
leads = (sm['radarState'].leadOne, sm['radarState'].leadTwo)
|
||||
recent_pedal_preview = 0 < self.model_y_handoff_preview_until_ns and sample_now_ns < self.model_y_handoff_preview_until_ns
|
||||
self.model_y_handoff_preview_until_ns = 0
|
||||
if (reset_state and self.CP.openpilotLongitudinalControl and sm['selfdriveState'].enabled and
|
||||
not sm['carControl'].longActive and cs.cruiseState.enabled and (cs.gasPressed or recent_pedal_preview) and not cs.brakePressed and
|
||||
cs.canValid and not cs.canTimeout and not cs.standstill and v_ego > MIN_ALLOW_THROTTLE_SPEED and
|
||||
-MODEL_Y_HANDOFF_COAST_TOLERANCE < cruise_seed <= 0.5 and v_cruise_initialized and v_cruise - v_ego > 1.0 and
|
||||
output_a_target_mpc > cruise_seed and self.mpc.solution_status == 0 and
|
||||
self.allow_throttle and not self.fcw and not sm['controlsState'].forceDecel and
|
||||
not self.force_stop_plan.should_stop and not self.force_stop_plan.forcing and
|
||||
not output_should_stop_mpc and not sm['modelV2'].action.shouldStop and downhill_error is None and
|
||||
ceiling.effective_mps is None and curve.effective_mps is None and navigation_target is None and
|
||||
not (coast_plan is not None and (coast_plan.force_decel or coast_plan.pulse_coasting or coast_plan.brake_floor is not None)) and
|
||||
all(not lead.present or (lead.vLead > v_ego and lead.dRel > max(15., 2. * v_ego)) for lead in leads)):
|
||||
# Preview one actuator delay while the pedal still owns acceleration. Lead and stop arbitration follow below.
|
||||
preview = min(0.25, action_t * np.interp(v_ego, A_CRUISE_MAX_BP, J_CRUISE_VALS))
|
||||
# Taper through coast-down so a near-zero reading does not drop the entire preview.
|
||||
cruise_seed += preview * min(1.0, 1.0 + cruise_seed / MODEL_Y_HANDOFF_COAST_TOLERANCE)
|
||||
if cs.gasPressed:
|
||||
# The pedal state can clear a planner frame before longitudinal control resumes.
|
||||
self.model_y_handoff_preview_until_ns = sample_now_ns + 100_000_000
|
||||
manual_cruise = (
|
||||
profile_eligible and not reset_state and v_ego > MIN_ALLOW_THROTTLE_SPEED and
|
||||
cs.canValid and not cs.canTimeout and not cs.gasPressed and not cs.brakePressed and not cs.standstill and
|
||||
not sm['controlsState'].forceDecel and self.allow_throttle and not self.fcw and
|
||||
not self.force_stop_plan.forcing and not self.force_stop_plan.should_stop and
|
||||
not output_should_stop_mpc and not sm['modelV2'].action.shouldStop and
|
||||
not any(lead.present for lead in (sm['radarState'].leadOne, sm['radarState'].leadTwo)) and
|
||||
not any(lead.present for lead in leads) and
|
||||
ceiling.effective_mps is None and curve.effective_mps is None and navigation_target is None and
|
||||
(coast_plan is None or not (coast_plan.force_decel or coast_plan.pulse_coasting or
|
||||
coast_plan.brake_floor is not None)) and self.mpc.solution_status == 0 and
|
||||
@@ -487,7 +512,7 @@ class LongitudinalPlanner:
|
||||
self.previous_manual_cruise_kph = None
|
||||
self.manual_cruise_step_until_ns = 0
|
||||
self.a_cruise = get_cruise_accel(sm['selfdriveState'].experimentalMode, v_cruise, v_ego,
|
||||
self.a_cruise, steer_angle_without_offset, self.CP, self.dt,
|
||||
cruise_seed, steer_angle_without_offset, self.CP, self.dt,
|
||||
accel_coast, self.allow_throttle, cruise_profile,
|
||||
base_brake_floor=global_floor, selected_acceleration_max=selected_acceleration, faster_takeoffs=faster_takeoffs,
|
||||
a_target_prev=self.output_a_target,
|
||||
|
||||
@@ -334,9 +334,12 @@ 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_surplus_mps=read_surplus(params))
|
||||
navigation_slowdown_percent=navigation_slowdown_percent)
|
||||
downhill_request_ns = -1_000_000_000
|
||||
if downhill_available and 'REPLAY' in os.environ:
|
||||
longitudinal_planner.downhill_surplus_mps = read_surplus(params)
|
||||
nudge_preferences = NudgePreferences(params)
|
||||
# Saved-on features start only for a finalized, supported driving owner. Their
|
||||
# current-source and longitudinal authority checks still run every frame.
|
||||
@@ -400,7 +403,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 longitudinal_planner.downhill_surplus_mps > 0.:
|
||||
if downhill_available:
|
||||
subscribed_services.append('deviceMotion')
|
||||
optional_conditional.append('deviceMotion')
|
||||
sm = messaging.SubMaster(subscribed_services, poll='modelV2',
|
||||
@@ -415,7 +418,11 @@ def starpilot_main():
|
||||
# Due saved-setting verification can block on Params. Complete it
|
||||
# before acquiring the model and fast-source batch, not after that
|
||||
# batch has already begun aging toward the CEM freshness deadline.
|
||||
slc_lifecycle.refresh(time.monotonic_ns(), pending_actions=pending_slc_actions, pending_cruise=pending_slc_cruise)
|
||||
settings_now_ns = time.monotonic_ns()
|
||||
slc_lifecycle.refresh(settings_now_ns, pending_actions=pending_slc_actions, pending_cruise=pending_slc_cruise)
|
||||
if downhill_available and not 0 <= settings_now_ns - downhill_request_ns < 1_000_000_000:
|
||||
downhill_request_ns = settings_now_ns
|
||||
longitudinal_planner.downhill_surplus_mps = read_surplus(params)
|
||||
sm.update()
|
||||
if sm.updated['modelV2']:
|
||||
# Only explicit replay uses the recorded model timeline. In a live host,
|
||||
|
||||
@@ -119,6 +119,28 @@ 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)
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
"""Accord on the angle-loop EPS: steerSaturated follows the carcontroller's limiter, not the raw angle error."""
|
||||
import pytest
|
||||
|
||||
from openpilot.cereal import log
|
||||
from opendbc.car import gen_empty_fingerprint
|
||||
from opendbc.car.structs import car
|
||||
from opendbc.car.honda import carcontroller as honda_carcontroller
|
||||
from opendbc.car.honda import interface as honda_interface
|
||||
from opendbc.car.honda.interface import CarInterface as HondaInterface
|
||||
from opendbc.car.honda.values import CAR as HONDA, HondaFlags
|
||||
from opendbc.car.nissan.interface import CarInterface as NissanInterface
|
||||
from opendbc.car.nissan.values import CAR as NISSAN
|
||||
from opendbc.car.structs import CarParams
|
||||
from opendbc.car.vehicle_model import VehicleModel
|
||||
from openpilot.selfdrive.controls.lib.latcontrol_angle import LatControlAngle
|
||||
|
||||
DT = 0.01
|
||||
ERROR_DEG = 6.0 # an ordinary turn-entry error on the angle-loop EPS, above the 2.5 deg raw-error threshold
|
||||
|
||||
|
||||
class FakeParams:
|
||||
def get_bool(self, key, block=False, default=False):
|
||||
return default
|
||||
|
||||
def get_float(self, key, block=False, default=0.0):
|
||||
return default
|
||||
|
||||
def put_float(self, key, value):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def fake_params(monkeypatch):
|
||||
# the Honda port may read Params in the interface/carcontroller; keep the test off the device store
|
||||
monkeypatch.setattr(honda_interface, "Params", FakeParams, raising=False)
|
||||
monkeypatch.setattr(honda_carcontroller, "Params", FakeParams, raising=False)
|
||||
|
||||
|
||||
def accord_cp(eps_fw: bytes):
|
||||
car_fw = [CarParams.CarFw(ecu=CarParams.Ecu.eps, fwVersion=eps_fw, address=0x18DA30F1, subAddress=0)]
|
||||
return HondaInterface.get_params(HONDA.HONDA_ACCORD, gen_empty_fingerprint(), car_fw, False, False, False)
|
||||
|
||||
|
||||
def angle_cp():
|
||||
return accord_cp(b"39990-TVA,A16C")
|
||||
|
||||
|
||||
def torque_honda_cp():
|
||||
return accord_cp(b"39990-TVA-A160\x00\x00")
|
||||
|
||||
|
||||
def nissan_cp():
|
||||
return NissanInterface.get_non_essential_params(NISSAN.NISSAN_LEAF)
|
||||
|
||||
|
||||
def run(cp, steer_limited_by_safety, seconds=2.0, v_ego=20.0):
|
||||
cp_reader = cp.as_reader()
|
||||
controller = LatControlAngle(cp_reader, None, DT)
|
||||
VM = VehicleModel(cp_reader)
|
||||
params = log.VehicleParameters.new_message()
|
||||
CS = car.CarState.new_message()
|
||||
CS.vEgo = v_ego
|
||||
CS.steeringPressed = False
|
||||
CS.steeringAngleDeg = 0.0
|
||||
# find the desired angle for a small curvature, then hold the wheel ERROR_DEG short of it
|
||||
_, angle_des, _ = controller.update(True, CS, VM, params, False, 0.002, False, 0.2)
|
||||
controller.reset()
|
||||
CS.steeringAngleDeg = angle_des - ERROR_DEG
|
||||
saturated = []
|
||||
for _ in range(round(seconds / DT)):
|
||||
_, des, lac_log = controller.update(True, CS, VM, params, steer_limited_by_safety, 0.002, False, 0.2)
|
||||
assert abs((des - CS.steeringAngleDeg) - ERROR_DEG) < 1e-6
|
||||
saturated.append(lac_log.saturated)
|
||||
return controller, saturated
|
||||
|
||||
|
||||
def test_accord_angle_cp_takes_the_carcontroller_path():
|
||||
cp = angle_cp()
|
||||
assert cp.steerControlType == CarParams.SteerControlType.angle
|
||||
assert cp.flags & HondaFlags.EPS_ANGLE_LOOP_FW
|
||||
assert cp.steerLimitTimer == pytest.approx(0.8)
|
||||
|
||||
|
||||
def test_accord_angle_error_alone_does_not_saturate():
|
||||
controller, saturated = run(angle_cp(), steer_limited_by_safety=False)
|
||||
assert controller.use_steer_limited_by_safety
|
||||
assert not any(saturated)
|
||||
|
||||
|
||||
def test_accord_angle_limited_by_carcontroller_saturates():
|
||||
_, saturated = run(angle_cp(), steer_limited_by_safety=True)
|
||||
assert saturated[-1]
|
||||
# debounced by steerLimitTimer (0.8 s), not instantly
|
||||
assert not saturated[round(0.7 / DT)]
|
||||
|
||||
|
||||
def test_accord_angle_curvature_limited_still_saturates():
|
||||
cp = angle_cp().as_reader()
|
||||
controller = LatControlAngle(cp, None, DT)
|
||||
VM = VehicleModel(cp)
|
||||
CS = car.CarState.new_message()
|
||||
CS.vEgo = 20.0
|
||||
params = log.VehicleParameters.new_message()
|
||||
for _ in range(200):
|
||||
_, _, lac_log = controller.update(True, CS, VM, params, False, 0.0, True, 0.2)
|
||||
assert lac_log.saturated
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cp_fn", [torque_honda_cp, nissan_cp], ids=["honda_torque_fw", "nissan"])
|
||||
def test_other_cars_keep_the_angle_error_rule(cp_fn):
|
||||
controller, saturated = run(cp_fn(), steer_limited_by_safety=False)
|
||||
assert not controller.use_steer_limited_by_safety
|
||||
assert saturated[-1]
|
||||
|
||||
|
||||
def test_tesla_still_uses_carcontroller_path():
|
||||
from opendbc.car.tesla.interface import CarInterface as TeslaInterface
|
||||
from opendbc.car.tesla.values import CAR as TESLA
|
||||
controller, saturated = run(TeslaInterface.get_non_essential_params(TESLA.TESLA_MODEL_3), steer_limited_by_safety=False)
|
||||
assert controller.use_steer_limited_by_safety
|
||||
assert not any(saturated)
|
||||
@@ -560,7 +560,8 @@ def main(demo=False):
|
||||
turn_models = (model.lateral, model.longitudinal) if isinstance(model, LaboratoryPair) else (model,)
|
||||
turn_supported = all(state.npy.get('desire') is not None and state.npy['desire'].shape[-1] == 8 for state in turn_models)
|
||||
desire = navigation_turn.select(sm, time.monotonic_ns(), DH.desire,
|
||||
supported=turn_supported, model_stop=bool(prev_action.shouldStop))
|
||||
supported=turn_supported, model_stop=bool(prev_action.shouldStop),
|
||||
waiting_for_lane=DH.waiting_for_lane(sm["carState"]))
|
||||
is_rhd = sm["driverMonitoringState"].isRHD
|
||||
frame_id = sm["narrowRoadCameraState"].frameId
|
||||
v_ego = max(sm["carState"].vEgo, 0.)
|
||||
@@ -691,7 +692,7 @@ def main(demo=False):
|
||||
DH.update(car_state, sm['carControl'].latActive, lane_change_prob,
|
||||
auto_evidence=auto_ready, engaged=auto_trigger_engaged(sm, runtime_lane_policy,
|
||||
openpilot_longitudinal=bool(CP.openpilotLongitudinalControl), now_mono_ns=mono_now_ns),
|
||||
navigation_turn=signal_turn or matching_turn_signal(sm, mono_now_ns, supported=navigation_turn.automatic_turn_enabled))
|
||||
navigation_turn=signal_turn, route_turn=matching_turn_signal(sm, mono_now_ns, supported=navigation_turn.automatic_turn_enabled))
|
||||
modelv2_send.modelV2.meta.laneChangeState = DH.lane_change_state
|
||||
modelv2_send.modelV2.meta.laneChangeDirection = DH.lane_change_direction
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user